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 _ = ();;
24 let cic_name_of_name = function
25 | Ast.Ident (n, None) -> n
29 let refine_term metasenv subst context uri term _ ~localization_tbl =
31 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s"
32 (NCicPp.ppterm ~metasenv ~subst ~context term)));
35 try NCicUntrusted.NCicHash.find localization_tbl t
36 with Not_found -> assert false
38 let metasenv, subst, term, _ =
39 NCicRefiner.typeof metasenv subst context term None ~localise
41 Disambiguate.Ok (term, metasenv, subst, ())
43 | NCicRefiner.Uncertain loc_msg ->
44 debug_print (lazy ("UNCERTAIN: [" ^ snd (Lazy.force loc_msg) ^ "] " ^
45 NCicPp.ppterm ~metasenv ~subst ~context term)) ;
46 Disambiguate.Uncertain loc_msg
47 | NCicRefiner.RefineFailure loc_msg ->
48 debug_print (lazy (sprintf "PRUNED:\nterm%s\nmessage:%s"
49 (NCicPp.ppterm ~metasenv ~subst ~context term) (snd(Lazy.force loc_msg))));
50 Disambiguate.Ko loc_msg
53 let resolve (env: NCic.term codomain_item Environment.t) (item: domain_item) ?(num = "") ?(args = []) () =
54 ignore (env,item,num,args);
56 snd (Environment.find item env) env num args
58 failwith ("Domain item not found: " ^
59 (DisambiguateTypes.string_of_domain_item item))
61 (* TODO move it to Cic *)
62 let find_in_context name context =
63 let rec aux acc = function
64 | [] -> raise Not_found
65 | hd :: _ when hd = name -> acc
66 | _ :: tl -> aux (acc + 1) tl
71 ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast ~localization_tbl
73 (* create_dummy_ids shouldbe used only for interpretating patterns *)
76 let rec aux ~localize loc context = function
77 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
78 let res = aux ~localize loc context term in
79 if localize then 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 resolve 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 resolve env (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 resolve env (Id indty_ident) () with
138 raise (Disambiguate.Try_again
139 (lazy "The type of the term to be matched is still unknown"))
141 raise (DisambiguateTypes.Invalid_choice
142 (lazy (loc,"The type of the term to be matched "^
143 "is not (co)inductive!"))))
145 let rec fst_constructor =
147 (Ast.Pattern (head, _, _), _) :: _ -> head
148 | (Ast.Wildcard, _) :: tl -> fst_constructor tl
149 | [] -> raise (Invalid_choice (lazy (loc,"The type "^
150 "of the term to be matched cannot be determined "^
151 "because it is an inductive type without constructors "^
152 "or because all patterns use wildcards")))
154 (match resolve env (Id (fst_constructor branches)) () with
157 raise (Disambiguate.Try_again
158 (lazy "The type of the term to be matched is still unknown"))
160 raise (DisambiguateTypes.Invalid_choice
162 "The type of the term to be matched is not (co)inductive!"))))
164 let _,leftsno,itl,_,indtyp_no =
165 NCicEnvironment.get_checked_indtys indtype_ref in
168 List.nth itl indtyp_no
169 with _ -> assert false in
170 let rec count_prod t =
171 match NCicReduction.whd [] t with
172 NCic.Prod (_, _, t) -> 1 + (count_prod t)
175 let rec sort branches cl =
178 let rec analyze unused unrecognized useless =
181 if unrecognized != [] then
182 raise (DisambiguateTypes.Invalid_choice
184 (loc,"Unrecognized constructors: " ^
185 String.concat " " unrecognized)))
186 else if useless > 0 then
187 raise (DisambiguateTypes.Invalid_choice
189 (loc,"The last " ^ string_of_int useless ^
190 "case" ^ if useless > 1 then "s are" else " is" ^
194 | (Ast.Wildcard,_)::tl when not unused ->
195 analyze true unrecognized useless tl
196 | (Ast.Pattern (head,_,_),_)::tl when not unused ->
197 analyze unused (head::unrecognized) useless tl
198 | _::tl -> analyze unused unrecognized (useless + 1) tl
200 analyze false [] 0 branches
201 | (_,name,ty)::cltl ->
202 let rec find_and_remove =
206 (DisambiguateTypes.Invalid_choice
207 (lazy (loc, "Missing case: " ^ name)))
208 | ((Ast.Wildcard, _) as branch :: _) as branches ->
210 | (Ast.Pattern (name',_,_),_) as branch :: tl
214 let found,rest = find_and_remove tl in
217 let branch,tl = find_and_remove branches in
219 Ast.Pattern (name,y,args),term ->
220 if List.length args = count_prod ty - leftsno then
221 ((name,y,args),term)::sort tl cltl
224 (DisambiguateTypes.Invalid_choice
225 (lazy (loc,"Wrong number of arguments for " ^ name)))
226 | Ast.Wildcard,term ->
232 (`Lambda, (CicNotationPt.Ident ("_", None), None),
235 (("wildcard",None,[]),
236 mk_lambdas (count_prod ty - leftsno)) :: sort tl cltl
238 let branches = sort branches cl in
239 NCic.Match (indtype_ref, cic_outtype, cic_term,
240 (List.map do_branch branches))
241 | CicNotationPt.Cast (t1, t2) ->
242 let cic_t1 = aux ~localize loc context t1 in
243 let cic_t2 = aux ~localize loc context t2 in
244 NCic.LetIn ("_",cic_t2,cic_t1, NCic.Rel 1)
245 | CicNotationPt.LetIn ((name, typ), def, body) ->
246 let cic_def = aux ~localize loc context def in
247 let cic_name = cic_name_of_name name in
250 | None -> NCic.Implicit `Type
251 | Some t -> aux ~localize loc context t
253 let cic_body = aux ~localize loc (cic_name :: context) body in
254 NCic.LetIn (cic_name, cic_def, cic_typ, cic_body)
255 | CicNotationPt.LetRec (_kind, _defs, _body) ->
259 (fun acc (_, (name, _), _, _) ->
260 cic_name_of_name name :: acc)
264 let unlocalized_body = aux ~localize:false loc context' body in
265 match unlocalized_body with
266 NCic.Rel n when n <= List.length defs -> `AvoidLetInNoAppl n
267 | NCic.Appl (NCic.Rel n::l) when n <= List.length defs ->
272 let t',subst,metasenv =
273 CicMetaSubst.delift_rels [] [] (List.length defs) t
276 assert (metasenv=[]);
279 (* We can avoid the LetIn. But maybe we need to recompute l'
280 so that it is localized *)
283 CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
284 (* since we avoid the letin, the context has no
286 let l' = List.map (aux ~localize loc context) l in
292 CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
294 `AddLetIn (aux ~localize loc context' body)
296 `AddLetIn unlocalized_body)
299 `AddLetIn (aux ~localize loc context' body)
301 `AddLetIn unlocalized_body
305 (fun (params, (name, typ), body, decr_idx) ->
306 let add_binders kind t =
308 (fun var t -> CicNotationPt.Binder (kind, var, t)) params t
311 aux ~localize loc context' (add_binders `Lambda body) in
313 aux_option ~localize loc context (Some `Type)
314 (HExtlib.map_option (add_binders `Pi) typ) in
316 match cic_name_of_name name with
318 CicNotationPt.fail loc
319 "Recursive functions cannot be anonymous"
320 | NCic.Name name -> name
322 (name, decr_idx, cic_type, cic_body))
327 `Inductive -> NCic.Fix (n,inductiveFuns)
329 let coinductiveFuns =
331 (fun (name, _, typ, body) -> name, typ, body)
334 NCic.CoFix (n,coinductiveFuns)
336 let counter = ref ~-1 in
337 let build_term _ (var,_,ty,_) t =
339 NCic.LetIn (NCic.Name var, fix_or_cofix !counter, ty, t)
342 `AvoidLetInNoAppl n ->
343 let n' = List.length inductiveFuns - n in
345 | `AvoidLetIn (n,l) ->
346 let n' = List.length inductiveFuns - n in
347 NCic.Appl (fix_or_cofix n'::l)
348 | `AddLetIn cic_body ->
349 List.fold_right (build_term inductiveFuns) inductiveFuns
352 | CicNotationPt.Ident _
353 | CicNotationPt.Uri _ when is_path -> raise Disambiguate.PathNotWellFormed
354 | CicNotationPt.Ident (name, subst) ->
355 assert (subst = None);
357 NCic.Rel (find_in_context name context)
358 with Not_found -> resolve env (Id name) ())
359 | CicNotationPt.Uri (name, subst) ->
360 assert (subst = None);
362 NCic.Const (NRef.reference_of_string name)
363 with NRef.IllFormedReference _ ->
364 CicNotationPt.fail loc "Ill formed reference")
365 | CicNotationPt.Implicit -> NCic.Implicit `Term
366 | CicNotationPt.UserInput -> assert false (*NCic.Implicit (Some `Hole)
367 patterns not implemented *)
368 | CicNotationPt.Num (num, i) -> resolve env (Num i) ~num ()
369 | CicNotationPt.Meta (index, subst) ->
372 (function None -> assert false| Some t -> aux ~localize loc context t)
375 NCic.Meta (index, (0, NCic.Ctx cic_subst))
376 | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
377 | CicNotationPt.Sort `Set -> assert false
378 | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
379 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
380 | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
381 [false,NUri.uri_of_string "cic:/matita/pts/CProp.univ"])
382 | CicNotationPt.Symbol (symbol, instance) ->
383 resolve env (Symbol (symbol, instance)) ()
384 | _ -> assert false (* god bless Bologna *)
385 and aux_option ~localize loc context annotation = function
386 | None -> NCic.Implicit annotation
387 | Some term -> aux ~localize loc context term
389 aux ~localize:true HExtlib.dummy_floc context ast
391 let interpretate_term ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast
394 let context = List.map fst context in
395 interpretate_term ~create_dummy_ids ~context ~env ~uri ~is_path ast
399 let domain_of_term ~context =
400 let context = List.map (fun name,_ -> Cic.Name name) context in
401 Disambiguate.domain_of_ast_term ~context
404 module Make (C : DisambiguateTypes.Callbacks) = struct
405 module Disambiguator = Disambiguate.Make(C)
407 let disambiguate_term ?(fresh_instances=false) ~context ~metasenv ~subst
408 ~aliases ~universe ~lookup_in_library ?goal
409 (text,prefix_len,term)
412 if fresh_instances then CicNotationUtil.freshen_term term else term
414 let localization_tbl = NCicUntrusted.NCicHash.create 503 in
417 None -> (fun _ y -> y),(fun x -> x)
420 let _,_,ty = NCicUtils.lookup_meta n metasenv in
421 NCic.LetIn ("_",ty,y,NCic.Rel 1)),
423 | Disambiguate.Ok (t,m,s,ug) ->
425 | NCic.LetIn ("_",_,y,NCic.Rel 1) -> Disambiguate.Ok (y,m,s,ug)
430 Disambiguator.disambiguate_thing
431 ~context ~metasenv ~initial_ugraph:() ~aliases
432 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
433 ~mk_implicit:(function None -> NCic.Implicit `Term
434 | Some `Closed -> NCic.Implicit `Closed)
435 ~lookup_in_library ~domain_of_thing:domain_of_term
436 ~interpretate_thing:(interpretate_term (?create_dummy_ids:None))
437 ~refine_thing:refine_term (text,prefix_len,term)
438 ~localization_tbl ~hint ~subst
440 List.map (function (a,b,c,d,_) -> a,b,c,d) res, b