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 _ ~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 (NCicPp.ppterm ~metasenv ~subst ~context t);
42 let metasenv, subst, term, _ =
47 NCicCoercion.look_for_coercion coercion_db
48 else (fun _ _ _ _ _ -> []))
49 metasenv subst context term None ~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) -> assert false
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 -> assert false (*NCic.Implicit (Some `Hole)
326 patterns not implemented *)
327 | CicNotationPt.Num (num, i) ->
328 Disambiguate.resolve ~env ~mk_choice (Num i) (`Num_arg num)
329 | CicNotationPt.Meta (index, subst) ->
332 (function None -> assert false| Some t -> aux ~localize loc context t)
335 NCic.Meta (index, (0, NCic.Ctx cic_subst))
336 | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
337 | CicNotationPt.Sort `Set -> NCic.Sort (NCic.Type
338 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
339 | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
340 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
341 | CicNotationPt.Sort (`NType s) -> NCic.Sort (NCic.Type
342 [false,NUri.uri_of_string ("cic:/matita/pts/Type" ^ s ^ ".univ")])
343 | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
344 [false,NUri.uri_of_string "cic:/matita/pts/CProp.univ"])
345 | CicNotationPt.Symbol (symbol, instance) ->
346 Disambiguate.resolve ~env ~mk_choice
347 (Symbol (symbol, instance)) (`Args [])
348 | CicNotationPt.Variable _
349 | CicNotationPt.Magic _
350 | CicNotationPt.Layout _
351 | CicNotationPt.Literal _ -> assert false (* god bless Bologna *)
352 and aux_option ~localize loc context annotation = function
353 | None -> NCic.Implicit annotation
354 | Some (CicNotationPt.AttributedTerm (`Loc loc, term)) ->
355 let res = aux_option ~localize loc context annotation (Some term) in
357 NCicUntrusted.NCicHash.add localization_tbl res loc;
359 | Some (CicNotationPt.AttributedTerm (_, term)) ->
360 aux_option ~localize loc context annotation (Some term)
361 | Some CicNotationPt.Implicit -> NCic.Implicit annotation
362 | Some term -> aux ~localize loc context term
364 (fun ~context -> aux ~localize:true HExtlib.dummy_floc context),
365 (fun ~context -> aux_option ~localize:true HExtlib.dummy_floc context)
368 let interpretate_term ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast
369 ~obj_context ~localization_tbl ~mk_choice
371 let context = List.map fst context in
373 (interpretate_term_and_interpretate_term_option
374 ~obj_context ~mk_choice ~create_dummy_ids ~env ~uri ~is_path ~localization_tbl)
378 let interpretate_term_option
379 ?(create_dummy_ids=false) ~context ~env ~uri ~is_path
380 ~localization_tbl ~mk_choice ~obj_context
382 let context = List.map fst context in
384 (interpretate_term_and_interpretate_term_option
385 ~obj_context ~mk_choice ~create_dummy_ids ~env ~uri ~is_path ~localization_tbl)
389 let new_flavour_of_flavour = function
390 | `Definition -> `Definition
391 | `MutualDefinition -> `Definition
394 | `Remark -> `Corollary
395 | `Theorem -> `Theorem
396 | `Variant -> `Corollary
400 let ncic_name_of_ident = function
401 | Ast.Ident (name, None) -> name
406 (* ?(create_dummy_ids=false) *)
407 ~context ~env ~uri ~is_path obj ~localization_tbl ~mk_choice
409 assert (context = []);
410 assert (is_path = false);
411 let interpretate_term ~obj_context =
412 interpretate_term ~mk_choice ~localization_tbl ~obj_context in
413 let interpretate_term_option ~obj_context =
414 interpretate_term_option ~mk_choice ~localization_tbl ~obj_context in
415 let uri = match uri with | None -> assert false | Some u -> u in
417 | CicNotationPt.Theorem (flavour, name, ty, bo) ->
420 ~obj_context:[] ~context:[] ~env ~uri:None ~is_path:false ty
422 let height = (* XXX calculate *) 0 in
424 (match bo,flavour with
426 let attrs = `Provided, new_flavour_of_flavour flavour, `Regular in
427 NCic.Constant ([],name,None,ty',attrs)
428 | Some _,`Axiom -> assert false
430 let attrs = `Provided, new_flavour_of_flavour flavour, `Regular in
431 NCic.Constant ([],name,Some (NCic.Implicit `Term),ty',attrs)
434 | CicNotationPt.LetRec (kind, defs, _) ->
435 let inductive = kind = `Inductive in
438 (fun (i,acc) (_,(name,_),_,k) ->
440 (ncic_name_of_ident name, NReference.reference_of_spec uri
441 (if inductive then NReference.Fix (i,k,0)
442 else NReference.CoFix i)) :: acc))
447 (fun (params, (name, typ), body, decr_idx) ->
448 let add_binders kind t =
451 CicNotationPt.Binder (kind, var, t)) params t
455 ~obj_context ~context ~env ~uri:None ~is_path:false
456 (add_binders `Lambda body)
459 interpretate_term_option
461 ~context ~env ~uri:None ~is_path:false `Type
462 (HExtlib.map_option (add_binders `Pi) typ)
464 ([],ncic_name_of_ident name, decr_idx, cic_type, cic_body))
467 let attrs = `Provided, new_flavour_of_flavour flavour in
468 NCic.Fixpoint (inductive,inductiveFuns,attrs)
472 ~obj_context:[] ~context:[] ~env ~uri:None ~is_path:false bo
474 let attrs = `Provided, new_flavour_of_flavour flavour, `Regular in
475 NCic.Constant ([],name,Some bo,ty',attrs))
476 | _ -> raise (MultiPassDisambiguator.DisambiguationError (0, []))
478 | CicNotationPt.Inductive (params,tyl) ->
479 let uri = match uri with Some uri -> uri | None -> assert false in
483 (fun (context,res) (name,t) ->
486 None -> CicNotationPt.Implicit
488 let name = CicNotationUtil.cic_name_of_name name in
489 name::context,(name, interpretate_term context env None false t)::res
492 context,List.rev res in
494 List.fold_right (fun (name,ty) t -> Cic.Prod (name,ty,t)) params in
498 (*here the explicit_named_substituion is assumed to be of length 0 *)
499 (fun (i,res) (name,_,_,_) -> i + 1,(name,Cic.MutInd (uri,i,[]))::res)
503 (fun (name,b,ty,cl) ->
504 let ty' = add_params (interpretate_term context env None false ty) in
510 (interpretate_term ~obj_context ~context ~env ~uri:None
519 Cic.InductiveDefinition (tyl,[],List.length params,[])
520 | CicNotationPt.Record (params,name,ty,fields) ->
521 let uri = match uri with Some uri -> uri | None -> assert false in
525 (fun (context,res) (name,t) ->
528 None -> CicNotationPt.Implicit
530 let name = CicNotationUtil.cic_name_of_name name in
531 name::context,(name, interpretate_term context env None false t)::res
534 context,List.rev res in
537 (fun (name,ty) t -> Cic.Prod (name,ty,t)) params in
538 let ty' = add_params (interpretate_term context env None false ty) in
542 (fun (context,res) (name,ty,_coercion,arity) ->
543 let context' = Cic.Name name :: context in
544 context',(name,interpretate_term context env None false ty)::res
545 ) (context,[]) fields) in
547 (*here the explicit_named_substituion is assumed to be of length 0 *)
548 let mutind = Cic.MutInd (uri,0,[]) in
549 if params = [] then mutind
552 (mutind::CicUtil.mk_rels (List.length params) (List.length fields)) in
555 (fun t (name,ty) -> Cic.Prod (Cic.Name name,ty,t))
557 let con' = add_params con in
558 let tyl = [name,true,ty',["mk_" ^ name,con']] in
559 let field_names = List.map (fun (x,_,y,z) -> x,y,z) fields in
560 Cic.InductiveDefinition
561 (tyl,[],List.length params,[`Class (`Record field_names)])
565 let disambiguate_term ~context ~metasenv ~subst ?goal
566 ~mk_implicit ~description_of_alias ~mk_choice
567 ~aliases ~universe ~coercion_db ~lookup_in_library
568 (text,prefix_len,term)
570 let mk_localization_tbl x = NCicUntrusted.NCicHash.create x in
573 None -> (fun _ y -> y),(fun x -> x)
576 let _,_,ty = NCicUtils.lookup_meta n metasenv in
577 NCic.LetIn ("_",ty,y,NCic.Rel 1)),
579 | Disambiguate.Ok (t,m,s,ug) ->
581 | NCic.LetIn ("_",_,y,NCic.Rel 1) -> Disambiguate.Ok (y,m,s,ug)
586 MultiPassDisambiguator.disambiguate_thing
587 ~freshen_thing:CicNotationUtil.freshen_term
588 ~context ~metasenv ~initial_ugraph:() ~aliases
589 ~mk_implicit ~description_of_alias
590 ~string_context_of_context:(List.map (fun (x,_) -> Some x))
591 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
592 ~passes:(MultiPassDisambiguator.passes ())
593 ~lookup_in_library ~domain_of_thing:Disambiguate.domain_of_term
594 ~interpretate_thing:(interpretate_term ~obj_context:[] ~mk_choice (?create_dummy_ids:None))
595 ~refine_thing:(refine_term ~coercion_db) (text,prefix_len,term)
596 ~mk_localization_tbl ~hint ~subst
598 List.map (function (a,b,c,d,_) -> a,b,c,d) res, b
602 ~mk_implicit ~description_of_alias ~mk_choice
603 ~aliases ~universe ~coercion_db ~lookup_in_library ~uri
604 (text,prefix_len,obj)
606 let mk_localization_tbl x = NCicUntrusted.NCicHash.create x in
607 let hint = (fun x y -> y), (fun x -> x) in
609 MultiPassDisambiguator.disambiguate_thing
610 ~freshen_thing:CicNotationUtil.freshen_obj
611 ~context:[] ~metasenv:[] ~subst:[] ~initial_ugraph:() ~aliases
612 ~mk_implicit ~description_of_alias
613 ~string_context_of_context:(List.map (fun (x,_) -> Some x))
616 ~pp_thing:(CicNotationPp.pp_obj CicNotationPp.pp_term)
617 ~passes:(MultiPassDisambiguator.passes ())
618 ~lookup_in_library ~domain_of_thing:Disambiguate.domain_of_obj
619 ~interpretate_thing:(interpretate_obj ~mk_choice)
620 ~refine_thing:(refine_obj ~coercion_db)
621 (text,prefix_len,obj)
622 ~mk_localization_tbl ~hint
624 List.map (function (a,b,c,d,_) -> a,b,c,d) res, b
629 [false, NUri.uri_of_string ("cic:/matita/pts/Type.univ")]
631 [false, NUri.uri_of_string ("cic:/matita/pts/Type"^string_of_int n^".univ")]
635 [false, NUri.uri_of_string ("cic:/matita/pts/CProp.univ")]
637 [false, NUri.uri_of_string ("cic:/matita/pts/CProp"^string_of_int n^".univ")]
639 NCicEnvironment.add_constraint true (mk_type 0) (mk_type 1);
640 NCicEnvironment.add_constraint true (mk_cprop 0) (mk_cprop 1);
641 NCicEnvironment.add_constraint true (mk_cprop 0) (mk_type 1);
642 NCicEnvironment.add_constraint true (mk_type 0) (mk_cprop 1);
643 NCicEnvironment.add_constraint false (mk_cprop 0) (mk_type 0);
644 NCicEnvironment.add_constraint false (mk_type 0) (mk_cprop 0);
646 NCicEnvironment.add_constraint true (mk_type 1) (mk_type 2);
647 NCicEnvironment.add_constraint true (mk_cprop 1) (mk_cprop 2);
648 NCicEnvironment.add_constraint true (mk_cprop 1) (mk_type 2);
649 NCicEnvironment.add_constraint true (mk_type 1) (mk_cprop 2);
650 NCicEnvironment.add_constraint false (mk_cprop 1) (mk_type 1);
651 NCicEnvironment.add_constraint false (mk_type 1) (mk_cprop 1);
653 NCicEnvironment.add_constraint true (mk_type 2) (mk_type 3);
654 NCicEnvironment.add_constraint true (mk_cprop 2) (mk_cprop 3);
655 NCicEnvironment.add_constraint true (mk_cprop 2) (mk_type 3);
656 NCicEnvironment.add_constraint true (mk_type 2) (mk_cprop 3);
657 NCicEnvironment.add_constraint false (mk_cprop 2) (mk_type 2);
658 NCicEnvironment.add_constraint false (mk_type 2) (mk_cprop 2);
660 NCicEnvironment.add_constraint false (mk_cprop 3) (mk_type 3);
661 NCicEnvironment.add_constraint false (mk_type 3) (mk_cprop 3);