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