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
30 let refine_term metasenv subst context uri ~use_coercions:_ term _ ~localization_tbl =
32 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s"
33 (NCicPp.ppterm ~metasenv ~subst ~context term)));
36 try NCicUntrusted.NCicHash.find localization_tbl t
38 prerr_endline (NCicPp.ppterm ~metasenv ~subst ~context t);
41 let metasenv, subst, term, _ =
42 NCicRefiner.typeof metasenv subst context term None ~localise
44 Disambiguate.Ok (term, metasenv, subst, ())
46 | NCicRefiner.Uncertain loc_msg ->
47 debug_print (lazy ("UNCERTAIN: [" ^ snd (Lazy.force loc_msg) ^ "] " ^
48 NCicPp.ppterm ~metasenv ~subst ~context term)) ;
49 Disambiguate.Uncertain loc_msg
50 | NCicRefiner.RefineFailure loc_msg ->
51 debug_print (lazy (sprintf "PRUNED:\nterm%s\nmessage:%s"
52 (NCicPp.ppterm ~metasenv ~subst ~context term) (snd(Lazy.force loc_msg))));
53 Disambiguate.Ko loc_msg
56 (* TODO move it to Cic *)
57 let find_in_context name context =
58 let rec aux acc = function
59 | [] -> raise Not_found
60 | hd :: _ when hd = name -> acc
61 | _ :: tl -> aux (acc + 1) tl
66 ?(create_dummy_ids=false) ~mk_choice ~context ~env ~uri ~is_path ast
69 (* create_dummy_ids shouldbe used only for interpretating patterns *)
72 let rec aux ~localize loc context = function
76 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
77 let res = aux ~localize loc context term in
79 NCicUntrusted.NCicHash.add localization_tbl res loc;
81 | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
82 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
83 let cic_args = List.map (aux ~localize loc context) args in
84 Disambiguate.resolve ~mk_choice ~env (Symbol (symb, i)) (`Args cic_args)
85 | CicNotationPt.Appl terms ->
86 NCic.Appl (List.map (aux ~localize loc context) terms)
87 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
88 let cic_type = aux_option ~localize loc context `Type typ in
89 let cic_name = cic_name_of_name var in
90 let cic_body = aux ~localize loc (cic_name :: context) body in
91 (match binder_kind with
92 | `Lambda -> NCic.Lambda (cic_name, cic_type, cic_body)
94 | `Forall -> NCic.Prod (cic_name, cic_type, cic_body)
96 Disambiguate.resolve ~env ~mk_choice (Symbol ("exists", 0))
97 (`Args [ cic_type; NCic.Lambda (cic_name, cic_type, cic_body) ]))
98 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
99 let cic_term = aux ~localize loc context term in
100 let cic_outtype = aux_option ~localize loc context `Term outtype in
101 let do_branch ((_, _, args), term) =
102 let rec do_branch' context = function
103 | [] -> aux ~localize loc context term
104 | (name, typ) :: tl ->
105 let cic_name = cic_name_of_name name in
106 let cic_body = do_branch' (cic_name :: context) tl in
109 | None -> NCic.Implicit `Type
110 | Some typ -> aux ~localize loc context typ
112 NCic.Lambda (cic_name, typ, cic_body)
114 do_branch' context args
116 if create_dummy_ids then
120 Ast.Wildcard,term -> ("wildcard",None,[]), term
122 raise (DisambiguateTypes.Invalid_choice
123 (lazy (loc, "Syntax error: the left hand side of a "^
124 "branch pattern must be \"_\"")))
128 NCic.MutCase (ref, cic_outtype, cic_term,
129 (List.map do_branch branches))
130 *) ignore branches; assert false (* patterns not implemented yet *)
133 match indty_ident with
134 | Some (indty_ident, _) ->
135 (match Disambiguate.resolve ~env ~mk_choice
136 (Id indty_ident) (`Args []) with
137 | NCic.Const (NReference.Ref (_,NReference.Ind _) as r) -> r
139 raise (Disambiguate.Try_again
140 (lazy "The type of the term to be matched is still unknown"))
142 raise (DisambiguateTypes.Invalid_choice
143 (lazy (loc,"The type of the term to be matched "^
144 "is not (co)inductive: " ^ NCicPp.ppterm
145 ~metasenv:[] ~subst:[] ~context:[] t))))
147 let rec fst_constructor =
149 (Ast.Pattern (head, _, _), _) :: _ -> head
150 | (Ast.Wildcard, _) :: tl -> fst_constructor tl
151 | [] -> raise (Invalid_choice (lazy (loc,"The type "^
152 "of the term to be matched cannot be determined "^
153 "because it is an inductive type without constructors "^
154 "or because all patterns use wildcards")))
157 DisambiguateTypes.Environment.iter
160 (DisambiguateTypes.string_of_domain_item k ^ " => " ^
161 description_of_alias v)) env;
163 (match Disambiguate.resolve ~env ~mk_choice
164 (Id (fst_constructor branches)) (`Args []) with
165 | NCic.Const (NReference.Ref (_,NReference.Con _) as r) ->
166 let b,_,_,_,_ = NCicEnvironment.get_checked_indtys r in
167 NReference.mk_indty b r
169 raise (Disambiguate.Try_again
170 (lazy "The type of the term to be matched is still unknown"))
172 raise (DisambiguateTypes.Invalid_choice
174 "The type of the term to be matched is not (co)inductive: "
175 ^ NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] t))))
177 let _,leftsno,itl,_,indtyp_no =
178 NCicEnvironment.get_checked_indtys indtype_ref in
181 List.nth itl indtyp_no
182 with _ -> assert false in
183 let rec count_prod t =
184 match NCicReduction.whd [] t with
185 NCic.Prod (_, _, t) -> 1 + (count_prod t)
188 let rec sort branches cl =
191 let rec analyze unused unrecognized useless =
194 if unrecognized != [] then
195 raise (DisambiguateTypes.Invalid_choice
197 (loc,"Unrecognized constructors: " ^
198 String.concat " " unrecognized)))
199 else if useless > 0 then
200 raise (DisambiguateTypes.Invalid_choice
202 (loc,"The last " ^ string_of_int useless ^
203 "case" ^ if useless > 1 then "s are" else " is" ^
207 | (Ast.Wildcard,_)::tl when not unused ->
208 analyze true unrecognized useless tl
209 | (Ast.Pattern (head,_,_),_)::tl when not unused ->
210 analyze unused (head::unrecognized) useless tl
211 | _::tl -> analyze unused unrecognized (useless + 1) tl
213 analyze false [] 0 branches
214 | (_,name,ty)::cltl ->
215 let rec find_and_remove =
219 (DisambiguateTypes.Invalid_choice
220 (lazy (loc, "Missing case: " ^ name)))
221 | ((Ast.Wildcard, _) as branch :: _) as branches ->
223 | (Ast.Pattern (name',_,_),_) as branch :: tl
227 let found,rest = find_and_remove tl in
230 let branch,tl = find_and_remove branches in
232 Ast.Pattern (name,y,args),term ->
233 if List.length args = count_prod ty - leftsno then
234 ((name,y,args),term)::sort tl cltl
237 (DisambiguateTypes.Invalid_choice
238 (lazy (loc,"Wrong number of arguments for " ^ name)))
239 | Ast.Wildcard,term ->
245 (`Lambda, (CicNotationPt.Ident ("_", None), None),
248 (("wildcard",None,[]),
249 mk_lambdas (count_prod ty - leftsno)) :: sort tl cltl
251 let branches = sort branches cl in
252 NCic.Match (indtype_ref, cic_outtype, cic_term,
253 (List.map do_branch branches))
254 | CicNotationPt.Cast (t1, t2) ->
255 let cic_t1 = aux ~localize loc context t1 in
256 let cic_t2 = aux ~localize loc context t2 in
257 NCic.LetIn ("_",cic_t2,cic_t1, NCic.Rel 1)
258 | CicNotationPt.LetIn ((name, typ), def, body) ->
259 let cic_def = aux ~localize loc context def in
260 let cic_name = cic_name_of_name name in
263 | None -> NCic.Implicit `Type
264 | Some t -> aux ~localize loc context t
266 let cic_body = aux ~localize loc (cic_name :: context) body in
267 NCic.LetIn (cic_name, cic_typ, cic_def, cic_body)
268 | CicNotationPt.LetRec (_kind, _defs, _body) ->
272 (fun acc (_, (name, _), _, _) ->
273 cic_name_of_name name :: acc)
277 let unlocalized_body = aux ~localize:false loc context' body in
278 match unlocalized_body with
279 NCic.Rel n when n <= List.length defs -> `AvoidLetInNoAppl n
280 | NCic.Appl (NCic.Rel n::l) when n <= List.length defs ->
285 let t',subst,metasenv =
286 CicMetaSubst.delift_rels [] [] (List.length defs) t
289 assert (metasenv=[]);
292 (* We can avoid the LetIn. But maybe we need to recompute l'
293 so that it is localized *)
296 CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
297 (* since we avoid the letin, the context has no
299 let l' = List.map (aux ~localize loc context) l in
305 CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
307 `AddLetIn (aux ~localize loc context' body)
309 `AddLetIn unlocalized_body)
312 `AddLetIn (aux ~localize loc context' body)
314 `AddLetIn unlocalized_body
318 (fun (params, (name, typ), body, decr_idx) ->
319 let add_binders kind t =
321 (fun var t -> CicNotationPt.Binder (kind, var, t)) params t
324 aux ~localize loc context' (add_binders `Lambda body) in
326 aux_option ~localize loc context (Some `Type)
327 (HExtlib.map_option (add_binders `Pi) typ) in
329 match cic_name_of_name name with
331 CicNotationPt.fail loc
332 "Recursive functions cannot be anonymous"
333 | NCic.Name name -> name
335 (name, decr_idx, cic_type, cic_body))
340 `Inductive -> NCic.Fix (n,inductiveFuns)
342 let coinductiveFuns =
344 (fun (name, _, typ, body) -> name, typ, body)
347 NCic.CoFix (n,coinductiveFuns)
349 let counter = ref ~-1 in
350 let build_term _ (var,_,ty,_) t =
352 NCic.LetIn (NCic.Name var, fix_or_cofix !counter, ty, t)
355 `AvoidLetInNoAppl n ->
356 let n' = List.length inductiveFuns - n in
358 | `AvoidLetIn (n,l) ->
359 let n' = List.length inductiveFuns - n in
360 NCic.Appl (fix_or_cofix n'::l)
361 | `AddLetIn cic_body ->
362 List.fold_right (build_term inductiveFuns) inductiveFuns
365 | CicNotationPt.Ident _
366 | CicNotationPt.Uri _ when is_path -> raise Disambiguate.PathNotWellFormed
367 | CicNotationPt.Ident (name, subst) ->
368 assert (subst = None);
370 NCic.Rel (find_in_context name context)
372 Disambiguate.resolve ~env ~mk_choice (Id name) (`Args []))
373 | CicNotationPt.Uri (name, subst) ->
374 assert (subst = None);
376 NCic.Const (NRef.reference_of_string name)
377 with NRef.IllFormedReference _ ->
378 CicNotationPt.fail loc "Ill formed reference")
379 | CicNotationPt.Implicit -> NCic.Implicit `Term
380 | CicNotationPt.UserInput -> assert false (*NCic.Implicit (Some `Hole)
381 patterns not implemented *)
382 | CicNotationPt.Num (num, i) ->
383 Disambiguate.resolve ~env ~mk_choice (Num i) (`Num_arg num)
384 | CicNotationPt.Meta (index, subst) ->
387 (function None -> assert false| Some t -> aux ~localize loc context t)
390 NCic.Meta (index, (0, NCic.Ctx cic_subst))
391 | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
392 | CicNotationPt.Sort `Set -> NCic.Sort (NCic.Type
393 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
394 | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
395 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
396 | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
397 [false,NUri.uri_of_string "cic:/matita/pts/CProp.univ"])
398 | CicNotationPt.Symbol (symbol, instance) ->
399 Disambiguate.resolve ~env ~mk_choice
400 (Symbol (symbol, instance)) (`Args [])
401 | _ -> assert false (* god bless Bologna *)
404 (* prerr_endline (NCicPp.ppterm ~metasenv:[] ~context:[] ~subst:[] res); *)
406 and aux_option ~localize loc context annotation = function
407 | None -> NCic.Implicit annotation
408 | Some (CicNotationPt.AttributedTerm (`Loc loc, term)) ->
409 let res = aux_option ~localize loc context annotation (Some term) in
411 NCicUntrusted.NCicHash.add localization_tbl res loc;
413 | Some (CicNotationPt.AttributedTerm (_, term)) ->
414 aux_option ~localize loc context annotation (Some term)
415 | Some CicNotationPt.Implicit -> NCic.Implicit annotation
416 | Some term -> aux ~localize loc context term
418 aux ~localize:true HExtlib.dummy_floc context ast
420 let interpretate_term ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast
423 let context = List.map fst context in
424 interpretate_term ~create_dummy_ids ~context ~env ~uri ~is_path ast
428 let domain_of_term ~context =
429 Disambiguate.domain_of_ast_term ~context
432 let disambiguate_term ~context ~metasenv ~subst ?goal
433 ~mk_implicit ~description_of_alias ~mk_choice
434 ~aliases ~universe ~lookup_in_library
435 (text,prefix_len,term)
437 let mk_localization_tbl x = NCicUntrusted.NCicHash.create x in
440 None -> (fun _ y -> y),(fun x -> x)
443 let _,_,ty = NCicUtils.lookup_meta n metasenv in
444 NCic.LetIn ("_",ty,y,NCic.Rel 1)),
446 | Disambiguate.Ok (t,m,s,ug) ->
448 | NCic.LetIn ("_",_,y,NCic.Rel 1) -> Disambiguate.Ok (y,m,s,ug)
453 MultiPassDisambiguator.disambiguate_thing
454 ~freshen_thing:CicNotationUtil.freshen_term
455 ~context ~metasenv ~initial_ugraph:() ~aliases
456 ~mk_implicit ~description_of_alias
457 ~string_context_of_context:(List.map (fun (x,_) -> Some x))
458 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
459 ~passes:(MultiPassDisambiguator.passes ())
460 ~lookup_in_library ~domain_of_thing:domain_of_term
461 ~interpretate_thing:(interpretate_term ~mk_choice (?create_dummy_ids:None))
462 ~refine_thing:refine_term (text,prefix_len,term)
463 ~mk_localization_tbl ~hint ~subst
465 List.map (function (a,b,c,d,_) -> a,b,c,d) res, b
471 [false, NUri.uri_of_string ("cic:/matita/pts/Type.univ")]
473 [false, NUri.uri_of_string ("cic:/matita/pts/Type"^string_of_int n^".univ")]
477 [false, NUri.uri_of_string ("cic:/matita/pts/CProp.univ")]
479 [false, NUri.uri_of_string ("cic:/matita/pts/CProp"^string_of_int n^".univ")]
481 NCicEnvironment.add_constraint true (mk_type 0) (mk_type 1);
482 NCicEnvironment.add_constraint true (mk_cprop 0) (mk_cprop 1);
483 NCicEnvironment.add_constraint true (mk_cprop 0) (mk_type 1);
484 NCicEnvironment.add_constraint true (mk_type 0) (mk_cprop 1);
485 NCicEnvironment.add_constraint false (mk_cprop 0) (mk_type 0);
486 NCicEnvironment.add_constraint false (mk_type 0) (mk_cprop 0);