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
63 (* TODO move it to Cic *)
64 let find_in_context name context =
65 let rec aux acc = function
66 | [] -> raise Not_found
67 | hd :: _ when hd = name -> acc
68 | _ :: tl -> aux (acc + 1) tl
73 ?(create_dummy_ids=false) ~mk_choice ~context ~env ~uri ~is_path ast
76 (* create_dummy_ids shouldbe used only for interpretating patterns *)
79 let rec aux ~localize loc context = function
80 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
81 let res = aux ~localize loc context term in
83 NCicUntrusted.NCicHash.add localization_tbl res loc;
85 | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
86 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
87 let cic_args = List.map (aux ~localize loc context) args in
88 Disambiguate.resolve ~mk_choice ~env (Symbol (symb, i)) (`Args cic_args)
89 | CicNotationPt.Appl terms ->
90 NCic.Appl (List.map (aux ~localize loc context) terms)
91 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
92 let cic_type = aux_option ~localize loc context `Type typ in
93 let cic_name = cic_name_of_name var in
94 let cic_body = aux ~localize loc (cic_name :: context) body in
95 (match binder_kind with
96 | `Lambda -> NCic.Lambda (cic_name, cic_type, cic_body)
98 | `Forall -> NCic.Prod (cic_name, cic_type, cic_body)
100 Disambiguate.resolve ~env ~mk_choice (Symbol ("exists", 0))
101 (`Args [ cic_type; NCic.Lambda (cic_name, cic_type, cic_body) ]))
102 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
103 let cic_term = aux ~localize loc context term in
104 let cic_outtype = aux_option ~localize loc context `Term outtype in
105 let do_branch ((_, _, args), term) =
106 let rec do_branch' context = function
107 | [] -> aux ~localize loc context term
108 | (name, typ) :: tl ->
109 let cic_name = cic_name_of_name name in
110 let cic_body = do_branch' (cic_name :: context) tl in
113 | None -> NCic.Implicit `Type
114 | Some typ -> aux ~localize loc context typ
116 NCic.Lambda (cic_name, typ, cic_body)
118 do_branch' context args
120 if create_dummy_ids then
124 Ast.Wildcard,term -> ("wildcard",None,[]), term
126 raise (DisambiguateTypes.Invalid_choice
127 (lazy (loc, "Syntax error: the left hand side of a "^
128 "branch pattern must be \"_\"")))
132 NCic.MutCase (ref, cic_outtype, cic_term,
133 (List.map do_branch branches))
134 *) ignore branches; assert false (* patterns not implemented yet *)
137 match indty_ident with
138 | Some (indty_ident, _) ->
139 (match Disambiguate.resolve ~env ~mk_choice
140 (Id indty_ident) (`Args []) with
141 | NCic.Const (NReference.Ref (_,NReference.Ind _) as r) -> r
143 raise (Disambiguate.Try_again
144 (lazy "The type of the term to be matched is still unknown"))
146 raise (DisambiguateTypes.Invalid_choice
147 (lazy (loc,"The type of the term to be matched "^
148 "is not (co)inductive: " ^ NCicPp.ppterm
149 ~metasenv:[] ~subst:[] ~context:[] t))))
151 let rec fst_constructor =
153 (Ast.Pattern (head, _, _), _) :: _ -> head
154 | (Ast.Wildcard, _) :: tl -> fst_constructor tl
155 | [] -> raise (Invalid_choice (lazy (loc,"The type "^
156 "of the term to be matched cannot be determined "^
157 "because it is an inductive type without constructors "^
158 "or because all patterns use wildcards")))
161 DisambiguateTypes.Environment.iter
164 (DisambiguateTypes.string_of_domain_item k ^ " => " ^
165 description_of_alias v)) env;
167 (match Disambiguate.resolve ~env ~mk_choice
168 (Id (fst_constructor branches)) (`Args []) with
169 | NCic.Const (NReference.Ref (_,NReference.Con _) as r) ->
170 let b,_,_,_,_ = NCicEnvironment.get_checked_indtys r in
171 NReference.mk_indty b r
173 raise (Disambiguate.Try_again
174 (lazy "The type of the term to be matched is still unknown"))
176 raise (DisambiguateTypes.Invalid_choice
178 "The type of the term to be matched is not (co)inductive: "
179 ^ NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] t))))
181 let _,leftsno,itl,_,indtyp_no =
182 NCicEnvironment.get_checked_indtys indtype_ref in
185 List.nth itl indtyp_no
186 with _ -> assert false in
187 let rec count_prod t =
188 match NCicReduction.whd ~subst:[] [] t with
189 NCic.Prod (_, _, t) -> 1 + (count_prod t)
192 let rec sort branches cl =
195 let rec analyze unused unrecognized useless =
198 if unrecognized != [] then
199 raise (DisambiguateTypes.Invalid_choice
201 (loc,"Unrecognized constructors: " ^
202 String.concat " " unrecognized)))
203 else if useless > 0 then
204 raise (DisambiguateTypes.Invalid_choice
206 (loc,"The last " ^ string_of_int useless ^
207 "case" ^ if useless > 1 then "s are" else " is" ^
211 | (Ast.Wildcard,_)::tl when not unused ->
212 analyze true unrecognized useless tl
213 | (Ast.Pattern (head,_,_),_)::tl when not unused ->
214 analyze unused (head::unrecognized) useless tl
215 | _::tl -> analyze unused unrecognized (useless + 1) tl
217 analyze false [] 0 branches
218 | (_,name,ty)::cltl ->
219 let rec find_and_remove =
223 (DisambiguateTypes.Invalid_choice
224 (lazy (loc, "Missing case: " ^ name)))
225 | ((Ast.Wildcard, _) as branch :: _) as branches ->
227 | (Ast.Pattern (name',_,_),_) as branch :: tl
231 let found,rest = find_and_remove tl in
234 let branch,tl = find_and_remove branches in
236 Ast.Pattern (name,y,args),term ->
237 if List.length args = count_prod ty - leftsno then
238 ((name,y,args),term)::sort tl cltl
241 (DisambiguateTypes.Invalid_choice
242 (lazy (loc,"Wrong number of arguments for " ^ name)))
243 | Ast.Wildcard,term ->
249 (`Lambda, (CicNotationPt.Ident ("_", None), None),
252 (("wildcard",None,[]),
253 mk_lambdas (count_prod ty - leftsno)) :: sort tl cltl
255 let branches = sort branches cl in
256 NCic.Match (indtype_ref, cic_outtype, cic_term,
257 (List.map do_branch branches))
258 | CicNotationPt.Cast (t1, t2) ->
259 let cic_t1 = aux ~localize loc context t1 in
260 let cic_t2 = aux ~localize loc context t2 in
261 NCic.LetIn ("_",cic_t2,cic_t1, NCic.Rel 1)
262 | CicNotationPt.LetIn ((name, typ), def, body) ->
263 let cic_def = aux ~localize loc context def in
264 let cic_name = cic_name_of_name name in
267 | None -> NCic.Implicit `Type
268 | Some t -> aux ~localize loc context t
270 let cic_body = aux ~localize loc (cic_name :: context) body in
271 NCic.LetIn (cic_name, cic_typ, cic_def, cic_body)
272 | CicNotationPt.LetRec (_kind, _defs, _body) ->
276 (fun acc (_, (name, _), _, _) ->
277 cic_name_of_name name :: acc)
281 let unlocalized_body = aux ~localize:false loc context' body in
282 match unlocalized_body with
283 NCic.Rel n when n <= List.length defs -> `AvoidLetInNoAppl n
284 | NCic.Appl (NCic.Rel n::l) when n <= List.length defs ->
289 let t',subst,metasenv =
290 CicMetaSubst.delift_rels [] [] (List.length defs) t
293 assert (metasenv=[]);
296 (* We can avoid the LetIn. But maybe we need to recompute l'
297 so that it is localized *)
300 CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
301 (* since we avoid the letin, the context has no
303 let l' = List.map (aux ~localize loc context) l in
309 CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
311 `AddLetIn (aux ~localize loc context' body)
313 `AddLetIn unlocalized_body)
316 `AddLetIn (aux ~localize loc context' body)
318 `AddLetIn unlocalized_body
322 (fun (params, (name, typ), body, decr_idx) ->
323 let add_binders kind t =
325 (fun var t -> CicNotationPt.Binder (kind, var, t)) params t
328 aux ~localize loc context' (add_binders `Lambda body) in
330 aux_option ~localize loc context (Some `Type)
331 (HExtlib.map_option (add_binders `Pi) typ) in
333 match cic_name_of_name name with
335 CicNotationPt.fail loc
336 "Recursive functions cannot be anonymous"
337 | NCic.Name name -> name
339 (name, decr_idx, cic_type, cic_body))
344 `Inductive -> NCic.Fix (n,inductiveFuns)
346 let coinductiveFuns =
348 (fun (name, _, typ, body) -> name, typ, body)
351 NCic.CoFix (n,coinductiveFuns)
353 let counter = ref ~-1 in
354 let build_term _ (var,_,ty,_) t =
356 NCic.LetIn (NCic.Name var, fix_or_cofix !counter, ty, t)
359 `AvoidLetInNoAppl n ->
360 let n' = List.length inductiveFuns - n in
362 | `AvoidLetIn (n,l) ->
363 let n' = List.length inductiveFuns - n in
364 NCic.Appl (fix_or_cofix n'::l)
365 | `AddLetIn cic_body ->
366 List.fold_right (build_term inductiveFuns) inductiveFuns
369 | CicNotationPt.Ident _
370 | CicNotationPt.Uri _ when is_path -> raise Disambiguate.PathNotWellFormed
371 | CicNotationPt.Ident (name, subst) ->
372 assert (subst = None);
374 NCic.Rel (find_in_context name context)
376 Disambiguate.resolve ~env ~mk_choice (Id name) (`Args []))
377 | CicNotationPt.Uri (name, subst) ->
378 assert (subst = None);
380 NCic.Const (NRef.reference_of_string name)
381 with NRef.IllFormedReference _ ->
382 CicNotationPt.fail loc "Ill formed reference")
383 | CicNotationPt.Implicit -> NCic.Implicit `Term
384 | CicNotationPt.UserInput -> assert false (*NCic.Implicit (Some `Hole)
385 patterns not implemented *)
386 | CicNotationPt.Num (num, i) ->
387 Disambiguate.resolve ~env ~mk_choice (Num i) (`Num_arg num)
388 | CicNotationPt.Meta (index, subst) ->
391 (function None -> assert false| Some t -> aux ~localize loc context t)
394 NCic.Meta (index, (0, NCic.Ctx cic_subst))
395 | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
396 | CicNotationPt.Sort `Set -> NCic.Sort (NCic.Type
397 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
398 | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
399 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
400 | CicNotationPt.Sort (`NType s) -> NCic.Sort (NCic.Type
401 [false,NUri.uri_of_string ("cic:/matita/pts/Type" ^ s ^ ".univ")])
402 | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
403 [false,NUri.uri_of_string "cic:/matita/pts/CProp.univ"])
404 | CicNotationPt.Symbol (symbol, instance) ->
405 Disambiguate.resolve ~env ~mk_choice
406 (Symbol (symbol, instance)) (`Args [])
407 | CicNotationPt.Variable _
408 | CicNotationPt.Magic _
409 | CicNotationPt.Layout _
410 | CicNotationPt.Literal _ -> assert false (* god bless Bologna *)
411 and aux_option ~localize loc context annotation = function
412 | None -> NCic.Implicit annotation
413 | Some (CicNotationPt.AttributedTerm (`Loc loc, term)) ->
414 let res = aux_option ~localize loc context annotation (Some term) in
416 NCicUntrusted.NCicHash.add localization_tbl res loc;
418 | Some (CicNotationPt.AttributedTerm (_, term)) ->
419 aux_option ~localize loc context annotation (Some term)
420 | Some CicNotationPt.Implicit -> NCic.Implicit annotation
421 | Some term -> aux ~localize loc context term
423 aux ~localize:true HExtlib.dummy_floc context ast
425 let interpretate_term ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast
428 let context = List.map fst context in
429 interpretate_term ~create_dummy_ids ~context ~env ~uri ~is_path ast
433 let disambiguate_term ~context ~metasenv ~subst ?goal
434 ~mk_implicit ~description_of_alias ~mk_choice
435 ~aliases ~universe ~coercion_db ~lookup_in_library
436 (text,prefix_len,term)
438 let mk_localization_tbl x = NCicUntrusted.NCicHash.create x in
441 None -> (fun _ y -> y),(fun x -> x)
444 let _,_,ty = NCicUtils.lookup_meta n metasenv in
445 NCic.LetIn ("_",ty,y,NCic.Rel 1)),
447 | Disambiguate.Ok (t,m,s,ug) ->
449 | NCic.LetIn ("_",_,y,NCic.Rel 1) -> Disambiguate.Ok (y,m,s,ug)
454 MultiPassDisambiguator.disambiguate_thing
455 ~freshen_thing:CicNotationUtil.freshen_term
456 ~context ~metasenv ~initial_ugraph:() ~aliases
457 ~mk_implicit ~description_of_alias
458 ~string_context_of_context:(List.map (fun (x,_) -> Some x))
459 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
460 ~passes:(MultiPassDisambiguator.passes ())
461 ~lookup_in_library ~domain_of_thing:Disambiguate.domain_of_term
462 ~interpretate_thing:(interpretate_term ~mk_choice (?create_dummy_ids:None))
463 ~refine_thing:(refine_term ~coercion_db) (text,prefix_len,term)
464 ~mk_localization_tbl ~hint ~subst
466 List.map (function (a,b,c,d,_) -> a,b,c,d) res, b
472 [false, NUri.uri_of_string ("cic:/matita/pts/Type.univ")]
474 [false, NUri.uri_of_string ("cic:/matita/pts/Type"^string_of_int n^".univ")]
478 [false, NUri.uri_of_string ("cic:/matita/pts/CProp.univ")]
480 [false, NUri.uri_of_string ("cic:/matita/pts/CProp"^string_of_int n^".univ")]
482 NCicEnvironment.add_constraint true (mk_type 0) (mk_type 1);
483 NCicEnvironment.add_constraint true (mk_cprop 0) (mk_cprop 1);
484 NCicEnvironment.add_constraint true (mk_cprop 0) (mk_type 1);
485 NCicEnvironment.add_constraint true (mk_type 0) (mk_cprop 1);
486 NCicEnvironment.add_constraint false (mk_cprop 0) (mk_type 0);
487 NCicEnvironment.add_constraint false (mk_type 0) (mk_cprop 0);
489 NCicEnvironment.add_constraint true (mk_type 1) (mk_type 2);
490 NCicEnvironment.add_constraint true (mk_cprop 1) (mk_cprop 2);
491 NCicEnvironment.add_constraint true (mk_cprop 1) (mk_type 2);
492 NCicEnvironment.add_constraint true (mk_type 1) (mk_cprop 2);
493 NCicEnvironment.add_constraint false (mk_cprop 1) (mk_type 1);
494 NCicEnvironment.add_constraint false (mk_type 1) (mk_cprop 1);
496 NCicEnvironment.add_constraint true (mk_type 2) (mk_type 3);
497 NCicEnvironment.add_constraint true (mk_cprop 2) (mk_cprop 3);
498 NCicEnvironment.add_constraint true (mk_cprop 2) (mk_type 3);
499 NCicEnvironment.add_constraint true (mk_type 2) (mk_cprop 3);
500 NCicEnvironment.add_constraint false (mk_cprop 2) (mk_type 2);
501 NCicEnvironment.add_constraint false (mk_type 2) (mk_cprop 2);
503 NCicEnvironment.add_constraint false (mk_cprop 3) (mk_type 3);
504 NCicEnvironment.add_constraint false (mk_type 3) (mk_cprop 3);