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: codomain_item Environment.t) (item: domain_item) ?(num = "") ?(args = []) () =
54 ignore (env,item,num,args);
58 snd (Environment.find item env) env num args
60 failwith ("Domain item not found: " ^
61 (DisambiguateTypes.string_of_domain_item item))
64 (* TODO move it to Cic *)
65 let find_in_context name context =
66 let rec aux acc = function
67 | [] -> raise Not_found
68 | hd :: _ when hd = name -> acc
69 | _ :: tl -> aux (acc + 1) tl
74 ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast ~localization_tbl
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
82 if localize then NCicUntrusted.NCicHash.add localization_tbl res loc;
84 | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
85 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
86 let cic_args = List.map (aux ~localize loc context) args in
87 resolve env (Symbol (symb, i)) ~args:cic_args ()
88 | CicNotationPt.Appl terms ->
89 NCic.Appl (List.map (aux ~localize loc context) terms)
90 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
91 let cic_type = aux_option ~localize loc context `Type typ in
92 let cic_name = cic_name_of_name var in
93 let cic_body = aux ~localize loc (cic_name :: context) body in
94 (match binder_kind with
95 | `Lambda -> NCic.Lambda (cic_name, cic_type, cic_body)
97 | `Forall -> NCic.Prod (cic_name, cic_type, cic_body)
99 resolve env (Symbol ("exists", 0))
100 ~args:[ cic_type; NCic.Lambda (cic_name, cic_type, cic_body) ] ())
101 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
102 let cic_term = aux ~localize loc context term in
103 let cic_outtype = aux_option ~localize loc context `Term outtype in
104 let do_branch ((_, _, args), term) =
105 let rec do_branch' context = function
106 | [] -> aux ~localize loc context term
107 | (name, typ) :: tl ->
108 let cic_name = cic_name_of_name name in
109 let cic_body = do_branch' (cic_name :: context) tl in
112 | None -> NCic.Implicit `Type
113 | Some typ -> aux ~localize loc context typ
115 NCic.Lambda (cic_name, typ, cic_body)
117 do_branch' context args
119 if create_dummy_ids then
123 Ast.Wildcard,term -> ("wildcard",None,[]), term
125 raise (DisambiguateTypes.Invalid_choice
126 (lazy (loc, "Syntax error: the left hand side of a "^
127 "branch pattern must be \"_\"")))
131 NCic.MutCase (ref, cic_outtype, cic_term,
132 (List.map do_branch branches))
133 *) ignore branches; assert false (* patterns not implemented yet *)
136 match indty_ident with
137 | Some (indty_ident, _) ->
138 (match resolve env (Id indty_ident) () with
141 raise (Disambiguate.Try_again
142 (lazy "The type of the term to be matched is still unknown"))
144 raise (DisambiguateTypes.Invalid_choice
145 (lazy (loc,"The type of the term to be matched "^
146 "is not (co)inductive!"))))
148 let rec fst_constructor =
150 (Ast.Pattern (head, _, _), _) :: _ -> head
151 | (Ast.Wildcard, _) :: tl -> fst_constructor tl
152 | [] -> raise (Invalid_choice (lazy (loc,"The type "^
153 "of the term to be matched cannot be determined "^
154 "because it is an inductive type without constructors "^
155 "or because all patterns use wildcards")))
157 (match resolve env (Id (fst_constructor branches)) () with
160 raise (Disambiguate.Try_again
161 (lazy "The type of the term to be matched is still unknown"))
163 raise (DisambiguateTypes.Invalid_choice
165 "The type of the term to be matched is not (co)inductive!"))))
167 let _,leftsno,itl,_,indtyp_no =
168 NCicEnvironment.get_checked_indtys indtype_ref in
171 List.nth itl indtyp_no
172 with _ -> assert false in
173 let rec count_prod t =
174 match NCicReduction.whd [] t with
175 NCic.Prod (_, _, t) -> 1 + (count_prod t)
178 let rec sort branches cl =
181 let rec analyze unused unrecognized useless =
184 if unrecognized != [] then
185 raise (DisambiguateTypes.Invalid_choice
187 (loc,"Unrecognized constructors: " ^
188 String.concat " " unrecognized)))
189 else if useless > 0 then
190 raise (DisambiguateTypes.Invalid_choice
192 (loc,"The last " ^ string_of_int useless ^
193 "case" ^ if useless > 1 then "s are" else " is" ^
197 | (Ast.Wildcard,_)::tl when not unused ->
198 analyze true unrecognized useless tl
199 | (Ast.Pattern (head,_,_),_)::tl when not unused ->
200 analyze unused (head::unrecognized) useless tl
201 | _::tl -> analyze unused unrecognized (useless + 1) tl
203 analyze false [] 0 branches
204 | (_,name,ty)::cltl ->
205 let rec find_and_remove =
209 (DisambiguateTypes.Invalid_choice
210 (lazy (loc, "Missing case: " ^ name)))
211 | ((Ast.Wildcard, _) as branch :: _) as branches ->
213 | (Ast.Pattern (name',_,_),_) as branch :: tl
217 let found,rest = find_and_remove tl in
220 let branch,tl = find_and_remove branches in
222 Ast.Pattern (name,y,args),term ->
223 if List.length args = count_prod ty - leftsno then
224 ((name,y,args),term)::sort tl cltl
227 (DisambiguateTypes.Invalid_choice
228 (lazy (loc,"Wrong number of arguments for " ^ name)))
229 | Ast.Wildcard,term ->
235 (`Lambda, (CicNotationPt.Ident ("_", None), None),
238 (("wildcard",None,[]),
239 mk_lambdas (count_prod ty - leftsno)) :: sort tl cltl
241 let branches = sort branches cl in
242 NCic.Match (indtype_ref, cic_outtype, cic_term,
243 (List.map do_branch branches))
244 | CicNotationPt.Cast (t1, t2) ->
245 let cic_t1 = aux ~localize loc context t1 in
246 let cic_t2 = aux ~localize loc context t2 in
247 NCic.LetIn ("_",cic_t2,cic_t1, NCic.Rel 1)
248 | CicNotationPt.LetIn ((name, typ), def, body) ->
249 let cic_def = aux ~localize loc context def in
250 let cic_name = cic_name_of_name name in
253 | None -> NCic.Implicit `Type
254 | Some t -> aux ~localize loc context t
256 let cic_body = aux ~localize loc (cic_name :: context) body in
257 NCic.LetIn (cic_name, cic_def, cic_typ, cic_body)
258 | CicNotationPt.LetRec (_kind, _defs, _body) ->
262 (fun acc (_, (name, _), _, _) ->
263 cic_name_of_name name :: acc)
267 let unlocalized_body = aux ~localize:false loc context' body in
268 match unlocalized_body with
269 NCic.Rel n when n <= List.length defs -> `AvoidLetInNoAppl n
270 | NCic.Appl (NCic.Rel n::l) when n <= List.length defs ->
275 let t',subst,metasenv =
276 CicMetaSubst.delift_rels [] [] (List.length defs) t
279 assert (metasenv=[]);
282 (* We can avoid the LetIn. But maybe we need to recompute l'
283 so that it is localized *)
286 CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
287 (* since we avoid the letin, the context has no
289 let l' = List.map (aux ~localize loc context) l in
295 CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
297 `AddLetIn (aux ~localize loc context' body)
299 `AddLetIn unlocalized_body)
302 `AddLetIn (aux ~localize loc context' body)
304 `AddLetIn unlocalized_body
308 (fun (params, (name, typ), body, decr_idx) ->
309 let add_binders kind t =
311 (fun var t -> CicNotationPt.Binder (kind, var, t)) params t
314 aux ~localize loc context' (add_binders `Lambda body) in
316 aux_option ~localize loc context (Some `Type)
317 (HExtlib.map_option (add_binders `Pi) typ) in
319 match cic_name_of_name name with
321 CicNotationPt.fail loc
322 "Recursive functions cannot be anonymous"
323 | NCic.Name name -> name
325 (name, decr_idx, cic_type, cic_body))
330 `Inductive -> NCic.Fix (n,inductiveFuns)
332 let coinductiveFuns =
334 (fun (name, _, typ, body) -> name, typ, body)
337 NCic.CoFix (n,coinductiveFuns)
339 let counter = ref ~-1 in
340 let build_term _ (var,_,ty,_) t =
342 NCic.LetIn (NCic.Name var, fix_or_cofix !counter, ty, t)
345 `AvoidLetInNoAppl n ->
346 let n' = List.length inductiveFuns - n in
348 | `AvoidLetIn (n,l) ->
349 let n' = List.length inductiveFuns - n in
350 NCic.Appl (fix_or_cofix n'::l)
351 | `AddLetIn cic_body ->
352 List.fold_right (build_term inductiveFuns) inductiveFuns
355 | CicNotationPt.Ident _
356 | CicNotationPt.Uri _ when is_path -> raise Disambiguate.PathNotWellFormed
357 | CicNotationPt.Ident (name, subst) ->
358 assert (subst = None);
360 NCic.Rel (find_in_context name context)
361 with Not_found -> resolve env (Id name) ())
362 | CicNotationPt.Uri (name, subst) ->
363 assert (subst = None);
365 NCic.Const (NRef.reference_of_string name)
366 with NRef.IllFormedReference _ ->
367 CicNotationPt.fail loc "Ill formed reference")
368 | CicNotationPt.Implicit -> NCic.Implicit `Term
369 | CicNotationPt.UserInput -> assert false (*NCic.Implicit (Some `Hole)
370 patterns not implemented *)
371 | CicNotationPt.Num (num, i) -> resolve env (Num i) ~num ()
372 | CicNotationPt.Meta (index, subst) ->
375 (function None -> assert false| Some t -> aux ~localize loc context t)
378 NCic.Meta (index, (0, NCic.Ctx cic_subst))
379 | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
380 | CicNotationPt.Sort `Set -> assert false
381 | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
382 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
383 | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
384 [false,NUri.uri_of_string "cic:/matita/pts/CProp.univ"])
385 | CicNotationPt.Symbol (symbol, instance) ->
386 resolve env (Symbol (symbol, instance)) ()
387 | _ -> assert false (* god bless Bologna *)
388 and aux_option ~localize loc context annotation = function
389 | None -> NCic.Implicit annotation
390 | Some term -> aux ~localize loc context term
392 aux ~localize:true HExtlib.dummy_floc context ast
394 let interpretate_term ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast
397 let context = List.map fst context in
398 interpretate_term ~create_dummy_ids ~context ~env ~uri ~is_path ast
402 let domain_of_term ~context =
403 let context = List.map (fun name,_ -> Cic.Name name) context in
404 Disambiguate.domain_of_ast_term ~context
407 module Make (C : DisambiguateTypes.Callbacks) = struct
408 module Disambiguator = Disambiguate.Make(C)
410 let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv ~subst
411 ~aliases ~universe ?goal (text,prefix_len,term)
414 if fresh_instances then CicNotationUtil.freshen_term term else term
416 let localization_tbl = NCicUntrusted.NCicHash.create 503 in
419 None -> (fun _ y -> y),(fun x -> x)
422 let _,_,ty = NCicUtils.lookup_meta n metasenv in
423 NCic.LetIn ("_",ty,y,NCic.Rel 1)),
425 | Disambiguate.Ok (t,m,s,ug) ->
427 | NCic.LetIn ("_",_,y,NCic.Rel 1) -> Disambiguate.Ok (y,m,s,ug)
432 Disambiguator.disambiguate_thing
433 ~dbd ~context ~metasenv ~initial_ugraph:() ~aliases
434 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
435 ~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