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 ~use_coercions:_ 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 (* TODO move it to Cic *)
54 let find_in_context name context =
55 let rec aux acc = function
56 | [] -> raise Not_found
57 | hd :: _ when hd = name -> acc
58 | _ :: tl -> aux (acc + 1) tl
63 ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast ~localization_tbl
65 (* create_dummy_ids shouldbe used only for interpretating patterns *)
68 let rec aux ~localize loc context = function
69 | CicNotationPt.AttributedTerm (`Loc loc, term) ->
70 let res = aux ~localize loc context term in
71 if localize then NCicUntrusted.NCicHash.add localization_tbl res loc;
73 | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
74 | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
75 let cic_args = List.map (aux ~localize loc context) args in
76 Disambiguate.resolve env (Symbol (symb, i)) ~args:cic_args ()
77 | CicNotationPt.Appl terms ->
78 NCic.Appl (List.map (aux ~localize loc context) terms)
79 | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
80 let cic_type = aux_option ~localize loc context `Type typ in
81 let cic_name = cic_name_of_name var in
82 let cic_body = aux ~localize loc (cic_name :: context) body in
83 (match binder_kind with
84 | `Lambda -> NCic.Lambda (cic_name, cic_type, cic_body)
86 | `Forall -> NCic.Prod (cic_name, cic_type, cic_body)
88 Disambiguate.resolve env (Symbol ("exists", 0))
89 ~args:[ cic_type; NCic.Lambda (cic_name, cic_type, cic_body) ] ())
90 | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
91 let cic_term = aux ~localize loc context term in
92 let cic_outtype = aux_option ~localize loc context `Term outtype in
93 let do_branch ((_, _, args), term) =
94 let rec do_branch' context = function
95 | [] -> aux ~localize loc context term
96 | (name, typ) :: tl ->
97 let cic_name = cic_name_of_name name in
98 let cic_body = do_branch' (cic_name :: context) tl in
101 | None -> NCic.Implicit `Type
102 | Some typ -> aux ~localize loc context typ
104 NCic.Lambda (cic_name, typ, cic_body)
106 do_branch' context args
108 if create_dummy_ids then
112 Ast.Wildcard,term -> ("wildcard",None,[]), term
114 raise (DisambiguateTypes.Invalid_choice
115 (lazy (loc, "Syntax error: the left hand side of a "^
116 "branch pattern must be \"_\"")))
120 NCic.MutCase (ref, cic_outtype, cic_term,
121 (List.map do_branch branches))
122 *) ignore branches; assert false (* patterns not implemented yet *)
125 match indty_ident with
126 | Some (indty_ident, _) ->
127 (match Disambiguate.resolve env (Id indty_ident) () with
130 raise (Disambiguate.Try_again
131 (lazy "The type of the term to be matched is still unknown"))
133 raise (DisambiguateTypes.Invalid_choice
134 (lazy (loc,"The type of the term to be matched "^
135 "is not (co)inductive!"))))
137 let rec fst_constructor =
139 (Ast.Pattern (head, _, _), _) :: _ -> head
140 | (Ast.Wildcard, _) :: tl -> fst_constructor tl
141 | [] -> raise (Invalid_choice (lazy (loc,"The type "^
142 "of the term to be matched cannot be determined "^
143 "because it is an inductive type without constructors "^
144 "or because all patterns use wildcards")))
146 (match Disambiguate.resolve env (Id (fst_constructor branches)) () with
149 raise (Disambiguate.Try_again
150 (lazy "The type of the term to be matched is still unknown"))
152 raise (DisambiguateTypes.Invalid_choice
154 "The type of the term to be matched is not (co)inductive!"))))
156 let _,leftsno,itl,_,indtyp_no =
157 NCicEnvironment.get_checked_indtys indtype_ref in
160 List.nth itl indtyp_no
161 with _ -> assert false in
162 let rec count_prod t =
163 match NCicReduction.whd [] t with
164 NCic.Prod (_, _, t) -> 1 + (count_prod t)
167 let rec sort branches cl =
170 let rec analyze unused unrecognized useless =
173 if unrecognized != [] then
174 raise (DisambiguateTypes.Invalid_choice
176 (loc,"Unrecognized constructors: " ^
177 String.concat " " unrecognized)))
178 else if useless > 0 then
179 raise (DisambiguateTypes.Invalid_choice
181 (loc,"The last " ^ string_of_int useless ^
182 "case" ^ if useless > 1 then "s are" else " is" ^
186 | (Ast.Wildcard,_)::tl when not unused ->
187 analyze true unrecognized useless tl
188 | (Ast.Pattern (head,_,_),_)::tl when not unused ->
189 analyze unused (head::unrecognized) useless tl
190 | _::tl -> analyze unused unrecognized (useless + 1) tl
192 analyze false [] 0 branches
193 | (_,name,ty)::cltl ->
194 let rec find_and_remove =
198 (DisambiguateTypes.Invalid_choice
199 (lazy (loc, "Missing case: " ^ name)))
200 | ((Ast.Wildcard, _) as branch :: _) as branches ->
202 | (Ast.Pattern (name',_,_),_) as branch :: tl
206 let found,rest = find_and_remove tl in
209 let branch,tl = find_and_remove branches in
211 Ast.Pattern (name,y,args),term ->
212 if List.length args = count_prod ty - leftsno then
213 ((name,y,args),term)::sort tl cltl
216 (DisambiguateTypes.Invalid_choice
217 (lazy (loc,"Wrong number of arguments for " ^ name)))
218 | Ast.Wildcard,term ->
224 (`Lambda, (CicNotationPt.Ident ("_", None), None),
227 (("wildcard",None,[]),
228 mk_lambdas (count_prod ty - leftsno)) :: sort tl cltl
230 let branches = sort branches cl in
231 NCic.Match (indtype_ref, cic_outtype, cic_term,
232 (List.map do_branch branches))
233 | CicNotationPt.Cast (t1, t2) ->
234 let cic_t1 = aux ~localize loc context t1 in
235 let cic_t2 = aux ~localize loc context t2 in
236 NCic.LetIn ("_",cic_t2,cic_t1, NCic.Rel 1)
237 | CicNotationPt.LetIn ((name, typ), def, body) ->
238 let cic_def = aux ~localize loc context def in
239 let cic_name = cic_name_of_name name in
242 | None -> NCic.Implicit `Type
243 | Some t -> aux ~localize loc context t
245 let cic_body = aux ~localize loc (cic_name :: context) body in
246 NCic.LetIn (cic_name, cic_def, cic_typ, cic_body)
247 | CicNotationPt.LetRec (_kind, _defs, _body) ->
251 (fun acc (_, (name, _), _, _) ->
252 cic_name_of_name name :: acc)
256 let unlocalized_body = aux ~localize:false loc context' body in
257 match unlocalized_body with
258 NCic.Rel n when n <= List.length defs -> `AvoidLetInNoAppl n
259 | NCic.Appl (NCic.Rel n::l) when n <= List.length defs ->
264 let t',subst,metasenv =
265 CicMetaSubst.delift_rels [] [] (List.length defs) t
268 assert (metasenv=[]);
271 (* We can avoid the LetIn. But maybe we need to recompute l'
272 so that it is localized *)
275 CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
276 (* since we avoid the letin, the context has no
278 let l' = List.map (aux ~localize loc context) l in
284 CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
286 `AddLetIn (aux ~localize loc context' body)
288 `AddLetIn unlocalized_body)
291 `AddLetIn (aux ~localize loc context' body)
293 `AddLetIn unlocalized_body
297 (fun (params, (name, typ), body, decr_idx) ->
298 let add_binders kind t =
300 (fun var t -> CicNotationPt.Binder (kind, var, t)) params t
303 aux ~localize loc context' (add_binders `Lambda body) in
305 aux_option ~localize loc context (Some `Type)
306 (HExtlib.map_option (add_binders `Pi) typ) in
308 match cic_name_of_name name with
310 CicNotationPt.fail loc
311 "Recursive functions cannot be anonymous"
312 | NCic.Name name -> name
314 (name, decr_idx, cic_type, cic_body))
319 `Inductive -> NCic.Fix (n,inductiveFuns)
321 let coinductiveFuns =
323 (fun (name, _, typ, body) -> name, typ, body)
326 NCic.CoFix (n,coinductiveFuns)
328 let counter = ref ~-1 in
329 let build_term _ (var,_,ty,_) t =
331 NCic.LetIn (NCic.Name var, fix_or_cofix !counter, ty, t)
334 `AvoidLetInNoAppl n ->
335 let n' = List.length inductiveFuns - n in
337 | `AvoidLetIn (n,l) ->
338 let n' = List.length inductiveFuns - n in
339 NCic.Appl (fix_or_cofix n'::l)
340 | `AddLetIn cic_body ->
341 List.fold_right (build_term inductiveFuns) inductiveFuns
344 | CicNotationPt.Ident _
345 | CicNotationPt.Uri _ when is_path -> raise Disambiguate.PathNotWellFormed
346 | CicNotationPt.Ident (name, subst) ->
347 assert (subst = None);
349 NCic.Rel (find_in_context name context)
350 with Not_found -> Disambiguate.resolve env (Id name) ())
351 | CicNotationPt.Uri (name, subst) ->
352 assert (subst = None);
354 NCic.Const (NRef.reference_of_string name)
355 with NRef.IllFormedReference _ ->
356 CicNotationPt.fail loc "Ill formed reference")
357 | CicNotationPt.Implicit -> NCic.Implicit `Term
358 | CicNotationPt.UserInput -> assert false (*NCic.Implicit (Some `Hole)
359 patterns not implemented *)
360 | CicNotationPt.Num (num, i) -> Disambiguate.resolve env (Num i) ~num ()
361 | CicNotationPt.Meta (index, subst) ->
364 (function None -> assert false| Some t -> aux ~localize loc context t)
367 NCic.Meta (index, (0, NCic.Ctx cic_subst))
368 | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
369 | CicNotationPt.Sort `Set -> assert false
370 | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
371 [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
372 | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
373 [false,NUri.uri_of_string "cic:/matita/pts/CProp.univ"])
374 | CicNotationPt.Symbol (symbol, instance) ->
375 Disambiguate.resolve env (Symbol (symbol, instance)) ()
376 | _ -> assert false (* god bless Bologna *)
377 and aux_option ~localize loc context annotation = function
378 | None -> NCic.Implicit annotation
379 | Some term -> aux ~localize loc context term
381 aux ~localize:true HExtlib.dummy_floc context ast
383 let interpretate_term ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast
386 let context = List.map fst context in
387 interpretate_term ~create_dummy_ids ~context ~env ~uri ~is_path ast
391 let domain_of_term ~context =
392 Disambiguate.domain_of_ast_term ~context
395 let disambiguate_term ~context ~metasenv ~subst ?goal
396 ~aliases ~universe ~lookup_in_library
397 (text,prefix_len,term)
399 let localization_tbl = NCicUntrusted.NCicHash.create 503 in
402 None -> (fun _ y -> y),(fun x -> x)
405 let _,_,ty = NCicUtils.lookup_meta n metasenv in
406 NCic.LetIn ("_",ty,y,NCic.Rel 1)),
408 | Disambiguate.Ok (t,m,s,ug) ->
410 | NCic.LetIn ("_",_,y,NCic.Rel 1) -> Disambiguate.Ok (y,m,s,ug)
415 MultiPassDisambiguator.disambiguate_thing
416 ~freshen_thing:CicNotationUtil.freshen_term
417 ~context ~metasenv ~initial_ugraph:() ~aliases
418 ~string_context_of_context:(List.map (fun (x,_) -> Some x))
419 ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
420 ~mk_implicit:(function false -> NCic.Implicit `Term
421 | true -> NCic.Implicit `Closed)
422 ~passes:(MultiPassDisambiguator.passes ())
423 ~lookup_in_library ~domain_of_thing:domain_of_term
424 ~interpretate_thing:(interpretate_term (?create_dummy_ids:None))
425 ~refine_thing:refine_term (text,prefix_len,term)
426 ~localization_tbl ~hint ~subst
428 List.map (function (a,b,c,d,_) -> a,b,c,d) res, b