1 (* Copyright (C) 2004, HELM Team.
3 * This file is part of HELM, an Hypertextual, Electronic
4 * Library of Mathematics, developed at the Computer Science
5 * Department, University of Bologna, Italy.
7 * HELM is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * HELM is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with HELM; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
26 (* $Id: disambiguate.ml 9178 2008-11-12 12:09:52Z tassi $ *)
30 open DisambiguateTypes
33 module Ast = CicNotationPt
34 module NRef = NReference
36 let debug_print _ = ();;
38 let cic_name_of_name = function
39 | Ast.Ident (n, None) -> n
43 let refine_term metasenv subst context uri term _ ~localization_tbl =
45 debug_print (lazy (sprintf "TEST_INTERPRETATION: %s"
46 (NCicPp.ppterm ~metasenv ~subst ~context term)));
49 try NCicUntrusted.NCicHash.find localization_tbl t
50 with Not_found -> assert false
52 let metasenv, subst, term, _ =
53 NCicRefiner.typeof metasenv subst context term None ~localise
55 Disambiguate.Ok (term, metasenv, subst, ())
57 | NCicRefiner.Uncertain loc_msg ->
58 debug_print (lazy ("UNCERTAIN: [" ^ snd (Lazy.force loc_msg) ^ "] " ^
59 NCicPp.ppterm ~metasenv ~subst ~context term)) ;
60 Disambiguate.Uncertain loc_msg
61 | NCicRefiner.RefineFailure loc_msg ->
62 debug_print (lazy (sprintf "PRUNED:\nterm%s\nmessage:%s"
63 (NCicPp.ppterm ~metasenv ~subst ~context term) (snd(Lazy.force loc_msg))));
64 Disambiguate.Ko loc_msg
67 let resolve (env: codomain_item Environment.t) (item: domain_item) ?(num = "") ?(args = []) () =
68 ignore (env,item,num,args);
72 snd (Environment.find item env) env num args
74 failwith ("Domain item not found: " ^
75 (DisambiguateTypes.string_of_domain_item item))
78 (* TODO move it to Cic *)
79 let find_in_context name context =
80 let rec aux acc = function
81 | [] -> raise Not_found
82 | hd :: _ when hd = name -> acc
83 | _ :: tl -> aux (acc + 1) tl
88 ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast ~localization_tbl
90 (* create_dummy_ids shouldbe used only for interpretating patterns *)
93 let rec aux ~localize loc context = function
94 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
95 let res = aux ~localize loc context term in
96 if localize then NCicUntrusted.NCicHash.add localization_tbl res loc;
98 | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
99 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
100 let cic_args = List.map (aux ~localize loc context) args in
101 resolve env (Symbol (symb, i)) ~args:cic_args ()
102 | CicNotationPt.Appl terms ->
103 NCic.Appl (List.map (aux ~localize loc context) terms)
104 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
105 let cic_type = aux_option ~localize loc context `Type typ in
106 let cic_name = cic_name_of_name var in
107 let cic_body = aux ~localize loc (cic_name :: context) body in
108 (match binder_kind with
109 | `Lambda -> NCic.Lambda (cic_name, cic_type, cic_body)
111 | `Forall -> NCic.Prod (cic_name, cic_type, cic_body)
113 resolve env (Symbol ("exists", 0))
114 ~args:[ cic_type; NCic.Lambda (cic_name, cic_type, cic_body) ] ())
115 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
116 let cic_term = aux ~localize loc context term in
117 let cic_outtype = aux_option ~localize loc context `Term outtype in
118 let do_branch ((_, _, args), term) =
119 let rec do_branch' context = function
120 | [] -> aux ~localize loc context term
121 | (name, typ) :: tl ->
122 let cic_name = cic_name_of_name name in
123 let cic_body = do_branch' (cic_name :: context) tl in
126 | None -> NCic.Implicit `Type
127 | Some typ -> aux ~localize loc context typ
129 NCic.Lambda (cic_name, typ, cic_body)
131 do_branch' context args
133 if create_dummy_ids then
137 Ast.Wildcard,term -> ("wildcard",None,[]), term
139 raise (DisambiguateTypes.Invalid_choice
140 (lazy (loc, "Syntax error: the left hand side of a "^
141 "branch pattern must be \"_\"")))
145 NCic.MutCase (ref, cic_outtype, cic_term,
146 (List.map do_branch branches))
147 *) ignore branches; assert false (* patterns not implemented yet *)
150 match indty_ident with
151 | Some (indty_ident, _) ->
152 (match resolve env (Id indty_ident) () with
155 raise (Disambiguate.Try_again
156 (lazy "The type of the term to be matched is still unknown"))
158 raise (DisambiguateTypes.Invalid_choice
159 (lazy (loc,"The type of the term to be matched "^
160 "is not (co)inductive!"))))
162 let rec fst_constructor =
164 (Ast.Pattern (head, _, _), _) :: _ -> head
165 | (Ast.Wildcard, _) :: tl -> fst_constructor tl
166 | [] -> raise (Invalid_choice (lazy (loc,"The type "^
167 "of the term to be matched cannot be determined "^
168 "because it is an inductive type without constructors "^
169 "or because all patterns use wildcards")))
171 (match resolve env (Id (fst_constructor branches)) () with
174 raise (Disambiguate.Try_again
175 (lazy "The type of the term to be matched is still unknown"))
177 raise (DisambiguateTypes.Invalid_choice
179 "The type of the term to be matched is not (co)inductive!"))))
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 [] 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_def, cic_typ, 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)
375 with Not_found -> resolve env (Id name) ())
376 | CicNotationPt.Uri (name, subst) ->
377 assert (subst = None);
379 NCic.Const (NRef.reference_of_string name)
380 with NRef.IllFormedReference _ ->
381 CicNotationPt.fail loc "Ill formed reference")
382 | CicNotationPt.Implicit -> NCic.Implicit `Term
383 | CicNotationPt.UserInput -> assert false (*NCic.Implicit (Some `Hole)
384 patterns not implemented *)
385 | CicNotationPt.Num (num, i) -> resolve env (Num i) ~num ()
386 | CicNotationPt.Meta (index, subst) ->
389 (function None -> assert false| Some t -> aux ~localize loc context t)
392 NCic.Meta (index, (0, NCic.Ctx cic_subst))
393 | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
394 | CicNotationPt.Sort `Set -> assert false
395 | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
396 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
397 | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
398 [false,NUri.uri_of_string "cic:/matita/pts/CProp.univ"])
399 | CicNotationPt.Symbol (symbol, instance) ->
400 resolve env (Symbol (symbol, instance)) ()
401 | _ -> assert false (* god bless Bologna *)
402 and aux_option ~localize loc context annotation = function
403 | None -> NCic.Implicit annotation
404 | Some term -> aux ~localize loc context term
406 aux ~localize:true HExtlib.dummy_floc context ast
408 let interpretate_term ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast
411 let context = List.map fst context in
412 interpretate_term ~create_dummy_ids ~context ~env ~uri ~is_path ast
416 let domain_of_term ~context =
417 let context = List.map (fun name,_ -> Cic.Name name) context in
418 Disambiguate.domain_of_ast_term ~context
421 module Make (C : DisambiguateTypes.Callbacks) = struct
422 module Disambiguator = Disambiguate.Make(C)
424 let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv ~subst
425 ~aliases ~universe ?goal (text,prefix_len,term)
428 if fresh_instances then CicNotationUtil.freshen_term term else term
430 let localization_tbl = NCicUntrusted.NCicHash.create 503 in
433 None -> (fun _ y -> y),(fun x -> x)
436 let _,_,ty = NCicUtils.lookup_meta n metasenv in
437 NCic.LetIn ("_",ty,y,NCic.Rel 1)),
439 | Disambiguate.Ok (t,m,s,ug) ->
441 | NCic.LetIn ("_",_,y,NCic.Rel 1) -> Disambiguate.Ok (y,m,s,ug)
446 Disambiguator.disambiguate_thing
447 ~dbd ~context ~metasenv ~initial_ugraph:() ~aliases
448 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
449 ~domain_of_thing:domain_of_term
450 ~interpretate_thing:(interpretate_term (?create_dummy_ids:None))
451 ~refine_thing:refine_term (text,prefix_len,term)
452 ~localization_tbl ~hint ~subst
454 List.map (function (a,b,c,d,_) -> a,b,c,d) res, b