aboutsummaryrefslogtreecommitdiffhomepage
path: root/printing/printer.ml
blob: 28b10c78120716414eb1c27aca7851eaabe906c0 (plain)
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
1001
1002
1003
1004
1005
1006
1007
(************************************************************************)
(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)
(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2017     *)
(*   \VV/  **************************************************************)
(*    //   *      This file is distributed under the terms of the       *)
(*         *       GNU Lesser General Public License Version 2.1        *)
(************************************************************************)

open Pp
open CErrors
open Util
open Names
open Term
open Environ
open Globnames
open Nametab
open Evd
open Proof_type
open Refiner
open Constrextern
open Ppconstr
open Declarations

module RelDecl = Context.Rel.Declaration
module NamedDecl = Context.Named.Declaration
module CompactedDecl = Context.Compacted.Declaration

let get_current_context () =
  Pfedit.get_current_context ()

let enable_unfocused_goal_printing = ref false
let enable_goal_tags_printing = ref false
let enable_goal_names_printing = ref false

let should_tag() = !enable_goal_tags_printing
let should_unfoc() = !enable_unfocused_goal_printing
let should_gname() = !enable_goal_names_printing


let _ =
  let open Goptions in
  declare_bool_option
    { optdepr  = false;
      optname  = "printing of unfocused goal";
      optkey   = ["Printing";"Unfocused"];
      optread  = (fun () -> !enable_unfocused_goal_printing);
      optwrite = (fun b -> enable_unfocused_goal_printing:=b) }

(* This is set on by proofgeneral proof-tree mode. But may be used for
   other purposes *)
let _ =
  let open Goptions in
  declare_bool_option
    { optdepr  = false;
      optname  = "printing of goal tags";
      optkey   = ["Printing";"Goal";"Tags"];
      optread  = (fun () -> !enable_goal_tags_printing);
      optwrite = (fun b -> enable_goal_tags_printing:=b) }


let _ =
  let open Goptions in
  declare_bool_option
    { optdepr  = false;
      optname  = "printing of goal names";
      optkey   = ["Printing";"Goal";"Names"];
      optread  = (fun () -> !enable_goal_names_printing);
      optwrite = (fun b -> enable_goal_names_printing:=b) }


(**********************************************************************)
(** Terms                                                             *)

(* [goal_concl_style] means that all names of goal/section variables
   and all names of rel variables (if any) in the given env and all short
   names of global definitions of the current module must be avoided while
   printing bound variables.
   Otherwise, short names of global definitions are printed qualified
   and only names of goal/section variables and rel names that do
   _not_ occur in the scope of the binder to be printed are avoided. *)

let pr_econstr_core goal_concl_style env sigma t =
  pr_constr_expr (extern_constr goal_concl_style env sigma t)
let pr_leconstr_core goal_concl_style env sigma t =
  pr_lconstr_expr (extern_constr goal_concl_style env sigma t)

let pr_lconstr_env env sigma c = pr_leconstr_core false env sigma (EConstr.of_constr c)
let pr_constr_env env sigma c = pr_econstr_core false env sigma (EConstr.of_constr c)
let _ = Hook.set Refine.pr_constr pr_constr_env

let pr_lconstr_goal_style_env env sigma c = pr_leconstr_core true env sigma (EConstr.of_constr c)
let pr_constr_goal_style_env env sigma c = pr_econstr_core true env sigma (EConstr.of_constr c)

let pr_open_lconstr_env env sigma (_,c) = pr_lconstr_env env sigma c
let pr_open_constr_env env sigma (_,c) = pr_constr_env env sigma c

let pr_leconstr_env env sigma c = pr_leconstr_core false env sigma c
let pr_econstr_env env sigma c = pr_econstr_core false env sigma c

(* NB do not remove the eta-redexes! Global.env() has side-effects... *)
let pr_lconstr t =
  let (sigma, env) = get_current_context () in
  pr_lconstr_env env sigma t
let pr_constr t =
  let (sigma, env) = get_current_context () in
  pr_constr_env env sigma t

let pr_open_lconstr (_,c) = pr_lconstr c
let pr_open_constr (_,c) = pr_constr c

let pr_leconstr c = pr_lconstr (EConstr.Unsafe.to_constr c)
let pr_econstr c = pr_constr (EConstr.Unsafe.to_constr c)

let pr_constr_under_binders_env_gen pr env sigma (ids,c) =
  (* Warning: clashes can occur with variables of same name in env but *)
  (* we also need to preserve the actual names of the patterns *)
  (* So what to do? *)
  let assums = List.map (fun id -> (Name id,(* dummy *) mkProp)) ids in
  pr (Termops.push_rels_assum assums env) sigma c

let pr_constr_under_binders_env = pr_constr_under_binders_env_gen pr_econstr_env
let pr_lconstr_under_binders_env = pr_constr_under_binders_env_gen pr_leconstr_env

let pr_constr_under_binders c =
  let (sigma, env) = get_current_context () in
  pr_constr_under_binders_env env sigma c
let pr_lconstr_under_binders c =
  let (sigma, env) = get_current_context () in
  pr_lconstr_under_binders_env env sigma c

let pr_etype_core goal_concl_style env sigma t =
  pr_constr_expr (extern_type goal_concl_style env sigma t)
let pr_letype_core goal_concl_style env sigma t =
  pr_lconstr_expr (extern_type goal_concl_style env sigma t)

let pr_ltype_env env sigma c = pr_letype_core false env sigma (EConstr.of_constr c)
let pr_type_env env sigma c = pr_etype_core false env sigma (EConstr.of_constr c)

let pr_ltype t =
    let (sigma, env) = get_current_context () in
    pr_ltype_env env sigma t
let pr_type t =
    let (sigma, env) = get_current_context () in
    pr_type_env env sigma t

let pr_etype_env env sigma c = pr_etype_core false env sigma c
let pr_letype_env env sigma c = pr_letype_core false env sigma c
let pr_goal_concl_style_env env sigma c = pr_letype_core true env sigma c

let pr_ljudge_env env sigma j =
  (pr_leconstr_env env sigma j.uj_val, pr_leconstr_env env sigma j.uj_type)

let pr_ljudge j =
  let (sigma, env) = get_current_context () in
  pr_ljudge_env env sigma j

let pr_lglob_constr_env env c =
  pr_lconstr_expr (extern_glob_constr (Termops.vars_of_env env) c)
let pr_glob_constr_env env c =
  pr_constr_expr (extern_glob_constr (Termops.vars_of_env env) c)

let pr_lglob_constr c =
  let (sigma, env) = get_current_context () in
  pr_lglob_constr_env env c
let pr_glob_constr c =
  let (sigma, env) = get_current_context () in
  pr_glob_constr_env env c

let pr_closed_glob_env env sigma c =
  pr_constr_expr (extern_closed_glob false env sigma c)
let pr_closed_glob c =
  let (sigma, env) = get_current_context () in
  pr_closed_glob_env env sigma c

let pr_lconstr_pattern_env env sigma c =
  pr_lconstr_pattern_expr (extern_constr_pattern (Termops.names_of_rel_context env) sigma c)
let pr_constr_pattern_env env sigma c =
  pr_constr_pattern_expr (extern_constr_pattern (Termops.names_of_rel_context env) sigma c)

let pr_cases_pattern t =
  pr_cases_pattern_expr (extern_cases_pattern Names.Id.Set.empty t)

let pr_lconstr_pattern t =
  let (sigma, env) = get_current_context () in
  pr_lconstr_pattern_env env sigma t
let pr_constr_pattern t =
  let (sigma, env) = get_current_context () in
  pr_constr_pattern_env env sigma t

let pr_sort sigma s = pr_glob_sort (extern_sort sigma s)

let _ = Termops.set_print_constr 
  (fun env sigma t -> pr_lconstr_expr (extern_constr ~lax:true false env sigma t))

let pr_in_comment pr x = str "(* " ++ pr x ++ str " *)"

(** Term printers resilient to [Nametab] errors *)

(** When the nametab isn't up-to-date, the term printers above
    could raise [Not_found] during [Nametab.shortest_qualid_of_global].
    In this case, we build here a fully-qualified name based upon
    the kernel modpath and label of constants, and the idents in
    the [mutual_inductive_body] for the inductives and constructors
    (needs an environment for this). *)

let id_of_global env = function
  | ConstRef kn -> Label.to_id (Constant.label kn)
  | IndRef (kn,0) -> Label.to_id (MutInd.label kn)
  | IndRef (kn,i) ->
    (Environ.lookup_mind kn env).mind_packets.(i).mind_typename
  | ConstructRef ((kn,i),j) ->
    (Environ.lookup_mind kn env).mind_packets.(i).mind_consnames.(j-1)
  | VarRef v -> v

let rec dirpath_of_mp = function
  | MPfile sl -> sl
  | MPbound uid -> DirPath.make [MBId.to_id uid]
  | MPdot (mp,l) ->
    Libnames.add_dirpath_suffix (dirpath_of_mp mp) (Label.to_id l)

let dirpath_of_global = function
  | ConstRef kn -> dirpath_of_mp (Constant.modpath kn)
  | IndRef (kn,_) | ConstructRef ((kn,_),_) ->
    dirpath_of_mp (MutInd.modpath kn)
  | VarRef _ -> DirPath.empty

let qualid_of_global env r =
  Libnames.make_qualid (dirpath_of_global r) (id_of_global env r)

let safe_gen f env sigma c =
  let orig_extern_ref = Constrextern.get_extern_reference () in
  let extern_ref ?loc vars r =
    try orig_extern_ref ?loc vars r
    with e when CErrors.noncritical e ->
      Libnames.Qualid (Loc.tag ?loc @@ qualid_of_global env r)
  in
  Constrextern.set_extern_reference extern_ref;
  try
    let p = f env sigma c in
    Constrextern.set_extern_reference orig_extern_ref;
    p
  with e when CErrors.noncritical e ->
    Constrextern.set_extern_reference orig_extern_ref;
    str "??"

let safe_pr_lconstr_env = safe_gen pr_lconstr_env
let safe_pr_constr_env = safe_gen pr_constr_env
let safe_pr_lconstr t =
  let (sigma, env) = get_current_context () in
  safe_pr_lconstr_env env sigma t

let safe_pr_constr t =
  let (sigma, env) = get_current_context () in
  safe_pr_constr_env env sigma t

let pr_universe_ctx sigma c =
  if !Detyping.print_universes && not (Univ.UContext.is_empty c) then
    fnl()++pr_in_comment (fun c -> v 0 
      (Univ.pr_universe_context (Termops.pr_evd_level sigma) c)) c
  else
    mt()

let pr_cumulativity_info sigma cumi =
  if !Detyping.print_universes 
  && not (Univ.UContext.is_empty (Univ.CumulativityInfo.univ_context cumi)) then
    fnl()++pr_in_comment (fun uii -> v 0 
      (Univ.pr_cumulativity_info (Termops.pr_evd_level sigma) uii)) cumi
  else
    mt()

(**********************************************************************)
(* Global references *)

let pr_global_env = pr_global_env
let pr_global = pr_global_env Id.Set.empty

let pr_puniverses f env (c,u) =
  f env c ++ 
  (if !Constrextern.print_universes then
    str"(*" ++ Univ.Instance.pr Universes.pr_with_global_universes u ++ str"*)"
   else mt ())

let pr_constant env cst = pr_global_env (Termops.vars_of_env env) (ConstRef cst)
let pr_existential_key = Termops.pr_existential_key
let pr_existential env sigma ev = pr_lconstr_env env sigma (mkEvar ev)
let pr_inductive env ind = pr_lconstr_env env Evd.empty (mkInd ind)
let pr_constructor env cstr = pr_lconstr_env env Evd.empty (mkConstruct cstr)

let pr_pconstant = pr_puniverses pr_constant
let pr_pinductive = pr_puniverses pr_inductive
let pr_pconstructor = pr_puniverses pr_constructor

let pr_evaluable_reference ref =
  pr_global (Tacred.global_of_evaluable_reference ref)

(*let pr_glob_constr t =
  pr_lconstr (Constrextern.extern_glob_constr Id.Set.empty t)*)

(*open Pattern

let pr_pattern t = pr_pattern_env (Global.env()) empty_names_context t*)

(**********************************************************************)
(* Contexts and declarations                                          *)


(* Flag for compact display of goals *)

let get_compact_context,set_compact_context =
  let compact_context = ref false in
  (fun () -> !compact_context),(fun b  -> compact_context := b)

let pr_compacted_decl env sigma decl =
  let ids, pbody, typ = match decl with
    | CompactedDecl.LocalAssum (ids, typ) ->
       ids, mt (), typ
    | CompactedDecl.LocalDef (ids,c,typ) ->
       (* Force evaluation *)
       let pb = pr_lconstr_env env sigma c in
       let pb = if isCast c then surround pb else pb in
       ids, (str" := " ++ pb ++ cut ()), typ
  in
  let pids = prlist_with_sep pr_comma pr_id ids in
  let pt = pr_ltype_env env sigma typ in
  let ptyp = (str" : " ++ pt) in
  hov 0 (pids ++ pbody ++ ptyp)

let pr_named_decl env sigma decl =
  decl |> CompactedDecl.of_named_decl |> pr_compacted_decl env sigma

let pr_rel_decl env sigma decl =
  let na = RelDecl.get_name decl in
  let typ = RelDecl.get_type decl in
  let pbody = match decl with
    | RelDecl.LocalAssum _ -> mt ()
    | RelDecl.LocalDef (_,c,_) ->
	(* Force evaluation *)
	let pb = pr_lconstr_env env sigma c in
	let pb = if isCast c then surround pb else pb in
	(str":=" ++ spc () ++ pb ++ spc ()) in
  let ptyp = pr_ltype_env env sigma typ in
  match na with
  | Anonymous -> hov 0 (str"<>" ++ spc () ++ pbody ++ str":" ++ spc () ++ ptyp)
  | Name id -> hov 0 (pr_id id ++ spc () ++ pbody ++ str":" ++ spc () ++ ptyp)


(* Prints out an "env" in a nice format.  We print out the
 * signature,then a horizontal bar, then the debruijn environment.
 * It's printed out from outermost to innermost, so it's readable. *)

(* Prints a signature, all declarations on the same line if possible *)
let pr_named_context_of env sigma =
  let make_decl_list env d pps = pr_named_decl env sigma d :: pps in
  let psl = List.rev (fold_named_context make_decl_list env ~init:[]) in
  hv 0 (prlist_with_sep (fun _ -> ws 2) (fun x -> x) psl)

let pr_var_list_decl env sigma decl =
  hov 0 (pr_compacted_decl env sigma decl)

let pr_named_context env sigma ne_context =
  hv 0 (Context.Named.fold_outside
	  (fun d pps -> pps ++ ws 2 ++ pr_named_decl env sigma d)
          ne_context ~init:(mt ()))

let pr_rel_context env sigma rel_context =
  let rel_context = List.map (fun d -> Termops.map_rel_decl EConstr.of_constr d) rel_context in
  pr_binders (extern_rel_context None env sigma rel_context)

let pr_rel_context_of env sigma =
  pr_rel_context env sigma (rel_context env)

(* Prints an env (variables and de Bruijn). Separator: newline *)
let pr_context_unlimited env sigma =
  let sign_env =
    Context.Compacted.fold
      (fun d pps ->
         let pidt =  pr_compacted_decl env sigma d in
         (pps ++ fnl () ++ pidt))
      (Termops.compact_named_context (named_context env)) ~init:(mt ())
  in
  let db_env =
    fold_rel_context
      (fun env d pps ->
         let pnat = pr_rel_decl env sigma d in (pps ++ fnl () ++ pnat))
      env ~init:(mt ())
  in
  (sign_env ++ db_env)

let pr_ne_context_of header env sigma =
  if List.is_empty (Environ.rel_context env) &&
    List.is_empty (Environ.named_context env)  then (mt ())
  else let penv = pr_context_unlimited env sigma in (header ++ penv ++ fnl ())

(* Heuristic for horizontalizing hypothesis that the user probably
   considers as "variables": An hypothesis H:T where T:S and S<>Prop. *)
let should_compact env sigma typ =
  get_compact_context() &&
    let type_of_typ = Retyping.get_type_of env sigma (EConstr.of_constr typ) in
    not (is_Prop (EConstr.to_constr sigma type_of_typ))


(* If option Compact Contexts is set, we pack "simple" hypothesis in a
   hov box (with three sapaces as a separator), the global box being a
   v box *)
let rec bld_sign_env env sigma ctxt pps =
  match ctxt with
  | [] -> pps
  | CompactedDecl.LocalAssum (ids,typ)::ctxt' when should_compact env sigma typ ->
    let pps',ctxt' = bld_sign_env_id env sigma ctxt (mt ()) true in
    (* putting simple hyps in a more horizontal flavor *)
    bld_sign_env env sigma ctxt' (pps ++ brk (0,0) ++ hov 0 pps')
  | d:: ctxt' ->
    let pidt = pr_var_list_decl env sigma d in
    let pps' = pps ++ brk (0,0) ++ pidt in
    bld_sign_env env sigma ctxt' pps'
and bld_sign_env_id env sigma ctxt pps is_start =
  match ctxt with
  | [] -> pps,ctxt
 | CompactedDecl.LocalAssum(ids,typ) as d :: ctxt' when should_compact env sigma typ ->
    let pidt = pr_var_list_decl env sigma d in
    let pps' = pps ++ (if not is_start then brk (3,0) else (mt ())) ++ pidt in
    bld_sign_env_id env sigma ctxt' pps' false
  | _ -> pps,ctxt


(* compact printing an env (variables and de Bruijn). Separator: three
   spaces between simple hyps, and newline otherwise *)
let pr_context_limit_compact ?n env sigma =
  let ctxt = Termops.compact_named_context (named_context env) in
  let lgth = List.length ctxt in
  let n_capped =
    match n with
    | None -> lgth
    | Some n when n > lgth -> lgth
    | Some n -> n in
  let ctxt_chopped,ctxt_hidden = Util.List.chop n_capped ctxt in
  (* a dot line hinting the number of hidden hyps. *)
  let hidden_dots = String.make (List.length ctxt_hidden) '.' in
  let sign_env = v 0 (str hidden_dots ++ (mt ())
                 ++ bld_sign_env env sigma (List.rev ctxt_chopped) (mt ())) in
  let db_env =
    fold_rel_context (fun env d pps -> pps ++ fnl () ++ pr_rel_decl env sigma d)
      env ~init:(mt ()) in
  sign_env ++ db_env

(* The number of printed hypothesis in a goal *)
(* If [None], no limit *)
let print_hyps_limit = ref (None : int option)

let _ =
  let open Goptions in
  declare_int_option
    { optdepr  = false;
      optname  = "the hypotheses limit";
      optkey   = ["Hyps";"Limit"];
      optread  = (fun () -> !print_hyps_limit);
      optwrite = (fun x -> print_hyps_limit := x) }

let pr_context_of env sigma = match !print_hyps_limit with
  | None -> hv 0 (pr_context_limit_compact env sigma)
  | Some n -> hv 0 (pr_context_limit_compact ~n env sigma)

(* display goal parts (Proof mode) *)

let pr_predicate pr_elt (b, elts) =
  let pr_elts = prlist_with_sep spc pr_elt elts in
    if b then
      str"all" ++
	(if List.is_empty elts then mt () else str" except: " ++ pr_elts)
    else
      if List.is_empty elts then str"none" else pr_elts

let pr_cpred p = pr_predicate (pr_constant (Global.env())) (Cpred.elements p)
let pr_idpred p = pr_predicate Nameops.pr_id (Id.Pred.elements p)

let pr_transparent_state (ids, csts) =
  hv 0 (str"VARIABLES: " ++ pr_idpred ids ++ fnl () ++
	str"CONSTANTS: " ++ pr_cpred csts ++ fnl ())

(* display complete goal *)
let default_pr_goal gs =
  let g = sig_it gs in
  let sigma = project gs in
  let env = Goal.V82.env sigma g in
  let concl = Goal.V82.concl sigma g in
  let goal =
    pr_context_of env sigma ++ cut () ++
      str "============================" ++ cut ()  ++
      pr_goal_concl_style_env env sigma concl in
  str "  " ++ v 0 goal

(* display a goal tag *)
let pr_goal_tag g =
  let s = " (ID " ^ Goal.uid g ^ ")" in
  str s

(* display a goal name *)
let pr_goal_name sigma g =
  if should_gname() then str " " ++ Pp.surround (pr_existential_key sigma g)
  else mt ()

let pr_goal_header nme sigma g =
  let (g,sigma) = Goal.V82.nf_evar sigma g in
  str "subgoal " ++ nme ++ (if should_tag() then pr_goal_tag g else str"")
  ++ (if should_gname() then str " " ++ Pp.surround (pr_existential_key sigma g) else mt ())  

(* display the conclusion of a goal *)
let pr_concl n sigma g =
  let (g,sigma) = Goal.V82.nf_evar sigma g in
  let env = Goal.V82.env sigma g in
  let pc = pr_goal_concl_style_env env sigma (Goal.V82.concl sigma g) in
  let header = pr_goal_header (int n) sigma g in
  header ++ str " is:" ++ cut () ++ str" "  ++ pc

(* display evar type: a context and a type *)
let pr_evgl_sign sigma evi =
  let env = evar_env evi in
  let ps = pr_named_context_of env sigma in
  let _, l = match Filter.repr (evar_filter evi) with
  | None -> [], []
  | Some f -> List.filter2 (fun b c -> not b) f (evar_context evi)
  in
  let ids = List.rev_map NamedDecl.get_id l in
  let warn =
    if List.is_empty ids then mt () else
      (str "(" ++ prlist_with_sep pr_comma pr_id ids ++ str " cannot be used)")
  in
  let pc = pr_lconstr_env env sigma evi.evar_concl in
  let candidates =
    match evi.evar_body, evi.evar_candidates with
    | Evar_empty, Some l ->
       spc () ++ str "= {" ++
         prlist_with_sep (fun () -> str "|") (pr_lconstr_env env sigma) l ++ str "}"
    | _ ->
       mt ()
  in
  hov 0 (str"[" ++ ps ++ spc () ++ str"|- "  ++ pc ++ str"]" ++
           candidates ++ spc () ++ warn)

(* Print an existential variable *)

let pr_evar sigma (evk, evi) =
  let pegl = pr_evgl_sign sigma evi in
  hov 0 (pr_existential_key sigma evk ++ str " : " ++ pegl)

(* Print an enumerated list of existential variables *)
let rec pr_evars_int_hd head sigma i = function
  | [] -> mt ()
  | (evk,evi)::rest ->
      (hov 0 (head i ++ pr_evar sigma (evk,evi))) ++
      (match rest with [] -> mt () | _ -> fnl () ++ pr_evars_int_hd head sigma (i+1) rest)

let pr_evars_int sigma i evs = pr_evars_int_hd (fun i -> str "Existential " ++ int i ++ str " =" ++ spc ()) sigma i (Evar.Map.bindings evs)

let pr_evars sigma evs = pr_evars_int_hd (fun i -> mt ()) sigma 1 (Evar.Map.bindings evs)

(* Display a list of evars given by their name, with a prefix *)
let pr_ne_evar_set hd tl sigma l =
  if l != Evar.Set.empty then
    let l = Evar.Set.fold (fun ev ->
      Evar.Map.add ev (Evarutil.nf_evar_info sigma (Evd.find sigma ev)))
      l Evar.Map.empty in
    hd ++ pr_evars sigma l ++ tl
  else
    mt ()

let pr_selected_subgoal name sigma g =
  let pg = default_pr_goal { sigma=sigma ; it=g; } in
  let header = pr_goal_header name sigma g in
  v 0 (header ++ str " is:" ++ cut () ++ pg)

let default_pr_subgoal n sigma =
  let rec prrec p = function
    | [] -> user_err Pp.(str "No such goal.")
    | g::rest ->
	if Int.equal p 1 then
          pr_selected_subgoal (int n) sigma g
	else
	  prrec (p-1) rest
  in
  prrec n

let pr_internal_existential_key ev = str (string_of_existential ev)

let print_evar_constraints gl sigma =
  let pr_env =
    match gl with
    | None -> fun e' -> pr_context_of e' sigma
    | Some g ->
       let env = Goal.V82.env sigma g in fun e' ->
       begin
         if Context.Named.equal Constr.equal (named_context env) (named_context e') then
           if Context.Rel.equal Constr.equal (rel_context env) (rel_context e') then mt ()
           else pr_rel_context_of e' sigma ++ str " |-" ++ spc ()
         else pr_context_of e' sigma ++ str " |-" ++ spc ()
       end
  in
  let pr_evconstr (pbty,env,t1,t2) =
    let t1 = Evarutil.nf_evar sigma (EConstr.of_constr t1)
    and t2 = Evarutil.nf_evar sigma (EConstr.of_constr t2) in
    let env =
      (** We currently allow evar instances to refer to anonymous de Bruijn
          indices, so we protect the error printing code in this case by giving
          names to every de Bruijn variable in the rel_context of the conversion
          problem. MS: we should rather stop depending on anonymous variables, they
          can be used to indicate independency. Also, this depends on a strategy for 
          naming/renaming *)
      Namegen.make_all_name_different env sigma in
    str" " ++
      hov 2 (pr_env env ++ pr_leconstr_env env sigma t1 ++ spc () ++
             str (match pbty with
                  | Reduction.CONV -> "=="
                  | Reduction.CUMUL -> "<=") ++
             spc () ++ pr_leconstr_env env sigma t2)
  in
  let pr_candidate ev evi (candidates,acc) =
    if Option.has_some evi.evar_candidates then
      (succ candidates, acc ++ pr_evar sigma (ev,evi) ++ fnl ())
    else (candidates, acc)
  in
  let constraints =
    let _, cstrs = Evd.extract_all_conv_pbs sigma in
    if List.is_empty cstrs then mt ()
    else fnl () ++ str (String.plural (List.length cstrs) "unification constraint")
         ++ str":" ++ fnl () ++ hov 0 (prlist_with_sep fnl pr_evconstr cstrs)
  in
  let candidates, ppcandidates = Evd.fold_undefined pr_candidate sigma (0,mt ()) in
  constraints ++
    if candidates > 0 then
      fnl () ++ str (String.plural candidates "existential") ++
        str" with candidates:" ++ fnl () ++ hov 0 ppcandidates
    else mt ()

let should_print_dependent_evars = ref false

let _ =
  let open Goptions in
  declare_bool_option
    { optdepr  = false;
      optname  = "Printing Dependent Evars Line";
      optkey   = ["Printing";"Dependent";"Evars";"Line"];
      optread  = (fun () -> !should_print_dependent_evars);
      optwrite = (fun v -> should_print_dependent_evars := v) }

let print_dependent_evars gl sigma seeds =
  let constraints = print_evar_constraints gl sigma in
  let evars () =
    if !should_print_dependent_evars then
      let evars = Evarutil.gather_dependent_evars sigma seeds in
      let evars =
	Evar.Map.fold begin fun e i s ->
	  let e' = pr_internal_existential_key e in
	  match i with
	  | None -> s ++ str" " ++ e' ++ str " open,"
	  | Some i ->
	    s ++ str " " ++ e' ++ str " using " ++
	      Evar.Set.fold begin fun d s ->
		pr_internal_existential_key d ++ str " " ++ s
	      end i (str ",")
	end evars (str "")
    in
    cut () ++ cut () ++
    str "(dependent evars:" ++ evars ++ str ")"
    else mt ()
  in
  constraints ++ evars ()

(* Print open subgoals. Checks for uninstantiated existential variables *)
(* spiwack: [seeds] is for printing dependent evars in emacs mode. *)
(* spiwack: [pr_first] is true when the first goal must be singled out
   and printed in its entirety. *)
let default_pr_subgoals ?(pr_first=true)
                        close_cmd sigma seeds shelf stack unfocused goals =
  (** Printing functions for the extra informations. *)
  let rec print_stack a = function
    | [] -> Pp.int a
    | b::l -> Pp.int a ++ str"-" ++ print_stack b l
  in
  let print_unfocused_nums l =
    match l with
    | [] -> None
    | a::l -> Some (str"unfocused: " ++ print_stack a l)
  in
  let print_shelf l =
    match l with
    | [] -> None
    | _ -> Some (str"shelved: " ++ Pp.int (List.length l))
  in
  let rec print_comma_separated_list a l =
    match l with
    | [] -> a
    | b::l -> print_comma_separated_list (a++str", "++b) l
  in
  let print_extra_list l =
    match l with
    | [] -> Pp.mt ()
    | a::l -> Pp.spc () ++ str"(" ++ print_comma_separated_list a l ++ str")"
  in
  let extra = Option.List.flatten [ print_unfocused_nums stack ; print_shelf shelf ] in
  let print_extra = print_extra_list extra in
  let focused_if_needed =
    let needed = not (CList.is_empty extra) && pr_first in
    if needed then str" focused "
    else str" " (* non-breakable space *)
  in
  (** Main function *)
  let rec pr_rec n = function
    | [] -> (mt ())
    | g::rest ->
        let pc = pr_concl n sigma g in
        let prest = pr_rec (n+1) rest in
        (cut () ++ pc ++ prest)
  in
  let print_multiple_goals g l =
    if pr_first then
      default_pr_goal { it = g ; sigma = sigma; }
      ++ (if l=[] then mt () else cut ())
      ++ pr_rec 2 l
    else 
      pr_rec 1 (g::l)
  in
  (* Side effect! This has to be made more robust *)
  let () =
    match close_cmd with
    | Some cmd -> Feedback.msg_info cmd
    | None -> ()
  in
  match goals with
  | [] ->
      begin
	let exl = Evd.undefined_map sigma in
	if Evar.Map.is_empty exl then
	  (str"No more subgoals." ++ print_dependent_evars None sigma seeds)
	else
	  let pei = pr_evars_int sigma 1 exl in
	  v 0 ((str "No more subgoals,"
                ++ str " but there are non-instantiated existential variables:"
	        ++ cut () ++ (hov 0 pei)
                ++ print_dependent_evars None sigma seeds
                ++ cut () ++ str "You can use Grab Existential Variables."))
      end
  | g1::rest ->
      let goals = print_multiple_goals g1 rest in
      let ngoals = List.length rest+1 in
      v 0 (
	int ngoals ++ focused_if_needed ++ str(String.plural ngoals "subgoal")
        ++ print_extra
        ++ str (if (should_gname()) then ", subgoal 1" else "")
        ++ (if should_tag() then pr_goal_tag g1 else str"")
        ++ pr_goal_name sigma g1 ++ cut () ++ goals
        ++ (if unfocused=[] then str ""
           else (cut() ++ cut() ++ str "*** Unfocused goals:" ++ cut()
                 ++ pr_rec (List.length rest + 2) unfocused))
	++ print_dependent_evars (Some g1) sigma seeds
      )

(**********************************************************************)
(* Abstraction layer                                                  *)


type printer_pr = {
 pr_subgoals            : ?pr_first:bool -> Pp.t option -> evar_map -> evar list -> Goal.goal list -> int list -> goal list -> goal list -> Pp.t;
 pr_subgoal             : int -> evar_map -> goal list -> Pp.t;
 pr_goal                : goal sigma -> Pp.t;
}

let default_printer_pr = {
 pr_subgoals = default_pr_subgoals;
 pr_subgoal  = default_pr_subgoal;
 pr_goal     = default_pr_goal;
}

let printer_pr = ref default_printer_pr

let set_printer_pr = (:=) printer_pr

let pr_subgoals ?pr_first x = !printer_pr.pr_subgoals ?pr_first x
let pr_subgoal  x = !printer_pr.pr_subgoal  x
let pr_goal     x = !printer_pr.pr_goal     x

(* End abstraction layer                                              *)
(**********************************************************************)

let pr_open_subgoals ?(proof=Proof_global.give_me_the_proof ()) () =
  (* spiwack: it shouldn't be the job of the printer to look up stuff
     in the [evar_map], I did stuff that way because it was more
     straightforward, but seriously, [Proof.proof] should return
     [evar_info]-s instead. *)
  let p = proof in
  let (goals , stack , shelf, given_up, sigma ) = Proof.proof p in
  let stack = List.map (fun (l,r) -> List.length l + List.length r) stack in
  let seeds = Proof.V82.top_evars p in
  begin match goals with
  | [] -> let { Evd.it = bgoals ; sigma = bsigma } = Proof.V82.background_subgoals p in
          begin match bgoals,shelf,given_up with
	  | [] , [] , [] -> pr_subgoals None sigma seeds shelf stack [] goals
          | [] , [] , _ ->
	     Feedback.msg_info (str "No more subgoals, but there are some goals you gave up:");
	     fnl ()
            ++ pr_subgoals ~pr_first:false None bsigma seeds [] [] [] given_up
            ++ fnl () ++ str "You need to go back and solve them."
          | [] , _ , _ ->
	    Feedback.msg_info (str "All the remaining goals are on the shelf.");
	    fnl ()
            ++ pr_subgoals ~pr_first:false None bsigma seeds [] [] [] shelf
	  | _ , _, _ ->
            let end_cmd =
              str "This subproof is complete, but there are some unfocused goals." ++
              (let s = Proof_bullet.suggest p in
               if Pp.ismt s then s else fnl () ++ s) ++
              fnl ()
            in
	    pr_subgoals ~pr_first:false (Some end_cmd) bsigma seeds shelf [] [] bgoals
	  end
  | _ -> 
     let { Evd.it = bgoals ; sigma = bsigma } = Proof.V82.background_subgoals p in
     let bgoals_focused, bgoals_unfocused = List.partition (fun x -> List.mem x goals) bgoals in
     let unfocused_if_needed = if should_unfoc() then bgoals_unfocused else [] in
     pr_subgoals ~pr_first:true None bsigma seeds shelf [] unfocused_if_needed bgoals_focused
  end

let pr_nth_open_subgoal n =
  let pf = Proof_global.give_me_the_proof () in
  let { it=gls ; sigma=sigma } = Proof.V82.subgoals pf in
  pr_subgoal n sigma gls

let pr_goal_by_id id =
  let p = Proof_global.give_me_the_proof () in
  try
    Proof.in_proof p (fun sigma ->
      let g = Evd.evar_key id sigma in
      pr_selected_subgoal (pr_id id) sigma g)
  with Not_found -> user_err Pp.(str "No such goal.")

let pr_goal_by_uid uid =
  let p = Proof_global.give_me_the_proof () in
  let g = Goal.get_by_uid uid in
  let pr gs =
    v 0 (str "goal / evar " ++ str uid ++ str " is:" ++ cut ()
	 ++ pr_goal gs)
  in
  try
    Proof.in_proof p (fun sigma -> pr {it=g;sigma=sigma;})
  with Not_found -> user_err Pp.(str "Invalid goal identifier.")

(* Elementary tactics *)

let pr_prim_rule = function
  | Refine c ->
      (** FIXME *)
      str(if Termops.occur_meta Evd.empty (EConstr.of_constr c) then "refine " else "exact ") ++
      Constrextern.with_meta_as_hole pr_constr c

(* Backwards compatibility *)

let prterm = pr_lconstr


(* Printer function for sets of Assumptions.assumptions.
   It is used primarily by the Print Assumptions command. *)

type axiom =
  | Constant of constant (* An axiom or a constant. *)
  | Positive of MutInd.t (* A mutually inductive definition which has been assumed positive. *)
  | Guarded of constant (* a constant whose (co)fixpoints have been assumed to be guarded *)

type context_object =
  | Variable of Id.t (* A section variable or a Let definition *)
  | Axiom of axiom * (Label.t * Context.Rel.t * types) list
  | Opaque of constant     (* An opaque constant. *)
  | Transparent of constant

(* Defines a set of [assumption] *)
module OrderedContextObject =
struct
  type t = context_object

  let compare_axiom x y =
    match x,y with
    | Constant k1 , Constant k2 ->
        con_ord k1 k2
    | Positive m1 , Positive m2 ->
        MutInd.CanOrd.compare m1 m2
    | Guarded k1 , Guarded k2 ->
        con_ord k1 k2
    | _ , Constant _ -> 1
    | _ , Positive _ -> 1
    | _ -> -1

  let compare x y =
    match x , y with
    | Variable i1 , Variable i2 -> Id.compare i1 i2
    | Variable _ , _ -> -1
    | _ , Variable _ -> 1
    | Axiom (k1,_) , Axiom (k2, _) -> compare_axiom k1 k2
    | Axiom _ , _ -> -1
    | _ , Axiom _ -> 1
    | Opaque k1 , Opaque k2 -> con_ord k1 k2
    | Opaque _ , _ -> -1
    | _ , Opaque _ -> 1
    | Transparent k1 , Transparent k2 -> con_ord k1 k2
end

module ContextObjectSet = Set.Make (OrderedContextObject)
module ContextObjectMap = Map.Make (OrderedContextObject)

let pr_assumptionset env s =
  if ContextObjectMap.is_empty s &&
       engagement env = PredicativeSet then
    str "Closed under the global context"
  else
    let safe_pr_constant env kn =
      try pr_constant env kn
      with Not_found ->
	let mp,_,lab = repr_con kn in
        str (string_of_mp mp) ++ str "." ++ pr_label lab
    in
    let safe_pr_ltype typ =
      try str " : " ++ pr_ltype typ
      with e when CErrors.noncritical e -> mt ()
    in
    let safe_pr_ltype_relctx (rctx, typ) =
      let sigma, env = get_current_context () in
      let env = Environ.push_rel_context rctx env in
      try str " " ++ pr_ltype_env env sigma typ
      with e when CErrors.noncritical e -> mt ()
    in
    let pr_axiom env ax typ =
      match ax with
      | Constant kn ->
          safe_pr_constant env kn ++ safe_pr_ltype typ
      | Positive m ->
          hov 2 (MutInd.print m ++ spc () ++ strbrk"is positive.")
      | Guarded kn ->
          hov 2 (safe_pr_constant env kn ++ spc () ++ strbrk"is positive.")
    in
    let fold t typ accu =
      let (v, a, o, tr) = accu in
      match t with
      | Variable id ->
        let var = pr_id id ++ str " : " ++ pr_ltype typ in
        (var :: v, a, o, tr)
      | Axiom (axiom, []) ->
        let ax = pr_axiom env axiom typ in
        (v, ax :: a, o, tr)
      | Axiom (axiom,l) ->
        let ax = pr_axiom env axiom typ ++
          cut() ++
          prlist_with_sep cut (fun (lbl, ctx, ty) ->
            str " used in " ++ pr_label lbl ++
            str " to prove:" ++ safe_pr_ltype_relctx (ctx,ty))
          l in
        (v, ax :: a, o, tr)
      | Opaque kn ->
        let opq = safe_pr_constant env kn ++ safe_pr_ltype typ in
        (v, a, opq :: o, tr)
      | Transparent kn ->
        let tran = safe_pr_constant env kn ++ safe_pr_ltype typ in
        (v, a, o, tran :: tr)
    in
    let (vars, axioms, opaque, trans) = 
      ContextObjectMap.fold fold s ([], [], [], [])
    in
    let theory =
      if is_impredicative_set env then
	[str "Set is impredicative"]
      else []
    in
    let theory =
      if type_in_type env then
	str "Type hierarchy is collapsed (logic is inconsistent)" :: theory
      else theory
    in
    let opt_list title = function
    | [] -> None
    | l ->
      let section =
        title ++ fnl () ++
        v 0 (prlist_with_sep fnl (fun s -> s) l) in
      Some section
    in
    let assums = [
      opt_list (str "Transparent constants:") trans;
      opt_list (str "Section Variables:") vars;
      opt_list (str "Axioms:") axioms;
      opt_list (str "Opaque constants:") opaque;
      opt_list (str "Theory:") theory;
    ] in
    prlist_with_sep fnl (fun x -> x) (Option.List.flatten assums)

let xor a b = 
  (a && not b) || (not a && b)

let pr_cumulative poly cum =
  if poly then
    if cum then str "Cumulative " else str "NonCumulative "
  else mt ()

let pr_polymorphic b = 
  let print = xor (Flags.is_universe_polymorphism ()) b in
  if print then
    if b then str"Polymorphic " else str"Monomorphic "
  else mt ()

let pr_universe_instance evd ctx =
  let inst = Univ.UContext.instance ctx in
    str"@{" ++ Univ.Instance.pr (Termops.pr_evd_level evd) inst ++ str"}"