]> matita.cs.unibo.it Git - helm.git/blobdiff - matita/components/ng_kernel/nCicExtraction.ml
Code to make all global names in a file fresh.
[helm.git] / matita / components / ng_kernel / nCicExtraction.ml
index c2d51b0bf39dabc719db732e3ccdf4677af083ad..72bb35b08265254f26c267fd114eea9bbc9dee88 100644 (file)
@@ -69,14 +69,14 @@ type typ =
 
 let rec size_of_type =
   function
-    | Var v -> 1
+    | Var _ -> 1
     | Unit -> 1
     | Top -> 1
-    | TConst c -> 1
+    | TConst _ -> 1
     | Arrow _ -> 2
     | TSkip t -> size_of_type t
     | Forall _ -> 2
-    | TAppl l -> 1
+    | TAppl _ -> 1
 ;;
 
 (* None = dropped abstraction *)
@@ -111,9 +111,9 @@ let mk_appl f x =
 
 let rec size_of_term =
   function
-    | Rel r -> 1
+    | Rel _ -> 1
     | UnitTerm -> 1
-    | Const c -> 1
+    | Const _ -> 1
     | Lambda (_, body) -> 1 + size_of_term body
     | Appl l -> List.length l
     | LetIn (_, def, body) -> 1 + size_of_term def + size_of_term body
@@ -125,16 +125,27 @@ let rec size_of_term =
     | UnsafeCoerce t -> 1 + size_of_term t
 ;;
 
+module ReferenceMap = Map.Make(struct type t = NReference.reference let compare = NReference.compare end)
+
+module GlobalNames = Set.Make(String)
+
+type info_el =
+ string * [`Type of typ_context * typ option | `Constructor | `Function ]
+type info = (NReference.reference * info_el) list
+type db = info_el ReferenceMap.t * GlobalNames.t
+
+let empty_info = []
+
 type obj_kind =
    TypeDeclaration of typ_former_decl
  | TypeDefinition of typ_former_def
  | TermDeclaration of term_former_decl
  | TermDefinition of term_former_def
- | LetRec of (NReference.reference * obj_kind) list
+ | LetRec of (info * NReference.reference * obj_kind) list
    (* reference, left, right, constructors *)
- | Algebraic of (NReference.reference * typ_context * typ_context * (NReference.reference * typ) list) list
+ | Algebraic of (info * NReference.reference * typ_context * typ_context * (NReference.reference * typ) list) list
 
-type obj = NReference.reference * obj_kind
+type obj = info * NReference.reference * obj_kind
 
 (* For LetRec and Algebraic blocks *)
 let dummyref =
@@ -176,13 +187,16 @@ let rec classify_not_term status context t =
      (* Lambdas can me met in branches of matches, expecially when the
         output type is a product *)
      classify_not_term status ((n,NCic.Decl s)::context) t
-  | NCic.Match (r,_,_,pl) ->
+  | NCic.Match (_,_,_,pl) ->
      let classified_pl = List.map (classify_not_term status context) pl in
       sup classified_pl
   | NCic.Const (NReference.Ref (_,NReference.Fix _)) ->
-     (* be aware: we can be the head of an application *)
-     assert false (* TODO *)
+     assert false (* IMPOSSIBLE *)
   | NCic.Meta _ -> assert false (* TODO *)
+  | NCic.Appl (NCic.Const (NReference.Ref (_,NReference.Fix (i,_,_)) as r)::_)->
+     let l,_,_ = NCicEnvironment.get_checked_fixes_or_cofixes status r in
+     let _,_,_,_,bo = List.nth l i in
+      classify_not_term status [] bo
   | NCic.Appl (he::_) -> classify_not_term status context he
   | NCic.Rel n ->
      let rec find_sort typ =
@@ -285,10 +299,6 @@ let rec skip_args status ~metasenv context =
       | `Term _ -> assert false (* IMPOSSIBLE *)
 ;;
 
-module ReferenceMap = Map.Make(struct type t = NReference.reference let compare = NReference.compare end)
-
-type db = (typ_context * typ option) ReferenceMap.t
-
 class type g_status =
  object
   method extraction_db: db
@@ -297,7 +307,7 @@ class type g_status =
 class virtual status =
  object
   inherit NCic.status
-  val extraction_db = ReferenceMap.empty
+  val extraction_db = ReferenceMap.empty, GlobalNames.empty
   method extraction_db = extraction_db
   method set_extraction_db v = {< extraction_db = v >}
   method set_extraction_status
@@ -352,13 +362,18 @@ let rev_context_of_typformer status ~metasenv context =
   | NCic.Const (NReference.Ref (_,NReference.Def _) as ref)
   | NCic.Const (NReference.Ref (_,NReference.Decl) as ref)
   | NCic.Const (NReference.Ref (_,NReference.Fix _) as ref) ->
-     (try List.rev (fst (ReferenceMap.find ref status#extraction_db))
+     (try
+       match snd (ReferenceMap.find ref (fst status#extraction_db)) with
+          `Type (ctx,_) -> List.rev ctx
+        | `Constructor
+        | `Function -> assert false
       with
        Not_found ->
         (* This can happen only when we are processing the type of
            the constructor of a small singleton type. In this case
            we are not interested in all the type, but only in its
-           backbone. That is why we can safely return the dummy context here *)
+           backbone. That is why we can safely return the dummy context
+           here *)
         let rec dummy = None::dummy in
         dummy)
   | NCic.Match _ -> assert false (* TODO ???? *)
@@ -399,6 +414,9 @@ let rec typ_of status ~metasenv context k =
   | NCic.Lambda _ -> assert false (* LAMBDA-LIFT INNER DECLARATION *)
   | NCic.Rel n -> Var n
   | NCic.Const ref -> TConst ref
+  | NCic.Match (_,_,_,_)
+  | NCic.Appl (NCic.Const (NReference.Ref (_,NReference.Fix _))::_) ->
+     Top
   | NCic.Appl (he::args) ->
      let rev_he_context= rev_context_of_typformer status ~metasenv context he in
      TAppl (typ_of status ~metasenv context he ::
@@ -407,8 +425,7 @@ let rec typ_of status ~metasenv context k =
        (skip_args status ~metasenv context (rev_he_context,args)))
   | NCic.Appl _ -> assert false (* TODO: when head is a match/let rec;
                                    otherwise NOT A TYPE *)
-  | NCic.Meta _
-  | NCic.Match (_,_,_,_) -> Top
+  | NCic.Meta _ -> assert false (*TODO*)
 ;;
 
 let rec fomega_lift_type_from n k =
@@ -475,7 +492,15 @@ let rec fomega_subst k t1 =
   | Forall (n,kind,t) -> Forall (n,kind,fomega_subst (k+1) t1 t)
   | TAppl args -> TAppl (List.map (fomega_subst k t1) args)
 
-let fomega_lookup status ref = snd (ReferenceMap.find ref status#extraction_db)
+let fomega_lookup status ref =
+ try
+  match snd (ReferenceMap.find ref (fst status#extraction_db)) with
+     `Type (_,bo) -> bo
+   | `Constructor
+   | `Function -> assert false
+ with
+  Not_found ->
+prerr_endline ("BUG, THIS SHOULD NEVER HAPPEN " ^ NReference.string_of_reference ref); None
 
 let rec fomega_whd status ty =
  match ty with
@@ -573,7 +598,7 @@ let rec term_of status ~metasenv context =
        in
         try
          List.map2
-          (fun (_, name, ty) pat ->
+          (fun (_, _name, ty) pat ->
             (*BUG: recomputing every time the type of the constructor*)
             let ty = typ_of status ~metasenv context ty in
             let context,lhs,rhs = eat_branch leftno ty context [] pat in
@@ -621,7 +646,8 @@ and eat_args status metasenv acc context tyhe =
            | `Term `TypeFormerOrTerm
            | `Term `Term -> term_of status ~metasenv context arg
          in
-          eat_args status metasenv (UnsafeCoerce (mk_appl acc arg))
+          eat_args status metasenv
+           (UnsafeCoerce (mk_appl acc (UnsafeCoerce arg)))
            context Top tl
       | Forall (_,_,t) ->
          (match classify status ~metasenv context arg with
@@ -649,6 +675,27 @@ type 'a result =
   | Success of 'a
 ;;
 
+let fresh_name_of_ref status ref =
+ let candidate = NCicPp.r2s status true ref in
+ let rec freshen candidate =
+  if GlobalNames.mem candidate (snd status#extraction_db) then
+   freshen (candidate ^ "'")
+  else
+   candidate
+ in
+  freshen candidate
+
+let register_info (db,names) (ref,(name,_ as info_el)) =
+ ReferenceMap.add ref info_el db,GlobalNames.add name names
+
+let register_name_and_info status (ref,info_el) =
+ let name = fresh_name_of_ref status ref in
+ let info = ref,(name,info_el) in
+ let infos,names = status#extraction_db in
+  status#set_extraction_db (register_info (infos,names) info), info
+
+let register_infos = List.fold_left register_info
+
 let object_of_constant status ~metasenv ref bo ty =
   match classify status ~metasenv [] ty with
     | `Kind ->
@@ -668,10 +715,9 @@ let object_of_constant status ~metasenv ref bo ty =
                 ctx0 ctx
               in
               let bo = typ_of status ~metasenv ctx bo in
-               status#set_extraction_db
-                (ReferenceMap.add ref (nicectx,Some bo)
-                  status#extraction_db),
-               Success (ref,TypeDefinition((nicectx,res),bo))
+              let info = ref,`Type (nicectx,Some bo) in
+              let status,info = register_name_and_info status info in
+               status,Success ([info],ref,TypeDefinition((nicectx,res),bo))
           | `Kind -> status, Erased (* DPM: but not really, more a failure! *)
           | `PropKind
           | `Proposition -> status, Erased
@@ -680,10 +726,12 @@ let object_of_constant status ~metasenv ref bo ty =
     | `Proposition -> status, Erased
     | `KindOrType (* ??? *)
     | `Type ->
-       (* CSC: TO BE FINISHED, REF NON REGISTERED *)
        let ty = typ_of status ~metasenv [] ty in
+       let info = ref,`Function in
+       let status,info = register_name_and_info status info in
         status,
-        Success (ref, TermDefinition (split_typ_prods [] ty, term_of status ~metasenv [] bo))
+         Success ([info],ref, TermDefinition (split_typ_prods [] ty,
+         term_of status ~metasenv [] bo))
     | `Term _ -> status, Failure "Non-term classified as a term.  This is a bug."
 ;;
 
@@ -702,24 +750,26 @@ let object_of_inductive status ~metasenv uri ind leftno il =
           let right,left = HExtlib.split_nth (List.length ctx - leftno) ctx in
           let ref =
            NReference.reference_of_spec uri (NReference.Ind (ind,i,leftno)) in
-          let status =
-           status#set_extraction_db
-            (ReferenceMap.add ref (ctx,None) status#extraction_db) in
-          let cl =
-           HExtlib.list_mapi
-            (fun (_,_,ty) j ->
+          let info = ref,`Type (ctx,None) in
+          let status,info = register_name_and_info status info in
+          let _,status,cl_rev,infos =
+           List.fold_left
+            (fun (j,status,res,infos) (_,_,ty) ->
               let ctx,ty =
                NCicReduction.split_prods status ~subst:[] [] leftno ty in
               let ty = typ_of status ~metasenv ctx ty in
-               NReference.mk_constructor (j+1) ref,ty
-            ) cl
+              let ref = NReference.mk_constructor j ref in
+              let info = ref,`Constructor in
+              let status,info = register_name_and_info status info in
+               j+1,status,((ref,ty)::res),info::infos
+            ) (1,status,[],[]) cl
           in
-           status,i+1,(ref,left,right,cl)::res
+           status,i+1,(info::infos,ref,left,right,List.rev cl_rev)::res
    ) (status,0,[]) il
  in
   match rev_tyl with
      [] -> status,Erased
-   | _ -> status, Success (dummyref, Algebraic (List.rev rev_tyl))
+   | _ -> status, Success ([], dummyref, Algebraic (List.rev rev_tyl))
 ;;
 
 let object_of status (uri,height,metasenv,subst,obj_kind) =
@@ -731,15 +781,18 @@ let object_of status (uri,height,metasenv,subst,obj_kind) =
             | `Kind ->
               let ty = kind_of status ~metasenv [] ty in
               let ctx,_ as res = split_kind_prods [] ty in
-                status#set_extraction_db
-                  (ReferenceMap.add ref (ctx,None) status#extraction_db),
-                    Success (ref, TypeDeclaration res)
+              let info = ref,`Type (ctx,None) in
+              let status,info = register_name_and_info status info in
+               status, Success ([info],ref, TypeDeclaration res)
             | `PropKind
             | `Proposition -> status, Erased
             | `Type
             | `KindOrType (*???*) ->
               let ty = typ_of status ~metasenv [] ty in
-                status, Success (ref, TermDeclaration (split_typ_prods [] ty))
+              let info = ref,`Function in
+              let status,info = register_name_and_info status info in
+               status,Success ([info],ref,
+                TermDeclaration (split_typ_prods [] ty))
             | `Term _ -> status, Failure "Type classified as a term.  This is a bug.")
         | NCic.Constant (_,_,Some bo,ty,_) ->
            let ref = NReference.reference_of_spec uri (NReference.Def height) in
@@ -757,10 +810,10 @@ let object_of status (uri,height,metasenv,subst,obj_kind) =
               in
               let status,obj = object_of_constant ~metasenv status ref bo ty in
                 match obj with
-                  | Success (ref,obj) -> i+1,status, (ref,obj)::res
+                  | Success (info,ref,obj) -> i+1,status, (info,ref,obj)::res
                   | _ -> i+1,status, res) fs (0,status,[])
           in
-            status, Success (dummyref,LetRec objs)
+            status, Success ([],dummyref,LetRec objs)
         | NCic.Inductive (ind,leftno,il,_) ->
            object_of_inductive status ~metasenv uri ind leftno il
 
@@ -807,7 +860,7 @@ let string_of_char_list s =
  * ----------------------------------------------------------------------------
  *)
 
-let remove_underscores_and_mark =
+let remove_underscores_and_mark =
   let rec aux char_list_buffer positions_buffer position =
     function
       | []    -> (string_of_char_list char_list_buffer, positions_buffer)
@@ -817,7 +870,7 @@ let remove_underscores_and_mark =
         else
           aux (x::char_list_buffer) positions_buffer (position + 1) xs
   in
-    aux [] [] 0
+   if l = ['_'] then "_",[] else aux [] [] 0 l
 ;;
 
 let rec capitalize_marked_positions s =
@@ -848,17 +901,15 @@ let idiomatic_haskell_term_name_of_string =
   String.uncapitalize
 ;;
 
-(*CSC: code to be changed soon when we implement constructors and
-  we fix the code for term application *)
 let classify_reference status ref =
-  if ReferenceMap.mem ref status#extraction_db then
-    `TypeName
-  else
-   let NReference.Ref (_,ref) = ref in
-    match ref with
-       NReference.Con _ -> `Constructor
-     | NReference.Ind _ -> assert false
-     | _ -> `FunctionName
+ try
+  match snd (ReferenceMap.find ref (fst status#extraction_db)) with
+     `Type _ -> `TypeName
+   | `Constructor -> `Constructor
+   | `Function -> `FunctionName
+ with
+  Not_found ->
+prerr_endline ("BUG, THIS SHOULD NEVER HAPPEN " ^ NReference.string_of_reference ref); `FunctionName
 ;;
 
 let capitalize classification name =
@@ -872,7 +923,12 @@ let capitalize classification name =
 
 let pp_ref status ref =
  capitalize (classify_reference status ref)
-  (NCicPp.r2s status true ref)
+  (try fst (ReferenceMap.find ref (fst status#extraction_db))
+   with Not_found ->
+prerr_endline ("BUG with coercions: " ^ NReference.string_of_reference ref);
+(*assert false*)
+ NCicPp.r2s status true ref (* BUG: this should never happen *)
+)
 
 (* cons avoid duplicates *)
 let rec (@:::) name l =
@@ -912,8 +968,11 @@ let pretty_print_term_context status ctx1 ctx2 =
     (fun el (ctx1,rev_res) ->
       match el with
          None -> ""@::ctx1,rev_res
-       | Some (name,`OfKind _) -> name@::ctx1,rev_res
+       | Some (name,`OfKind _) ->
+          let name = capitalize `TypeVariable name in
+           name@::ctx1,rev_res
        | Some (name,`OfType typ) ->
+          let name = capitalize `TypeVariable name in
           let name,ctx1 = name@:::ctx1 in
            name::ctx1,
             ("(" ^ name ^ " :: " ^ pretty_print_type status ctx1 typ ^ ")")::rev_res
@@ -943,8 +1002,8 @@ let rec pretty_print_term status ctxt =
       if pl = [] then
        "error \"Case analysis over empty type\""
       else
-       "case " ^ pretty_print_term status ctxt matched ^ " of\n" ^
-         String.concat "\n"
+       "case " ^ pretty_print_term status ctxt matched ^ " of {\n" ^
+         String.concat " ;\n"
            (HExtlib.list_mapi
              (fun (bound_names,rhs) i ->
                let ref = NReference.mk_constructor (i+1) r in
@@ -955,7 +1014,7 @@ let rec pretty_print_term status ctxt =
                 pretty_print_term status ctxt rhs
                in
                  "  " ^ name ^ " " ^ bound_names ^ " -> " ^ body
-             ) pl)
+             ) pl) ^ "}\n  "
     | Skip t -> pretty_print_term status ("[[skipped]]"@::ctxt) t
     | TLambda (name,t) ->
        let name = capitalize `TypeVariable name in
@@ -963,7 +1022,7 @@ let rec pretty_print_term status ctxt =
     | Inst t -> pretty_print_term status ctxt t
 ;;
 
-let rec pp_obj status (ref,obj_kind) =
+let rec pp_obj status (_,ref,obj_kind) =
   let pretty_print_context ctx =
     String.concat " " (List.rev (snd
       (List.fold_right
@@ -1007,7 +1066,7 @@ let rec pp_obj status (ref,obj_kind) =
  | Algebraic il ->
     String.concat "\n"
      (List.map
-      (fun ref,left,right,cl ->
+      (fun _,ref,left,right,cl ->
         "data " ^ pp_ref status ref ^ " " ^
         pretty_print_context (right@left) ^ " where\n  " ^
         String.concat "\n  " (List.map
@@ -1015,15 +1074,51 @@ let rec pp_obj status (ref,obj_kind) =
            let namectx = namectx_of_ctx left in
             pp_ref status ref ^ " :: " ^
              pretty_print_type status namectx tys
-         ) cl
-      )) il)
+         ) cl) ^ "\n    deriving (Prelude.Show)"
+      ) il)
  (* inductive and records missing *)
 
+let rec infos_of (info,_,obj_kind) =
+ info @
+  match obj_kind with
+     LetRec l -> List.concat (List.map (fun (infos,_,_) -> infos) l)
+   | Algebraic l -> List.concat (List.map (fun (infos,_,_,_,_) -> infos) l)
+   | _ -> []
+
 let haskell_of_obj status (uri,_,_,_,_ as obj) =
  let status, obj = object_of status obj in
   status,
    match obj with
-      Erased -> "-- [?] " ^ NUri.name_of_uri uri ^ " erased due to term being propositionally irrelevant.\n"
-    | OutsideTheory -> "-- [?] " ^ NUri.name_of_uri uri ^ " erased due to image of term under extraction residing outside Fω.\n"
-    | Failure msg -> "-- [?] " ^ NUri.name_of_uri uri ^ " FAILURE: " ^ msg ^ "\n"
-    | Success o -> pp_obj status o ^ "\n"
+      Erased -> "-- [?] " ^ NUri.name_of_uri uri ^ " erased due to term being propositionally irrelevant.\n",[]
+    | OutsideTheory -> "-- [?] " ^ NUri.name_of_uri uri ^ " erased due to image of term under extraction residing outside Fω.\n",[]
+    | Failure msg -> "-- [?] " ^ NUri.name_of_uri uri ^ " FAILURE: " ^ msg ^ "\n",[]
+    | Success o -> pp_obj status o ^ "\n", infos_of o
+
+let refresh_uri_in_typ ~refresh_uri_in_reference =
+ let rec refresh_uri_in_typ =
+  function
+   | Var _
+   | Unit
+   | Top as t -> t
+   | TConst r -> TConst (refresh_uri_in_reference r)
+   | Arrow (t1,t2) -> Arrow (refresh_uri_in_typ t1, refresh_uri_in_typ t2)
+   | TSkip t -> TSkip (refresh_uri_in_typ t)
+   | Forall (n,k,t) -> Forall (n,k,refresh_uri_in_typ t)
+   | TAppl tl -> TAppl (List.map refresh_uri_in_typ tl)
+ in
+  refresh_uri_in_typ
+
+let refresh_uri_in_info ~refresh_uri_in_reference infos =
+ List.map
+  (function (ref,el) ->
+    match el with
+       _,`Constructor
+     | _,`Function -> refresh_uri_in_reference ref,el
+     | name,`Type (ctx,typ) ->
+         let typ =
+          match typ with
+             None -> None
+           | Some t -> Some (refresh_uri_in_typ ~refresh_uri_in_reference t)
+         in
+          refresh_uri_in_reference ref, (name,`Type (ctx,typ)))
+  infos