2 ||M|| This file is part of HELM, an Hypertextual, Electronic
3 ||A|| Library of Mathematics, developed at the Computer Science
4 ||T|| Department, University of Bologna, Italy.
6 ||T|| HELM is free software; you can redistribute it and/or
7 ||A|| modify it under the terms of the GNU General Public License
8 \ / version 2 or (at your option) any later version.
9 \ / This software is distributed as is, NO WARRANTY.
10 V_______________________________________________________________ *)
12 (* $Id: nCic.ml 9058 2008-10-13 17:42:30Z tassi $ *)
16 open DisambiguateTypes
19 module Ast = CicNotationPt
20 module NRef = NReference
22 let debug_print _ = ();;
23 (* let debug_print s = prerr_endline (Lazy.force s);; *)
25 let cic_name_of_name = function
26 | Ast.Ident (n, None) -> n
31 metasenv subst context uri ~coercion_db ~use_coercions term expty _ ~localization_tbl=
33 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s"
34 (NCicPp.ppterm ~metasenv ~subst ~context term)));
37 try NCicUntrusted.NCicHash.find localization_tbl t
39 prerr_endline ("NOT LOCALISED" ^ NCicPp.ppterm ~metasenv ~subst ~context t);
40 (*assert false*) HExtlib.dummy_floc
42 let metasenv, subst, term, _ =
47 NCicCoercion.look_for_coercion coercion_db
48 else (fun _ _ _ _ _ -> []))
49 metasenv subst context term expty ~localise
51 Disambiguate.Ok (term, metasenv, subst, ())
53 | NCicRefiner.Uncertain loc_msg ->
54 debug_print (lazy ("UNCERTAIN: [" ^ snd (Lazy.force loc_msg) ^ "] " ^
55 NCicPp.ppterm ~metasenv ~subst ~context term)) ;
56 Disambiguate.Uncertain loc_msg
57 | NCicRefiner.RefineFailure loc_msg ->
58 debug_print (lazy (sprintf "PRUNED:\nterm%s\nmessage:%s"
59 (NCicPp.ppterm ~metasenv ~subst ~context term) (snd(Lazy.force loc_msg))));
60 Disambiguate.Ko loc_msg
64 ~coercion_db metasenv subst context _uri
65 ~use_coercions obj _ _ugraph ~localization_tbl
70 try NCicUntrusted.NCicHash.find localization_tbl t
72 prerr_endline (NCicPp.ppterm ~metasenv ~subst ~context t);
73 (*assert false*)HExtlib.dummy_floc
77 NCicRefiner.typeof_obj
81 NCicCoercion.look_for_coercion coercion_db
82 else (fun _ _ _ _ _ -> []))
85 Disambiguate.Ok (obj, [], [], ())
87 | NCicRefiner.Uncertain loc_msg ->
88 debug_print (lazy ("UNCERTAIN: [" ^ snd (Lazy.force loc_msg) ^ "] " ^
90 Disambiguate.Uncertain loc_msg
91 | NCicRefiner.RefineFailure loc_msg ->
92 debug_print (lazy (sprintf "PRUNED:\nobj: %s\nmessage: %s"
93 (NCicPp.ppobj obj) (snd(Lazy.force loc_msg))));
94 Disambiguate.Ko loc_msg
98 (* TODO move it to Cic *)
99 let find_in_context name context =
100 let rec aux acc = function
101 | [] -> raise Not_found
102 | hd :: _ when hd = name -> acc
103 | _ :: tl -> aux (acc + 1) tl
107 let interpretate_term_and_interpretate_term_option
108 ?(create_dummy_ids=false)
109 ~obj_context ~mk_choice ~env ~uri ~is_path ~localization_tbl
111 (* create_dummy_ids shouldbe used only for interpretating patterns *)
114 let rec aux ~localize loc context = function
115 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
116 let res = aux ~localize loc context term in
118 NCicUntrusted.NCicHash.add localization_tbl res loc;
120 | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
121 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
122 let cic_args = List.map (aux ~localize loc context) args in
123 Disambiguate.resolve ~mk_choice ~env (Symbol (symb, i)) (`Args cic_args)
124 | CicNotationPt.Appl terms ->
125 NCic.Appl (List.map (aux ~localize loc context) terms)
126 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
127 let cic_type = aux_option ~localize loc context `Type typ in
128 let cic_name = cic_name_of_name var in
129 let cic_body = aux ~localize loc (cic_name :: context) body in
130 (match binder_kind with
131 | `Lambda -> NCic.Lambda (cic_name, cic_type, cic_body)
133 | `Forall -> NCic.Prod (cic_name, cic_type, cic_body)
135 Disambiguate.resolve ~env ~mk_choice (Symbol ("exists", 0))
136 (`Args [ cic_type; NCic.Lambda (cic_name, cic_type, cic_body) ]))
137 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
138 let cic_term = aux ~localize loc context term in
139 let cic_outtype = aux_option ~localize loc context `Term outtype in
140 let do_branch ((_, _, args), term) =
141 let rec do_branch' context = function
142 | [] -> aux ~localize loc context term
143 | (name, typ) :: tl ->
144 let cic_name = cic_name_of_name name in
145 let cic_body = do_branch' (cic_name :: context) tl in
148 | None -> NCic.Implicit `Type
149 | Some typ -> aux ~localize loc context typ
151 NCic.Lambda (cic_name, typ, cic_body)
153 do_branch' context args
155 if create_dummy_ids then
159 Ast.Wildcard,term -> ("wildcard",None,[]), term
161 raise (DisambiguateTypes.Invalid_choice
162 (lazy (loc, "Syntax error: the left hand side of a "^
163 "branch pattern must be \"_\"")))
167 NCic.MutCase (ref, cic_outtype, cic_term,
168 (List.map do_branch branches))
169 *) ignore branches; assert false (* patterns not implemented yet *)
172 match indty_ident with
173 | Some (indty_ident, _) ->
174 (match Disambiguate.resolve ~env ~mk_choice
175 (Id indty_ident) (`Args []) with
176 | NCic.Const (NReference.Ref (_,NReference.Ind _) as r) -> r
178 raise (Disambiguate.Try_again
179 (lazy "The type of the term to be matched is still unknown"))
181 raise (DisambiguateTypes.Invalid_choice
182 (lazy (loc,"The type of the term to be matched "^
183 "is not (co)inductive: " ^ NCicPp.ppterm
184 ~metasenv:[] ~subst:[] ~context:[] t))))
186 let rec fst_constructor =
188 (Ast.Pattern (head, _, _), _) :: _ -> head
189 | (Ast.Wildcard, _) :: tl -> fst_constructor tl
190 | [] -> raise (Invalid_choice (lazy (loc,"The type "^
191 "of the term to be matched cannot be determined "^
192 "because it is an inductive type without constructors "^
193 "or because all patterns use wildcards")))
196 DisambiguateTypes.Environment.iter
199 (DisambiguateTypes.string_of_domain_item k ^ " => " ^
200 description_of_alias v)) env;
202 (match Disambiguate.resolve ~env ~mk_choice
203 (Id (fst_constructor branches)) (`Args []) with
204 | NCic.Const (NReference.Ref (_,NReference.Con _) as r) ->
205 let b,_,_,_,_ = NCicEnvironment.get_checked_indtys r in
206 NReference.mk_indty b r
208 raise (Disambiguate.Try_again
209 (lazy "The type of the term to be matched is still unknown"))
211 raise (DisambiguateTypes.Invalid_choice
213 "The type of the term to be matched is not (co)inductive: "
214 ^ NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] t))))
216 let _,leftsno,itl,_,indtyp_no =
217 NCicEnvironment.get_checked_indtys indtype_ref in
220 List.nth itl indtyp_no
221 with _ -> assert false in
222 let rec count_prod t =
223 match NCicReduction.whd ~subst:[] [] t with
224 NCic.Prod (_, _, t) -> 1 + (count_prod t)
227 let rec sort branches cl =
230 let rec analyze unused unrecognized useless =
233 if unrecognized != [] then
234 raise (DisambiguateTypes.Invalid_choice
236 (loc,"Unrecognized constructors: " ^
237 String.concat " " unrecognized)))
238 else if useless > 0 then
239 raise (DisambiguateTypes.Invalid_choice
241 (loc,"The last " ^ string_of_int useless ^
242 "case" ^ if useless > 1 then "s are" else " is" ^
246 | (Ast.Wildcard,_)::tl when not unused ->
247 analyze true unrecognized useless tl
248 | (Ast.Pattern (head,_,_),_)::tl when not unused ->
249 analyze unused (head::unrecognized) useless tl
250 | _::tl -> analyze unused unrecognized (useless + 1) tl
252 analyze false [] 0 branches
253 | (_,name,ty)::cltl ->
254 let rec find_and_remove =
258 (DisambiguateTypes.Invalid_choice
259 (lazy (loc, "Missing case: " ^ name)))
260 | ((Ast.Wildcard, _) as branch :: _) as branches ->
262 | (Ast.Pattern (name',_,_),_) as branch :: tl
266 let found,rest = find_and_remove tl in
269 let branch,tl = find_and_remove branches in
271 Ast.Pattern (name,y,args),term ->
272 if List.length args = count_prod ty - leftsno then
273 ((name,y,args),term)::sort tl cltl
276 (DisambiguateTypes.Invalid_choice
277 (lazy (loc,"Wrong number of arguments for " ^ name)))
278 | Ast.Wildcard,term ->
284 (`Lambda, (CicNotationPt.Ident ("_", None), None),
287 (("wildcard",None,[]),
288 mk_lambdas (count_prod ty - leftsno)) :: sort tl cltl
290 let branches = sort branches cl in
291 NCic.Match (indtype_ref, cic_outtype, cic_term,
292 (List.map do_branch branches))
293 | CicNotationPt.Cast (t1, t2) ->
294 let cic_t1 = aux ~localize loc context t1 in
295 let cic_t2 = aux ~localize loc context t2 in
296 NCic.LetIn ("_",cic_t2,cic_t1, NCic.Rel 1)
297 | CicNotationPt.LetIn ((name, typ), def, body) ->
298 let cic_def = aux ~localize loc context def in
299 let cic_name = cic_name_of_name name in
302 | None -> NCic.Implicit `Type
303 | Some t -> aux ~localize loc context t
305 let cic_body = aux ~localize loc (cic_name :: context) body in
306 NCic.LetIn (cic_name, cic_typ, cic_def, cic_body)
307 | CicNotationPt.LetRec (_kind, _defs, _body) -> NCic.Implicit `Term
308 | CicNotationPt.Ident _
309 | CicNotationPt.Uri _ when is_path -> raise Disambiguate.PathNotWellFormed
310 | CicNotationPt.Ident (name, subst) ->
311 assert (subst = None);
313 NCic.Rel (find_in_context name context)
315 try NCic.Const (List.assoc name obj_context)
317 Disambiguate.resolve ~env ~mk_choice (Id name) (`Args []))
318 | CicNotationPt.Uri (name, subst) ->
319 assert (subst = None);
321 NCic.Const (NRef.reference_of_string name)
322 with NRef.IllFormedReference _ ->
323 CicNotationPt.fail loc "Ill formed reference")
324 | CicNotationPt.Implicit -> NCic.Implicit `Term
325 | CicNotationPt.UserInput -> NCic.Implicit `Hole
326 | CicNotationPt.Num (num, i) ->
327 Disambiguate.resolve ~env ~mk_choice (Num i) (`Num_arg num)
328 | CicNotationPt.Meta (index, subst) ->
331 (function None -> assert false| Some t -> aux ~localize loc context t)
334 NCic.Meta (index, (0, NCic.Ctx cic_subst))
335 | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
336 | CicNotationPt.Sort `Set -> NCic.Sort (NCic.Type
337 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
338 | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
339 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
340 | CicNotationPt.Sort (`NType s) -> NCic.Sort (NCic.Type
341 [false,NUri.uri_of_string ("cic:/matita/pts/Type" ^ s ^ ".univ")])
342 | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
343 [false,NUri.uri_of_string "cic:/matita/pts/CProp.univ"])
344 | CicNotationPt.Symbol (symbol, instance) ->
345 Disambiguate.resolve ~env ~mk_choice
346 (Symbol (symbol, instance)) (`Args [])
347 | CicNotationPt.Variable _
348 | CicNotationPt.Magic _
349 | CicNotationPt.Layout _
350 | CicNotationPt.Literal _ -> assert false (* god bless Bologna *)
351 and aux_option ~localize loc context annotation = function
352 | None -> NCic.Implicit annotation
353 | Some (CicNotationPt.AttributedTerm (`Loc loc, term)) ->
354 let res = aux_option ~localize loc context annotation (Some term) in
356 NCicUntrusted.NCicHash.add localization_tbl res loc;
358 | Some (CicNotationPt.AttributedTerm (_, term)) ->
359 aux_option ~localize loc context annotation (Some term)
360 | Some CicNotationPt.Implicit -> NCic.Implicit annotation
361 | Some term -> aux ~localize loc context term
363 (fun ~context -> aux ~localize:true HExtlib.dummy_floc context),
364 (fun ~context -> aux_option ~localize:true HExtlib.dummy_floc context)
367 let interpretate_term ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast
368 ~obj_context ~localization_tbl ~mk_choice
370 let context = List.map fst context in
372 (interpretate_term_and_interpretate_term_option
373 ~obj_context ~mk_choice ~create_dummy_ids ~env ~uri ~is_path ~localization_tbl)
377 let interpretate_term_option
378 ?(create_dummy_ids=false) ~context ~env ~uri ~is_path
379 ~localization_tbl ~mk_choice ~obj_context
381 let context = List.map fst context in
383 (interpretate_term_and_interpretate_term_option
384 ~obj_context ~mk_choice ~create_dummy_ids ~env ~uri ~is_path ~localization_tbl)
388 let disambiguate_path path =
389 let localization_tbl = NCicUntrusted.NCicHash.create 23 in
391 (interpretate_term_and_interpretate_term_option
392 ~obj_context:[] ~mk_choice:(fun _ -> assert false)
393 ~create_dummy_ids:true ~env:DisambiguateTypes.Environment.empty
394 ~uri:None ~is_path:true ~localization_tbl) ~context:[] path
397 let new_flavour_of_flavour = function
398 | `Definition -> `Definition
399 | `MutualDefinition -> `Definition
402 | `Remark -> `Corollary
403 | `Theorem -> `Theorem
404 | `Variant -> `Corollary
408 let ncic_name_of_ident = function
409 | Ast.Ident (name, None) -> name
414 (* ?(create_dummy_ids=false) *)
415 ~context ~env ~uri ~is_path obj ~localization_tbl ~mk_choice
417 assert (context = []);
418 assert (is_path = false);
419 let interpretate_term ~obj_context =
420 interpretate_term ~mk_choice ~localization_tbl ~obj_context in
421 let interpretate_term_option ~obj_context =
422 interpretate_term_option ~mk_choice ~localization_tbl ~obj_context in
423 let uri = match uri with | None -> assert false | Some u -> u in
425 | CicNotationPt.Theorem (flavour, name, ty, bo) ->
428 ~obj_context:[] ~context:[] ~env ~uri:None ~is_path:false ty
430 let height = (* XXX calculate *) 0 in
432 (match bo,flavour with
434 let attrs = `Provided, new_flavour_of_flavour flavour, `Regular in
435 NCic.Constant ([],name,None,ty',attrs)
436 | Some _,`Axiom -> assert false
438 let attrs = `Provided, new_flavour_of_flavour flavour, `Regular in
439 NCic.Constant ([],name,Some (NCic.Implicit `Term),ty',attrs)
442 | CicNotationPt.LetRec (kind, defs, _) ->
443 let inductive = kind = `Inductive in
446 (fun (i,acc) (_,(name,_),_,k) ->
448 (ncic_name_of_ident name, NReference.reference_of_spec uri
449 (if inductive then NReference.Fix (i,k,0)
450 else NReference.CoFix i)) :: acc))
455 (fun (params, (name, typ), body, decr_idx) ->
456 let add_binders kind t =
459 CicNotationPt.Binder (kind, var, t)) params t
463 ~obj_context ~context ~env ~uri:None ~is_path:false
464 (add_binders `Lambda body)
467 interpretate_term_option
469 ~context ~env ~uri:None ~is_path:false `Type
470 (HExtlib.map_option (add_binders `Pi) typ)
472 ([],ncic_name_of_ident name, decr_idx, cic_type, cic_body))
475 let attrs = `Provided, new_flavour_of_flavour flavour in
476 NCic.Fixpoint (inductive,inductiveFuns,attrs)
480 ~obj_context:[] ~context:[] ~env ~uri:None ~is_path:false bo
482 let attrs = `Provided, new_flavour_of_flavour flavour, `Regular in
483 NCic.Constant ([],name,Some bo,ty',attrs))
484 | _ -> raise (MultiPassDisambiguator.DisambiguationError (0, []))
486 | CicNotationPt.Inductive (params,tyl) ->
487 let uri = match uri with Some uri -> uri | None -> assert false in
491 (fun (context,res) (name,t) ->
494 None -> CicNotationPt.Implicit
496 let name = CicNotationUtil.cic_name_of_name name in
497 name::context,(name, interpretate_term context env None false t)::res
500 context,List.rev res in
502 List.fold_right (fun (name,ty) t -> Cic.Prod (name,ty,t)) params in
506 (*here the explicit_named_substituion is assumed to be of length 0 *)
507 (fun (i,res) (name,_,_,_) -> i + 1,(name,Cic.MutInd (uri,i,[]))::res)
511 (fun (name,b,ty,cl) ->
512 let ty' = add_params (interpretate_term context env None false ty) in
518 (interpretate_term ~obj_context ~context ~env ~uri:None
527 Cic.InductiveDefinition (tyl,[],List.length params,[])
528 | CicNotationPt.Record (params,name,ty,fields) ->
529 let uri = match uri with Some uri -> uri | None -> assert false in
533 (fun (context,res) (name,t) ->
536 None -> CicNotationPt.Implicit
538 let name = CicNotationUtil.cic_name_of_name name in
539 name::context,(name, interpretate_term context env None false t)::res
542 context,List.rev res in
545 (fun (name,ty) t -> Cic.Prod (name,ty,t)) params in
546 let ty' = add_params (interpretate_term context env None false ty) in
550 (fun (context,res) (name,ty,_coercion,arity) ->
551 let context' = Cic.Name name :: context in
552 context',(name,interpretate_term context env None false ty)::res
553 ) (context,[]) fields) in
555 (*here the explicit_named_substituion is assumed to be of length 0 *)
556 let mutind = Cic.MutInd (uri,0,[]) in
557 if params = [] then mutind
560 (mutind::CicUtil.mk_rels (List.length params) (List.length fields)) in
563 (fun t (name,ty) -> Cic.Prod (Cic.Name name,ty,t))
565 let con' = add_params con in
566 let tyl = [name,true,ty',["mk_" ^ name,con']] in
567 let field_names = List.map (fun (x,_,y,z) -> x,y,z) fields in
568 Cic.InductiveDefinition
569 (tyl,[],List.length params,[`Class (`Record field_names)])
573 let disambiguate_term ~context ~metasenv ~subst ~expty
574 ~mk_implicit ~description_of_alias ~mk_choice
575 ~aliases ~universe ~coercion_db ~lookup_in_library
576 (text,prefix_len,term)
578 let mk_localization_tbl x = NCicUntrusted.NCicHash.create x in
580 MultiPassDisambiguator.disambiguate_thing
581 ~freshen_thing:CicNotationUtil.freshen_term
582 ~context ~metasenv ~initial_ugraph:() ~aliases
583 ~mk_implicit ~description_of_alias
584 ~string_context_of_context:(List.map (fun (x,_) -> Some x))
585 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
586 ~passes:(MultiPassDisambiguator.passes ())
587 ~lookup_in_library ~domain_of_thing:Disambiguate.domain_of_term
588 ~interpretate_thing:(interpretate_term ~obj_context:[] ~mk_choice (?create_dummy_ids:None))
589 ~refine_thing:(refine_term ~coercion_db) (text,prefix_len,term)
590 ~mk_localization_tbl ~expty ~subst
592 List.map (function (a,b,c,d,_) -> a,b,c,d) res, b
596 ~mk_implicit ~description_of_alias ~mk_choice
597 ~aliases ~universe ~coercion_db ~lookup_in_library ~uri
598 (text,prefix_len,obj)
600 let mk_localization_tbl x = NCicUntrusted.NCicHash.create x in
602 MultiPassDisambiguator.disambiguate_thing
603 ~freshen_thing:CicNotationUtil.freshen_obj
604 ~context:[] ~metasenv:[] ~subst:[] ~initial_ugraph:() ~aliases
605 ~mk_implicit ~description_of_alias
606 ~string_context_of_context:(List.map (fun (x,_) -> Some x))
609 ~pp_thing:(CicNotationPp.pp_obj CicNotationPp.pp_term)
610 ~passes:(MultiPassDisambiguator.passes ())
611 ~lookup_in_library ~domain_of_thing:Disambiguate.domain_of_obj
612 ~interpretate_thing:(interpretate_obj ~mk_choice)
613 ~refine_thing:(refine_obj ~coercion_db)
614 (text,prefix_len,obj)
615 ~mk_localization_tbl ~expty:None
617 List.map (function (a,b,c,d,_) -> a,b,c,d) res, b
622 [false, NUri.uri_of_string ("cic:/matita/pts/Type.univ")]
624 [false, NUri.uri_of_string ("cic:/matita/pts/Type"^string_of_int n^".univ")]
628 [false, NUri.uri_of_string ("cic:/matita/pts/CProp.univ")]
630 [false, NUri.uri_of_string ("cic:/matita/pts/CProp"^string_of_int n^".univ")]
632 NCicEnvironment.add_constraint true (mk_type 0) (mk_type 1);
633 NCicEnvironment.add_constraint true (mk_cprop 0) (mk_cprop 1);
634 NCicEnvironment.add_constraint true (mk_cprop 0) (mk_type 1);
635 NCicEnvironment.add_constraint true (mk_type 0) (mk_cprop 1);
636 NCicEnvironment.add_constraint false (mk_cprop 0) (mk_type 0);
637 NCicEnvironment.add_constraint false (mk_type 0) (mk_cprop 0);
639 NCicEnvironment.add_constraint true (mk_type 1) (mk_type 2);
640 NCicEnvironment.add_constraint true (mk_cprop 1) (mk_cprop 2);
641 NCicEnvironment.add_constraint true (mk_cprop 1) (mk_type 2);
642 NCicEnvironment.add_constraint true (mk_type 1) (mk_cprop 2);
643 NCicEnvironment.add_constraint false (mk_cprop 1) (mk_type 1);
644 NCicEnvironment.add_constraint false (mk_type 1) (mk_cprop 1);
646 NCicEnvironment.add_constraint true (mk_type 2) (mk_type 3);
647 NCicEnvironment.add_constraint true (mk_cprop 2) (mk_cprop 3);
648 NCicEnvironment.add_constraint true (mk_cprop 2) (mk_type 3);
649 NCicEnvironment.add_constraint true (mk_type 2) (mk_cprop 3);
650 NCicEnvironment.add_constraint false (mk_cprop 2) (mk_type 2);
651 NCicEnvironment.add_constraint false (mk_type 2) (mk_cprop 2);
653 NCicEnvironment.add_constraint false (mk_cprop 3) (mk_type 3);
654 NCicEnvironment.add_constraint false (mk_type 3) (mk_cprop 3);