Debian Codegraph @

vernac/prettyp.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 (* Collective work; includes changes by (and thus parts copyright ©)
12 by Lionel Elie Mamane <[email protected]> on May-June 2006 for
13 implementation of abstraction of pretty-printing of objects. *)
14
15 open Pp
16 open CErrors
17 open Util
18 open CAst
19 open Names
20 open Termops
21 open Declarations
22 open Environ
23 open Impargs
24 open Libobject
25 open Libnames
26 open Globnames
27 open Printer
28 open Context.Rel.Declaration
29
30 module RelDecl = Context.Rel.Declaration
31 module NamedDecl = Context.Named.Declaration
32
33 let print_module mp = Printmod.print_module ~with_body:true mp
34 let print_modtype = Printmod.print_modtype
35
36 (**************)
37 (** Utilities *)
38
39 let print_closed_sections = ref false
40
41 let pr_infos_list l = v 0 (prlist_with_sep cut (fun x -> x) l)
42
43 let with_line_skip l = if List.is_empty l then mt() else fnl() ++ fnl () ++ pr_infos_list l
44
45 let blankline = mt() (* add a blank sentence in the list of infos *)
46
47 let add_colon prefix = if ismt prefix then mt () else prefix ++ str ": "
48
49 let int_or_no n = if Int.equal n 0 then str "no" else int n
50
51 (*******************)
52 (** Basic printing *)
53
54 let print_basename cst = pr_global (GlobRef.ConstRef cst)
55
56 let print_ref env reduce ref udecl =
57 let typ, univs = Typeops.type_of_global_in_context env ref in
58 let inst = UVars.make_abstract_instance univs in
59 let udecl = Option.map (fun x -> ref, x) udecl in
60 let bl = Printer.universe_binders_with_opt_names (Environ.universes_of_global env ref) udecl in
61 let sigma = Evd.from_ctx (UState.of_names bl) in
62 let typ =
63 if reduce then
64 let ctx,ccl = Reductionops.whd_decompose_prod_decls env sigma (EConstr.of_constr typ)
65 in EConstr.to_constr sigma (EConstr.it_mkProd_or_LetIn ccl ctx)
66 else typ in
67 let typ = Arguments_renaming.rename_type env typ ref in
68 let impargs = select_stronger_impargs (implicits_of_global ref) in
69 let impargs = List.map binding_kind_of_status impargs in
70 let variance = let open GlobRef in match ref with
71 | VarRef _ | ConstRef _ -> None
72 | IndRef (ind,_) | ConstructRef ((ind,_),_) ->
73 let mind = Environ.lookup_mind ind env in
74 mind.Declarations.mind_variance
75 in
76 let inst =
77 if Environ.is_polymorphic env ref
78 then Printer.pr_universe_instance_binder sigma inst Univ.UnivConstraints.empty
79 else mt ()
80 in
81 let priv = None in (* We deliberately don't print private univs in About. *)
82 hov 0 (pr_global ref ++ inst ++ str " :" ++ spc () ++ pr_ltype_env env sigma ~impargs typ ++
83 Printer.pr_abstract_universe_ctx sigma ?variance univs ?priv)
84
85 (** Command [Print Implicit], somehow subsumed by [About] *)
86
87 let pr_impl_name imp = Id.print (name_of_implicit imp)
88
89 let print_impargs_by_name max = function
90 | [] -> []
91 | impls ->
92 let n = List.length impls in
93 [hov 0 (str (String.plural n "Argument") ++ spc() ++
94 prlist_with_sep pr_comma pr_impl_name impls ++ spc() ++
95 str (String.conjugate_verb_to_be n) ++ str" implicit" ++
96 (if max then strbrk " and maximally inserted" else mt()))]
97
98 let print_one_impargs_list l =
99 let imps = List.filter is_status_implicit l in
100 let maximps = List.filter Impargs.maximal_insertion_of imps in
101 let nonmaximps = List.subtract (=) imps maximps in (* FIXME *)
102 print_impargs_by_name false nonmaximps @
103 print_impargs_by_name true maximps
104
105 let print_impargs_list prefix l =
106 let l = extract_impargs_data l in
107 List.flatten (List.map (fun (cond,imps) ->
108 match cond with
109 | None ->
110 List.map (fun pp -> add_colon prefix ++ pp)
111 (print_one_impargs_list imps)
112 | Some (n1,n2) ->
113 [v 2 (prlist_with_sep cut (fun x -> x)
114 [(if ismt prefix then str "When" else prefix ++ str ", when") ++
115 str " applied to " ++
116 (if Int.equal n1 n2 then int_or_no n2 else
117 if Int.equal n1 0 then str "no more than " ++ int n2
118 else int n1 ++ str " to " ++ int_or_no n2) ++
119 str (String.plural n2 " argument") ++ str ":";
120 v 0 (prlist_with_sep cut (fun x -> x)
121 (if List.exists is_status_implicit imps
122 then print_one_impargs_list imps
123 else [str "No implicit arguments"]))])]) l)
124
125 let need_expansion env impl ref =
126 let typ, _ = Typeops.type_of_global_in_context env ref in
127 let ctx = Term.prod_decls typ in
128 let nprods = List.count is_local_assum ctx in
129 not (List.is_empty impl) && List.length impl >= nprods &&
130 let _,lastimpl = List.chop nprods impl in
131 List.exists is_status_implicit lastimpl
132
133 let print_impargs env ref =
134 let impl = implicits_of_global ref in
135 let has_impl = not (List.is_empty impl) in
136 (* Need to reduce since implicits are computed with products flattened *)
137 pr_infos_list
138 ([ print_ref env (need_expansion env (select_impargs_size 0 impl) ref) ref None;
139 blankline ] @
140 (if has_impl then print_impargs_list (mt()) impl
141 else [str "No implicit arguments"]))
142
143 (** Printing reduction behavior *)
144
145 let print_reduction_behaviour = function
146 | GlobRef.ConstRef ref -> let p = Reductionops.ReductionBehaviour.print ref in if Pp.ismt p then [] else [p]
147 | _ -> []
148
149 (** Printing opacity status *)
150
151 type opacity =
152 | FullyOpaque
153 | TransparentMaybeOpacified of Conv_oracle.level
154
155 let opacity env =
156 function
157 | GlobRef.VarRef v when NamedDecl.is_local_def (Environ.lookup_named v env) ->
158 Some(TransparentMaybeOpacified
159 (Conv_oracle.get_strategy (Environ.oracle env) (Conv_oracle.EvalVarRef v)))
160 | GlobRef.ConstRef cst ->
161 let cb = Environ.lookup_constant cst env in
162 (match cb.const_body with
163 | Undef _ | Primitive _ | Symbol _ -> None
164 | OpaqueDef _ -> Some FullyOpaque
165 | Def _ -> Some
166 (TransparentMaybeOpacified
167 (Conv_oracle.get_strategy (Environ.oracle env) (Conv_oracle.EvalConstRef cst))))
168 | _ -> None
169
170 let print_opacity env ref =
171 match opacity env ref with
172 | None -> []
173 | Some s ->
174 [pr_global ref ++ str " is " ++
175 match s with
176 | FullyOpaque -> str "opaque"
177 | TransparentMaybeOpacified Conv_oracle.Opaque ->
178 str "opaque but may be made transparent"
179 | TransparentMaybeOpacified lev when Conv_oracle.is_transparent lev ->
180 str "transparent"
181 | TransparentMaybeOpacified (Conv_oracle.Level n) ->
182 str "transparent (level " ++ int n ++ str ")"
183 | TransparentMaybeOpacified Conv_oracle.Expand ->
184 str "transparent (expand)"]
185
186 (** Printing coercion status *)
187
188 let print_if_is_coercion ref =
189 if Coercionops.coercion_exists ref then
190 let i = Coercionops.coercion_info ref in
191 let r = if i.Coercionops.coe_reversible then " reversible" else "" in
192 [pr_global ref ++ str " is a" ++ str r ++ str " coercion"]
193 else []
194
195 (** Printing polymorphic status *)
196
197 (* XXX TODO print based on the actual binders not from the monomorphic data *)
198 let template_poly_variables env ind =
199 let mib, mip = Inductive.lookup_mind_specif env ind in
200 match mib.mind_template with
201 | None -> assert false
202 | Some { template_defaults; template_concl } ->
203 let pseudo_poly = match template_concl with
204 | QSort (q, _) when Option.has_some (Sorts.QVar.var_index q) -> true
205 | _ -> false
206 in
207 let _, vars = UVars.Instance.levels template_defaults in
208 Univ.Level.Set.elements vars, pseudo_poly
209
210 let get_template_poly_variables env = function
211 | GlobRef.IndRef ind | ConstructRef (ind,_) -> template_poly_variables env ind
212 | VarRef _ | ConstRef _ -> assert false
213
214 let pr_template_variables env ref =
215 let vars, pseudo_sort_poly = get_template_poly_variables env ref in
216 str " on " ++ prlist_with_sep spc UnivNames.pr_level_with_global_universes vars
217 ++ spc() ++
218 (if pseudo_sort_poly
219 then str "(can be instantiated to Prop)"
220 else str "(cannot be instantiated to Prop)")
221
222 let print_polymorphism env ref =
223 let poly = Environ.is_polymorphic env ref in
224 let template_poly = Environ.is_template_polymorphic env ref in
225 [ pr_global ref ++ str " is " ++
226 (if poly then str "universe polymorphic"
227 else if template_poly then
228 str "template universe polymorphic"
229 ++ if !PrintingFlags.print_universes then h (pr_template_variables env ref) else mt()
230 else str "not universe polymorphic") ]
231
232 let print_squash env ref udecl = match ref with
233 | GlobRef.IndRef ind ->
234 let _, mip = Inductive.lookup_mind_specif env ind in
235 begin match mip.mind_squashed with
236 | None -> []
237 | Some squash ->
238 let univs = Environ.universes_of_global env ref in
239 let udecl = Option.map (fun x -> ref, x) udecl in
240 let bl = Printer.universe_binders_with_opt_names univs udecl in
241 let sigma = Evd.from_ctx (UState.of_names bl) in
242 let inst = if fst @@ UVars.AbstractContext.size univs = 0 then mt()
243 else Printer.pr_universe_instance sigma (UVars.make_abstract_instance univs)
244 in
245 let inds = mip.mind_sort in
246 let target = match inds with
247 | SProp -> str "SProp"
248 | Prop -> str "SProp or Prop"
249 | Set -> str "SProp, Prop or Set"
250 | Type _ -> str "not in a variable sort quality"
251 | QSort (q,_) -> str "in sort quality " ++ Termops.pr_evd_qvar sigma q
252 in
253 let unless = match squash with
254 | AlwaysSquashed -> str "."
255 | SometimesSquashed qs ->
256 let target = match inds with
257 | SProp | Prop | Set -> target
258 | Type _ -> str "instantiated to constant qualities"
259 | QSort (q,_) ->
260 let ppq = Termops.pr_evd_qvar sigma q in
261 str "equal to the instantiation of " ++ ppq ++ pr_comma() ++
262 str "or to qualities smaller" ++ spc() ++
263 str "(SProp <= Prop <= Type, and all variables <= Type)" ++ spc() ++
264 str "than the instantiation of " ++ ppq
265 in
266 let qs = Sorts.Quality.Set.elements qs in
267 let quality_s, is_s = match qs with
268 | [_] -> "quality", "is"
269 | _ -> "qualities", "are"
270 in
271 (* this reads kinda weird when qs is singleton of a constant quality, we get eg
272 "quality Prop is equal to the instantiation of q" *)
273 pr_comma () ++
274 hov 0 (str "unless instantiated such that the " ++ str quality_s ++ str " " ++
275 pr_enum (Sorts.Quality.pr (Termops.pr_evd_qvar sigma)) qs ++
276 spc() ++ str is_s ++ str " " ++ target ++ str ".")
277 in
278 [hv 2 (hov 1 (pr_global ref ++ inst) ++ str " may only be eliminated to produce values whose type is " ++
279 target ++ unless)]
280 end
281 | _ -> []
282
283 let print_prop_but_default_dep_elim ref =
284 match ref with
285 | GlobRef.IndRef ind ->
286 if Elimschemes.is_prop_but_default_dependent_elim ind
287 then [pr_global ref ++ str " is in Prop but its eliminators are declared dependent by default"]
288 else []
289 | _ -> []
290
291 (** Print projection status *)
292
293 let print_projection env ref =
294 match ref with
295 | GlobRef.ConstRef cst ->
296 begin
297 match Structures.PrimitiveProjections.find_opt cst with
298 | Some p -> [pr_global ref ++ str " is a primitive projection of " ++ pr_global (IndRef (Projection.Repr.inductive p))]
299 | None ->
300 try
301 let ind = (Structures.Structure.find_from_projection env cst).name in
302 [pr_global ref ++ str " is a projection of " ++ pr_global (IndRef ind)]
303 with Not_found -> []
304 end
305 | _ -> []
306
307 (** Printing type-in-type status *)
308
309 let print_type_in_type env ref =
310 let unsafe = Environ.is_type_in_type env ref in
311 if unsafe then
312 [ pr_global ref ++ str " relies on an unsafe universe hierarchy"]
313 else []
314
315 (** Printing primitive projection status *)
316
317 let print_primitive_record recflag mipv =
318 let mipv = Array.to_list mipv in
319 mipv |> List.concat_map @@ fun mip -> match mip.mind_record with
320 | PrimRecord { has_eta; _ } ->
321 let eta = match recflag with
322 | CoFinite | Finite -> str " without eta conversion"
323 | BiFinite -> match has_eta with
324 | NoEta -> str " without eta conversion"
325 | AlwaysEta -> str " with eta conversion"
326 in
327 [Id.print mip.mind_typename ++ str" has primitive projections" ++ eta ++ str"."]
328 | FakeRecord | NotRecord -> []
329
330 let print_primitive env ref =
331 match ref with
332 | GlobRef.IndRef ind ->
333 let mib = Environ.lookup_mind (fst ind) env in
334 print_primitive_record mib.mind_finite mib.mind_packets
335 | _ -> []
336
337 (** Printing arguments status (scopes, implicit, names) *)
338
339 let needs_extra_scopes env ref scopes =
340 let open Constr in
341 let rec aux env t = function
342 | [] -> false
343 | _::scopes -> match kind (Reduction.whd_all env t) with
344 | Prod (na,dom,codom) -> aux (push_rel (RelDecl.LocalAssum (na,dom)) env) codom scopes
345 | _ -> true
346 in
347 let ty, _ctx = Typeops.type_of_global_in_context env ref in
348 aux env ty scopes
349
350 let implicit_kind_of_status = function
351 | None -> Anonymous, Glob_term.Explicit
352 | Some imp -> pi1 imp.impl_pos, if imp.impl_max then Glob_term.MaxImplicit else Glob_term.NonMaxImplicit
353
354 let extra_implicit_kind_of_status imp =
355 let _,imp = implicit_kind_of_status imp in
356 (Anonymous, imp)
357
358 let dummy = {
359 Vernacexpr.implicit_status = Glob_term.Explicit;
360 name = Anonymous;
361 recarg_like = false;
362 notation_scope = [];
363 }
364
365 let is_dummy = function
366 | Vernacexpr.(RealArg {implicit_status; name; recarg_like; notation_scope}) ->
367 name = Anonymous && not recarg_like && notation_scope = [] && implicit_status = Glob_term.Explicit
368 | _ -> false
369
370 let rec main_implicits i renames recargs scopes impls =
371 if renames = [] && recargs = [] && scopes = [] && impls = [] then []
372 else
373 let recarg_like, recargs = match recargs with
374 | j :: recargs when i = j -> true, recargs
375 | _ -> false, recargs
376 in
377 let (name, implicit_status) =
378 match renames, impls with
379 | _, (Some _ as i) :: _ -> implicit_kind_of_status i
380 | name::_, _ -> (name,Glob_term.Explicit)
381 | [], (None::_ | []) -> (Anonymous, Glob_term.Explicit)
382 in
383 let notation_scope = match scopes with
384 | scope :: _ -> List.map (fun s -> CAst.make (Constrexpr.DelimOnlyTmpScope, s)) scope
385 | [] -> []
386 in
387 let status = {Vernacexpr.implicit_status; name; recarg_like; notation_scope} in
388 let tl = function [] -> [] | _::tl -> tl in
389 (* recargs is special -> tl handled above *)
390 let rest = main_implicits (i+1) (tl renames) recargs (tl scopes) (tl impls) in
391 status :: rest
392
393 let rec insert_fake_args volatile bidi impls =
394 let open Vernacexpr in
395 match volatile, bidi with
396 | Some 0, _ -> VolatileArg :: insert_fake_args None bidi impls
397 | _, Some 0 -> BidiArg :: insert_fake_args volatile None impls
398 | None, None -> List.map (fun a -> RealArg a) impls
399 | _, _ ->
400 let hd, tl = match impls with
401 | impl :: impls -> impl, impls
402 | [] -> dummy, []
403 in
404 let f = Option.map pred in
405 RealArg hd :: insert_fake_args (f volatile) (f bidi) tl
406
407 let print_arguments env ref =
408 let qid = Nametab.shortest_qualid_of_global Id.Set.empty ref in
409 let flags, recargs, nargs_for_red =
410 match ref with
411 | ConstRef ref ->
412 begin match Reductionops.ReductionBehaviour.get ref with
413 | None -> [], [], None
414 | Some NeverUnfold -> [`SimplNeverUnfold], [], None
415 | Some (UnfoldWhen { nargs; recargs }) -> [], recargs, nargs
416 | Some (UnfoldWhenNoMatch { nargs; recargs }) -> [`SimplDontExposeCase], recargs, nargs
417 end
418 | _ -> [], [], None
419 in
420 let names, not_renamed =
421 try Arguments_renaming.arguments_names env ref, false
422 with Not_found ->
423 let ty, _ = Typeops.type_of_global_in_context env ref in
424 List.map pi1 (Impargs.compute_implicits_names env (Evd.from_env env) (EConstr.of_constr ty)), true in
425 let scopes = Notation.find_arguments_scope env ref in
426 let flags = if needs_extra_scopes env ref scopes then `ExtraScopes::flags else flags in
427 let impls = Impargs.extract_impargs_data (Impargs.implicits_of_global ref) in
428 let impls, moreimpls = match impls with
429 | (_, impls) :: rest -> impls, rest
430 | [] -> assert false
431 in
432 let impls = main_implicits 0 names recargs scopes impls in
433 let moreimpls = List.map (fun (_,i) -> List.map extra_implicit_kind_of_status i) moreimpls in
434 let bidi = Pretyping.get_bidirectionality_hint env ref in
435 let impls = insert_fake_args nargs_for_red bidi impls in
436 if List.for_all is_dummy impls && moreimpls = [] && flags = [] then []
437 else
438 let open Constrexpr in
439 let open Vernacexpr in
440 [Ppvernac.pr_vernac_expr
441 (VernacSynPure (VernacArguments (CAst.make (AN qid), impls, moreimpls, flags))) ++
442 (if not_renamed then mt () else
443 fnl () ++ str " (where some original arguments have been renamed)")]
444
445 (** Printing dependencies in section variables *)
446
447 let print_section_deps env ref =
448 let hyps = let open GlobRef in match ref with
449 | VarRef _ -> None
450 | ConstRef c ->
451 let bd = Environ.lookup_constant c env in
452 Some bd.const_hyps
453 | IndRef (mind,_) | ConstructRef ((mind,_),_) ->
454 let mb = Environ.lookup_mind mind env in
455 Some mb.mind_hyps
456 in
457 let hyps = Option.map (List.filter NamedDecl.is_local_assum) hyps in
458 match hyps with
459 | None | Some [] -> []
460 | Some hyps ->
461 [hov 0 (pr_global ref ++ str (String.plural (List.length hyps) " uses section variable") ++ spc () ++
462 hv 1 (prlist_with_sep spc (fun d -> Id.print (NamedDecl.get_id d)) (List.rev hyps)) ++ str ".")]
463
464 (** Printing bidirectionality status *)
465
466 let print_bidi_hints env gr =
467 match Pretyping.get_bidirectionality_hint env gr with
468 | None -> []
469 | Some nargs ->
470 [str "Using typing information from context after typing the " ++ int nargs ++ str " first arguments"]
471
472 (** Printing basic information about references (common to Print and About) *)
473
474 let print_name_infos env ref =
475 let type_info_for_implicit =
476 if need_expansion env (select_impargs_size 0 (implicits_of_global ref)) ref then
477 (* Need to reduce since implicits are computed with products flattened *)
478 [str "Expanded type for implicit arguments";
479 print_ref env true ref None; blankline]
480 else
481 [] in
482 print_type_in_type env ref @
483 print_prop_but_default_dep_elim ref @
484 print_projection env ref @
485 print_primitive env ref @
486 type_info_for_implicit @
487 print_arguments env ref @
488 print_section_deps env ref @
489 print_if_is_coercion ref
490
491 (******************************************)
492 (**** Printing declarations and judgments *)
493 (**** Gallina layer *****)
494
495 let print_typed_value_in_env env sigma (trm,typ) =
496 (pr_leconstr_env ~inctx:true env sigma trm ++ fnl () ++
497 str " : " ++ pr_letype_env env sigma typ)
498
499 (* To be improved; the type should be used to provide the types in the
500 abstractions. This should be done recursively inside pr_lconstr, so that
501 the pretty-print of a proposition (P:(nat->nat)->Prop)(P [u]u)
502 synthesizes the type nat of the abstraction on u *)
503
504 let print_named_def env sigma ~impargs name body typ =
505 let pbody = pr_lconstr_env ~inctx:true env sigma body in
506 let ptyp = pr_ltype_env env sigma ~impargs typ in
507 let pbody = if Constr.isCast body then surround pbody else pbody in
508 (str "*** [" ++ str name ++ str " " ++
509 hov 0 (str ":=" ++ brk (1,2) ++ pbody ++ spc () ++
510 str ":" ++ brk (1,2) ++ ptyp) ++
511 str "]")
512
513 let print_named_assum env sigma ~impargs name typ =
514 str "*** [" ++ str name ++ str " : " ++ pr_ltype_env env sigma ~impargs typ ++ str "]"
515
516 let print_named_decl env sigma with_implicit id =
517 let open Context.Named.Declaration in
518 let impargs = if with_implicit then select_stronger_impargs (implicits_of_global (VarRef id)) else [] in
519 let impargs = List.map binding_kind_of_status impargs in
520 match lookup_named id env with
521 | LocalAssum (id, typ) ->
522 print_named_assum env sigma ~impargs (Id.to_string id.Context.binder_name) typ
523 | LocalDef (id, body, typ) ->
524 print_named_def env sigma ~impargs (Id.to_string id.Context.binder_name) body typ
525
526 let assumptions_for_print lna =
527 List.fold_right (fun na env -> add_name na env) lna empty_names_context
528
529 (*********************)
530 (* *)
531
532 let print_inductive_args env mind mib =
533 let flatmapi f v = List.flatten (Array.to_list (Array.mapi f v)) in
534 let mips =
535 (* We don't use the PrimRecord field as it misses the projections corresponding to local definition *)
536 try
537 Array.mapi (fun i mip ->
538 let projs = Option.List.flatten (Structures.Structure.find_projections env (mind,i)) in
539 (mip.mind_consnames, Array.of_list projs)) mib.mind_packets
540 with
541 Not_found (* find_projections *) ->
542 Array.map (fun mip -> (mip.mind_consnames,[||])) mib.mind_packets in
543 flatmapi
544 (fun i (constructs, projs) ->
545 print_arguments env (GlobRef.IndRef (mind,i)) @
546 flatmapi (fun j _ -> print_arguments env (GlobRef.ConstructRef ((mind,i),j+1))) constructs @
547 flatmapi (fun _ cst -> print_arguments env (GlobRef.ConstRef cst)) projs)
548 mips
549
550 let print_inductive env mind udecl =
551 let mib = Environ.lookup_mind mind env in
552 Printmod.pr_mutual_inductive_body env mind mib udecl
553
554 let print_inductive_with_infos env mind udecl =
555 let mib = Environ.lookup_mind mind env in
556 let mipv = mib.mind_packets in
557 Printmod.pr_mutual_inductive_body env mind mib udecl ++
558 with_line_skip
559 (print_primitive_record mib.mind_finite mipv @
560 print_inductive_args env mind mib)
561
562 let print_section_variable_with_infos env sigma id =
563 print_named_decl env sigma true id ++
564 with_line_skip (print_name_infos env (GlobRef.VarRef id))
565
566 let print_instance sigma cb =
567 if Declareops.constant_is_polymorphic cb then
568 let univs = Declareops.constant_polymorphic_context cb in
569 let inst = UVars.make_abstract_instance univs in
570 pr_universe_instance_binder sigma inst Univ.UnivConstraints.empty
571 else mt()
572
573 let print_constant env ~with_values with_implicit cst udecl =
574 let cb = Environ.lookup_constant cst env in
575 let typ = cb.const_type in
576 let univs = cb.const_universes in
577 let udecl = Option.map (fun x -> GlobRef.ConstRef cst, x) udecl in
578 let uctx =
579 UState.of_names
580 (Printer.universe_binders_with_opt_names (Declareops.constant_polymorphic_context cb) udecl)
581 in
582 let sigma = Evd.from_ctx uctx in
583 let impargs = if with_implicit then select_stronger_impargs (implicits_of_global (ConstRef cst)) else [] in
584 let impargs = List.map binding_kind_of_status impargs in
585 let pptyp = pr_ltype_env env sigma ~impargs typ in
586 let typonly = str " :" ++ spc() ++ pptyp in
587 let sep_body_typ = fnl() ++ str " : " in
588 let withbody c =
589 str " =" ++ spc() ++
590 pr_lconstr_env ~inctx:true env sigma c ++
591 sep_body_typ ++
592 pptyp
593 in
594 let is_axiom, ppdata, priv = match cb.const_body with
595 | Undef _ ->
596 let ex p = CPrimitives.PTE p in
597 let prims = CPrimitives.[ex PT_int63; ex PT_float64; ex PT_string; ex PT_array] in
598 let is_prim (CPrimitives.PTE p) =
599 let test = match p with
600 | PT_int63 -> Environ.is_int63_type
601 | PT_float64 -> Environ.is_float64_type
602 | PT_string -> Environ.is_string_type
603 | PT_array -> Environ.is_array_type
604 in
605 if test env cst then Some (CPrimitives.prim_type_to_string p)
606 else None
607 in
608 let prim = List.find_map is_prim prims in
609 let pp = match prim with
610 | None -> typonly
611 | Some prim -> str " =" ++ spc() ++ str "#" ++ str prim ++ sep_body_typ ++ pptyp
612 in
613 true, pp, None
614 | Symbol _ -> true, typonly, None
615 | Def c ->
616 let pp = if Option.has_some with_values then withbody c else typonly in
617 false, pp, None
618 | OpaqueDef o -> begin match with_values with
619 | None -> false, typonly, None
620 | Some access ->
621 let c, priv = Global.force_proof access o in
622 let priv = match priv with
623 | PrivateMonomorphic () -> None
624 | PrivatePolymorphic priv -> Some priv
625 in
626 false, withbody c, priv
627 end
628 | Primitive prim ->
629 let pp = str " =" ++ spc() ++ str "#" ++ str (CPrimitives.to_string prim) ++ sep_body_typ ++ pptyp in
630 (* do we want to print with is_axiom = false? *)
631 true, pp, None
632 in
633 let ppmain = print_basename cst ++ print_instance sigma cb ++ ppdata in
634 let ppmain = if is_axiom then str"*** [ " ++ ppmain ++ str" ]" else ppmain in
635 hov 0 (ppmain ++ Printer.pr_universes sigma univs ?priv)
636
637 let print_constant_with_infos env access cst udecl =
638 print_constant env ~with_values:(Some access) true cst udecl ++
639 with_line_skip (print_name_infos env (GlobRef.ConstRef cst))
640
641 let print_global_reference access env sigma gref udecl =
642 let open GlobRef in
643 match gref with
644 | ConstRef cst ->
645 (match Structures.PrimitiveProjections.find_opt cst with
646 | Some p -> print_inductive_with_infos env (fst (Projection.Repr.inductive p)) udecl
647 | None -> print_constant_with_infos env access cst udecl)
648 | IndRef (mind,_) -> print_inductive_with_infos env mind udecl
649 | ConstructRef ((mind,_),_) -> print_inductive_with_infos env mind udecl
650 | VarRef id -> print_section_variable_with_infos env sigma id
651
652 let glob_constr_of_abbreviation kn =
653 let (vars,a) = Abbreviation.find_interp kn in
654 (List.map fst vars, Notation_ops.glob_constr_of_notation_constr a)
655
656 let print_abbreviation_body env kn (vars,c) =
657 let qid = Nametab.shortest_qualid_of_abbreviation Id.Set.empty kn in
658 hov 2
659 (hov 4
660 (str "Notation " ++ pr_qualid qid ++
661 prlist (fun id -> spc () ++ Id.print id) vars ++
662 spc () ++ str ":=") ++
663 spc () ++
664 Vernacstate.System.protect (fun () ->
665 Abbreviation.toggle ~on:false ~use:ParsingAndPrinting kn;
666 pr_glob_constr_env env (Evd.from_env env) c) ())
667
668 let print_abbreviation access env sigma kn =
669 let (vars,c) = glob_constr_of_abbreviation kn in
670 let pp = match DAst.get c with
671 | GRef (gref,_udecl) -> (* TODO: don't drop universes? *) [print_global_reference access env sigma gref None]
672 | _ -> [] in
673 print_abbreviation_body env kn (vars,c) ++
674 with_line_skip pp
675
676 (** Unused outside? *)
677
678 let pr_prefix_name prefix = Id.print (basename prefix.obj_path)
679
680 let print_library_node = function
681 | Lib.OpenedSection (prefix, _) ->
682 str " >>>>>>> Section " ++ pr_prefix_name prefix
683 | Lib.OpenedModule (_,_,prefix,_) ->
684 str " >>>>>>> Module " ++ pr_prefix_name prefix
685 | Lib.CompilingLibrary { obj_path; _ } ->
686 str " >>>>>>> Library " ++ pr_path obj_path
687
688 (** Printing part of command [Check] *)
689
690 let print_judgment env sigma {uj_val=trm;uj_type=typ} =
691 print_typed_value_in_env env sigma (trm, typ)
692
693 let print_safe_judgment {Safe_typing.jdg_env=senv; jdg_val=trm; jdg_type=typ} =
694 let env = Safe_typing.env_of_safe_env senv in
695 let sigma = Evd.from_env env in
696 let trm = EConstr.of_constr trm in
697 let typ = EConstr.of_constr typ in
698 print_typed_value_in_env env sigma (trm, typ)
699
700 (** Command [Print All] *)
701
702 module DynHandle = Libobject.Dyn.Map(struct type 'a t = 'a -> Pp.t option end)
703
704 let handle h (Libobject.Dyn.Dyn (tag, o)) = match DynHandle.find tag h with
705 | f -> f o
706 | exception Not_found -> None
707
708 (* TODO: this kind of feature should not rely on the Libobject stack. There is
709 no reason that an object in the stack corresponds to a user-facing
710 declaration. It may have been so at the time this was written, but this
711 needs to be done in a more principled way. *)
712 let print_library_leaf env sigma ~with_values mp lobj =
713 match lobj with
714 | AtomicObject o ->
715 let handler =
716 DynHandle.add Declare.Internal.objVariable begin fun id ->
717 (* Outside sections, VARIABLES still exist but only with universes
718 constraints *)
719 (try Some(print_named_decl env sigma false id) with Not_found -> None)
720 end @@
721 DynHandle.add Declare.Internal.Constant.tag begin fun (id,_) ->
722 let kn = Constant.make2 mp id in
723 Some (print_constant env ~with_values false kn None)
724 end @@
725 DynHandle.add DeclareInd.Internal.objInductive begin fun (id,_) ->
726 let kn = MutInd.make2 mp id in
727 Some (print_inductive env kn None)
728 end @@
729 DynHandle.empty
730 in
731 handle handler o
732 | ModuleObject (id,_) ->
733 Some (Printmod.print_module ~with_body:(Option.has_some with_values) (MPdot (mp, id)))
734 | ModuleTypeObject (id,_) ->
735 Some (print_modtype (MPdot (mp, id)))
736 | IncludeObject _ | KeepObject _ | EscapeObject _ | ExportObject _ -> None
737
738 let decr = Option.map ((+) (-1))
739
740 let is_done = Option.equal Int.equal (Some 0)
741
742 let print_leaves env sigma ~with_values mp n leaves =
743 let rec prec n = function
744 | [] -> n, []
745 | o :: rest ->
746 if is_done n then n, []
747 else begin match print_library_leaf env sigma ~with_values mp o with
748 | Some pp ->
749 let n, prest = prec (decr n) rest in
750 n, pp :: prest
751 | None -> prec n rest
752 end
753 in
754 let n, l = prec n leaves in
755 n, v 0 (pr_sequence (fun x -> x) (List.rev l))
756
757 let print_context env sigma ~with_values =
758 let rec prec n = function
759 | [] -> mt()
760 | (node, leaves) :: rest ->
761 if is_done n then mt()
762 else
763 let mp = (Lib.node_prefix node).obj_mp in
764 let n, pleaves = print_leaves env sigma ~with_values mp n leaves in
765 if is_done n then pleaves
766 else prec n rest ++ pleaves
767 in
768 prec
769
770 let print_full_context access env sigma =
771 print_context env sigma ~with_values:(Some access) None (Lib.contents ())
772 let print_full_context_typ env sigma = (* Command [Print All] *)
773 print_context env sigma ~with_values:None None (Lib.contents ())
774
775 (** Command line [-output-context] *)
776
777 module DynHandleF = Libobject.Dyn.Map(struct type 'a t = 'a -> Pp.t end)
778
779 let handleF h (Libobject.Dyn.Dyn (tag, o)) = match DynHandleF.find tag h with
780 | f -> f o
781 | exception Not_found -> mt ()
782
783 (* TODO: see the comment for {!print_leaf_entry} *)
784 let print_full_pure_atomic access env sigma mp lobj =
785 let handler =
786 DynHandleF.add Declare.Internal.Constant.tag begin fun (id,_) ->
787 let kn = KerName.make mp id in
788 let con = Global.constant_of_delta_kn kn in
789 let cb = Global.lookup_constant con in
790 let typ = cb.const_type in
791 hov 0 (
792 match cb.const_body with
793 | Undef _ ->
794 str "Parameter " ++
795 print_basename con ++ str " :" ++ spc () ++ pr_ltype_env env sigma typ
796 | OpaqueDef lc ->
797 str "Theorem " ++ print_basename con ++ cut () ++
798 str " : " ++ pr_ltype_env env sigma typ ++ str "." ++ fnl () ++
799 str "Proof " ++ pr_lconstr_env env sigma
800 (fst (Global.force_proof access lc))
801 | Def c ->
802 str "Definition " ++ print_basename con ++ cut () ++
803 str " : " ++ pr_ltype_env env sigma typ ++ cut () ++ str " := " ++
804 pr_lconstr_env env sigma c
805 | Primitive _ ->
806 str "Primitive " ++
807 print_basename con ++ str " :" ++ spc () ++ pr_ltype_env env sigma typ
808 | Symbol _ ->
809 str "Symbol " ++
810 print_basename con ++ str " :" ++ spc () ++ pr_ltype_env env sigma typ)
811 ++ str "." ++ fnl () ++ fnl ()
812 end @@
813 DynHandleF.add DeclareInd.Internal.objInductive begin fun (id,_) ->
814 let kn = KerName.make mp id in
815 let mind = Global.mind_of_delta_kn kn in
816 let mib = Global.lookup_mind mind in
817 Printmod.pr_mutual_inductive_body (Global.env()) mind mib None ++
818 fnl () ++ fnl ()
819 end @@
820 DynHandleF.empty
821 in
822 handleF handler lobj
823
824 let print_full_pure_leaf access env sigma mp = function
825 | AtomicObject lobj -> print_full_pure_atomic access env sigma mp lobj
826 | ModuleObject (id, _) ->
827 (* TODO: make it reparsable *)
828 print_module (MPdot (mp, id)) ++ str "." ++ fnl () ++ fnl ()
829 | ModuleTypeObject (id, _) ->
830 (* TODO: make it reparsable *)
831 print_modtype (MPdot (mp, id)) ++ str "." ++ fnl () ++ fnl ()
832 | _ -> mt()
833
834 let print_full_pure_context access env sigma =
835 let rec prec = function
836 | (node,leaves)::rest ->
837 let mp = (Lib.node_prefix node).obj_mp in
838 let pp = Pp.prlist (print_full_pure_leaf access env sigma mp) leaves in
839 prec rest ++ pp
840 | [] -> mt ()
841 in
842 prec (Lib.contents ())
843
844 (** Command [Print Section] *)
845
846 (* For printing an inductive definition with
847 its constructors and elimination,
848 assume that the declaration of constructors and eliminations
849 follows the definition of the inductive type *)
850
851 (* This is designed to print the contents of an opened section *)
852 let read_sec_context qid =
853 let dir =
854 try Nametab.locate_section qid
855 with Not_found ->
856 user_err ?loc:qid.loc (str "Unknown section.") in
857 let rec get_cxt in_cxt = function
858 | (Lib.OpenedSection ({obj_path;_},_), _ as hd)::rest ->
859 if eq_full_path dir obj_path then (hd::in_cxt) else get_cxt (hd::in_cxt) rest
860 | [] -> []
861 | hd::rest -> get_cxt (hd::in_cxt) rest
862 in
863 let cxt = Lib.contents () in
864 List.rev (get_cxt [] cxt)
865
866 let print_sec_context access env sigma sec =
867 print_context env sigma ~with_values:(Some access) None (read_sec_context sec)
868
869 let print_sec_context_typ env sigma sec =
870 print_context env sigma ~with_values:None None (read_sec_context sec)
871
872 (** Command [Print] *)
873
874 type 'a locatable_info = {
875 locate : qualid -> 'a option;
876 locate_all : qualid -> 'a list;
877 shortest_qualid : 'a -> qualid;
878 name : 'a -> Pp.t;
879 print : 'a -> Pp.t;
880 about : 'a -> Pp.t;
881 }
882
883 type logical_name =
884 | Term of GlobRef.t
885 | Dir of Nametab.GlobDirRef.t
886 | Abbreviation of abbreviation
887 | Module of ModPath.t
888 | ModuleType of ModPath.t
889 | Other : 'a * 'a locatable_info -> logical_name
890 | Undefined of qualid
891
892 type locatable = Locatable : 'a locatable_info -> locatable
893
894 (** Generic table for objects that are accessible through a name. *)
895 let locatable_map : locatable String.Map.t ref = ref String.Map.empty
896
897 let register_locatable name f =
898 locatable_map := String.Map.add name (Locatable f) !locatable_map
899
900 exception ObjFound of logical_name
901
902 let locate_any_name qid =
903 try Term (Nametab.locate qid)
904 with Not_found ->
905 try Abbreviation (Nametab.locate_abbreviation qid)
906 with Not_found ->
907 try Dir (Nametab.locate_dir qid)
908 with Not_found ->
909 try Module (Nametab.locate_module qid)
910 with Not_found ->
911 try ModuleType (Nametab.locate_modtype qid)
912 with Not_found ->
913 let iter _ (Locatable info) = match info.locate qid with
914 | None -> ()
915 | Some ans -> raise (ObjFound (Other (ans, info)))
916 in
917 try String.Map.iter iter !locatable_map; Undefined qid
918 with ObjFound obj -> obj
919
920 let canonical_info env ref =
921 let cref = QGlobRef.canonize env ref in
922 if GlobRef.UserOrd.equal ref cref then mt ()
923 else match Nametab.path_of_global cref with
924 | path -> spc() ++ str "(syntactically equal to" ++ spc() ++ pr_path path ++ str ")"
925 | exception Not_found -> spc() ++ str "(missing canonical, bug?)"
926
927 let pr_loc_use_dp loc = match loc.Loc.fname with
928 | Loc.ToplevelInput ->
929 (* NB emacs mangles the message if it contains the capitalized "Toplevel input" of [Loc.pr] *)
930 str "toplevel input, characters " ++ int loc.bp ++ str "-" ++ int loc.ep
931 | InFile { dirpath = None } -> Loc.pr loc
932 | InFile { dirpath = Some dp } ->
933 let f = str "library " ++ str dp in
934 (f ++
935 str", line " ++ int loc.line_nb ++ str", characters " ++
936 int (loc.bp-loc.bol_pos) ++ str"-" ++ int (loc.ep-loc.bol_pos))
937
938
939 let loc_info gr =
940 match Nametab.cci_src_loc gr with
941 | None -> mt()
942 | Some loc -> cut() ++ hov 0 (str "Declared in" ++ spc() ++ pr_loc_use_dp loc)
943
944 let pr_dir dir =
945 let s,mp =
946 let open Nametab in
947 let open GlobDirRef in match dir with
948 | DirOpenModule mp -> "Open Module", ModPath.print mp
949 | DirOpenModtype mp -> "Open Module Type", ModPath.print mp
950 | DirOpenSection dir -> "Open Section", pr_path dir
951 in
952 str s ++ spc () ++ mp
953
954 let pr_located_qualid env = function
955 | Term ref ->
956 let ref_str = let open GlobRef in match ref with
957 ConstRef _ -> "Constant"
958 | IndRef _ -> "Inductive"
959 | ConstructRef _ -> "Constructor"
960 | VarRef _ -> "Variable"
961 in
962 let extra = canonical_info env ref in
963 v 0 (hov 0 (str ref_str ++ spc () ++ pr_path (Nametab.path_of_global ref) ++ extra))
964 | Abbreviation kn ->
965 str "Notation" ++ spc () ++ pr_path (Nametab.path_of_abbreviation kn)
966 | Dir dir -> pr_dir dir
967 | Module mp ->
968 str "Module" ++ spc () ++ pr_path (Nametab.path_of_module mp)
969 | ModuleType mp ->
970 str "Module Type" ++ spc () ++ pr_path (Nametab.path_of_modtype mp)
971 | Other (obj, info) -> info.name obj
972 | Undefined qid ->
973 pr_qualid qid ++ spc () ++ str "not a defined object."
974
975 let maybe_error_reject_univ_decl na udecl =
976 let open GlobRef in
977 match na, udecl with
978 | _, None | Term (ConstRef _ | IndRef _ | ConstructRef _), Some _ -> ()
979 | (Term (VarRef _) | Abbreviation _ | Dir _ | Module _ | ModuleType _ | Other _ | Undefined _), Some udecl ->
980 (* TODO Print na somehow *)
981 user_err (str "This object does not support universe names.")
982
983 let print_any_name access env sigma na udecl =
984 maybe_error_reject_univ_decl na udecl;
985 match na with
986 | Term gref -> print_global_reference access env sigma gref udecl
987 | Abbreviation kn -> print_abbreviation access env sigma kn
988 | Module mp -> print_module mp
989 | Dir dir -> pr_dir dir
990 | ModuleType mp -> print_modtype mp
991 | Other (obj, info) -> info.print obj
992 | Undefined qid ->
993 try (* A goal variable which is not a section variable *)
994 let dir,str = repr_qualid qid in
995 if not (DirPath.is_empty dir) then raise Not_found;
996 print_named_decl env sigma true str
997 with Not_found -> user_err ?loc:qid.loc (pr_qualid qid ++ spc () ++ str "not a defined object.")
998
999 let print_notation_interpretation env sigma (entry,ntn) df sc c =
1000 let filter = Notation.{
1001 notation_entry_pattern = [entry];
1002 interp_rule_key_pattern = Some (Inl ntn);
1003 use_pattern = OnlyPrinting;
1004 scope_pattern = sc;
1005 interpretation_pattern = Some c;
1006 } in
1007 Vernacstate.System.protect (fun () ->
1008 Notation.toggle_notations ~on:false ~all:false ~verbose:false (pr_glob_constr_env env sigma) filter;
1009 hov 0 (str "Notation" ++ spc () ++ Notation_ops.pr_notation_info (pr_glob_constr_env env sigma) df (snd c))) ()
1010
1011 let print_name access env sigma na udecl =
1012 match na with
1013 | {loc; v=Constrexpr.ByNotation (ntn,sc)} ->
1014 let ntn, df, sc, c, ref = Notation.interp_notation_as_global_reference_expanded ?loc ~head:false (fun _ -> true) ntn sc in
1015 print_notation_interpretation env sigma ntn df (Some sc) c ++ fnl () ++ fnl () ++
1016 print_any_name access env sigma (Term ref) udecl
1017 | {loc; v=Constrexpr.AN ref} ->
1018 print_any_name access env sigma (locate_any_name ref) udecl
1019
1020 (** Command [Print Notation] *)
1021
1022 let print_notation_grammar env sigma ntn =
1023 let ng = List.hd (Notgram_ops.grammar_of_notation ntn) in
1024 let assoc = ng.Notation_gram.notgram_assoc in
1025 let prdf () = Pp.str "no associativity" in
1026 Pp.(pr_opt_no_spc_default prdf Gramlib.Gramext.pr_assoc assoc)
1027
1028 exception PrintNotationNotFound of Constrexpr.notation_entry * string
1029
1030 let () = CErrors.register_handler @@ function
1031 | PrintNotationNotFound (entry, ntn_str) ->
1032 let entry_string = match entry with
1033 | Constrexpr.InConstrEntry -> str "."
1034 | Constrexpr.InCustomEntry e -> str " in " ++ Nametab.CustomEntries.pr e ++ str " entry."
1035 in
1036 Some Pp.(str "\"" ++ str ntn_str ++ str "\"" ++ spc ()
1037 ++ str "cannot be interpreted as a known notation" ++ entry_string ++ spc ()
1038 ++ strbrk "Make sure that symbols are surrounded by spaces and that holes are explicitly denoted by \"_\".")
1039 | _ -> None
1040
1041 let error_print_notation_not_found e s =
1042 raise @@ PrintNotationNotFound (e, s)
1043
1044 let print_notation env sigma entry raw_ntn =
1045 (* make sure entry exists *)
1046 let entry = Metasyntax.intern_notation_entry entry in
1047 (* convert notation string to key. eg. "x + y" to "_ + _" *)
1048 let interp_ntn = Notation.interpret_notation_string raw_ntn in
1049 let ntn = (entry, interp_ntn) in
1050 try
1051 let lvl = Notation.level_of_notation ntn in
1052 let args = Notgram_ops.non_terminals_of_notation ntn in
1053 let pplvl = Metasyntax.pr_level lvl args in
1054 Pp.(str "Notation \"" ++ str interp_ntn ++ str "\"" ++ spc ()
1055 ++ pplvl ++ pr_comma () ++ print_notation_grammar env sigma ntn
1056 ++ str ".")
1057 with Not_found -> error_print_notation_not_found entry raw_ntn
1058
1059 (** Command [About] *)
1060
1061 let print_about_global_reference ?loc env ref udecl =
1062 pr_infos_list
1063 (print_ref env false ref udecl :: blankline ::
1064 print_polymorphism env ref @
1065 print_squash env ref udecl @
1066 print_name_infos env ref @
1067 print_reduction_behaviour ref @
1068 print_opacity env ref @
1069 print_bidi_hints env ref @
1070 [hov 0 (str "Expands to: " ++ pr_located_qualid env (Term ref)) ++
1071 loc_info (TrueGlobal ref)])
1072
1073 let print_about_abbreviation env sigma kn =
1074 let (vars,c) = glob_constr_of_abbreviation kn in
1075 let pp = match DAst.get c with
1076 | GRef (gref,_udecl) -> (* TODO: don't drop universes? *) [print_about_global_reference env gref None]
1077 | _ -> [] in
1078 print_abbreviation_body env kn (vars,c) ++ fnl () ++
1079 hov 0 (str "Expands to: " ++ pr_located_qualid env (Abbreviation kn)) ++
1080 loc_info (Abbrev kn) ++
1081 with_line_skip pp
1082
1083 let print_about_any ?loc env sigma k udecl =
1084 maybe_error_reject_univ_decl k udecl;
1085 match k with
1086 | Term ref -> Dumpglob.add_glob ?loc ref; print_about_global_reference env ref udecl
1087 | Abbreviation kn -> v 0 (print_about_abbreviation env sigma kn)
1088 | Dir _ | Module _ | ModuleType _ | Undefined _ -> hov 0 (pr_located_qualid env k)
1089 | Other (obj, info) -> hov 0 (info.about obj)
1090
1091 let print_about env sigma na udecl =
1092 match na with
1093 | {loc;v=Constrexpr.ByNotation (ntn,sc)} ->
1094 let ntn, df, sc, c, ref = Notation.interp_notation_as_global_reference_expanded ?loc ~head:false (fun _ -> true) ntn sc in
1095 print_notation_interpretation env sigma ntn df (Some sc) c ++ fnl () ++ fnl () ++
1096 print_about_any ?loc env sigma (Term ref) udecl
1097 | {loc;v=Constrexpr.AN ref} ->
1098 print_about_any ?loc env sigma (locate_any_name ref) udecl
1099
1100 (* Command [Inspect], for debug *)
1101
1102 let inspect env sigma depth =
1103 print_context env sigma ~with_values:None (Some depth) (Lib.contents ())
1104
1105 (*************************************************************************)
1106 (* Pretty-printing functions coming from classops.ml *)
1107
1108 (** Command [Print Classes] *)
1109
1110 open Coercionops
1111
1112 let print_coercion_value v = Printer.pr_global v.coe_value
1113
1114 let print_path ((i,j),p) =
1115 hov 2 (
1116 str"[" ++ hov 0 (prlist_with_sep pr_semicolon print_coercion_value p) ++
1117 str"] : ") ++
1118 pr_class i ++ str" >-> " ++ pr_class j ++
1119 str (if path_is_reversible p then " (reversible)" else "")
1120
1121 let _ = Coercionops.install_path_printer print_path
1122
1123 let print_graph () =
1124 prlist_with_sep fnl print_path (inheritance_graph())
1125
1126 (** Command [Print Classes] *)
1127
1128 let print_classes () =
1129 pr_sequence pr_class (classes())
1130
1131 (** Command [Print Coercions] *)
1132
1133 let print_coercions () =
1134 pr_sequence print_coercion_value (coercions())
1135
1136 (** Command [Print Coercion Paths] *)
1137
1138 let print_coercion_paths cls clt =
1139 let p =
1140 try
1141 lookup_path_between_class (cls, clt)
1142 with Not_found ->
1143 user_err
1144 (str"No path between " ++ pr_class cls ++ str" and " ++ pr_class clt
1145 ++ str ".")
1146 in
1147 print_path ((cls, clt), p)
1148
1149 (** Command [Print Canonical Projections] *)
1150
1151 let print_canonical_projections env sigma grefs =
1152 let open Structures in
1153 let match_proj_gref { CSTable.projection; value; solution } gr =
1154 QGlobRef.equal env projection gr ||
1155 begin match value with
1156 | ValuePattern.Const_cs y -> QGlobRef.equal env y gr
1157 | _ -> false
1158 end ||
1159 QGlobRef.equal env solution gr
1160 in
1161 let projs =
1162 List.filter (fun p -> List.for_all (match_proj_gref p) grefs)
1163 (CSTable.entries ())
1164 in
1165 prlist_with_sep fnl
1166 (fun { CSTable.projection; value; solution } ->
1167 ValuePattern.print value ++
1168 str " <- " ++
1169 pr_global projection ++ str " ( " ++ pr_global solution ++ str " )")
1170 projs
1171
1172 (***********************************************)
1173 (** Pretty-printing functions for type classes *)
1174
1175 (** Command [Print Typeclasses] *)
1176
1177 open Typeclasses
1178
1179 let pr_typeclass env t =
1180 print_ref env false t.cl_impl None
1181
1182 let print_typeclasses () =
1183 let env = Global.env () in
1184 prlist_with_sep fnl (pr_typeclass env) (typeclasses ())
1185
1186 (** Command [Print Instances] *)
1187
1188 let pr_instance env i =
1189 (* print_constant_with_infos i.is_impl *)
1190 (* lighter *)
1191 print_ref env false (instance_impl i) None ++
1192 begin match hint_priority i with
1193 | None -> mt ()
1194 | Some i -> spc () ++ str "|" ++ spc () ++ int i
1195 end
1196
1197 let print_all_instances () =
1198 let env = Global.env () in
1199 let inst = all_instances () in
1200 prlist_with_sep fnl (pr_instance env) inst
1201
1202 let print_instances r =
1203 let env = Global.env () in
1204 let inst = instances_exn env (Evd.from_env env) r in
1205 prlist_with_sep fnl (pr_instance env) inst
1206
1207 (*********************)
1208 (* Commands [Locate] *)
1209
1210 let canonize_ref = let open GlobRef in function
1211 | ConstRef c ->
1212 let kn = Constant.canonical c in
1213 if KerName.equal (Constant.user c) kn then None
1214 else Some (ConstRef (Constant.make1 kn))
1215 | IndRef (ind,i) ->
1216 let kn = MutInd.canonical ind in
1217 if KerName.equal (MutInd.user ind) kn then None
1218 else Some (IndRef (MutInd.make1 kn, i))
1219 | ConstructRef ((ind,i),j) ->
1220 let kn = MutInd.canonical ind in
1221 if KerName.equal (MutInd.user ind) kn then None
1222 else Some (ConstructRef ((MutInd.make1 kn, i),j))
1223 | VarRef _ -> None
1224
1225 let display_alias = function
1226 | Term r ->
1227 begin match canonize_ref r with
1228 | None -> mt ()
1229 | Some r' ->
1230 let q' = Nametab.shortest_qualid_of_global Id.Set.empty r' in
1231 spc () ++ str "(alias of " ++ pr_qualid q' ++ str ")"
1232 end
1233 | _ -> mt ()
1234
1235 let locate_term qid =
1236 let expand = function
1237 | TrueGlobal ref ->
1238 Term ref, Nametab.shortest_qualid_of_global Id.Set.empty ref
1239 | Abbrev kn ->
1240 Abbreviation kn, Nametab.shortest_qualid_of_abbreviation Id.Set.empty kn
1241 in
1242 List.map expand (Nametab.locate_extended_all qid)
1243
1244 let locate_module qid =
1245 let all = Nametab.locate_extended_all_module qid in
1246 let map mp = Module mp, Nametab.shortest_qualid_of_module mp in
1247 let mods = List.map map all in
1248 (* Don't forget the opened modules: they are not part of the same name tab. *)
1249 let all = Nametab.locate_extended_all_dir qid in
1250 let map dir = let open Nametab.GlobDirRef in match dir with
1251 | DirOpenModule _ -> Some (Dir dir, qid)
1252 | _ -> None
1253 in
1254 mods @ List.map_filter map all
1255
1256 let locate_modtype qid =
1257 let all = Nametab.locate_extended_all_modtype qid in
1258 let map mp = ModuleType mp, Nametab.shortest_qualid_of_modtype mp in
1259 let modtypes = List.map map all in
1260 (* Don't forget the opened module types: they are not part of the same name tab. *)
1261 let all = Nametab.locate_extended_all_dir qid in
1262 let map dir = let open Nametab.GlobDirRef in match dir with
1263 | DirOpenModtype _ -> Some (Dir dir, qid)
1264 | _ -> None
1265 in
1266 modtypes @ List.map_filter map all
1267
1268 let locate_other s qid =
1269 let Locatable info = String.Map.find s !locatable_map in
1270 let ans = info.locate_all qid in
1271 let map obj = (Other (obj, info), info.shortest_qualid obj) in
1272 List.map map ans
1273
1274 type locatable_kind =
1275 | LocTerm
1276 | LocModule
1277 | LocOther of string
1278 | LocAny
1279
1280 let print_located_qualid env name flags qid =
1281 let located = match flags with
1282 | LocTerm -> locate_term qid
1283 | LocModule -> locate_modtype qid @ locate_module qid
1284 | LocOther s -> locate_other s qid
1285 | LocAny ->
1286 locate_term qid @
1287 locate_modtype qid @
1288 locate_module qid @
1289 String.Map.fold (fun s _ accu -> locate_other s qid @ accu) !locatable_map []
1290 in
1291 match located with
1292 | [] ->
1293 let (dir,id) = repr_qualid qid in
1294 if DirPath.is_empty dir then
1295 str "No " ++ str name ++ str " of basename" ++ spc () ++ Id.print id
1296 else
1297 str "No " ++ str name ++ str " of suffix" ++ spc () ++ pr_qualid qid
1298 | l ->
1299 prlist_with_sep fnl
1300 (fun (o,oqid) ->
1301 hov 2 (pr_located_qualid env o ++
1302 (if not (qualid_eq oqid qid) then
1303 spc() ++ str "(shorter name to refer to it in current context is "
1304 ++ pr_qualid oqid ++ str")"
1305 else mt ()) ++
1306 display_alias o)) l
1307
1308 let print_located_term env ref = print_located_qualid env "term" LocTerm ref
1309 let print_located_other env s ref = print_located_qualid env s (LocOther s) ref
1310 let print_located_module env ref = print_located_qualid env "module" LocModule ref
1311 let print_located_qualid env ref = print_located_qualid env "object" LocAny ref