1 (* Copyright (C) 2004, HELM Team.
3 * This file is part of HELM, an Hypertextual, Electronic
4 * Library of Mathematics, developed at the Computer Science
5 * Department, University of Bologna, Italy.
7 * HELM is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * HELM is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with HELM; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
30 open DisambiguateTypes
33 module Ast = CicNotationPt
35 (* the integer is an offset to be added to each location *)
36 exception Ambiguous_input
37 (* the integer is an offset to be added to each location *)
38 exception NoWellTypedInterpretation of
40 ((Stdpp.location list * string * string) list *
41 (DisambiguateTypes.domain_item * string) list *
42 (Stdpp.location * string) Lazy.t * bool) list
43 exception PathNotWellFormed
45 (** raised when an environment is not enough informative to decide *)
46 exception Try_again of string Lazy.t
48 type ('alias,'term) aliases =
49 bool * 'term DisambiguateTypes.codomain_item DisambiguateTypes.Environment.t
50 type 'a disambiguator_input = string * int * 'a
52 type domain = domain_tree list
53 and domain_tree = Node of Stdpp.location list * domain_item * domain
55 let mono_uris_callback ~selection_mode ?ok
56 ?(enable_button_for_non_vars = true) ~title ~msg ~id =
57 if Helm_registry.get_opt_default Helm_registry.get_bool ~default:true
58 "matita.auto_disambiguation"
64 let mono_interp_callback _ _ _ = raise Ambiguous_input
66 let _choose_uris_callback = ref mono_uris_callback
67 let _choose_interp_callback = ref mono_interp_callback
68 let set_choose_uris_callback f = _choose_uris_callback := f
69 let set_choose_interp_callback f = _choose_interp_callback := f
71 let interactive_user_uri_choice = !_choose_uris_callback
72 let interactive_interpretation_choice interp = !_choose_interp_callback interp
73 let input_or_locate_uri ~(title:string) ?id () = None
74 (* Zack: I try to avoid using this callback. I therefore assume that
75 * the presence of an identifier that can't be resolved via "locate"
76 * query is a syntax error *)
79 let rec string_of_domain =
82 | Node (_,domain_item,l)::tl ->
83 DisambiguateTypes.string_of_domain_item domain_item ^
84 " [ " ^ string_of_domain l ^ " ] " ^ string_of_domain tl
86 let rec filter_map_domain f =
89 | Node (locs,domain_item,l)::tl ->
90 match f locs domain_item with
91 None -> filter_map_domain f l @ filter_map_domain f tl
92 | Some res -> res :: filter_map_domain f l @ filter_map_domain f tl
94 let rec map_domain f =
97 | Node (locs,domain_item,l)::tl ->
98 f locs domain_item :: map_domain f l @ map_domain f tl
100 let uniq_domain dom =
104 | Node (locs,domain_item,l)::tl ->
105 if List.mem domain_item seen then
106 let seen,l = aux seen l in
107 let seen,tl = aux seen tl in
110 let seen,l = aux (domain_item::seen) l in
111 let seen,tl = aux seen tl in
112 seen, Node (locs,domain_item,l)::tl
117 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
120 (** print benchmark information *)
122 let max_refinements = ref 0 (* benchmarking is not thread safe *)
123 let actual_refinements = ref 0
124 let domain_size = ref 0
125 let choices_avg = ref 0.
128 let descr_of_domain_item = function
131 | Num i -> string_of_int i
133 type ('term,'metasenv,'subst,'graph) test_result =
134 | Ok of 'term * 'metasenv * 'subst * 'graph
135 | Ko of (Stdpp.location * string) Lazy.t
136 | Uncertain of (Stdpp.location * string) Lazy.t
138 let resolve ~env ~mk_choice (item: domain_item) arg =
140 match snd (mk_choice (Environment.find item env)), arg with
141 `Num_interp f, `Num_arg n -> f n
142 | `Sym_interp f, `Args l -> f l
143 | `Sym_interp f, `Num_arg n -> (* Implicit number! *) f []
144 | _,_ -> assert false
146 failwith ("Domain item not found: " ^
147 (DisambiguateTypes.string_of_domain_item item))
149 (* TODO move it to Cic *)
150 let find_in_context name context =
151 let rec aux acc = function
152 | [] -> raise Not_found
153 | Some hd :: tl when hd = name -> acc
154 | _ :: tl -> aux (acc + 1) tl
160 | Ast.Ident (n, None) -> Some n
164 let rec domain_of_term ?(loc = HExtlib.dummy_floc) ~context = function
165 | Ast.AttributedTerm (`Loc loc, term) ->
166 domain_of_term ~loc ~context term
167 | Ast.AttributedTerm (_, term) ->
168 domain_of_term ~loc ~context term
169 | Ast.Symbol (symbol, instance) ->
170 [ Node ([loc], Symbol (symbol, instance), []) ]
171 (* to be kept in sync with Ast.Appl (Ast.Symbol ...) *)
172 | Ast.Appl (Ast.Symbol (symbol, instance) as hd :: args)
173 | Ast.Appl (Ast.AttributedTerm (_,Ast.Symbol (symbol, instance)) as hd :: args)
177 (fun term acc -> domain_of_term ~loc ~context term @ acc)
181 Ast.AttributedTerm (`Loc loc,_) -> loc
184 [ Node ([loc], Symbol (symbol, instance), args_dom) ]
185 | Ast.Appl (Ast.Ident (name, subst) as hd :: args)
186 | Ast.Appl (Ast.AttributedTerm (_,Ast.Ident (name, subst)) as hd :: args) ->
189 (fun term acc -> domain_of_term ~loc ~context term @ acc)
193 Ast.AttributedTerm (`Loc loc,_) -> loc
197 (* the next line can raise Not_found *)
198 ignore(find_in_context name context);
199 if subst <> None then
200 Ast.fail loc "Explicit substitutions not allowed here"
205 | None -> [ Node ([loc], Id name, args_dom) ]
209 (fun dom (_, term) ->
210 let dom' = domain_of_term ~loc ~context term in
213 [ Node ([loc], Id name, terms @ args_dom) ]))
216 (fun term acc -> domain_of_term ~loc ~context term @ acc)
218 | Ast.Binder (kind, (var, typ), body) ->
219 let type_dom = domain_of_term_option ~loc ~context typ in
222 ~context:(string_of_name var :: context) body in
224 | `Exists -> [ Node ([loc], Symbol ("exists", 0), (type_dom @ body_dom)) ]
225 | _ -> type_dom @ body_dom)
226 | Ast.Case (term, indty_ident, outtype, branches) ->
227 let term_dom = domain_of_term ~loc ~context term in
228 let outtype_dom = domain_of_term_option ~loc ~context outtype in
229 let rec get_first_constructor = function
231 | (Ast.Pattern (head, _, _), _) :: _ -> [ Node ([loc], Id head, []) ]
232 | _ :: tl -> get_first_constructor tl in
235 Ast.Pattern (head, _, args), term ->
236 let (term_context, args_domain) =
238 (fun (cont, dom) (name, typ) ->
239 (string_of_name name :: cont,
242 | Some typ -> dom @ domain_of_term ~loc ~context:cont typ)))
245 domain_of_term ~loc ~context:term_context term @ args_domain
246 | Ast.Wildcard, term ->
247 domain_of_term ~loc ~context term
250 List.fold_left (fun dom branch -> dom @ do_branch branch) [] branches in
251 (match indty_ident with
252 | None -> get_first_constructor branches
253 | Some (ident, _) -> [ Node ([loc], Id ident, []) ])
254 @ term_dom @ outtype_dom @ branches_dom
255 | Ast.Cast (term, ty) ->
256 let term_dom = domain_of_term ~loc ~context term in
257 let ty_dom = domain_of_term ~loc ~context ty in
259 | Ast.LetIn ((var, typ), body, where) ->
260 let body_dom = domain_of_term ~loc ~context body in
261 let type_dom = domain_of_term_option ~loc ~context typ in
263 domain_of_term ~loc ~context:(string_of_name var :: context) where in
264 body_dom @ type_dom @ where_dom
265 | Ast.LetRec (kind, defs, where) ->
266 let add_defs context =
268 (fun acc (_, (var, _), _, _) -> string_of_name var :: acc
270 let where_dom = domain_of_term ~loc ~context:(add_defs context) where in
273 (fun dom (params, (_, typ), body, _) ->
277 (fun acc (var,_) -> string_of_name var :: acc)
283 (fun (context,res) (var,ty) ->
284 string_of_name var :: context,
285 domain_of_term_option ~loc ~context ty @ res)
286 (add_defs context,[]) params))
288 @ domain_of_term_option ~loc ~context:context' typ
289 @ domain_of_term ~loc ~context:context' body
293 | Ast.Ident (name, subst) ->
295 (* the next line can raise Not_found *)
296 ignore(find_in_context name context);
297 if subst <> None then
298 Ast.fail loc "Explicit substitutions not allowed here"
303 | None -> [ Node ([loc], Id name, []) ]
307 (fun dom (_, term) ->
308 let dom' = domain_of_term ~loc ~context term in
311 [ Node ([loc], Id name, terms) ]))
314 | Ast.Num (num, i) -> [ Node ([loc], Num i, []) ]
315 | Ast.Meta (index, local_context) ->
317 (fun dom term -> dom @ domain_of_term_option ~loc ~context term)
324 | Ast.Variable _ -> assert false
326 and domain_of_term_option ~loc ~context = function
328 | Some t -> domain_of_term ~loc ~context t
330 let domain_of_term ~context term =
331 uniq_domain (domain_of_term ~context term)
333 let domain_of_obj ~context ast =
334 assert (context = []);
336 | Ast.Theorem (_,_,ty,bo) ->
340 | Some bo -> domain_of_term [] bo)
341 | Ast.Inductive (params,tyl) ->
344 (fun (context, dom) (var, ty) ->
345 let context' = string_of_name var :: context in
347 None -> context', dom
348 | Some ty -> context', dom @ domain_of_term context ty
350 let context_w_types =
351 List.rev_map (fun (var, _, _, _) -> Some var) tyl @ context in
356 domain_of_term context ty
359 (fun (_,ty) -> domain_of_term context_w_types ty) cl))
361 | Ast.Record (params,var,ty,fields) ->
364 (fun (context, dom) (var, ty) ->
365 let context' = string_of_name var :: context in
367 None -> context', dom
368 | Some ty -> context', dom @ domain_of_term context ty
370 let context_w_types = Some var :: context in
372 @ domain_of_term context ty
375 (fun (context,res) (name,ty,_,_) ->
376 Some name::context, res @ domain_of_term context ty
377 ) (context_w_types,[]) fields)
379 let domain_of_obj ~context obj =
380 uniq_domain (domain_of_obj ~context obj)
382 let domain_of_ast_term = domain_of_term;;
385 let domain_diff dom1 dom2 =
386 (* let domain_diff = Domain.diff *)
390 | Symbol (symb, 0) ->
392 Symbol (symb',_) when symb = symb' -> true
404 | Node (_,elt,l)::tl when is_in_dom2 elt -> aux (l @ tl)
405 | Node (loc,elt,l)::tl -> Node (loc,elt,aux l)::(aux tl)
409 module type Disambiguator =
411 val disambiguate_thing:
413 metasenv:'metasenv ->
415 use_coercions:bool ->
416 string_context_of_context:('context -> string option list) ->
417 initial_ugraph:'ugraph ->
419 ('metasenv -> 'raw_thing -> 'raw_thing) *
420 (('refined_thing,'metasenv,'subst,'ugraph) test_result ->
421 ('refined_thing,'metasenv,'subst,'ugraph) test_result) ->
422 mk_implicit:(bool -> 'alias) ->
423 description_of_alias:('alias -> string) ->
424 aliases:'alias DisambiguateTypes.Environment.t ->
425 universe:'alias list DisambiguateTypes.Environment.t option ->
427 DisambiguateTypes.interactive_user_uri_choice_type ->
428 DisambiguateTypes.input_or_locate_uri_type ->
429 DisambiguateTypes.Environment.key ->
432 pp_thing:('ast_thing -> string) ->
433 domain_of_thing:(context: string option list -> 'ast_thing -> domain) ->
436 env:'alias DisambiguateTypes.Environment.t ->
440 localization_tbl:'cichash ->
443 'metasenv -> 'subst -> 'context -> 'uri -> use_coercions:bool ->
444 'raw_thing -> 'ugraph -> localization_tbl:'cichash ->
445 ('refined_thing, 'metasenv,'subst,'ugraph) test_result) ->
446 localization_tbl:'cichash ->
447 string * int * 'ast_thing ->
448 ((DisambiguateTypes.Environment.key * 'alias) list *
449 'metasenv * 'subst * 'refined_thing * 'ugraph)
453 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
455 let disambiguate_thing
456 ~context ~metasenv ~subst ~use_coercions
457 ~string_context_of_context
458 ~initial_ugraph:base_univ ~hint
459 ~mk_implicit ~description_of_alias
460 ~aliases ~universe ~lookup_in_library
461 ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing
463 (thing_txt,thing_txt_prefix_len,thing)
465 debug_print (lazy "DISAMBIGUATE INPUT");
466 debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
468 domain_of_thing ~context:(string_context_of_context context) thing in
470 (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"(string_of_domain thing_dom)));
472 Environment.fold (fun item _ dom -> item :: dom) aliases [] in
473 let todo_dom = domain_diff thing_dom current_dom in
475 (lazy (sprintf "DISAMBIGUATION DOMAIN AFTER DIFF: %s"(string_of_domain todo_dom)));
476 (* (2) lookup function for any item (Id/Symbol/Num) *)
482 interactive_user_uri_choice
483 input_or_locate_uri item
488 | Symbol (symb, _) -> Symbol (symb, 0)
491 Environment.find item e
494 interactive_user_uri_choice
495 input_or_locate_uri item)
500 if benchmark then begin
501 let per_item_choices =
505 let len = List.length (lookup_choices dom_item) in
506 debug_print (lazy (sprintf "BENCHMARK %s: %d"
507 (string_of_domain_item dom_item) len));
509 with No_choices _ -> 0)
512 max_refinements := List.fold_left ( * ) 1 per_item_choices;
513 actual_refinements := 0;
514 domain_size := List.length thing_dom;
516 (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
522 (* (3) test an interpretation filling with meta uninterpreted identifiers
524 let test_env aliases todo_dom ugraph =
526 let rec aux env = function
528 | Node (_, item, l) :: tl ->
532 (match item with | Id _ | Num _ -> true | Symbol _ -> false))
534 aux (aux env l) tl in
535 let filled_env = aux aliases todo_dom in
537 interpretate_thing ~context ~env:filled_env
538 ~uri ~is_path:false thing ~localization_tbl
540 let cic_thing = (fst hint) metasenv cic_thing in
543 refine_thing metasenv subst context uri
544 ~use_coercions cic_thing ugraph ~localization_tbl
546 let k = (snd hint) k in
548 in refine_profiler.HExtlib.profile foo ()
550 | Try_again msg -> Uncertain (lazy (Stdpp.dummy_loc,Lazy.force msg))
551 | Invalid_choice loc_msg -> Ko loc_msg
553 (* (4) build all possible interpretations *)
554 let (@@) (l1,l2,l3) (l1',l2',l3') = l1@l1', l2@l2', l3@l3' in
555 (* aux returns triples Ok/Uncertain/Ko *)
556 (* rem_dom is the concatenation of all the remainin domains *)
557 let rec aux aliases diff lookup_in_todo_dom todo_dom rem_dom =
558 debug_print (lazy ("ZZZ: " ^ string_of_domain todo_dom));
561 assert (lookup_in_todo_dom = None);
562 (match test_env aliases rem_dom base_univ with
563 | Ok (thing, metasenv,subst,new_univ) ->
564 [ aliases, diff, metasenv, subst, thing, new_univ ], [], []
565 | Ko loc_msg -> [],[],[aliases,diff,loc_msg,true]
566 | Uncertain loc_msg ->
567 [],[aliases,diff,loc_msg],[])
568 | Node (locs,item,inner_dom) :: remaining_dom ->
569 debug_print (lazy (sprintf "CHOOSED ITEM: %s"
570 (string_of_domain_item item)));
572 match lookup_in_todo_dom with
573 None -> lookup_choices item
574 | Some choices -> choices in
580 "No choices for " ^ string_of_domain_item item)),
584 (* just one choice. We perform a one-step look-up and
585 if the next set of choices is also a singleton we
586 skip this refinement step *)
587 debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
588 let new_env = Environment.add item codomain_item aliases in
589 let new_diff = (item,codomain_item)::diff in
590 let lookup_in_todo_dom,next_choice_is_single =
591 match remaining_dom with
594 let choices = lookup_choices he in
595 Some choices,List.length choices = 1
597 if next_choice_is_single then
598 aux new_env new_diff lookup_in_todo_dom remaining_dom
601 (match test_env new_env remaining_dom base_univ with
602 | Ok (thing, metasenv),new_univ ->
603 (match remaining_dom with
605 [ new_env, new_diff, metasenv, thing, new_univ ], []
607 aux new_env new_diff lookup_in_todo_dom
608 remaining_dom new_univ)
609 | Uncertain (loc,msg),new_univ ->
610 (match remaining_dom with
611 | [] -> [], [new_env,new_diff,loc,msg,true]
613 aux new_env new_diff lookup_in_todo_dom
614 remaining_dom new_univ)
615 | Ko (loc,msg),_ -> [], [new_env,new_diff,loc,msg,true])
618 let mark_not_significant failures =
620 (fun (env, diff, loc_msg, _b) ->
621 env, diff, loc_msg, false)
623 let classify_errors ((ok_l,uncertain_l,error_l) as outcome) =
624 if ok_l <> [] || uncertain_l <> [] then
625 ok_l,uncertain_l,mark_not_significant error_l
628 let rec filter = function
630 | codomain_item :: tl ->
631 (*debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));*)
632 let new_env = Environment.add item codomain_item aliases in
633 let new_diff = (item,codomain_item)::diff in
636 (inner_dom@remaining_dom@rem_dom) base_univ
638 | Ok (thing, metasenv,subst,new_univ) ->
640 (match inner_dom with
642 [new_env,new_diff,metasenv,subst,thing,new_univ],
645 aux new_env new_diff None inner_dom
646 (remaining_dom@rem_dom)
650 | Uncertain loc_msg ->
652 (match inner_dom with
653 | [] -> [],[new_env,new_diff,loc_msg],[]
655 aux new_env new_diff None inner_dom
656 (remaining_dom@rem_dom)
661 let res = [],[],[new_env,new_diff,loc_msg,true] in
664 let ok_l,uncertain_l,error_l =
665 classify_errors (filter choices)
669 (fun (env,diff,_,_,_,_) res ->
670 aux env diff None remaining_dom rem_dom @@ res
671 ) ok_l ([],[],error_l)
674 (fun (env,diff,_) res ->
675 aux env diff None remaining_dom rem_dom @@ res
676 ) uncertain_l res_after_ok_l
678 let aux' aliases diff lookup_in_todo_dom todo_dom =
679 match test_env aliases todo_dom base_univ with
682 aux aliases diff lookup_in_todo_dom todo_dom []
683 | Ko (loc_msg) -> [],[],[aliases,diff,loc_msg,true]
686 match aux' aliases [] None todo_dom with
687 | [],uncertain,errors ->
690 (fun (env,diff,loc_msg) -> (env,diff,loc_msg,true)
695 (fun (env,diff,loc_msg,significant) ->
698 (fun locs domain_item ->
701 description_of_alias (Environment.find domain_item env)
703 Some (locs,descr_of_domain_item domain_item,description)
708 let diff= List.map (fun a,b -> a,description_of_alias b) diff in
709 env',diff,loc_msg,significant
712 raise (NoWellTypedInterpretation (0,errors))
713 | [_,diff,metasenv,subst,t,ugraph],_,_ ->
714 debug_print (lazy "SINGLE INTERPRETATION");
715 [diff,metasenv,subst,t,ugraph], false
718 (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
721 (fun (env, _, _, _, _, _) ->
723 (fun locs domain_item ->
725 description_of_alias (Environment.find domain_item env)
727 locs,descr_of_domain_item domain_item, description)
732 interactive_interpretation_choice
733 thing_txt thing_txt_prefix_len choices
735 (List.map (fun n->let _,d,m,s,t,u= List.nth l n in d,m,s,t,u)