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
37 with Not_found -> assert false
39 let metasenv, subst, term, _ =
40 NCicRefiner.typeof metasenv subst context term None ~localise
42 Disambiguate.Ok (term, metasenv, subst, ())
44 | NCicRefiner.Uncertain loc_msg ->
45 debug_print (lazy ("UNCERTAIN: [" ^ snd (Lazy.force loc_msg) ^ "] " ^
46 NCicPp.ppterm ~metasenv ~subst ~context term)) ;
47 Disambiguate.Uncertain loc_msg
48 | NCicRefiner.RefineFailure loc_msg ->
49 debug_print (lazy (sprintf "PRUNED:\nterm%s\nmessage:%s"
50 (NCicPp.ppterm ~metasenv ~subst ~context term) (snd(Lazy.force loc_msg))));
51 Disambiguate.Ko loc_msg
54 (* TODO move it to Cic *)
55 let find_in_context name context =
56 let rec aux acc = function
57 | [] -> raise Not_found
58 | hd :: _ when hd = name -> acc
59 | _ :: tl -> aux (acc + 1) tl
64 ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast ~localization_tbl
66 (* create_dummy_ids shouldbe used only for interpretating patterns *)
69 let rec aux ~localize loc context = function
70 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
71 let res = aux ~localize loc context term in
72 if localize then NCicUntrusted.NCicHash.add localization_tbl res loc;
74 | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
75 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
76 let cic_args = List.map (aux ~localize loc context) args in
77 Disambiguate.resolve env (Symbol (symb, i)) ~args:cic_args ()
78 | CicNotationPt.Appl terms ->
79 NCic.Appl (List.map (aux ~localize loc context) terms)
80 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
81 let cic_type = aux_option ~localize loc context `Type typ in
82 let cic_name = cic_name_of_name var in
83 let cic_body = aux ~localize loc (cic_name :: context) body in
84 (match binder_kind with
85 | `Lambda -> NCic.Lambda (cic_name, cic_type, cic_body)
87 | `Forall -> NCic.Prod (cic_name, cic_type, cic_body)
89 Disambiguate.resolve env (Symbol ("exists", 0))
90 ~args:[ cic_type; NCic.Lambda (cic_name, cic_type, cic_body) ] ())
91 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
92 let cic_term = aux ~localize loc context term in
93 let cic_outtype = aux_option ~localize loc context `Term outtype in
94 let do_branch ((_, _, args), term) =
95 let rec do_branch' context = function
96 | [] -> aux ~localize loc context term
97 | (name, typ) :: tl ->
98 let cic_name = cic_name_of_name name in
99 let cic_body = do_branch' (cic_name :: context) tl in
102 | None -> NCic.Implicit `Type
103 | Some typ -> aux ~localize loc context typ
105 NCic.Lambda (cic_name, typ, cic_body)
107 do_branch' context args
109 if create_dummy_ids then
113 Ast.Wildcard,term -> ("wildcard",None,[]), term
115 raise (DisambiguateTypes.Invalid_choice
116 (lazy (loc, "Syntax error: the left hand side of a "^
117 "branch pattern must be \"_\"")))
121 NCic.MutCase (ref, cic_outtype, cic_term,
122 (List.map do_branch branches))
123 *) ignore branches; assert false (* patterns not implemented yet *)
126 match indty_ident with
127 | Some (indty_ident, _) ->
128 (match Disambiguate.resolve env (Id indty_ident) () with
131 raise (Disambiguate.Try_again
132 (lazy "The type of the term to be matched is still unknown"))
134 raise (DisambiguateTypes.Invalid_choice
135 (lazy (loc,"The type of the term to be matched "^
136 "is not (co)inductive!"))))
138 let rec fst_constructor =
140 (Ast.Pattern (head, _, _), _) :: _ -> head
141 | (Ast.Wildcard, _) :: tl -> fst_constructor tl
142 | [] -> raise (Invalid_choice (lazy (loc,"The type "^
143 "of the term to be matched cannot be determined "^
144 "because it is an inductive type without constructors "^
145 "or because all patterns use wildcards")))
147 (match Disambiguate.resolve env (Id (fst_constructor branches)) () with
150 raise (Disambiguate.Try_again
151 (lazy "The type of the term to be matched is still unknown"))
153 raise (DisambiguateTypes.Invalid_choice
155 "The type of the term to be matched is not (co)inductive!"))))
157 let _,leftsno,itl,_,indtyp_no =
158 NCicEnvironment.get_checked_indtys indtype_ref in
161 List.nth itl indtyp_no
162 with _ -> assert false in
163 let rec count_prod t =
164 match NCicReduction.whd [] t with
165 NCic.Prod (_, _, t) -> 1 + (count_prod t)
168 let rec sort branches cl =
171 let rec analyze unused unrecognized useless =
174 if unrecognized != [] then
175 raise (DisambiguateTypes.Invalid_choice
177 (loc,"Unrecognized constructors: " ^
178 String.concat " " unrecognized)))
179 else if useless > 0 then
180 raise (DisambiguateTypes.Invalid_choice
182 (loc,"The last " ^ string_of_int useless ^
183 "case" ^ if useless > 1 then "s are" else " is" ^
187 | (Ast.Wildcard,_)::tl when not unused ->
188 analyze true unrecognized useless tl
189 | (Ast.Pattern (head,_,_),_)::tl when not unused ->
190 analyze unused (head::unrecognized) useless tl
191 | _::tl -> analyze unused unrecognized (useless + 1) tl
193 analyze false [] 0 branches
194 | (_,name,ty)::cltl ->
195 let rec find_and_remove =
199 (DisambiguateTypes.Invalid_choice
200 (lazy (loc, "Missing case: " ^ name)))
201 | ((Ast.Wildcard, _) as branch :: _) as branches ->
203 | (Ast.Pattern (name',_,_),_) as branch :: tl
207 let found,rest = find_and_remove tl in
210 let branch,tl = find_and_remove branches in
212 Ast.Pattern (name,y,args),term ->
213 if List.length args = count_prod ty - leftsno then
214 ((name,y,args),term)::sort tl cltl
217 (DisambiguateTypes.Invalid_choice
218 (lazy (loc,"Wrong number of arguments for " ^ name)))
219 | Ast.Wildcard,term ->
225 (`Lambda, (CicNotationPt.Ident ("_", None), None),
228 (("wildcard",None,[]),
229 mk_lambdas (count_prod ty - leftsno)) :: sort tl cltl
231 let branches = sort branches cl in
232 NCic.Match (indtype_ref, cic_outtype, cic_term,
233 (List.map do_branch branches))
234 | CicNotationPt.Cast (t1, t2) ->
235 let cic_t1 = aux ~localize loc context t1 in
236 let cic_t2 = aux ~localize loc context t2 in
237 NCic.LetIn ("_",cic_t2,cic_t1, NCic.Rel 1)
238 | CicNotationPt.LetIn ((name, typ), def, body) ->
239 let cic_def = aux ~localize loc context def in
240 let cic_name = cic_name_of_name name in
243 | None -> NCic.Implicit `Type
244 | Some t -> aux ~localize loc context t
246 let cic_body = aux ~localize loc (cic_name :: context) body in
247 NCic.LetIn (cic_name, cic_def, cic_typ, cic_body)
248 | CicNotationPt.LetRec (_kind, _defs, _body) ->
252 (fun acc (_, (name, _), _, _) ->
253 cic_name_of_name name :: acc)
257 let unlocalized_body = aux ~localize:false loc context' body in
258 match unlocalized_body with
259 NCic.Rel n when n <= List.length defs -> `AvoidLetInNoAppl n
260 | NCic.Appl (NCic.Rel n::l) when n <= List.length defs ->
265 let t',subst,metasenv =
266 CicMetaSubst.delift_rels [] [] (List.length defs) t
269 assert (metasenv=[]);
272 (* We can avoid the LetIn. But maybe we need to recompute l'
273 so that it is localized *)
276 CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
277 (* since we avoid the letin, the context has no
279 let l' = List.map (aux ~localize loc context) l in
285 CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
287 `AddLetIn (aux ~localize loc context' body)
289 `AddLetIn unlocalized_body)
292 `AddLetIn (aux ~localize loc context' body)
294 `AddLetIn unlocalized_body
298 (fun (params, (name, typ), body, decr_idx) ->
299 let add_binders kind t =
301 (fun var t -> CicNotationPt.Binder (kind, var, t)) params t
304 aux ~localize loc context' (add_binders `Lambda body) in
306 aux_option ~localize loc context (Some `Type)
307 (HExtlib.map_option (add_binders `Pi) typ) in
309 match cic_name_of_name name with
311 CicNotationPt.fail loc
312 "Recursive functions cannot be anonymous"
313 | NCic.Name name -> name
315 (name, decr_idx, cic_type, cic_body))
320 `Inductive -> NCic.Fix (n,inductiveFuns)
322 let coinductiveFuns =
324 (fun (name, _, typ, body) -> name, typ, body)
327 NCic.CoFix (n,coinductiveFuns)
329 let counter = ref ~-1 in
330 let build_term _ (var,_,ty,_) t =
332 NCic.LetIn (NCic.Name var, fix_or_cofix !counter, ty, t)
335 `AvoidLetInNoAppl n ->
336 let n' = List.length inductiveFuns - n in
338 | `AvoidLetIn (n,l) ->
339 let n' = List.length inductiveFuns - n in
340 NCic.Appl (fix_or_cofix n'::l)
341 | `AddLetIn cic_body ->
342 List.fold_right (build_term inductiveFuns) inductiveFuns
345 | CicNotationPt.Ident _
346 | CicNotationPt.Uri _ when is_path -> raise Disambiguate.PathNotWellFormed
347 | CicNotationPt.Ident (name, subst) ->
348 assert (subst = None);
350 NCic.Rel (find_in_context name context)
351 with Not_found -> Disambiguate.resolve env (Id name) ())
352 | CicNotationPt.Uri (name, subst) ->
353 assert (subst = None);
355 NCic.Const (NRef.reference_of_string name)
356 with NRef.IllFormedReference _ ->
357 CicNotationPt.fail loc "Ill formed reference")
358 | CicNotationPt.Implicit -> NCic.Implicit `Term
359 | CicNotationPt.UserInput -> assert false (*NCic.Implicit (Some `Hole)
360 patterns not implemented *)
361 | CicNotationPt.Num (num, i) -> Disambiguate.resolve env (Num i) ~num ()
362 | CicNotationPt.Meta (index, subst) ->
365 (function None -> assert false| Some t -> aux ~localize loc context t)
368 NCic.Meta (index, (0, NCic.Ctx cic_subst))
369 | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
370 | CicNotationPt.Sort `Set -> assert false
371 | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
372 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
373 | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
374 [false,NUri.uri_of_string "cic:/matita/pts/CProp.univ"])
375 | CicNotationPt.Symbol (symbol, instance) ->
376 Disambiguate.resolve env (Symbol (symbol, instance)) ()
377 | _ -> assert false (* god bless Bologna *)
378 and aux_option ~localize loc context annotation = function
379 | None -> NCic.Implicit annotation
380 | Some (CicNotationPt.AttributedTerm (`Loc loc, term)) ->
381 let res = aux_option ~localize loc context annotation (Some term) in
382 if localize then NCicUntrusted.NCicHash.add localization_tbl res loc;
384 | Some (CicNotationPt.AttributedTerm (_, term)) ->
385 aux_option ~localize loc context annotation (Some term)
386 | Some CicNotationPt.Implicit -> 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 Disambiguate.domain_of_ast_term ~context
403 let disambiguate_term ~context ~metasenv ~subst ?goal
404 ~aliases ~universe ~lookup_in_library
405 (text,prefix_len,term)
407 let localization_tbl = NCicUntrusted.NCicHash.create 503 in
410 None -> (fun _ y -> y),(fun x -> x)
413 let _,_,ty = NCicUtils.lookup_meta n metasenv in
414 NCic.LetIn ("_",ty,y,NCic.Rel 1)),
416 | Disambiguate.Ok (t,m,s,ug) ->
418 | NCic.LetIn ("_",_,y,NCic.Rel 1) -> Disambiguate.Ok (y,m,s,ug)
423 MultiPassDisambiguator.disambiguate_thing
424 ~freshen_thing:CicNotationUtil.freshen_term
425 ~context ~metasenv ~initial_ugraph:() ~aliases
426 ~string_context_of_context:(List.map (fun (x,_) -> Some x))
427 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
428 ~mk_implicit:(function false -> NCic.Implicit `Term
429 | true -> NCic.Implicit `Closed)
430 ~passes:(MultiPassDisambiguator.passes ())
431 ~lookup_in_library ~domain_of_thing:domain_of_term
432 ~interpretate_thing:(interpretate_term (?create_dummy_ids:None))
433 ~refine_thing:refine_term (text,prefix_len,term)
434 ~localization_tbl ~hint ~subst
436 List.map (function (a,b,c,d,_) -> a,b,c,d) res, b