]> matita.cs.unibo.it Git - helm.git/blob - components/tactics/proofEngineHelpers.ml
- ProofEngineHelpers: namer_of moved to GrafiteEngine
[helm.git] / components / tactics / proofEngineHelpers.ml
1 (* Copyright (C) 2002, HELM Team.
2  * 
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.
6  * 
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.
11  * 
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.
16  *
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,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 (* $Id$ *)
27
28 exception Bad_pattern of string Lazy.t
29
30 let new_meta_of_proof ~proof:(_, metasenv, _, _, _, _) =
31   CicMkImplicit.new_meta metasenv []
32
33 let subst_meta_in_proof proof meta term newmetasenv =
34  let uri,metasenv,initial_subst,bo,ty, attrs = proof in
35    (* empty context is ok for term since it wont be used by apply_subst *)
36    (* hack: since we do not know the context and the type of term, we
37       create a substitution with cc =[] and type = Implicit; they will be
38       in  any case dropped by apply_subst, but it would be better to rewrite
39       the code. Cannot we just use apply_subst_metasenv, etc. ?? *)
40   let subst_in = CicMetaSubst.apply_subst [meta,([], term,Cic.Implicit None)] in
41    let metasenv' =
42     newmetasenv @ (List.filter (function (m,_,_) -> m <> meta) metasenv)
43    in
44     let metasenv'' =
45      List.map
46       (function i,canonical_context,ty ->
47         let canonical_context' =
48          List.map
49           (function
50               Some (n,Cic.Decl s) -> Some (n,Cic.Decl (subst_in s))
51             | Some (n,Cic.Def (s,None)) -> Some (n,Cic.Def (subst_in s,None))
52             | None -> None
53             | Some (n,Cic.Def (bo,Some ty)) ->
54                Some (n,Cic.Def (subst_in bo,Some (subst_in ty)))
55           ) canonical_context
56         in
57          i,canonical_context',(subst_in ty)
58       ) metasenv'
59     in
60      let bo' = subst_in bo in
61      (* Metavariables can appear also in the *statement* of the theorem
62       * since the parser does not reject as statements terms with
63       * metavariable therein *)
64      let ty' = subst_in ty in
65       let newproof = uri,metasenv'',initial_subst,bo',ty', attrs in
66        (newproof, metasenv'')
67
68 (*CSC: commento vecchio *)
69 (* refine_meta_with_brand_new_metasenv meta term subst_in newmetasenv     *)
70 (* This (heavy) function must be called when a tactic can instantiate old *)
71 (* metavariables (i.e. existential variables). It substitues the metasenv *)
72 (* of the proof with the result of removing [meta] from the domain of     *)
73 (* [newmetasenv]. Then it replaces Cic.Meta [meta] with [term] everywhere *)
74 (* in the current proof. Finally it applies [apply_subst_replacing] to    *)
75 (*  current proof.                                                        *)
76 (*CSC: A questo punto perche' passare un bo' gia' istantiato, se tanto poi *)
77 (*CSC: ci ripasso sopra apply_subst!!!                                     *)
78 (*CSC: Attenzione! Ora questa funzione applica anche [subst_in] a *)
79 (*CSC: [newmetasenv].                                             *)
80 let subst_meta_and_metasenv_in_proof proof meta subst newmetasenv =
81  let (uri,_,initial_subst,bo,ty, attrs) = proof in
82   let subst_in = CicMetaSubst.apply_subst subst in
83   let bo' = subst_in bo in
84   (* Metavariables can appear also in the *statement* of the theorem
85    * since the parser does not reject as statements terms with
86    * metavariable therein *)
87   let ty' = subst_in ty in
88   let metasenv' =
89    List.fold_right
90     (fun metasenv_entry i ->
91       match metasenv_entry with
92          (m,canonical_context,ty) when m <> meta ->
93            let canonical_context' =
94             List.map
95              (function
96                  None -> None
97                | Some (i,Cic.Decl t) -> Some (i,Cic.Decl (subst_in t))
98                | Some (i,Cic.Def (t,None))  ->
99                   Some (i,Cic.Def (subst_in t,None))
100                | Some (i,Cic.Def (bo,Some ty)) ->
101                   Some (i,Cic.Def (subst_in bo,Some (subst_in ty)))
102              ) canonical_context
103            in
104             (m,canonical_context',subst_in ty)::i
105        | _ -> i
106     ) newmetasenv []
107   in
108   (* qui da capire se per la fase transitoria si fa initial_subst @ subst
109    * oppure subst *)
110    let newproof = uri,metasenv',subst,bo',ty', attrs in
111     (newproof, metasenv')
112
113 let compare_metasenvs ~oldmetasenv ~newmetasenv =
114  List.map (function (i,_,_) -> i)
115   (List.filter
116    (function (i,_,_) ->
117      not (List.exists (fun (j,_,_) -> i=j) oldmetasenv)) newmetasenv)
118 ;;
119
120 (** finds the _pointers_ to subterms that are alpha-equivalent to wanted in t *)
121 let find_subterms ~subst ~metasenv ~ugraph ~wanted ~context t =
122   let rec find subst metasenv ugraph context w t =
123    try
124     let subst,metasenv,ugraph =
125      CicUnification.fo_unif_subst subst context metasenv w t ugraph
126     in
127       subst,metasenv,ugraph,[context,t]
128    with
129      CicUnification.UnificationFailure _
130    | CicUnification.Uncertain _ ->
131       match t with
132       | Cic.Sort _ 
133       | Cic.Rel _ -> subst,metasenv,ugraph,[]
134       | Cic.Meta (_, ctx) -> 
135           List.fold_left (
136             fun (subst,metasenv,ugraph,acc) e -> 
137               match e with 
138               | None -> subst,metasenv,ugraph,acc 
139               | Some t ->
140                  let subst,metasenv,ugraph,res =
141                   find subst metasenv ugraph context w t
142                  in
143                   subst,metasenv,ugraph, res @ acc
144           ) (subst,metasenv,ugraph,[]) ctx
145       | Cic.Lambda (name, t1, t2) 
146       | Cic.Prod (name, t1, t2) ->
147          let subst,metasenv,ugraph,rest1 =
148           find subst metasenv ugraph context w t1 in
149          let subst,metasenv,ugraph,rest2 =
150           find subst metasenv ugraph (Some (name, Cic.Decl t1)::context)
151            (CicSubstitution.lift 1 w) t2
152          in
153           subst,metasenv,ugraph,rest1 @ rest2
154       | Cic.LetIn (name, t1, t2) -> 
155          let subst,metasenv,ugraph,rest1 =
156           find subst metasenv ugraph context w t1 in
157          let subst,metasenv,ugraph,rest2 =
158           find subst metasenv ugraph (Some (name, Cic.Def (t1,None))::context)
159            (CicSubstitution.lift 1 w) t2
160          in
161           subst,metasenv,ugraph,rest1 @ rest2
162       | Cic.Appl l -> 
163           List.fold_left
164            (fun (subst,metasenv,ugraph,acc) t ->
165              let subst,metasenv,ugraph,res =
166               find subst metasenv ugraph context w t
167              in
168               subst,metasenv,ugraph,res @ acc)
169            (subst,metasenv,ugraph,[]) l
170       | Cic.Cast (t, ty) ->
171          let subst,metasenv,ugraph,rest =
172           find subst metasenv ugraph context w t in
173          let subst,metasenv,ugraph,resty =
174           find subst metasenv ugraph context w ty
175          in
176           subst,metasenv,ugraph,rest @ resty
177       | Cic.Implicit _ -> assert false
178       | Cic.Const (_, esubst)
179       | Cic.Var (_, esubst) 
180       | Cic.MutInd (_, _, esubst) 
181       | Cic.MutConstruct (_, _, _, esubst) -> 
182           List.fold_left
183            (fun (subst,metasenv,ugraph,acc) (_, t) ->
184              let subst,metasenv,ugraph,res =
185               find subst metasenv ugraph context w t
186              in
187               subst,metasenv,ugraph,res @ acc)
188            (subst,metasenv,ugraph,[]) esubst
189       | Cic.MutCase (_, _, outty, indterm, patterns) -> 
190          let subst,metasenv,ugraph,resoutty =
191           find subst metasenv ugraph context w outty in
192          let subst,metasenv,ugraph,resindterm =
193           find subst metasenv ugraph context w indterm in
194          let subst,metasenv,ugraph,respatterns =
195           List.fold_left
196            (fun (subst,metasenv,ugraph,acc) p ->
197              let subst,metaseng,ugraph,res =
198               find subst metasenv ugraph context w p
199              in
200               subst,metasenv,ugraph,res @ acc
201            ) (subst,metasenv,ugraph,[]) patterns
202          in
203           subst,metasenv,ugraph,resoutty @ resindterm @ respatterns
204       | Cic.Fix (_, funl) -> 
205          let tys =
206           List.map (fun (n,_,ty,_) -> Some (Cic.Name n,(Cic.Decl ty))) funl
207          in
208           List.fold_left (
209             fun (subst,metasenv,ugraph,acc) (_, _, ty, bo) ->
210              let subst,metasenv,ugraph,resty =
211               find subst metasenv ugraph context w ty in
212              let subst,metasenv,ugraph,resbo =
213               find subst metasenv ugraph (tys @ context) w bo
214              in
215               subst,metasenv,ugraph, resty @ resbo @ acc
216           ) (subst,metasenv,ugraph,[]) funl
217       | Cic.CoFix (_, funl) ->
218          let tys =
219           List.map (fun (n,ty,_) -> Some (Cic.Name n,(Cic.Decl ty))) funl
220          in
221           List.fold_left (
222             fun (subst,metasenv,ugraph,acc) (_, ty, bo) ->
223              let subst,metasenv,ugraph,resty =
224               find subst metasenv ugraph context w ty in
225              let subst,metasenv,ugraph,resbo =
226               find subst metasenv ugraph (tys @ context) w bo
227              in
228               subst,metasenv,ugraph, resty @ resbo @ acc
229           ) (subst,metasenv,ugraph,[]) funl
230   in
231   find subst metasenv ugraph context wanted t
232   
233 let select_in_term ~metasenv ~context ~ugraph ~term ~pattern:(wanted,where) =
234   let add_ctx context name entry = (Some (name, entry)) :: context in
235   let map2 error_msg f l1 l2 = 
236     try 
237       List.map2 f l1 l2 
238     with
239     | Invalid_argument _ -> raise (Bad_pattern (lazy error_msg))
240   in
241   let rec aux context where term =
242     match (where, term) with
243     | Cic.Implicit (Some `Hole), t -> [context,t]
244     | Cic.Implicit (Some `Type), t -> []
245     | Cic.Implicit None,_ -> []
246     | Cic.Meta (_, ctxt1), Cic.Meta (_, ctxt2) ->
247         List.concat
248           (map2 "wrong number of argument in explicit substitution"
249             (fun t1 t2 ->
250               (match (t1, t2) with
251                   Some t1, Some t2 -> aux context t1 t2
252                 | _ -> []))
253             ctxt1 ctxt2)
254     | Cic.Cast (te1, ty1), Cic.Cast (te2, ty2) ->
255        aux context te1 te2 @ aux context ty1 ty2
256     | Cic.Prod (Cic.Anonymous, s1, t1), Cic.Prod (name, s2, t2)
257     | Cic.Lambda (Cic.Anonymous, s1, t1), Cic.Lambda (name, s2, t2) ->
258         aux context s1 s2 @ aux (add_ctx context name (Cic.Decl s2)) t1 t2
259     | Cic.Prod (Cic.Name n1, s1, t1), 
260       Cic.Prod ((Cic.Name n2) as name , s2, t2)
261     | Cic.Lambda (Cic.Name n1, s1, t1), 
262       Cic.Lambda ((Cic.Name n2) as name, s2, t2) when n1 = n2->
263         aux context s1 s2 @ aux (add_ctx context name (Cic.Decl s2)) t1 t2
264     | Cic.Prod (name1, s1, t1), Cic.Prod (name2, s2, t2)
265     | Cic.Lambda (name1, s1, t1), Cic.Lambda (name2, s2, t2) -> []
266     | Cic.LetIn (Cic.Anonymous, s1, t1), Cic.LetIn (name, s2, t2) -> 
267         aux context s1 s2 @ aux (add_ctx context name (Cic.Def (s2,None))) t1 t2
268     | Cic.LetIn (Cic.Name n1, s1, t1), 
269       Cic.LetIn ((Cic.Name n2) as name, s2, t2) when n1 = n2-> 
270         aux context s1 s2 @ aux (add_ctx context name (Cic.Def (s2,None))) t1 t2
271     | Cic.LetIn (name1, s1, t1), Cic.LetIn (name2, s2, t2) -> []
272     | Cic.Appl terms1, Cic.Appl terms2 -> auxs context terms1 terms2
273     | Cic.Var (_, subst1), Cic.Var (_, subst2)
274     | Cic.Const (_, subst1), Cic.Const (_, subst2)
275     | Cic.MutInd (_, _, subst1), Cic.MutInd (_, _, subst2)
276     | Cic.MutConstruct (_, _, _, subst1), Cic.MutConstruct (_, _, _, subst2) ->
277         auxs context (List.map snd subst1) (List.map snd subst2)
278     | Cic.MutCase (_, _, out1, t1, pat1), Cic.MutCase (_ , _, out2, t2, pat2) ->
279         aux context out1 out2 @ aux context t1 t2 @ auxs context pat1 pat2
280     | Cic.Fix (_, funs1), Cic.Fix (_, funs2) ->
281        let tys =
282         List.map (fun (n,_,ty,_) -> Some (Cic.Name n,(Cic.Decl ty))) funs2
283        in
284         List.concat
285           (map2 "wrong number of mutually recursive functions"
286             (fun (_, _, ty1, bo1) (_, _, ty2, bo2) -> 
287               aux context ty1 ty2 @ aux (tys @ context) bo1 bo2)
288             funs1 funs2)
289     | Cic.CoFix (_, funs1), Cic.CoFix (_, funs2) ->
290        let tys =
291         List.map (fun (n,ty,_) -> Some (Cic.Name n,(Cic.Decl ty))) funs2
292        in
293         List.concat
294           (map2 "wrong number of mutually co-recursive functions"
295             (fun (_, ty1, bo1) (_, ty2, bo2) ->
296               aux context ty1 ty2 @ aux (tys @ context) bo1 bo2)
297             funs1 funs2)
298     | x,y -> 
299         raise (Bad_pattern 
300                 (lazy (Printf.sprintf "Pattern %s versus term %s" 
301                   (CicPp.ppterm x)
302                   (CicPp.ppterm y))))
303   and auxs context terms1 terms2 =  (* as aux for list of terms *)
304     List.concat (map2 "wrong number of arguments in application"
305       (fun t1 t2 -> aux context t1 t2) terms1 terms2)
306   in
307    let roots =
308      match where with
309      | None -> []
310      | Some where -> aux context where term
311    in
312     match wanted with
313        None -> [],metasenv,ugraph,roots
314      | Some wanted ->
315         let rec find_in_roots =
316          function
317             [] -> [],metasenv,ugraph,[]
318           | (context',where)::tl ->
319              let subst,metasenv,ugraph,tl' = find_in_roots tl in
320              let subst,metasenv,ugraph,found =
321               let wanted, metasenv, ugraph = wanted context' metasenv ugraph in
322                find_subterms ~subst ~metasenv ~ugraph ~wanted ~context:context'
323                 where
324              in
325               subst,metasenv,ugraph,found @ tl'
326         in
327          find_in_roots roots
328
329 (** create a pattern from a term and a list of subterms.
330 * the pattern is granted to have a ? for every subterm that has no selected
331 * subterms
332 * @param equality equality function used while walking the term. Defaults to
333 * physical equality (==) *)
334 let pattern_of ?(equality=(==)) ~term terms =
335   let (===) x y = equality x y in
336   let not_found = false, Cic.Implicit None in
337   let rec aux t =
338     match t with
339     | t when List.exists (fun t' -> t === t') terms ->
340        true,Cic.Implicit (Some `Hole)
341     | Cic.Var (uri, subst) ->
342        let b,subst = aux_subst subst in
343         if b then
344          true,Cic.Var (uri, subst)
345         else
346          not_found
347     | Cic.Meta (i, ctxt) ->
348         let b,ctxt =
349           List.fold_right
350            (fun e (b,ctxt) ->
351              match e with
352                 None -> b,None::ctxt
353               | Some t -> let bt,t = aux t in b||bt ,Some t::ctxt
354            ) ctxt (false,[])
355         in
356          if b then
357           true,Cic.Meta (i, ctxt)
358          else
359           not_found
360     | Cic.Cast (te, ty) ->
361        let b1,te = aux te in
362        let b2,ty = aux ty in
363         if b1||b2 then true,Cic.Cast (te, ty)
364         else
365          not_found
366     | Cic.Prod (_, s, t) ->
367        let b1,s = aux s in
368        let b2,t = aux t in
369         if b1||b2 then
370          true, Cic.Prod (Cic.Anonymous, s, t)
371         else
372          not_found
373     | Cic.Lambda (_, s, t) ->
374        let b1,s = aux s in
375        let b2,t = aux t in
376         if b1||b2 then
377          true, Cic.Lambda (Cic.Anonymous, s, t)
378         else
379          not_found
380     | Cic.LetIn (_, s, t) ->
381        let b1,s = aux s in
382        let b2,t = aux t in
383         if b1||b2 then
384          true, Cic.LetIn (Cic.Anonymous, s, t)
385         else
386          not_found
387     | Cic.Appl terms ->
388        let b,terms =
389         List.fold_right
390          (fun t (b,terms) ->
391            let bt,t = aux t in
392             b||bt,t::terms
393          ) terms (false,[])
394        in
395         if b then
396          true,Cic.Appl terms
397         else
398          not_found
399     | Cic.Const (uri, subst) ->
400        let b,subst = aux_subst subst in
401         if b then
402          true, Cic.Const (uri, subst)
403         else
404          not_found
405     | Cic.MutInd (uri, tyno, subst) ->
406        let b,subst = aux_subst subst in
407         if b then
408          true, Cic.MutInd (uri, tyno, subst)
409         else
410          not_found
411     | Cic.MutConstruct (uri, tyno, consno, subst) ->
412        let b,subst = aux_subst subst in
413         if b then
414          true, Cic.MutConstruct (uri, tyno, consno, subst)
415         else
416          not_found
417     | Cic.MutCase (uri, tyno, outty, t, pat) ->
418        let b1,outty = aux outty in
419        let b2,t = aux t in
420        let b3,pat =
421         List.fold_right
422          (fun t (b,pat) ->
423            let bt,t = aux t in
424             bt||b,t::pat
425          ) pat (false,[])
426        in
427         if b1 || b2 || b3 then
428          true, Cic.MutCase (uri, tyno, outty, t, pat)
429         else
430          not_found
431     | Cic.Fix (funno, funs) ->
432         let b,funs =
433           List.fold_right
434            (fun (name, i, ty, bo) (b,funs) ->
435              let b1,ty = aux ty in
436              let b2,bo = aux bo in
437               b||b1||b2, (name, i, ty, bo)::funs) funs (false,[])
438         in
439          if b then
440           true, Cic.Fix (funno, funs)
441          else
442           not_found
443     | Cic.CoFix (funno, funs) ->
444         let b,funs =
445           List.fold_right
446            (fun (name, ty, bo) (b,funs) ->
447              let b1,ty = aux ty in
448              let b2,bo = aux bo in
449               b||b1||b2, (name, ty, bo)::funs) funs (false,[])
450         in
451          if b then
452           true, Cic.CoFix (funno, funs)
453          else
454           not_found
455     | Cic.Rel _
456     | Cic.Sort _
457     | Cic.Implicit _ -> not_found
458   and aux_subst subst =
459     List.fold_right
460      (fun (uri, t) (b,subst) ->
461        let b1,t = aux t in
462         b||b1,(uri, t)::subst) subst (false,[])
463   in
464    snd (aux term)
465
466 exception Fail of string Lazy.t
467
468   (** select metasenv conjecture pattern
469   * select all subterms of [conjecture] matching [pattern].
470   * It returns the set of matched terms (that can be compared using physical
471   * equality to the subterms of [conjecture]) together with their contexts.
472   * The representation of the set mimics the ProofEngineTypes.pattern type:
473   * a list of hypothesis (names of) together with the list of its matched
474   * subterms (and their contexts) + the list of matched subterms of the
475   * with their context conclusion. Note: in the result the list of hypothesis
476   * has an entry for each entry in the context and in the same order.
477   * Of course the list of terms (with their context) associated to the
478   * hypothesis name may be empty. 
479   *
480   * @raise Bad_pattern
481   * *)
482   let select ~metasenv ~ugraph ~conjecture:(_,context,ty)
483        ~(pattern: (Cic.term, Cic.lazy_term) ProofEngineTypes.pattern)
484   =
485    let what, hyp_patterns, goal_pattern = pattern in
486    let find_pattern_for name =
487      try Some (snd (List.find (fun (n, pat) -> Cic.Name n = name) hyp_patterns))
488      with Not_found -> None in
489    (* Multiple hypotheses with the same name can be in the context.
490       In this case we need to pick the last one, but we will perform
491       a fold_right on the context. Thus we pre-process hyp_patterns. *)
492    let full_hyp_pattern =
493     let rec aux blacklist =
494      function
495         [] -> []
496       | None::tl -> None::aux blacklist tl
497       | Some (name,_)::tl ->
498          if List.mem name blacklist then
499           None::aux blacklist tl
500          else
501           find_pattern_for name::aux (name::blacklist) tl
502     in
503      aux [] context
504    in
505    let subst,metasenv,ugraph,ty_terms =
506     select_in_term ~metasenv ~context ~ugraph ~term:ty
507      ~pattern:(what,goal_pattern) in
508    let subst,metasenv,ugraph,context_terms =
509     let subst,metasenv,ugraph,res,_ =
510      (List.fold_right
511       (fun (pattern,entry) (subst,metasenv,ugraph,res,context) ->
512         match entry with
513           None -> subst,metasenv,ugraph,None::res,None::context
514         | Some (name,Cic.Decl term) ->
515             (match pattern with
516             | None ->
517                subst,metasenv,ugraph,((Some (`Decl []))::res),(entry::context)
518             | Some pat ->
519                 let subst,metasenv,ugraph,terms =
520                  select_in_term ~metasenv ~context ~ugraph ~term
521                   ~pattern:(what, Some pat)
522                 in
523                  subst,metasenv,ugraph,((Some (`Decl terms))::res),
524                   (entry::context))
525         | Some (name,Cic.Def (bo, ty)) ->
526             (match pattern with
527             | None ->
528                let selected_ty=match ty with None -> None | Some _ -> Some [] in
529                 subst,metasenv,ugraph,((Some (`Def ([],selected_ty)))::res),
530                  (entry::context)
531             | Some pat -> 
532                 let subst,metasenv,ugraph,terms_bo =
533                  select_in_term ~metasenv ~context ~ugraph ~term:bo
534                   ~pattern:(what, Some pat) in
535                 let subst,metasenv,ugraph,terms_ty =
536                  match ty with
537                     None -> subst,metasenv,ugraph,None
538                   | Some ty ->
539                      let subst,metasenv,ugraph,res =
540                       select_in_term ~metasenv ~context ~ugraph ~term:ty
541                        ~pattern:(what, Some pat)
542                      in
543                       subst,metasenv,ugraph,Some res
544                 in
545                  subst,metasenv,ugraph,((Some (`Def (terms_bo,terms_ty)))::res),
546                   (entry::context))
547       ) (List.combine full_hyp_pattern context) (subst,metasenv,ugraph,[],[]))
548     in
549      subst,metasenv,ugraph,res
550    in
551     subst,metasenv,ugraph,context_terms, ty_terms
552
553 (** locate_in_term equality what where context
554 * [what] must match a subterm of [where] according to [equality]
555 * It returns the matched terms together with their contexts in [where]
556 * [equality] defaults to physical equality
557 * [context] must be the context of [where]
558 *)
559 let locate_in_term ?(equality=(fun _ -> (==))) what ~where context =
560   let add_ctx context name entry =
561       (Some (name, entry)) :: context in
562   let rec aux context where =
563    if equality context what where then [context,where]
564    else
565     match where with
566     | Cic.Implicit _
567     | Cic.Meta _
568     | Cic.Rel _
569     | Cic.Sort _
570     | Cic.Var _
571     | Cic.Const _
572     | Cic.MutInd _
573     | Cic.MutConstruct _ -> []
574     | Cic.Cast (te, ty) -> aux context te @ aux context ty
575     | Cic.Prod (name, s, t)
576     | Cic.Lambda (name, s, t) ->
577         aux context s @ aux (add_ctx context name (Cic.Decl s)) t
578     | Cic.LetIn (name, s, t) -> 
579         aux context s @ aux (add_ctx context name (Cic.Def (s,None))) t
580     | Cic.Appl tl -> auxs context tl
581     | Cic.MutCase (_, _, out, t, pat) ->
582         aux context out @ aux context t @ auxs context pat
583     | Cic.Fix (_, funs) ->
584        let tys =
585         List.map (fun (n,_,ty,_) -> Some (Cic.Name n,(Cic.Decl ty))) funs
586        in
587         List.concat
588           (List.map
589             (fun (_, _, ty, bo) -> 
590               aux context ty @ aux (tys @ context) bo)
591             funs)
592     | Cic.CoFix (_, funs) ->
593        let tys =
594         List.map (fun (n,ty,_) -> Some (Cic.Name n,(Cic.Decl ty))) funs
595        in
596         List.concat
597           (List.map
598             (fun (_, ty, bo) ->
599               aux context ty @ aux (tys @ context) bo)
600             funs)
601   and auxs context tl =  (* as aux for list of terms *)
602     List.concat (List.map (fun t -> aux context t) tl)
603   in
604    aux context where
605
606 (** locate_in_conjecture equality what where context
607 * [what] must match a subterm of [where] according to [equality]
608 * It returns the matched terms together with their contexts in [where]
609 * [equality] defaults to physical equality
610 * [context] must be the context of [where]
611 *)
612 let locate_in_conjecture ?(equality=fun _ -> (==)) what (_,context,ty) =
613  let context,res =
614   List.fold_right
615    (fun entry (context,res) ->
616      match entry with
617         None -> entry::context, res
618       | Some (_, Cic.Decl ty) ->
619          let res = res @ locate_in_term what ~where:ty context in
620          let context' = entry::context in
621           context',res
622       | Some (_, Cic.Def (bo,ty)) ->
623          let res = res @ locate_in_term what ~where:bo context in
624          let res =
625           match ty with
626              None -> res
627            | Some ty ->
628               res @ locate_in_term what ~where:ty context in
629          let context' = entry::context in
630           context',res
631    ) context ([],[])
632  in
633   res @ locate_in_term what ~where:ty context
634
635 let lookup_type metasenv context hyp =
636    let rec aux p = function
637       | Some (Cic.Name name, Cic.Decl t) :: _ when name = hyp -> p, t
638       | Some (Cic.Name name, Cic.Def (_, Some t)) :: _ when name = hyp -> p, t
639       | Some (Cic.Name name, Cic.Def (u, _)) :: tail when name = hyp ->
640          p, fst (CicTypeChecker.type_of_aux' metasenv tail u CicUniv.empty_ugraph)
641       | _ :: tail -> aux (succ p) tail
642       | [] -> raise (ProofEngineTypes.Fail (lazy "lookup_type: not premise in the current goal"))
643    in
644    aux 1 context
645
646 (* FG: **********************************************************************)
647
648 let get_name context index =
649    try match List.nth context (pred index) with
650       | Some (Cic.Name name, _)     -> Some name
651       | _                           -> None
652    with Invalid_argument "List.nth" -> None
653
654 let get_rel context name =
655    let rec aux i = function
656       | []                                      -> None
657       | Some (Cic.Name s, _) :: _ when s = name -> Some (Cic.Rel i)
658       | _ :: tl                                 -> aux (succ i) tl
659    in
660    aux 1 context
661
662 let split_with_whd (c, t) =
663    let add s v c = Some (s, Cic.Decl v) :: c in
664    let rec aux whd a n c = function
665       | Cic.Prod (s, v, t)  -> aux false ((c, v) :: a) (succ n) (add s v c) t
666       | v when whd          -> (c, v) :: a, n
667       | v                   -> aux true a n c (CicReduction.whd c v)
668     in
669     aux false [] 0 c t
670
671 let split_with_normalize (c, t) =
672    let add s v c = Some (s, Cic.Decl v) :: c in
673    let rec aux a n c = function
674       | Cic.Prod (s, v, t)  -> aux ((c, v) :: a) (succ n) (add s v c) t
675       | v                   -> (c, v) :: a, n
676     in
677     aux [] 0 c (CicReduction.normalize c t)
678
679   (* menv sorting *)
680 module OT = 
681   struct 
682     type t = Cic.conjecture
683     let compare (i,_,_) (j,_,_) = Pervasives.compare i j
684   end
685 module MS = HTopoSort.Make(OT)
686 let relations_of_menv m c =
687   let i, ctx, ty = c in
688   let m = List.filter (fun (j,_,_) -> j <> i) m in
689   let m_ty = List.map fst (CicUtil.metas_of_term ty) in
690   let m_ctx = 
691     List.flatten
692       (List.map 
693         (function 
694          | None -> []
695          | Some (_,Cic.Decl t)
696          | Some (_,Cic.Def (t,None)) -> 
697              List.map fst (CicUtil.metas_of_term ty)
698          | Some (_,Cic.Def (t,Some ty)) -> 
699              List.map fst (CicUtil.metas_of_term ty) @
700              List.map fst (CicUtil.metas_of_term t))
701         ctx)
702   in
703   let metas = HExtlib.list_uniq (List.sort compare (m_ty @ m_ctx)) in
704   List.filter (fun (i,_,_) -> List.exists ((=) i) metas) m
705 ;;
706 let sort_metasenv (m : Cic.metasenv) =
707   (MS.topological_sort m (relations_of_menv m) : Cic.metasenv)
708 ;;