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