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) ~mk_choice ~context ~env ~uri ~is_path ast
67 (* create_dummy_ids shouldbe used only for interpretating patterns *)
70 let rec aux ~localize loc context = function
71 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
72 let res = aux ~localize loc context term in
73 if localize then NCicUntrusted.NCicHash.add localization_tbl res loc;
75 | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
76 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
77 let cic_args = List.map (aux ~localize loc context) args in
78 Disambiguate.resolve ~mk_choice ~env (Symbol (symb, i)) (`Args cic_args)
79 | CicNotationPt.Appl terms ->
80 NCic.Appl (List.map (aux ~localize loc context) terms)
81 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
82 let cic_type = aux_option ~localize loc context `Type typ in
83 let cic_name = cic_name_of_name var in
84 let cic_body = aux ~localize loc (cic_name :: context) body in
85 (match binder_kind with
86 | `Lambda -> NCic.Lambda (cic_name, cic_type, cic_body)
88 | `Forall -> NCic.Prod (cic_name, cic_type, cic_body)
90 Disambiguate.resolve ~env ~mk_choice (Symbol ("exists", 0))
91 (`Args [ cic_type; NCic.Lambda (cic_name, cic_type, cic_body) ]))
92 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
93 let cic_term = aux ~localize loc context term in
94 let cic_outtype = aux_option ~localize loc context `Term outtype in
95 let do_branch ((_, _, args), term) =
96 let rec do_branch' context = function
97 | [] -> aux ~localize loc context term
98 | (name, typ) :: tl ->
99 let cic_name = cic_name_of_name name in
100 let cic_body = do_branch' (cic_name :: context) tl in
103 | None -> NCic.Implicit `Type
104 | Some typ -> aux ~localize loc context typ
106 NCic.Lambda (cic_name, typ, cic_body)
108 do_branch' context args
110 if create_dummy_ids then
114 Ast.Wildcard,term -> ("wildcard",None,[]), term
116 raise (DisambiguateTypes.Invalid_choice
117 (lazy (loc, "Syntax error: the left hand side of a "^
118 "branch pattern must be \"_\"")))
122 NCic.MutCase (ref, cic_outtype, cic_term,
123 (List.map do_branch branches))
124 *) ignore branches; assert false (* patterns not implemented yet *)
127 match indty_ident with
128 | Some (indty_ident, _) ->
129 (match Disambiguate.resolve ~env ~mk_choice
130 (Id indty_ident) (`Args []) with
133 raise (Disambiguate.Try_again
134 (lazy "The type of the term to be matched is still unknown"))
136 raise (DisambiguateTypes.Invalid_choice
137 (lazy (loc,"The type of the term to be matched "^
138 "is not (co)inductive!"))))
140 let rec fst_constructor =
142 (Ast.Pattern (head, _, _), _) :: _ -> head
143 | (Ast.Wildcard, _) :: tl -> fst_constructor tl
144 | [] -> raise (Invalid_choice (lazy (loc,"The type "^
145 "of the term to be matched cannot be determined "^
146 "because it is an inductive type without constructors "^
147 "or because all patterns use wildcards")))
149 (match Disambiguate.resolve ~env ~mk_choice
150 (Id (fst_constructor branches)) (`Args []) with
153 raise (Disambiguate.Try_again
154 (lazy "The type of the term to be matched is still unknown"))
156 raise (DisambiguateTypes.Invalid_choice
158 "The type of the term to be matched is not (co)inductive!"))))
160 let _,leftsno,itl,_,indtyp_no =
161 NCicEnvironment.get_checked_indtys indtype_ref in
164 List.nth itl indtyp_no
165 with _ -> assert false in
166 let rec count_prod t =
167 match NCicReduction.whd [] t with
168 NCic.Prod (_, _, t) -> 1 + (count_prod t)
171 let rec sort branches cl =
174 let rec analyze unused unrecognized useless =
177 if unrecognized != [] then
178 raise (DisambiguateTypes.Invalid_choice
180 (loc,"Unrecognized constructors: " ^
181 String.concat " " unrecognized)))
182 else if useless > 0 then
183 raise (DisambiguateTypes.Invalid_choice
185 (loc,"The last " ^ string_of_int useless ^
186 "case" ^ if useless > 1 then "s are" else " is" ^
190 | (Ast.Wildcard,_)::tl when not unused ->
191 analyze true unrecognized useless tl
192 | (Ast.Pattern (head,_,_),_)::tl when not unused ->
193 analyze unused (head::unrecognized) useless tl
194 | _::tl -> analyze unused unrecognized (useless + 1) tl
196 analyze false [] 0 branches
197 | (_,name,ty)::cltl ->
198 let rec find_and_remove =
202 (DisambiguateTypes.Invalid_choice
203 (lazy (loc, "Missing case: " ^ name)))
204 | ((Ast.Wildcard, _) as branch :: _) as branches ->
206 | (Ast.Pattern (name',_,_),_) as branch :: tl
210 let found,rest = find_and_remove tl in
213 let branch,tl = find_and_remove branches in
215 Ast.Pattern (name,y,args),term ->
216 if List.length args = count_prod ty - leftsno then
217 ((name,y,args),term)::sort tl cltl
220 (DisambiguateTypes.Invalid_choice
221 (lazy (loc,"Wrong number of arguments for " ^ name)))
222 | Ast.Wildcard,term ->
228 (`Lambda, (CicNotationPt.Ident ("_", None), None),
231 (("wildcard",None,[]),
232 mk_lambdas (count_prod ty - leftsno)) :: sort tl cltl
234 let branches = sort branches cl in
235 NCic.Match (indtype_ref, cic_outtype, cic_term,
236 (List.map do_branch branches))
237 | CicNotationPt.Cast (t1, t2) ->
238 let cic_t1 = aux ~localize loc context t1 in
239 let cic_t2 = aux ~localize loc context t2 in
240 NCic.LetIn ("_",cic_t2,cic_t1, NCic.Rel 1)
241 | CicNotationPt.LetIn ((name, typ), def, body) ->
242 let cic_def = aux ~localize loc context def in
243 let cic_name = cic_name_of_name name in
246 | None -> NCic.Implicit `Type
247 | Some t -> aux ~localize loc context t
249 let cic_body = aux ~localize loc (cic_name :: context) body in
250 NCic.LetIn (cic_name, cic_def, cic_typ, cic_body)
251 | CicNotationPt.LetRec (_kind, _defs, _body) ->
255 (fun acc (_, (name, _), _, _) ->
256 cic_name_of_name name :: acc)
260 let unlocalized_body = aux ~localize:false loc context' body in
261 match unlocalized_body with
262 NCic.Rel n when n <= List.length defs -> `AvoidLetInNoAppl n
263 | NCic.Appl (NCic.Rel n::l) when n <= List.length defs ->
268 let t',subst,metasenv =
269 CicMetaSubst.delift_rels [] [] (List.length defs) t
272 assert (metasenv=[]);
275 (* We can avoid the LetIn. But maybe we need to recompute l'
276 so that it is localized *)
279 CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
280 (* since we avoid the letin, the context has no
282 let l' = List.map (aux ~localize loc context) l in
288 CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
290 `AddLetIn (aux ~localize loc context' body)
292 `AddLetIn unlocalized_body)
295 `AddLetIn (aux ~localize loc context' body)
297 `AddLetIn unlocalized_body
301 (fun (params, (name, typ), body, decr_idx) ->
302 let add_binders kind t =
304 (fun var t -> CicNotationPt.Binder (kind, var, t)) params t
307 aux ~localize loc context' (add_binders `Lambda body) in
309 aux_option ~localize loc context (Some `Type)
310 (HExtlib.map_option (add_binders `Pi) typ) in
312 match cic_name_of_name name with
314 CicNotationPt.fail loc
315 "Recursive functions cannot be anonymous"
316 | NCic.Name name -> name
318 (name, decr_idx, cic_type, cic_body))
323 `Inductive -> NCic.Fix (n,inductiveFuns)
325 let coinductiveFuns =
327 (fun (name, _, typ, body) -> name, typ, body)
330 NCic.CoFix (n,coinductiveFuns)
332 let counter = ref ~-1 in
333 let build_term _ (var,_,ty,_) t =
335 NCic.LetIn (NCic.Name var, fix_or_cofix !counter, ty, t)
338 `AvoidLetInNoAppl n ->
339 let n' = List.length inductiveFuns - n in
341 | `AvoidLetIn (n,l) ->
342 let n' = List.length inductiveFuns - n in
343 NCic.Appl (fix_or_cofix n'::l)
344 | `AddLetIn cic_body ->
345 List.fold_right (build_term inductiveFuns) inductiveFuns
348 | CicNotationPt.Ident _
349 | CicNotationPt.Uri _ when is_path -> raise Disambiguate.PathNotWellFormed
350 | CicNotationPt.Ident (name, subst) ->
351 assert (subst = None);
353 NCic.Rel (find_in_context name context)
355 Disambiguate.resolve ~env ~mk_choice (Id name) (`Args []))
356 | CicNotationPt.Uri (name, subst) ->
357 assert (subst = None);
359 NCic.Const (NRef.reference_of_string name)
360 with NRef.IllFormedReference _ ->
361 CicNotationPt.fail loc "Ill formed reference")
362 | CicNotationPt.Implicit -> NCic.Implicit `Term
363 | CicNotationPt.UserInput -> assert false (*NCic.Implicit (Some `Hole)
364 patterns not implemented *)
365 | CicNotationPt.Num (num, i) ->
366 Disambiguate.resolve ~env ~mk_choice (Num i) (`Num_arg num)
367 | CicNotationPt.Meta (index, subst) ->
370 (function None -> assert false| Some t -> aux ~localize loc context t)
373 NCic.Meta (index, (0, NCic.Ctx cic_subst))
374 | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
375 | CicNotationPt.Sort `Set -> assert false
376 | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
377 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
378 | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
379 [false,NUri.uri_of_string "cic:/matita/pts/CProp.univ"])
380 | CicNotationPt.Symbol (symbol, instance) ->
381 Disambiguate.resolve ~env ~mk_choice
382 (Symbol (symbol, instance)) (`Args [])
383 | _ -> assert false (* god bless Bologna *)
384 and aux_option ~localize loc context annotation = function
385 | None -> NCic.Implicit annotation
386 | Some (CicNotationPt.AttributedTerm (`Loc loc, term)) ->
387 let res = aux_option ~localize loc context annotation (Some term) in
388 if localize then NCicUntrusted.NCicHash.add localization_tbl res loc;
390 | Some (CicNotationPt.AttributedTerm (_, term)) ->
391 aux_option ~localize loc context annotation (Some term)
392 | Some CicNotationPt.Implicit -> NCic.Implicit annotation
393 | Some term -> aux ~localize loc context term
395 aux ~localize:true HExtlib.dummy_floc context ast
397 let interpretate_term ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast
400 let context = List.map fst context in
401 interpretate_term ~create_dummy_ids ~context ~env ~uri ~is_path ast
405 let domain_of_term ~context =
406 Disambiguate.domain_of_ast_term ~context
409 let disambiguate_term ~context ~metasenv ~subst ?goal
410 ~mk_implicit ~description_of_alias ~mk_choice
411 ~aliases ~universe ~lookup_in_library
412 (text,prefix_len,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 MultiPassDisambiguator.disambiguate_thing
431 ~freshen_thing:CicNotationUtil.freshen_term
432 ~context ~metasenv ~initial_ugraph:() ~aliases
433 ~mk_implicit ~description_of_alias
434 ~string_context_of_context:(List.map (fun (x,_) -> Some x))
435 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
436 ~passes:(MultiPassDisambiguator.passes ())
437 ~lookup_in_library ~domain_of_thing:domain_of_term
438 ~interpretate_thing:(interpretate_term ~mk_choice (?create_dummy_ids:None))
439 ~refine_thing:refine_term (text,prefix_len,term)
440 ~localization_tbl ~hint ~subst
442 List.map (function (a,b,c,d,_) -> a,b,c,d) res, b