src/HOL/Import/proof_kernel.ML
author obua
Thu Feb 16 14:59:57 2006 +0100 (2006-02-16)
changeset 19068 04b302f2902d
parent 19067 c0321d7d6b3d
child 19264 61e775c03ed8
permissions -rw-r--r--
cache improvements
     1 (*  Title:      HOL/Import/proof_kernel.ML
     2     ID:         $Id$
     3     Author:     Sebastian Skalberg (TU Muenchen), Steven Obua
     4 *)
     5 
     6 signature ProofKernel =
     7 sig
     8     type hol_type
     9     type tag
    10     type term
    11     type thm
    12     type ('a,'b) subst
    13 	 
    14     type proof_info
    15     datatype proof = Proof of proof_info * proof_content
    16 	 and proof_content
    17 	   = PRefl of term
    18 	   | PInstT of proof * (hol_type,hol_type) subst
    19 	   | PSubst of proof list * term * proof
    20 	   | PAbs of proof * term
    21 	   | PDisch of proof * term
    22 	   | PMp of proof * proof
    23 	   | PHyp of term
    24 	   | PAxm of string * term
    25 	   | PDef of string * string * term
    26 	   | PTmSpec of string * string list * proof
    27 	   | PTyDef of string * string * proof
    28 	   | PTyIntro of string * string * string * string * term * term * proof
    29 	   | POracle of tag * term list * term
    30 	   | PDisk
    31 	   | PSpec of proof * term
    32 	   | PInst of proof * (term,term) subst
    33 	   | PGen of proof * term
    34 	   | PGenAbs of proof * term option * term list
    35 	   | PImpAS of proof * proof
    36 	   | PSym of proof
    37 	   | PTrans of proof * proof
    38 	   | PComb of proof * proof
    39 	   | PEqMp of proof * proof
    40 	   | PEqImp of proof
    41 	   | PExists of proof * term * term
    42 	   | PChoose of term * proof * proof
    43 	   | PConj of proof * proof
    44 	   | PConjunct1 of proof
    45 	   | PConjunct2 of proof
    46 	   | PDisj1 of proof * term
    47 	   | PDisj2 of proof * term
    48 	   | PDisjCases of proof * proof * proof
    49 	   | PNotI of proof
    50 	   | PNotE of proof
    51 	   | PContr of proof * term
    52 
    53     exception PK of string * string
    54 
    55     val get_proof_dir: string -> theory -> string option
    56     val disambiguate_frees : Thm.thm -> Thm.thm
    57     val debug : bool ref
    58     val disk_info_of : proof -> (string * string) option
    59     val set_disk_info_of : proof -> string -> string -> unit
    60     val mk_proof : proof_content -> proof
    61     val content_of : proof -> proof_content
    62     val import_proof : string -> string -> theory -> (theory -> term) option * (theory -> proof)
    63 
    64     val rewrite_hol4_term: Term.term -> theory -> Thm.thm
    65 
    66     val type_of : term -> hol_type
    67 
    68     val get_thm  : string -> string         -> theory -> (theory * thm option)
    69     val get_def  : string -> string -> term -> theory -> (theory * thm option)
    70     val get_axiom: string -> string         -> theory -> (theory * thm option)
    71 
    72     val store_thm : string -> string -> thm -> theory -> theory * thm
    73 
    74     val to_isa_thm : thm -> (term * term) list * Thm.thm
    75     val to_isa_term: term -> Term.term
    76     val to_hol_thm : Thm.thm -> thm
    77 
    78     val REFL : term -> theory -> theory * thm
    79     val ASSUME : term -> theory -> theory * thm
    80     val INST_TYPE : (hol_type,hol_type) subst -> thm -> theory -> theory * thm
    81     val INST : (term,term)subst -> thm -> theory -> theory * thm
    82     val EQ_MP : thm -> thm -> theory -> theory * thm
    83     val EQ_IMP_RULE : thm -> theory -> theory * thm
    84     val SUBST : thm list -> term -> thm -> theory -> theory * thm
    85     val DISJ_CASES : thm -> thm -> thm -> theory -> theory * thm
    86     val DISJ1: thm -> term -> theory -> theory * thm
    87     val DISJ2: term -> thm -> theory -> theory * thm
    88     val IMP_ANTISYM: thm -> thm -> theory -> theory * thm
    89     val SYM : thm -> theory -> theory * thm
    90     val MP : thm -> thm -> theory -> theory * thm
    91     val GEN : term -> thm -> theory -> theory * thm
    92     val CHOOSE : term -> thm -> thm -> theory -> theory * thm
    93     val EXISTS : term -> term -> thm -> theory -> theory * thm
    94     val ABS : term -> thm -> theory -> theory * thm
    95     val GEN_ABS : term option -> term list -> thm -> theory -> theory * thm
    96     val TRANS : thm -> thm -> theory -> theory * thm
    97     val CCONTR : term -> thm -> theory -> theory * thm
    98     val CONJ : thm -> thm -> theory -> theory * thm
    99     val CONJUNCT1: thm -> theory -> theory * thm
   100     val CONJUNCT2: thm -> theory -> theory * thm
   101     val NOT_INTRO: thm -> theory -> theory * thm
   102     val NOT_ELIM : thm -> theory -> theory * thm
   103     val SPEC : term -> thm -> theory -> theory * thm
   104     val COMB : thm -> thm -> theory -> theory * thm
   105     val DISCH: term -> thm -> theory -> theory * thm
   106 
   107     val type_introduction: string -> string -> string -> string -> string -> term * term -> thm -> theory -> theory * thm
   108 
   109     val new_definition : string -> string -> term -> theory -> theory * thm
   110     val new_specification : string -> string -> string list -> thm -> theory -> theory * thm
   111     val new_type_definition : string -> string -> string -> thm -> theory -> theory * thm
   112     val new_axiom : string -> term -> theory -> theory * thm
   113 
   114     val prin : term -> unit 
   115     val protect_factname : string -> string 
   116     val replay_protect_varname : string -> string -> unit
   117     val replay_add_dump : string -> theory -> theory
   118 end
   119 
   120 structure ProofKernel :> ProofKernel =
   121 struct
   122 type hol_type = Term.typ
   123 type term = Term.term
   124 datatype tag = Tag of string list
   125 type ('a,'b) subst = ('a * 'b) list
   126 datatype thm = HOLThm of (Term.term * Term.term) list * Thm.thm
   127 
   128 fun hthm2thm (HOLThm (_, th)) = th 
   129 
   130 fun to_hol_thm th = HOLThm ([], th)
   131 
   132 val replay_add_dump = add_dump
   133 fun add_dump s thy = (ImportRecorder.add_dump s; replay_add_dump s thy)
   134 
   135 datatype proof_info
   136   = Info of {disk_info: (string * string) option ref}
   137 	    
   138 datatype proof = Proof of proof_info * proof_content
   139      and proof_content
   140        = PRefl of term
   141        | PInstT of proof * (hol_type,hol_type) subst
   142        | PSubst of proof list * term * proof
   143        | PAbs of proof * term
   144        | PDisch of proof * term
   145        | PMp of proof * proof
   146        | PHyp of term
   147        | PAxm of string * term
   148        | PDef of string * string * term
   149        | PTmSpec of string * string list * proof
   150        | PTyDef of string * string * proof
   151        | PTyIntro of string * string * string * string * term * term * proof
   152        | POracle of tag * term list * term
   153        | PDisk
   154        | PSpec of proof * term
   155        | PInst of proof * (term,term) subst
   156        | PGen of proof * term
   157        | PGenAbs of proof * term option * term list
   158        | PImpAS of proof * proof
   159        | PSym of proof
   160        | PTrans of proof * proof
   161        | PComb of proof * proof
   162        | PEqMp of proof * proof
   163        | PEqImp of proof
   164        | PExists of proof * term * term
   165        | PChoose of term * proof * proof
   166        | PConj of proof * proof
   167        | PConjunct1 of proof
   168        | PConjunct2 of proof
   169        | PDisj1 of proof * term
   170        | PDisj2 of proof * term
   171        | PDisjCases of proof * proof * proof
   172        | PNotI of proof
   173        | PNotE of proof
   174        | PContr of proof * term
   175 
   176 exception PK of string * string
   177 fun ERR f mesg = PK (f,mesg)
   178 
   179 fun print_exn e = 
   180     case e of
   181 	PK (m,s) => (writeln ("PK (" ^ m ^ "): " ^ s); raise e)
   182       | _ => OldGoals.print_exn e
   183 
   184 (* Compatibility. *)
   185 
   186 fun mk_syn thy c =
   187   if Syntax.is_identifier c andalso not (Syntax.is_keyword (Sign.syn_of thy) c) then NoSyn
   188   else Syntax.literal c
   189 
   190 fun quotename c =
   191   if Syntax.is_identifier c andalso not (OuterSyntax.is_keyword c) then c else quote c
   192 
   193 fun simple_smart_string_of_cterm ct =
   194     let
   195 	val {sign,t,T,...} = rep_cterm ct
   196 	(* Hack to avoid parse errors with Trueprop *)
   197 	val ct  = (cterm_of sign (HOLogic.dest_Trueprop t)
   198 			   handle TERM _ => ct)
   199     in
   200 	quote(
   201 	Library.setmp print_mode [] (
   202 	Library.setmp show_brackets false (
   203 	Library.setmp show_all_types true (
   204 	Library.setmp Syntax.ambiguity_is_error false (
   205 	Library.setmp show_sorts true string_of_cterm))))
   206 	ct)
   207     end
   208 
   209 exception SMART_STRING
   210 
   211 fun smart_string_of_cterm ct =
   212     let
   213 	val {sign,t,T,...} = rep_cterm ct
   214         (* Hack to avoid parse errors with Trueprop *)
   215 	val ct  = (cterm_of sign (HOLogic.dest_Trueprop t)
   216 		   handle TERM _ => ct)
   217 	fun match cu = t aconv (term_of cu)
   218 	fun G 0 = Library.setmp show_types true (Library.setmp show_sorts true)
   219 	  | G 1 = Library.setmp show_brackets true (G 0)
   220 	  | G 2 = Library.setmp show_all_types true (G 0)
   221 	  | G 3 = Library.setmp show_brackets true (G 2)
   222           | G _ = raise SMART_STRING 
   223 	fun F n =
   224 	    let
   225 		val str = Library.setmp show_brackets false (G n string_of_cterm) ct
   226 		val cu  = read_cterm sign (str,T)
   227 	    in
   228 		if match cu
   229 		then quote str
   230 		else F (n+1)
   231 	    end
   232 	    handle ERROR mesg => F (n+1)
   233 		 | SMART_STRING => raise ERROR ("smart_string failed for: "^(G 0 string_of_cterm ct))
   234     in
   235       Library.setmp print_mode [] (Library.setmp Syntax.ambiguity_is_error true F) 0
   236     end
   237     handle ERROR mesg => simple_smart_string_of_cterm ct
   238  
   239 val smart_string_of_thm = smart_string_of_cterm o cprop_of
   240 
   241 fun prth th = writeln (Library.setmp print_mode [] string_of_thm th)
   242 fun prc ct = writeln (Library.setmp print_mode [] string_of_cterm ct)
   243 fun prin t = writeln
   244   (Library.setmp print_mode [] (fn () => Sign.string_of_term (the_context ()) t) ());
   245 fun pth (HOLThm(ren,thm)) =
   246     let
   247 	(*val _ = writeln "Renaming:"
   248 	val _ = app (fn(v,w) => (prin v; writeln " -->"; prin w)) ren*)
   249 	val _ = prth thm
   250     in
   251 	()
   252     end
   253 
   254 fun disk_info_of (Proof(Info{disk_info,...},_)) = !disk_info
   255 fun mk_proof p = Proof(Info{disk_info = ref NONE},p)
   256 fun content_of (Proof(_,p)) = p
   257 
   258 fun set_disk_info_of (Proof(Info{disk_info,...},_)) thyname thmname =
   259     disk_info := SOME(thyname,thmname)
   260 
   261 structure Lib =
   262 struct
   263 fun wrap b e s = String.concat[b,s,e]
   264 
   265 fun assoc x =
   266     let
   267 	fun F [] = raise PK("Lib.assoc","Not found")
   268 	  | F ((x',y)::rest) = if x = x'
   269 			       then y
   270 			       else F rest
   271     in
   272 	F
   273     end
   274 fun i mem L = 
   275     let fun itr [] = false 
   276 	  | itr (a::rst) = i=a orelse itr rst 
   277     in itr L end;
   278     
   279 fun insert i L = if i mem L then L else i::L
   280 					
   281 fun mk_set [] = []
   282   | mk_set (a::rst) = insert a (mk_set rst)
   283 		      
   284 fun [] union S = S
   285   | S union [] = S
   286   | (a::rst) union S2 = rst union (insert a S2)
   287 			
   288 fun implode_subst [] = []
   289   | implode_subst (x::r::rest) = ((x,r)::(implode_subst rest))
   290   | implode_subst _ = raise ERR "implode_subst" "malformed substitution list"
   291 
   292 fun apboth f (x,y) = (f x,f y)
   293 end
   294 open Lib
   295 
   296 structure Tag =
   297 struct
   298 val empty_tag = Tag []
   299 fun read name = Tag [name]
   300 fun merge (Tag tag1) (Tag tag2) = Tag (Lib.union(tag1,tag2))
   301 end
   302 
   303 (* Acutal code. *)
   304 
   305 fun get_segment thyname l = (Lib.assoc "s" l
   306 			     handle PK _ => thyname)
   307 val get_name : (string * string) list -> string = Lib.assoc "n"
   308 
   309 local
   310     open LazyScan
   311     infix 7 |-- --|
   312     infix 5 :-- -- ^^
   313     infix 3 >>
   314     infix 0 ||
   315 in
   316 exception XML of string
   317 
   318 datatype xml = Elem of string * (string * string) list * xml list
   319 datatype XMLtype = XMLty of xml | FullType of hol_type
   320 datatype XMLterm = XMLtm of xml | FullTerm of term
   321 
   322 fun pair x y = (x,y)
   323 
   324 fun scan_id toks =
   325     let
   326         val (x,toks2) = one Char.isAlpha toks
   327         val (xs,toks3) = any Char.isAlphaNum toks2
   328     in
   329         (String.implode (x::xs),toks3)
   330     end
   331 
   332 fun scan_string str c =
   333     let
   334 	fun F [] toks = (c,toks)
   335 	  | F (c::cs) toks =
   336 	    case LazySeq.getItem toks of
   337 		SOME(c',toks') =>
   338 		if c = c'
   339 		then F cs toks'
   340 		else raise SyntaxError
   341 	      | NONE => raise SyntaxError
   342     in
   343 	F (String.explode str)
   344     end
   345 
   346 local
   347     val scan_entity =
   348 	(scan_string "amp;" #"&")
   349 	    || scan_string "quot;" #"\""
   350 	    || scan_string "gt;" #">"
   351 	    || scan_string "lt;" #"<"
   352             || scan_string "apos;" #"'"
   353 in
   354 fun scan_nonquote toks =
   355     case LazySeq.getItem toks of
   356 	SOME (c,toks') =>
   357 	(case c of
   358 	     #"\"" => raise SyntaxError
   359 	   | #"&" => scan_entity toks'
   360 	   | c => (c,toks'))
   361       | NONE => raise SyntaxError
   362 end
   363 
   364 val scan_string = $$ #"\"" |-- repeat scan_nonquote --| $$ #"\"" >>
   365 		     String.implode
   366 
   367 val scan_attribute = scan_id -- $$ #"=" |-- scan_string
   368 
   369 val scan_start_of_tag = $$ #"<" |-- scan_id --
   370 			   repeat ($$ #" " |-- scan_attribute)
   371 
   372 (* The evaluation delay introduced through the 'toks' argument is needed
   373 for the sake of the SML/NJ (110.9.1) compiler.  Either that or an explicit
   374 type :-( *)
   375 fun scan_end_of_tag toks = ($$ #"/" |-- $$ #">" |-- succeed []) toks
   376 
   377 val scan_end_tag = $$ #"<" |-- $$ #"/" |-- scan_id --| $$ #">"
   378 
   379 fun scan_children id = $$ #">" |-- repeat scan_tag -- scan_end_tag >>
   380 		       (fn (chldr,id') => if id = id'
   381 					  then chldr
   382 					  else raise XML "Tag mismatch")
   383 and scan_tag toks =
   384     let
   385 	val ((id,atts),toks2) = scan_start_of_tag toks
   386 	val (chldr,toks3) = (scan_children id || scan_end_of_tag) toks2
   387     in
   388 	(Elem (id,atts,chldr),toks3)
   389     end
   390 end
   391 
   392 val type_of = Term.type_of
   393 
   394 val boolT = Type("bool",[])
   395 val propT = Type("prop",[])
   396 
   397 fun mk_defeq name rhs thy =
   398     let
   399 	val ty = type_of rhs
   400     in
   401 	Logic.mk_equals (Const(Sign.intern_const thy name,ty),rhs)
   402     end
   403 
   404 fun mk_teq name rhs thy =
   405     let
   406 	val ty = type_of rhs
   407     in
   408 	HOLogic.mk_eq (Const(Sign.intern_const thy name,ty),rhs)
   409     end
   410 
   411 fun intern_const_name thyname const thy =
   412     case get_hol4_const_mapping thyname const thy of
   413 	SOME (_,cname,_) => cname
   414       | NONE => (case get_hol4_const_renaming thyname const thy of
   415 		     SOME cname => Sign.intern_const thy (thyname ^ "." ^ cname)
   416 		   | NONE => Sign.intern_const thy (thyname ^ "." ^ const))
   417 
   418 fun intern_type_name thyname const thy =
   419     case get_hol4_type_mapping thyname const thy of
   420 	SOME (_,cname) => cname
   421       | NONE => Sign.intern_const thy (thyname ^ "." ^ const)
   422 
   423 fun mk_vartype name = TFree(name,["HOL.type"])
   424 fun mk_thy_type thy Thy Tyop Args = Type(intern_type_name Thy Tyop thy,Args)
   425 
   426 val mk_var = Free
   427 
   428 fun dom_rng (Type("fun",[dom,rng])) = (dom,rng)
   429   | dom_rng _ = raise ERR "dom_rng" "Not a functional type"
   430 
   431 fun mk_thy_const thy Thy Nam Ty = Const(intern_const_name Thy Nam thy,Ty)
   432 
   433 local 
   434   fun get_const sg thyname name = 
   435     (case Sign.const_type sg name of
   436       SOME ty => Const (name, ty)
   437     | NONE => raise ERR "get_type" (name ^ ": No such constant"))
   438 in
   439 fun prim_mk_const thy Thy Nam =
   440     let
   441       val name = intern_const_name Thy Nam thy
   442       val cmaps = HOL4ConstMaps.get thy
   443     in
   444       case StringPair.lookup cmaps (Thy,Nam) of
   445         SOME(_,_,SOME ty) => Const(name,ty)
   446       | _ => get_const thy Thy name
   447     end
   448 end
   449 
   450 fun mk_comb(f,a) = f $ a
   451 
   452 (* Needed for HOL Light *)
   453 fun protect_tyvarname s =
   454     let
   455 	fun no_quest s =
   456 	    if Char.contains s #"?"
   457 	    then String.translate (fn #"?" => "q_" | c => Char.toString c) s
   458 	    else s
   459 	fun beg_prime s =
   460 	    if String.isPrefix "'" s
   461 	    then s
   462 	    else "'" ^ s
   463     in
   464 	s |> no_quest |> beg_prime
   465     end
   466 
   467 val protected_varnames = ref (Symtab.empty:string Symtab.table)
   468 val invented_isavar = ref (IntInf.fromInt 0)
   469 
   470 fun innocent_varname s = Syntax.is_identifier s andalso not (String.isPrefix "u_" s)
   471 
   472 val check_name_thy = theory "Main"
   473 
   474 fun valid_boundvarname s =
   475   can (fn () => read_cterm check_name_thy ("SOME "^s^". True", TypeInfer.logicT)) ();
   476 
   477 fun valid_varname s =
   478   can (fn () => read_cterm check_name_thy (s, TypeInfer.logicT)) ();
   479 
   480 fun protect_varname s =
   481     if innocent_varname s andalso valid_varname s then s else
   482     case Symtab.lookup (!protected_varnames) s of
   483       SOME t => t
   484     | NONE => 
   485       let
   486 	  val _ = invented_isavar := IntInf.+ (!invented_isavar, IntInf.fromInt 1)
   487 	  val t = "u_"^(IntInf.toString (!invented_isavar))
   488 	  val _ = ImportRecorder.protect_varname s t
   489           val _ = protected_varnames := Symtab.update (s, t) (!protected_varnames)
   490       in
   491 	  t
   492       end
   493 
   494 exception REPLAY_PROTECT_VARNAME of string*string*string
   495 
   496 fun replay_protect_varname s t = 
   497 	case Symtab.lookup (!protected_varnames) s of
   498 	  SOME t' => raise REPLAY_PROTECT_VARNAME (s, t, t')
   499 	| NONE => 	
   500           let
   501 	      val _ = invented_isavar := IntInf.+ (!invented_isavar, IntInf.fromInt 1)
   502 	      val t = "u_"^(IntInf.toString (!invented_isavar))
   503               val _ = protected_varnames := Symtab.update (s, t) (!protected_varnames)
   504           in
   505 	      ()
   506           end	       	
   507 	 
   508 fun protect_boundvarname s = if innocent_varname s andalso valid_boundvarname s then s else "u"
   509 
   510 fun mk_lambda (v as Free (x, T)) t = Abs (protect_boundvarname x, T, abstract_over (v, t))
   511   | mk_lambda (v as Var ((x, _), T)) t = Abs (protect_boundvarname x, T, abstract_over (v, t))
   512   | mk_lambda v t = raise TERM ("lambda", [v, t]);
   513  
   514 fun replacestr x y s = 
   515 let
   516   val xl = explode x
   517   val yl = explode y
   518   fun isprefix [] ys = true
   519     | isprefix (x::xs) (y::ys) = if x = y then isprefix xs ys else false
   520     | isprefix _ _ = false  
   521   fun isp s = isprefix xl s
   522   fun chg s = yl@(List.drop (s, List.length xl))
   523   fun r [] = []
   524     | r (S as (s::ss)) = if isp S then r (chg S) else s::(r ss) 
   525 in
   526   implode(r (explode s))
   527 end    
   528 
   529 fun protect_factname s = replacestr "." "_dot_" s
   530 fun unprotect_factname s = replacestr "_dot_" "." s 
   531 
   532 val ty_num_prefix = "N_"
   533 
   534 fun startsWithDigit s = Char.isDigit (hd (String.explode s))
   535 
   536 fun protect_tyname tyn = 
   537   let
   538     val tyn' = 
   539       if String.isPrefix ty_num_prefix tyn then raise (ERR "protect_ty_name" ("type name '"^tyn^"' is reserved")) else 
   540       (if startsWithDigit tyn then ty_num_prefix^tyn else tyn)
   541   in
   542     tyn'
   543   end
   544 
   545 fun protect_constname tcn = tcn 
   546  (* if tcn = ".." then "dotdot"
   547   else if tcn = "==" then "eqeq"
   548   else tcn*)
   549 
   550 structure TypeNet =
   551 struct
   552 
   553 fun get_type_from_index thy thyname types is =
   554     case Int.fromString is of
   555 	SOME i => (case Array.sub(types,i) of
   556 		       FullType ty => ty
   557 		     | XMLty xty =>
   558 		       let
   559 			   val ty = get_type_from_xml thy thyname types xty
   560 			   val _  = Array.update(types,i,FullType ty)
   561 		       in
   562 			   ty
   563 		       end)
   564       | NONE => raise ERR "get_type_from_index" "Bad index"
   565 and get_type_from_xml thy thyname types =
   566     let
   567 	fun gtfx (Elem("tyi",[("i",iS)],[])) =
   568 		 get_type_from_index thy thyname types iS
   569 	  | gtfx (Elem("tyc",atts,[])) =
   570 	    mk_thy_type thy
   571 			(get_segment thyname atts)
   572 			(protect_tyname (get_name atts))
   573 			[]
   574 	  | gtfx (Elem("tyv",[("n",s)],[])) = mk_vartype (protect_tyvarname s)
   575 	  | gtfx (Elem("tya",[],(Elem("tyc",atts,[]))::tys)) =
   576 	    mk_thy_type thy
   577 			(get_segment thyname atts)
   578 			(protect_tyname (get_name atts))
   579 			(map gtfx tys)
   580 	  | gtfx _ = raise ERR "get_type" "Bad type"
   581     in
   582 	gtfx
   583     end
   584 
   585 fun input_types thyname (Elem("tylist",[("i",i)],xtys)) =
   586     let
   587 	val types = Array.array(valOf (Int.fromString i),XMLty (Elem("",[],[])))
   588 	fun IT _ [] = ()
   589 	  | IT n (xty::xtys) =
   590 	    (Array.update(types,n,XMLty xty);
   591 	     IT (n+1) xtys)
   592 	val _ = IT 0 xtys
   593     in
   594 	types
   595     end
   596   | input_types _ _ = raise ERR "input_types" "Bad type list"
   597 end
   598 
   599 structure TermNet =
   600 struct
   601 
   602 fun get_term_from_index thy thyname types terms is =
   603     case Int.fromString is of
   604 	SOME i => (case Array.sub(terms,i) of
   605 		       FullTerm tm => tm
   606 		     | XMLtm xtm =>
   607 		       let
   608 			   val tm = get_term_from_xml thy thyname types terms xtm
   609 			   val _  = Array.update(terms,i,FullTerm tm)
   610 		       in
   611 			   tm
   612 		       end)
   613       | NONE => raise ERR "get_term_from_index" "Bad index"
   614 and get_term_from_xml thy thyname types terms =
   615     let
   616 	fun get_type [] = NONE
   617 	  | get_type [ty] = SOME (TypeNet.get_type_from_xml thy thyname types ty)
   618 	  | get_type _ = raise ERR "get_term" "Bad type"
   619 
   620 	fun gtfx (Elem("tmv",[("n",name),("t",tyi)],[])) =
   621 	    mk_var(protect_varname name,TypeNet.get_type_from_index thy thyname types tyi)
   622 	  | gtfx (Elem("tmc",atts,[])) =
   623 	    let
   624 		val segment = get_segment thyname atts
   625 		val name = protect_constname(get_name atts)
   626 	    in
   627 		mk_thy_const thy segment name (TypeNet.get_type_from_index thy thyname types (Lib.assoc "t" atts))
   628 		handle PK _ => prim_mk_const thy segment name
   629 	    end
   630 	  | gtfx (Elem("tma",[("f",tmf),("a",tma)],[])) =
   631 	    let
   632 		val f = get_term_from_index thy thyname types terms tmf
   633 		val a = get_term_from_index thy thyname types terms tma
   634 	    in
   635 		mk_comb(f,a)
   636 	    end
   637 	  | gtfx (Elem("tml",[("x",tmx),("a",tma)],[])) = 
   638 	    let		
   639                 val x = get_term_from_index thy thyname types terms tmx 
   640                 val a = get_term_from_index thy thyname types terms tma
   641 	    in
   642 		mk_lambda x a
   643 	    end
   644 	  | gtfx (Elem("tmi",[("i",iS)],[])) =
   645 	    get_term_from_index thy thyname types terms iS
   646 	  | gtfx (Elem(tag,_,_)) =
   647 	    raise ERR "get_term" ("Not a term: "^tag)
   648     in
   649 	gtfx
   650     end
   651 
   652 fun input_terms thyname types (Elem("tmlist",[("i",i)],xtms)) =
   653     let
   654 	val terms = Array.array(valOf(Int.fromString i),XMLtm (Elem("",[],[])))
   655 
   656 	fun IT _ [] = ()
   657 	  | IT n (xtm::xtms) =
   658 	    (Array.update(terms,n,XMLtm xtm);
   659 	     IT (n+1) xtms)
   660 	val _ = IT 0 xtms
   661     in
   662 	terms
   663     end
   664   | input_terms _ _ _ = raise ERR "input_terms" "Bad term list"
   665 end
   666 
   667 fun get_proof_dir (thyname:string) thy =
   668     let
   669 	val import_segment =
   670 	    case get_segment2 thyname thy of
   671 		SOME seg => seg
   672 	      | NONE => get_import_segment thy
   673 	val path = space_explode ":" (getenv "HOL4_PROOFS")
   674 	fun find [] = NONE
   675 	  | find (p::ps) =
   676 	    (let
   677 		 val dir = OS.Path.joinDirFile {dir = p,file=import_segment}
   678 	     in
   679 		 if OS.FileSys.isDir dir
   680 		 then SOME dir
   681 		 else find ps
   682 	     end) handle OS.SysErr _ => find ps
   683     in
   684 	Option.map (fn p => OS.Path.joinDirFile {dir = p, file = thyname}) (find path)
   685     end
   686 			   
   687 fun proof_file_name thyname thmname thy =
   688     let
   689 	val path = case get_proof_dir thyname thy of
   690 		       SOME p => p
   691 		     | NONE => error "Cannot find proof files"
   692 	val _ = OS.FileSys.mkDir path handle OS.SysErr _ => ()
   693     in
   694 	OS.Path.joinDirFile {dir = path, file = OS.Path.joinBaseExt {base = (unprotect_factname thmname), ext = SOME "prf"}}
   695     end
   696 	
   697 fun xml_to_proof thyname types terms prf thy =
   698     let
   699 	val xml_to_hol_type = TypeNet.get_type_from_xml thy thyname types
   700 	val xml_to_term = TermNet.get_term_from_xml thy thyname types terms
   701 
   702 	fun index_to_term is =
   703 	    TermNet.get_term_from_index thy thyname types terms is
   704 
   705 	fun x2p (Elem("prefl",[("i",is)],[])) = mk_proof (PRefl (index_to_term is))
   706 	  | x2p (Elem("pinstt",[],p::lambda)) =
   707 	    let
   708 		val p = x2p p
   709 		val lambda = implode_subst (map xml_to_hol_type lambda)
   710 	    in
   711 		mk_proof (PInstT(p,lambda))
   712 	    end
   713 	  | x2p (Elem("psubst",[("i",is)],prf::prfs)) =
   714 	    let
   715 		val tm = index_to_term is
   716 		val prf = x2p prf
   717 		val prfs = map x2p prfs
   718 	    in
   719 		mk_proof (PSubst(prfs,tm,prf))
   720 	    end
   721 	  | x2p (Elem("pabs",[("i",is)],[prf])) =
   722 	    let
   723 		val p = x2p prf
   724 		val t = index_to_term is
   725 	    in
   726 		mk_proof (PAbs (p,t))
   727 	    end
   728 	  | x2p (Elem("pdisch",[("i",is)],[prf])) =
   729 	    let
   730 		val p = x2p prf
   731 		val t = index_to_term is
   732 	    in
   733 		mk_proof (PDisch (p,t))
   734 	    end
   735 	  | x2p (Elem("pmp",[],[prf1,prf2])) =
   736 	    let
   737 		val p1 = x2p prf1
   738 		val p2 = x2p prf2
   739 	    in
   740 		mk_proof (PMp(p1,p2))
   741 	    end
   742 	  | x2p (Elem("phyp",[("i",is)],[])) = mk_proof (PHyp (index_to_term is))
   743 	  | x2p (Elem("paxiom",[("n",n),("i",is)],[])) =
   744 	    mk_proof (PAxm(n,index_to_term is))
   745 	  | x2p (Elem("pfact",atts,[])) =
   746 	    let
   747 		val thyname = get_segment thyname atts
   748 		val thmname = protect_factname (get_name atts)
   749 		val p = mk_proof PDisk
   750 		val _  = set_disk_info_of p thyname thmname
   751 	    in
   752 		p
   753 	    end
   754 	  | x2p (Elem("pdef",[("s",seg),("n",name),("i",is)],[])) =
   755 	    mk_proof (PDef(seg,protect_constname name,index_to_term is))
   756 	  | x2p (Elem("ptmspec",[("s",seg)],p::names)) =
   757 	    let
   758 		val names = map (fn Elem("name",[("n",name)],[]) => name
   759 				  | _ => raise ERR "x2p" "Bad proof (ptmspec)") names
   760 	    in
   761 		mk_proof (PTmSpec(seg,names,x2p p))
   762 	    end
   763 	  | x2p (Elem("ptyintro",[("s",seg),("n",name),("a",abs_name),("r",rep_name)],[xP,xt,p])) =
   764 	    let
   765 		val P = xml_to_term xP
   766 		val t = xml_to_term xt
   767 	    in
   768 		mk_proof (PTyIntro(seg,protect_tyname name,protect_constname abs_name,protect_constname rep_name,P,t,x2p p))
   769 	    end
   770 	  | x2p (Elem("ptydef",[("s",seg),("n",name)],[p])) =
   771 	    mk_proof (PTyDef(seg,protect_tyname name,x2p p))
   772 	  | x2p (xml as Elem("poracle",[],chldr)) =
   773 	    let
   774 		val (oracles,terms) = Library.partition (fn (Elem("oracle",_,_)) => true | _ => false) chldr
   775 		val ors = map (fn (Elem("oracle",[("n",name)],[])) => name | xml => raise ERR "x2p" "bad oracle") oracles
   776 		val (c,asl) = case terms of
   777 				  [] => raise ERR "x2p" "Bad oracle description"
   778 				| (hd::tl) => (hd,tl)
   779 		val tg = foldr (fn (oracle,tg) => Tag.merge (Tag.read oracle) tg) Tag.empty_tag ors
   780 	    in
   781 		mk_proof (POracle(tg,map xml_to_term asl,xml_to_term c))
   782 	    end
   783 	  | x2p (Elem("pspec",[("i",is)],[prf])) =
   784 	    let
   785 		val p = x2p prf
   786 		val tm = index_to_term is
   787 	    in
   788 		mk_proof (PSpec(p,tm))
   789 	    end
   790 	  | x2p (Elem("pinst",[],p::theta)) =
   791 	    let
   792 		val p = x2p p
   793 		val theta = implode_subst (map xml_to_term theta)
   794 	    in
   795 		mk_proof (PInst(p,theta))
   796 	    end
   797 	  | x2p (Elem("pgen",[("i",is)],[prf])) =
   798 	    let
   799 		val p = x2p prf
   800 		val tm = index_to_term is
   801 	    in
   802 		mk_proof (PGen(p,tm))
   803 	    end
   804 	  | x2p (Elem("pgenabs",[],prf::tms)) =
   805 	    let
   806 		val p = x2p prf
   807 		val tml = map xml_to_term tms
   808 	    in
   809 		mk_proof (PGenAbs(p,NONE,tml))
   810 	    end
   811 	  | x2p (Elem("pgenabs",[("i",is)],prf::tms)) =
   812 	    let
   813 		val p = x2p prf
   814 		val tml = map xml_to_term tms
   815 	    in
   816 		mk_proof (PGenAbs(p,SOME (index_to_term is),tml))
   817 	    end
   818 	  | x2p (Elem("pimpas",[],[prf1,prf2])) =
   819 	    let
   820 		val p1 = x2p prf1
   821 		val p2 = x2p prf2
   822 	    in
   823 		mk_proof (PImpAS(p1,p2))
   824 	    end
   825 	  | x2p (Elem("psym",[],[prf])) =
   826 	    let
   827 		val p = x2p prf
   828 	    in
   829 		mk_proof (PSym p)
   830 	    end
   831 	  | x2p (Elem("ptrans",[],[prf1,prf2])) =
   832 	    let
   833 		val p1 = x2p prf1
   834 		val p2 = x2p prf2
   835 	    in
   836 		mk_proof (PTrans(p1,p2))
   837 	    end
   838 	  | x2p (Elem("pcomb",[],[prf1,prf2])) =
   839 	    let
   840 		val p1 = x2p prf1
   841 		val p2 = x2p prf2
   842 	    in
   843 		mk_proof (PComb(p1,p2))
   844 	    end
   845 	  | x2p (Elem("peqmp",[],[prf1,prf2])) =
   846 	    let
   847 		val p1 = x2p prf1
   848 		val p2 = x2p prf2
   849 	    in
   850 		mk_proof (PEqMp(p1,p2))
   851 	    end
   852 	  | x2p (Elem("peqimp",[],[prf])) =
   853 	    let
   854 		val p = x2p prf
   855 	    in
   856 		mk_proof (PEqImp p)
   857 	    end
   858 	  | x2p (Elem("pexists",[("e",ise),("w",isw)],[prf])) =
   859 	    let
   860 		val p = x2p prf
   861 		val ex = index_to_term ise
   862 		val w = index_to_term isw
   863 	    in
   864 		mk_proof (PExists(p,ex,w))
   865 	    end
   866 	  | x2p (Elem("pchoose",[("i",is)],[prf1,prf2])) =
   867 	    let
   868 		val v  = index_to_term is
   869 		val p1 = x2p prf1
   870 		val p2 = x2p prf2
   871 	    in
   872 		mk_proof (PChoose(v,p1,p2))
   873 	    end
   874 	  | x2p (Elem("pconj",[],[prf1,prf2])) =
   875 	    let
   876 		val p1 = x2p prf1
   877 		val p2 = x2p prf2
   878 	    in
   879 		mk_proof (PConj(p1,p2))
   880 	    end
   881 	  | x2p (Elem("pconjunct1",[],[prf])) =
   882 	    let
   883 		val p = x2p prf
   884 	    in
   885 		mk_proof (PConjunct1 p)
   886 	    end
   887 	  | x2p (Elem("pconjunct2",[],[prf])) =
   888 	    let
   889 		val p = x2p prf
   890 	    in
   891 		mk_proof (PConjunct2 p)
   892 	    end
   893 	  | x2p (Elem("pdisj1",[("i",is)],[prf])) =
   894 	    let
   895 		val p = x2p prf
   896 		val t = index_to_term is
   897 	    in
   898 		mk_proof (PDisj1 (p,t))
   899 	    end
   900 	  | x2p (Elem("pdisj2",[("i",is)],[prf])) =
   901 	    let
   902 		val p = x2p prf
   903 		val t = index_to_term is
   904 	    in
   905 		mk_proof (PDisj2 (p,t))
   906 	    end
   907 	  | x2p (Elem("pdisjcases",[],[prf1,prf2,prf3])) =
   908 	    let
   909 		val p1 = x2p prf1
   910 		val p2 = x2p prf2
   911 		val p3 = x2p prf3
   912 	    in
   913 		mk_proof (PDisjCases(p1,p2,p3))
   914 	    end
   915 	  | x2p (Elem("pnoti",[],[prf])) =
   916 	    let
   917 		val p = x2p prf
   918 	    in
   919 		mk_proof (PNotI p)
   920 	    end
   921 	  | x2p (Elem("pnote",[],[prf])) =
   922 	    let
   923 		val p = x2p prf
   924 	    in
   925 		mk_proof (PNotE p)
   926 	    end
   927 	  | x2p (Elem("pcontr",[("i",is)],[prf])) =
   928 	    let
   929 		val p = x2p prf
   930 		val t = index_to_term is
   931 	    in
   932 		mk_proof (PContr (p,t))
   933 	    end
   934 	  | x2p xml = raise ERR "x2p" "Bad proof"
   935     in
   936 	x2p prf
   937     end
   938 
   939 fun import_proof_concl thyname thmname thy = 
   940     let
   941 	val is = TextIO.openIn(proof_file_name thyname thmname thy)
   942 	val (proof_xml,_) = scan_tag (LazySeq.of_instream is)
   943 	val _ = TextIO.closeIn is
   944     in 
   945 	case proof_xml of
   946 	    Elem("proof",[],xtypes::xterms::prf::rest) =>
   947 	    let
   948 		val types = TypeNet.input_types thyname xtypes
   949 		val terms = TermNet.input_terms thyname types xterms
   950                 fun f xtm thy = TermNet.get_term_from_xml thy thyname types terms xtm               
   951 	    in
   952 		case rest of
   953 		    [] => NONE
   954 		  | [xtm] => SOME (f xtm)
   955 		  | _ => raise ERR "import_proof" "Bad argument list"
   956 	    end
   957 	  | _ => raise ERR "import_proof" "Bad proof"
   958     end
   959 
   960 fun import_proof thyname thmname thy =
   961     let
   962 	val is = TextIO.openIn(proof_file_name thyname thmname thy)
   963 	val (proof_xml,_) = scan_tag (LazySeq.of_instream is)
   964 	val _ = TextIO.closeIn is
   965     in 
   966 	case proof_xml of
   967 	    Elem("proof",[],xtypes::xterms::prf::rest) =>
   968 	    let
   969 		val types = TypeNet.input_types thyname xtypes
   970 		val terms = TermNet.input_terms thyname types xterms
   971 	    in
   972 		(case rest of
   973 		     [] => NONE
   974 		   | [xtm] => SOME (fn thy => TermNet.get_term_from_xml thy thyname types terms xtm)
   975 		   | _ => raise ERR "import_proof" "Bad argument list",
   976 		 xml_to_proof thyname types terms prf)
   977 	    end
   978 	  | _ => raise ERR "import_proof" "Bad proof"
   979     end
   980 
   981 fun uniq_compose m th i st =
   982     let
   983 	val res = bicompose false (false,th,m) i st
   984     in
   985 	case Seq.pull res of
   986 	    SOME (th,rest) => (case Seq.pull rest of
   987 				   SOME _ => raise ERR "uniq_compose" "Not unique!"
   988 				 | NONE => th)
   989 	  | NONE => raise ERR "uniq_compose" "No result"
   990     end
   991 
   992 val reflexivity_thm = thm "refl"
   993 val substitution_thm = thm "subst"
   994 val mp_thm = thm "mp"
   995 val imp_antisym_thm = thm "light_imp_as"
   996 val disch_thm = thm "impI"
   997 val ccontr_thm = thm "ccontr"
   998 
   999 val meta_eq_to_obj_eq_thm = thm "meta_eq_to_obj_eq"
  1000 
  1001 val gen_thm = thm "HOLallI"
  1002 val choose_thm = thm "exE"
  1003 val exists_thm = thm "exI"
  1004 val conj_thm = thm "conjI"
  1005 val conjunct1_thm = thm "conjunct1"
  1006 val conjunct2_thm = thm "conjunct2"
  1007 val spec_thm = thm "spec"
  1008 val disj_cases_thm = thm "disjE"
  1009 val disj1_thm = thm "disjI1"
  1010 val disj2_thm = thm "disjI2"
  1011 
  1012 local
  1013     val th = thm "not_def"
  1014     val thy = theory_of_thm th
  1015     val pp = reflexive (cterm_of thy (Const("Trueprop",boolT-->propT)))
  1016 in
  1017 val not_elim_thm = combination pp th
  1018 end
  1019 
  1020 val not_intro_thm = symmetric not_elim_thm
  1021 val abs_thm = thm "ext"
  1022 val trans_thm = thm "trans"
  1023 val symmetry_thm = thm "sym"
  1024 val transitivity_thm = thm "trans"
  1025 val eqmp_thm = thm "iffD1"
  1026 val eqimp_thm = thm "HOL4Setup.eq_imp"
  1027 val comb_thm = thm "cong"
  1028 
  1029 (* Beta-eta normalizes a theorem (only the conclusion, not the *
  1030 hypotheses!)  *)
  1031 
  1032 fun beta_eta_thm th =
  1033     let
  1034 	val th1 = Thm.equal_elim (Thm.beta_conversion true (cprop_of th))  th
  1035 	val th2 = Thm.equal_elim (Thm.eta_conversion       (cprop_of th1)) th1
  1036     in
  1037 	th2
  1038     end
  1039 
  1040 fun implies_elim_all th =
  1041     Library.foldl (fn (th,p) => implies_elim th (assume p)) (th,cprems_of th)
  1042 
  1043 fun norm_hyps th =
  1044     th |> beta_eta_thm
  1045        |> implies_elim_all
  1046        |> implies_intr_hyps
  1047 
  1048 fun mk_GEN v th sg =
  1049     let
  1050 	val c = HOLogic.dest_Trueprop (concl_of th)
  1051 	val cv = cterm_of sg v
  1052 	val lc = Term.lambda v c
  1053 	val clc = Thm.cterm_of sg lc
  1054 	val cvty = ctyp_of_term cv
  1055 	val th1 = implies_elim_all th
  1056 	val th2 = beta_eta_thm (forall_intr cv th1)
  1057 	val th3 = th2 COMP (beta_eta_thm (Drule.instantiate' [SOME cvty] [SOME clc] gen_thm))
  1058 	val c = prop_of th3
  1059 	val vname = fst(dest_Free v)
  1060 	val (cold,cnew) = case c of
  1061 			      tpc $ (Const("All",allT) $ Abs(oldname,ty,body)) =>
  1062 			      (Abs(oldname,dummyT,Bound 0),Abs(vname,dummyT,Bound 0))
  1063 			    | tpc $ (Const("All",allT) $ rest) => (tpc,tpc)
  1064 			    | _ => raise ERR "mk_GEN" "Unknown conclusion"
  1065 	val th4 = Thm.rename_boundvars cold cnew th3
  1066 	val res = implies_intr_hyps th4
  1067     in
  1068 	res
  1069     end
  1070 
  1071 val permute_prems = Thm.permute_prems 
  1072 
  1073 fun rearrange sg tm th =
  1074     let
  1075 	val tm' = Envir.beta_eta_contract tm
  1076 	fun find []      n = permute_prems 0 1 (implies_intr (Thm.cterm_of sg tm) th)
  1077 	  | find (p::ps) n = if tm' aconv (Envir.beta_eta_contract p)
  1078 			     then permute_prems n 1 th
  1079 			     else find ps (n+1)
  1080     in
  1081 	find (prems_of th) 0
  1082     end
  1083 
  1084 fun zip (x::xs) (y::ys) = (x,y)::(zip xs ys)
  1085   | zip [] [] = []
  1086   | zip _ _ = raise ERR "zip" "arguments not of same length"
  1087 
  1088 fun mk_INST dom rng th =
  1089     th |> forall_intr_list dom
  1090        |> forall_elim_list rng
  1091 
  1092 val collect_vars =
  1093     let
  1094 	fun F vars (Bound _) = vars
  1095 	  | F vars (tm as Free _) =
  1096 	    if tm mem vars
  1097 	    then vars
  1098 	    else (tm::vars)
  1099 	  | F vars (Const _) = vars
  1100 	  | F vars (tm1 $ tm2) = F (F vars tm1) tm2
  1101 	  | F vars (Abs(_,_,body)) = F vars body
  1102 	  | F vars (Var _) = raise ERR "collect_vars" "Schematic variable found"
  1103     in
  1104 	F []
  1105     end
  1106 
  1107 (* Code for disambiguating variablenames (wrt. types) *)
  1108 
  1109 val disamb_info_empty = {vars=[],rens=[]}
  1110 
  1111 fun rens_of {vars,rens} = rens
  1112 
  1113 fun name_of_var (Free(vname,_)) = vname
  1114   | name_of_var _ = raise ERR "name_of_var" "Not a variable"
  1115 
  1116 fun disamb_term_from info tm = (info, tm)
  1117 
  1118 fun swap (x,y) = (y,x)
  1119 
  1120 fun has_ren (HOLThm _) = false
  1121 
  1122 fun prinfo {vars,rens} = (writeln "Vars:";
  1123 			  app prin vars;
  1124 			  writeln "Renaming:";
  1125 			  app (fn(x,y)=>(prin x; writeln " -->"; prin y)) rens)
  1126 
  1127 fun disamb_thm_from info (HOLThm (_,thm)) = (info, thm)
  1128 
  1129 fun disamb_terms_from info tms = (info, tms)
  1130 
  1131 fun disamb_thms_from info hthms = (info, map hthm2thm hthms)
  1132 
  1133 fun disamb_term tm   = disamb_term_from disamb_info_empty tm
  1134 fun disamb_terms tms = disamb_terms_from disamb_info_empty tms
  1135 fun disamb_thm thm   = disamb_thm_from disamb_info_empty thm
  1136 fun disamb_thms thms = disamb_thms_from disamb_info_empty thms
  1137 
  1138 fun norm_hthm sg (hth as HOLThm _) = hth
  1139 
  1140 (* End of disambiguating code *)
  1141 
  1142 fun disambiguate_frees thm =
  1143     let
  1144       fun ERR s = error ("Drule.disambiguate_frees: "^s)
  1145       val ct = cprop_of thm
  1146       val t = term_of ct
  1147       val thy = theory_of_cterm ct
  1148       val frees = term_frees t
  1149       val freenames = add_term_free_names (t, [])
  1150       fun is_old_name n = n mem_string freenames
  1151       fun name_of (Free (n, _)) = n
  1152         | name_of _ = ERR "name_of"
  1153       fun new_name' bump map n =
  1154           let val n' = n^bump in
  1155             if is_old_name n' orelse Symtab.lookup map n' <> NONE then 
  1156               new_name' (Symbol.bump_string bump) map n
  1157             else
  1158               n'
  1159           end              
  1160       val new_name = new_name' "a"
  1161       fun replace_name n' (Free (n, t)) = Free (n', t)
  1162         | replace_name n' _ = ERR "replace_name"
  1163       (* map: old or fresh name -> old free, 
  1164          invmap: old free which has fresh name assigned to it -> fresh name *)
  1165       fun dis (v, mapping as (map,invmap)) =
  1166           let val n = name_of v in
  1167             case Symtab.lookup map n of
  1168               NONE => (Symtab.update (n, v) map, invmap)
  1169             | SOME v' => 
  1170               if v=v' then 
  1171                 mapping 
  1172               else
  1173                 let val n' = new_name map n in
  1174                   (Symtab.update (n', v) map, 
  1175                    Termtab.update (v, n') invmap)
  1176                 end
  1177           end
  1178     in
  1179       if (length freenames = length frees) then
  1180         thm
  1181       else
  1182         let 
  1183           val (_, invmap) = 
  1184               List.foldl dis (Symtab.empty, Termtab.empty) frees 
  1185           fun make_subst ((oldfree, newname), (intros, elims)) =
  1186               (cterm_of thy oldfree :: intros, 
  1187                cterm_of thy (replace_name newname oldfree) :: elims)
  1188           val (intros, elims) = List.foldl make_subst ([], []) (Termtab.dest invmap)
  1189         in 
  1190           forall_elim_list elims (forall_intr_list intros thm)
  1191         end     
  1192     end
  1193 
  1194 val debug = ref false
  1195 
  1196 fun if_debug f x = if !debug then f x else ()
  1197 val message = if_debug writeln
  1198 
  1199 val conjE_helper = permute_prems 0 1 conjE
  1200 
  1201 fun get_hol4_thm thyname thmname thy =
  1202     case get_hol4_theorem thyname thmname thy of
  1203 	SOME hth => SOME (HOLThm hth)
  1204       | NONE => 
  1205 	let
  1206 	    val pending = HOL4Pending.get thy
  1207 	in
  1208 	    case StringPair.lookup pending (thyname,thmname) of
  1209 		SOME hth => SOME (HOLThm hth)
  1210 	      | NONE => NONE
  1211 	end
  1212 
  1213 fun non_trivial_term_consts tm =
  1214     List.filter (fn c => not (c = "Trueprop" orelse
  1215 			 c = "All" orelse
  1216 			 c = "op -->" orelse
  1217 			 c = "op &" orelse
  1218 			 c = "op =")) (Term.term_consts tm) 
  1219 
  1220 fun match_consts t (* th *) =
  1221     let
  1222 	fun add_consts (Const (c, _), cs) =
  1223 	    (case c of
  1224 		 "op =" => "==" ins_string cs
  1225 	       | "op -->" => "==>" ins_string cs
  1226 	       | "All" => cs
  1227 	       | "all" => cs
  1228 	       | "op &" => cs
  1229 	       | "Trueprop" => cs
  1230 	       | _ => c ins_string cs)
  1231 	  | add_consts (t $ u, cs) = add_consts (t, add_consts (u, cs))
  1232 	  | add_consts (Abs (_, _, t), cs) = add_consts (t, cs)
  1233 	  | add_consts (_, cs) = cs
  1234 	val t_consts = add_consts(t,[])
  1235     in
  1236 	fn th => eq_set(t_consts,add_consts(prop_of th,[]))
  1237     end
  1238 
  1239 fun split_name str =
  1240     let
  1241 	val sub = Substring.full str
  1242 	val (f,idx) = apsnd Substring.string (Substring.splitr Char.isDigit sub)
  1243 	val (newstr,u) = apboth Substring.string (Substring.splitr (fn c => c = #"_") f)
  1244     in
  1245 	if not (idx = "") andalso u = "_"
  1246 	then SOME (newstr,valOf(Int.fromString idx))
  1247 	else NONE
  1248     end
  1249     handle _ => NONE
  1250 
  1251 fun rewrite_hol4_term t thy =
  1252     let
  1253 	val hol4rews1 = map (Thm.transfer thy) (HOL4Rewrites.get thy)
  1254 	val hol4ss = Simplifier.theory_context thy empty_ss
  1255           setmksimps single addsimps hol4rews1
  1256     in
  1257 	Thm.transfer thy (Simplifier.full_rewrite hol4ss (cterm_of thy t))
  1258     end
  1259 
  1260 fun get_isabelle_thm thyname thmname hol4conc thy =
  1261     let
  1262 	val (info,hol4conc') = disamb_term hol4conc
  1263 	val i2h_conc = symmetric (rewrite_hol4_term (HOLogic.mk_Trueprop hol4conc') thy)
  1264 	val isaconc =
  1265 	    case concl_of i2h_conc of
  1266 		Const("==",_) $ lhs $ _ => lhs
  1267 	      | _ => error "get_isabelle_thm" "Bad rewrite rule"
  1268 	val _ = (message "Original conclusion:";
  1269 		 if_debug prin hol4conc';
  1270 		 message "Modified conclusion:";
  1271 		 if_debug prin isaconc)
  1272 
  1273 	fun mk_res th = HOLThm(rens_of info,equal_elim i2h_conc th)
  1274     in
  1275 	case get_hol4_mapping thyname thmname thy of
  1276 	    SOME (SOME thmname) =>
  1277 	    let
  1278 		val th1 = (SOME (PureThy.get_thm thy (Name thmname))
  1279 			   handle ERROR _ =>
  1280 				  (case split_name thmname of
  1281 				       SOME (listname,idx) => (SOME (List.nth(PureThy.get_thms thy (Name listname),idx-1))
  1282 							       handle _ => NONE)
  1283 				     | NONE => NONE))
  1284 	    in
  1285 		case th1 of
  1286 		    SOME th2 =>
  1287 		    (case Shuffler.set_prop thy isaconc [(thmname,th2)] of
  1288 			 SOME (_,th) => (message "YES";(thy, SOME (mk_res th)))
  1289 		       | NONE => (message "NO2";error "get_isabelle_thm" "Bad mapping"))
  1290 		  | NONE => (message "NO1";error "get_isabelle_thm" "Bad mapping")
  1291 	    end
  1292 	  | SOME NONE => error ("Trying to access ignored theorem " ^ thmname)
  1293 	  | NONE =>
  1294 	    let		
  1295 		val _ = (message "Looking for conclusion:";
  1296 			 if_debug prin isaconc)
  1297 		val cs = non_trivial_term_consts isaconc
  1298 		val _ = (message "Looking for consts:";
  1299 			 message (commas cs))
  1300 		val pot_thms = Shuffler.find_potential thy isaconc
  1301 		val _ = message ((Int.toString (length pot_thms)) ^ " potential theorems")
  1302 	    in
  1303 		case Shuffler.set_prop thy isaconc pot_thms of
  1304 		    SOME (isaname,th) =>
  1305 		    let
  1306 			val hth as HOLThm args = mk_res th
  1307 			val thy' =  thy |> add_hol4_theorem thyname thmname args
  1308 					|> add_hol4_mapping thyname thmname isaname
  1309 			val _ = ImportRecorder.add_hol_theorem thyname thmname (snd args)
  1310 			val _ = ImportRecorder.add_hol_mapping thyname thmname isaname
  1311 		    in
  1312 			(thy',SOME hth)
  1313 		    end
  1314 		  | NONE => (thy,NONE)
  1315 	    end
  1316     end
  1317     handle e => (message "Exception in get_isabelle_thm"; if_debug print_exn e handle _ => (); (thy,NONE))
  1318 
  1319 fun get_isabelle_thm_and_warn thyname thmname hol4conc thy =
  1320   let
  1321     val (a, b) = get_isabelle_thm thyname thmname hol4conc thy
  1322     fun warn () =
  1323         let
  1324 	    val (info,hol4conc') = disamb_term hol4conc
  1325 	    val i2h_conc = symmetric (rewrite_hol4_term (HOLogic.mk_Trueprop hol4conc') thy)
  1326 	in
  1327 	    case concl_of i2h_conc of
  1328 		Const("==",_) $ lhs $ _ => 
  1329 		(warning ("Failed lookup of theorem '"^thmname^"':");
  1330 	         writeln "Original conclusion:";
  1331 		 prin hol4conc';
  1332 		 writeln "Modified conclusion:";
  1333 		 prin lhs)
  1334 	      | _ => ()
  1335 	end
  1336   in
  1337       case b of 
  1338 	  NONE => (warn () handle _ => (); (a,b))
  1339 	| _ => (a, b)
  1340   end 
  1341 
  1342 fun get_thm thyname thmname thy =
  1343     case get_hol4_thm thyname thmname thy of
  1344 	SOME hth => (thy,SOME hth)
  1345       | NONE => ((case import_proof_concl thyname thmname thy of
  1346 		      SOME f => get_isabelle_thm_and_warn thyname thmname (f thy) thy
  1347 		    | NONE => (message "No conclusion"; (thy,NONE)))
  1348 		 handle e as IO.Io _ => (message "IO exception"; (thy,NONE))
  1349 		      | e as PK _ => (message "PK exception"; (thy,NONE)))
  1350 
  1351 fun rename_const thyname thy name =
  1352     case get_hol4_const_renaming thyname name thy of
  1353 	SOME cname => cname
  1354       | NONE => name
  1355 
  1356 fun get_def thyname constname rhs thy =
  1357     let
  1358 	val constname = rename_const thyname thy constname
  1359 	val (thmname,thy') = get_defname thyname constname thy
  1360 	val _ = message ("Looking for definition " ^ thyname ^ "." ^ thmname)
  1361     in
  1362 	get_isabelle_thm_and_warn thyname thmname (mk_teq (thyname ^ "." ^ constname) rhs thy') thy'
  1363     end
  1364 
  1365 fun get_axiom thyname axname thy =
  1366     case get_thm thyname axname thy of
  1367 	arg as (_,SOME _) => arg
  1368       | _ => raise ERR "get_axiom" ("Trying to retrieve axiom (" ^ axname ^ ")")
  1369 
  1370 fun intern_store_thm gen_output thyname thmname hth thy =
  1371     let
  1372 	val (hth' as HOLThm (args as (_,th))) = norm_hthm thy hth
  1373 	val rew = rewrite_hol4_term (concl_of th) thy
  1374 	val th  = equal_elim rew th
  1375 	val thy' = add_hol4_pending thyname thmname args thy
  1376 	val _ = ImportRecorder.add_hol_pending thyname thmname (hthm2thm hth') 
  1377         val th = disambiguate_frees th
  1378 	val thy2 = if gen_output
  1379 		   then add_dump ("lemma " ^ (quotename thmname) ^ ": " ^ 
  1380                                   (smart_string_of_thm th) ^ "\n  by (import " ^ 
  1381                                   thyname ^ " " ^ (quotename thmname) ^ ")") thy'
  1382 		   else thy'
  1383     in
  1384 	(thy2,hth')
  1385     end
  1386 
  1387 val store_thm = intern_store_thm true
  1388 
  1389 fun mk_REFL ctm =
  1390     let
  1391 	val cty = Thm.ctyp_of_term ctm
  1392     in
  1393 	Drule.instantiate' [SOME cty] [SOME ctm] reflexivity_thm
  1394     end
  1395 
  1396 fun REFL tm thy =
  1397     let
  1398 	val _ = message "REFL:"
  1399 	val (info,tm') = disamb_term tm
  1400 	val ctm = Thm.cterm_of thy tm'
  1401 	val res = HOLThm(rens_of info,mk_REFL ctm)
  1402 	val _ = if_debug pth res
  1403     in
  1404 	(thy,res)
  1405     end
  1406 
  1407 fun ASSUME tm thy =
  1408     let
  1409 	val _ = message "ASSUME:"
  1410 	val (info,tm') = disamb_term tm
  1411 	val ctm = Thm.cterm_of thy (HOLogic.mk_Trueprop tm')
  1412 	val th = Thm.trivial ctm
  1413 	val res = HOLThm(rens_of info,th)
  1414 	val _ = if_debug pth res
  1415     in
  1416 	(thy,res)
  1417     end
  1418 
  1419 fun INST_TYPE lambda (hth as HOLThm(rens,th)) thy =
  1420     let
  1421 	val _ = message "INST_TYPE:"
  1422 	val _ = if_debug pth hth
  1423 	val tys_before = add_term_tfrees (prop_of th,[])
  1424 	val th1 = varifyT th
  1425 	val tys_after = add_term_tvars (prop_of th1,[])
  1426 	val tyinst = map (fn (bef, iS) =>
  1427 			     (case try (Lib.assoc (TFree bef)) lambda of
  1428 				  SOME ty => (ctyp_of thy (TVar iS), ctyp_of thy ty)
  1429 				| NONE => (ctyp_of thy (TVar iS), ctyp_of thy (TFree bef))
  1430 			     ))
  1431 			 (zip tys_before tys_after)
  1432 	val res = Drule.instantiate (tyinst,[]) th1
  1433 	val hth = HOLThm([],res)
  1434 	val res = norm_hthm thy hth
  1435 	val _ = message "RESULT:"
  1436 	val _ = if_debug pth res
  1437     in
  1438 	(thy,res)
  1439     end
  1440 
  1441 fun INST sigma hth thy =
  1442     let
  1443 	val _ = message "INST:"
  1444 	val _ = if_debug (app (fn (x,y) => (prin x; prin y))) sigma
  1445 	val _ = if_debug pth hth
  1446 	val (sdom,srng) = ListPair.unzip (rev sigma)
  1447 	val th = hthm2thm hth
  1448 	val th1 = mk_INST (map (cterm_of thy) sdom) (map (cterm_of thy) srng) th
  1449 	val res = HOLThm([],th1)
  1450 	val _ = message "RESULT:"
  1451 	val _ = if_debug pth res
  1452     in
  1453 	(thy,res)
  1454     end
  1455 
  1456 fun EQ_IMP_RULE (hth as HOLThm(rens,th)) thy =
  1457     let
  1458 	val _ = message "EQ_IMP_RULE:"
  1459 	val _ = if_debug pth hth
  1460 	val res = HOLThm(rens,th RS eqimp_thm)
  1461 	val _ = message "RESULT:"
  1462 	val _ = if_debug pth res
  1463     in
  1464 	(thy,res)
  1465     end
  1466 
  1467 fun mk_EQ_MP th1 th2 = [beta_eta_thm th1, beta_eta_thm th2] MRS eqmp_thm
  1468 
  1469 fun EQ_MP hth1 hth2 thy =
  1470     let
  1471 	val _ = message "EQ_MP:"
  1472 	val _ = if_debug pth hth1
  1473 	val _ = if_debug pth hth2
  1474 	val (info,[th1,th2]) = disamb_thms [hth1,hth2]
  1475 	val res = HOLThm(rens_of info,mk_EQ_MP th1 th2)
  1476 	val _ = message "RESULT:"
  1477 	val _ = if_debug pth res
  1478     in
  1479 	(thy,res)
  1480     end
  1481 
  1482 fun mk_COMB th1 th2 thy =
  1483     let
  1484 	val (f,g) = case concl_of th1 of
  1485 			_ $ (Const("op =",_) $ f $ g) => (f,g)
  1486 		      | _ => raise ERR "mk_COMB" "First theorem not an equality"
  1487 	val (x,y) = case concl_of th2 of
  1488 			_ $ (Const("op =",_) $ x $ y) => (x,y)
  1489 		      | _ => raise ERR "mk_COMB" "Second theorem not an equality"
  1490 	val fty = type_of f
  1491 	val (fd,fr) = dom_rng fty
  1492 	val comb_thm' = Drule.instantiate'
  1493 			    [SOME (ctyp_of thy fd),SOME (ctyp_of thy fr)]
  1494 			    [SOME (cterm_of thy f),SOME (cterm_of thy g),
  1495 			     SOME (cterm_of thy x),SOME (cterm_of thy y)] comb_thm
  1496     in
  1497 	[th1,th2] MRS comb_thm'
  1498     end
  1499 
  1500 fun SUBST rews ctxt hth thy =
  1501     let
  1502 	val _ = message "SUBST:"
  1503 	val _ = if_debug (app pth) rews
  1504 	val _ = if_debug prin ctxt
  1505 	val _ = if_debug pth hth
  1506 	val (info,th) = disamb_thm hth
  1507 	val (info1,ctxt') = disamb_term_from info ctxt
  1508 	val (info2,rews') = disamb_thms_from info1 rews
  1509 
  1510 	val cctxt = cterm_of thy ctxt'
  1511 	fun subst th [] = th
  1512 	  | subst th (rew::rews) = subst (mk_COMB th rew thy) rews
  1513 	val res = HOLThm(rens_of info2,mk_EQ_MP (subst (mk_REFL cctxt) rews') th)
  1514 	val _ = message "RESULT:"
  1515 	val _ = if_debug pth res
  1516     in
  1517 	(thy,res)
  1518     end
  1519 
  1520 fun DISJ_CASES hth hth1 hth2 thy =
  1521     let
  1522 	val _ = message "DISJ_CASES:"
  1523 	val _ = if_debug (app pth) [hth,hth1,hth2]
  1524 	val (info,th) = disamb_thm hth
  1525 	val (info1,th1) = disamb_thm_from info hth1
  1526 	val (info2,th2) = disamb_thm_from info1 hth2
  1527 	val th1 = norm_hyps th1
  1528 	val th2 = norm_hyps th2
  1529 	val (l,r) = case concl_of th of
  1530 			_ $ (Const("op |",_) $ l $ r) => (l,r)
  1531 		      | _ => raise ERR "DISJ_CASES" "Conclusion not a disjunction"
  1532 	val th1' = rearrange thy (HOLogic.mk_Trueprop l) th1
  1533 	val th2' = rearrange thy (HOLogic.mk_Trueprop r) th2
  1534 	val res1 = th RS disj_cases_thm
  1535 	val res2 = uniq_compose ((nprems_of th1')-1) th1' ((nprems_of th)+1) res1
  1536 	val res3 = uniq_compose ((nprems_of th2')-1) th2' (nprems_of res2) res2
  1537 	val res  = HOLThm(rens_of info2,res3)
  1538 	val _ = message "RESULT:"
  1539 	val _ = if_debug pth res
  1540     in
  1541 	(thy,res)
  1542     end
  1543 
  1544 fun DISJ1 hth tm thy =
  1545     let
  1546 	val _ = message "DISJ1:"
  1547 	val _ = if_debug pth hth
  1548 	val _ = if_debug prin tm
  1549 	val (info,th) = disamb_thm hth
  1550 	val (info',tm') = disamb_term_from info tm
  1551 	val ct = Thm.cterm_of thy tm'
  1552 	val disj1_thm' = Drule.instantiate' [] [NONE,SOME ct] disj1_thm
  1553 	val res = HOLThm(rens_of info',th RS disj1_thm')
  1554 	val _ = message "RESULT:"
  1555 	val _ = if_debug pth res
  1556     in
  1557 	(thy,res)
  1558     end
  1559 
  1560 fun DISJ2 tm hth thy =
  1561     let
  1562 	val _ = message "DISJ1:"
  1563 	val _ = if_debug prin tm
  1564 	val _ = if_debug pth hth
  1565 	val (info,th) = disamb_thm hth
  1566 	val (info',tm') = disamb_term_from info tm
  1567 	val ct = Thm.cterm_of thy tm'
  1568 	val disj2_thm' = Drule.instantiate' [] [NONE,SOME ct] disj2_thm
  1569 	val res = HOLThm(rens_of info',th RS disj2_thm')
  1570 	val _ = message "RESULT:"
  1571 	val _ = if_debug pth res
  1572     in
  1573 	(thy,res)
  1574     end
  1575 
  1576 fun IMP_ANTISYM hth1 hth2 thy =
  1577     let
  1578 	val _ = message "IMP_ANTISYM:"
  1579 	val _ = if_debug pth hth1
  1580 	val _ = if_debug pth hth2
  1581 	val (info,[th1,th2]) = disamb_thms [hth1,hth2]
  1582 	val th = [beta_eta_thm th1,beta_eta_thm th2] MRS imp_antisym_thm
  1583 	val res = HOLThm(rens_of info,th)
  1584 	val _ = message "RESULT:"
  1585 	val _ = if_debug pth res
  1586     in
  1587 	(thy,res)
  1588     end
  1589 
  1590 fun SYM (hth as HOLThm(rens,th)) thy =
  1591     let
  1592 	val _ = message "SYM:"
  1593 	val _ = if_debug pth hth
  1594 	val th = th RS symmetry_thm
  1595 	val res = HOLThm(rens,th)
  1596 	val _ = message "RESULT:"
  1597 	val _ = if_debug pth res
  1598     in
  1599 	(thy,res)
  1600     end
  1601 
  1602 fun MP hth1 hth2 thy =
  1603     let
  1604 	val _ = message "MP:"
  1605 	val _ = if_debug pth hth1
  1606 	val _ = if_debug pth hth2
  1607 	val (info,[th1,th2]) = disamb_thms [hth1,hth2]
  1608 	val th = [beta_eta_thm th1,beta_eta_thm th2] MRS mp_thm
  1609 	val res = HOLThm(rens_of info,th)
  1610 	val _ = message "RESULT:"
  1611 	val _ = if_debug pth res
  1612     in
  1613 	(thy,res)
  1614     end
  1615 
  1616 fun CONJ hth1 hth2 thy =
  1617     let
  1618 	val _ = message "CONJ:"
  1619 	val _ = if_debug pth hth1
  1620 	val _ = if_debug pth hth2
  1621 	val (info,[th1,th2]) = disamb_thms [hth1,hth2]
  1622 	val th = [th1,th2] MRS conj_thm
  1623 	val res = HOLThm(rens_of info,th)
  1624 	val _ = message "RESULT:"
  1625 	val _ = if_debug pth res
  1626     in
  1627 	(thy,res)
  1628     end
  1629 
  1630 fun CONJUNCT1 (hth as HOLThm(rens,th)) thy =
  1631     let
  1632 	val _ = message "CONJUNCT1:"
  1633 	val _ = if_debug pth hth
  1634 	val res = HOLThm(rens,th RS conjunct1_thm)
  1635 	val _ = message "RESULT:"
  1636 	val _ = if_debug pth res
  1637     in
  1638 	(thy,res)
  1639     end
  1640 
  1641 fun CONJUNCT2 (hth as HOLThm(rens,th)) thy =
  1642     let
  1643 	val _ = message "CONJUNCT1:"
  1644 	val _ = if_debug pth hth
  1645 	val res = HOLThm(rens,th RS conjunct2_thm)
  1646 	val _ = message "RESULT:"
  1647 	val _ = if_debug pth res
  1648     in
  1649 	(thy,res)
  1650     end
  1651 
  1652 fun EXISTS ex wit hth thy =
  1653     let
  1654 	val _ = message "EXISTS:"
  1655 	val _ = if_debug prin ex
  1656 	val _ = if_debug prin wit
  1657 	val _ = if_debug pth hth
  1658 	val (info,th) = disamb_thm hth
  1659 	val (info',[ex',wit']) = disamb_terms_from info [ex,wit]
  1660 	val cwit = cterm_of thy wit'
  1661 	val cty = ctyp_of_term cwit
  1662 	val a = case ex' of
  1663 		    (Const("Ex",_) $ a) => a
  1664 		  | _ => raise ERR "EXISTS" "Argument not existential"
  1665 	val ca = cterm_of thy a
  1666 	val exists_thm' = beta_eta_thm (Drule.instantiate' [SOME cty] [SOME ca,SOME cwit] exists_thm)
  1667 	val th1 = beta_eta_thm th
  1668 	val th2 = implies_elim_all th1
  1669 	val th3 = th2 COMP exists_thm'
  1670 	val th  = implies_intr_hyps th3
  1671 	val res = HOLThm(rens_of info',th)
  1672 	val _   = message "RESULT:"
  1673 	val _   = if_debug pth res
  1674     in
  1675 	(thy,res)
  1676     end
  1677 
  1678 fun CHOOSE v hth1 hth2 thy =
  1679     let
  1680 	val _ = message "CHOOSE:"
  1681 	val _ = if_debug prin v
  1682 	val _ = if_debug pth hth1
  1683 	val _ = if_debug pth hth2
  1684 	val (info,[th1,th2]) = disamb_thms [hth1,hth2]
  1685 	val (info',v') = disamb_term_from info v
  1686 	fun strip 0 _ th = th
  1687 	  | strip n (p::ps) th =
  1688 	    strip (n-1) ps (implies_elim th (assume p))
  1689 	  | strip _ _ _ = raise ERR "CHOOSE" "strip error"
  1690 	val cv = cterm_of thy v'
  1691 	val th2 = norm_hyps th2
  1692 	val cvty = ctyp_of_term cv
  1693 	val c = HOLogic.dest_Trueprop (concl_of th2)
  1694 	val cc = cterm_of thy c
  1695 	val a = case concl_of th1 of
  1696 		    _ $ (Const("Ex",_) $ a) => a
  1697 		  | _ => raise ERR "CHOOSE" "Conclusion not existential"
  1698 	val ca = cterm_of (theory_of_thm th1) a
  1699 	val choose_thm' = beta_eta_thm (Drule.instantiate' [SOME cvty] [SOME ca,SOME cc] choose_thm)
  1700 	val th21 = rearrange thy (HOLogic.mk_Trueprop (a $ v')) th2
  1701 	val th22 = strip ((nprems_of th21)-1) (cprems_of th21) th21
  1702 	val th23 = beta_eta_thm (forall_intr cv th22)
  1703 	val th11 = implies_elim_all (beta_eta_thm th1)
  1704 	val th' = th23 COMP (th11 COMP choose_thm')
  1705 	val th = implies_intr_hyps th'
  1706 	val res = HOLThm(rens_of info',th)
  1707 	val _   = message "RESULT:"
  1708 	val _   = if_debug pth res
  1709     in
  1710 	(thy,res)
  1711     end
  1712 
  1713 fun GEN v hth thy =
  1714     let
  1715       val _ = message "GEN:"
  1716 	val _ = if_debug prin v
  1717 	val _ = if_debug pth hth
  1718 	val (info,th) = disamb_thm hth
  1719 	val (info',v') = disamb_term_from info v
  1720 	val res = HOLThm(rens_of info',mk_GEN v' th thy)
  1721 	val _ = message "RESULT:"
  1722 	val _ = if_debug pth res
  1723     in
  1724 	(thy,res)
  1725     end
  1726 
  1727 fun SPEC tm hth thy =
  1728     let
  1729 	val _ = message "SPEC:"
  1730 	val _ = if_debug prin tm
  1731 	val _ = if_debug pth hth
  1732 	val (info,th) = disamb_thm hth
  1733 	val (info',tm') = disamb_term_from info tm
  1734 	val ctm = Thm.cterm_of thy tm'
  1735 	val cty = Thm.ctyp_of_term ctm
  1736 	val spec' = Drule.instantiate' [SOME cty] [NONE,SOME ctm] spec_thm
  1737 	val th = th RS spec'
  1738 	val res = HOLThm(rens_of info',th)
  1739 	val _ = message "RESULT:"
  1740 	val _ = if_debug pth res
  1741     in
  1742 	(thy,res)
  1743     end
  1744 
  1745 fun COMB hth1 hth2 thy =
  1746     let
  1747 	val _ = message "COMB:"
  1748 	val _ = if_debug pth hth1
  1749 	val _ = if_debug pth hth2
  1750 	val (info,[th1,th2]) = disamb_thms [hth1,hth2]
  1751 	val res = HOLThm(rens_of info,mk_COMB th1 th2 thy)
  1752 	val _ = message "RESULT:"
  1753 	val _ = if_debug pth res
  1754     in
  1755 	(thy,res)
  1756     end
  1757 
  1758 fun TRANS hth1 hth2 thy =
  1759     let
  1760 	val _ = message "TRANS:"
  1761 	val _ = if_debug pth hth1
  1762 	val _ = if_debug pth hth2
  1763 	val (info,[th1,th2]) = disamb_thms [hth1,hth2]
  1764 	val th = [th1,th2] MRS trans_thm
  1765 	val res = HOLThm(rens_of info,th)
  1766 	val _ = message "RESULT:"
  1767 	val _ = if_debug pth res
  1768     in
  1769 	(thy,res)
  1770     end
  1771 	
  1772 
  1773 fun CCONTR tm hth thy =
  1774     let
  1775 	val _ = message "SPEC:"
  1776 	val _ = if_debug prin tm
  1777 	val _ = if_debug pth hth
  1778 	val (info,th) = disamb_thm hth
  1779 	val (info',tm') = disamb_term_from info tm
  1780 	val th = norm_hyps th
  1781 	val ct = cterm_of thy tm'
  1782 	val th1 = rearrange thy (HOLogic.mk_Trueprop (Const("Not",boolT-->boolT) $ tm')) th
  1783 	val ccontr_thm' = Drule.instantiate' [] [SOME ct] ccontr_thm
  1784 	val res1 = uniq_compose ((nprems_of th1) - 1) th1 1 ccontr_thm'
  1785 	val res = HOLThm(rens_of info',res1)
  1786 	val _ = message "RESULT:"
  1787 	val _ = if_debug pth res
  1788     in
  1789 	(thy,res)
  1790     end
  1791 
  1792 fun mk_ABS v th thy =
  1793     let
  1794 	val cv = cterm_of thy v
  1795 	val th1 = implies_elim_all (beta_eta_thm th)
  1796 	val (f,g) = case concl_of th1 of
  1797 			_ $ (Const("op =",_) $ f $ g) => (Term.lambda v f,Term.lambda v g)
  1798 		      | _ => raise ERR "mk_ABS" "Bad conclusion"
  1799 	val (fd,fr) = dom_rng (type_of f)
  1800 	val abs_thm' = Drule.instantiate' [SOME (ctyp_of thy fd), SOME (ctyp_of thy fr)] [SOME (cterm_of thy f), SOME (cterm_of thy g)] abs_thm
  1801 	val th2 = forall_intr cv th1
  1802 	val th3 = th2 COMP abs_thm'
  1803 	val res = implies_intr_hyps th3
  1804     in
  1805 	res
  1806     end
  1807 
  1808 fun ABS v hth thy =
  1809     let
  1810 	val _ = message "ABS:"
  1811 	val _ = if_debug prin v
  1812 	val _ = if_debug pth hth
  1813 	val (info,th) = disamb_thm hth
  1814 	val (info',v') = disamb_term_from info v
  1815 	val res = HOLThm(rens_of info',mk_ABS v' th thy)
  1816 	val _ = message "RESULT:"
  1817 	val _ = if_debug pth res
  1818     in
  1819 	(thy,res)
  1820     end
  1821 
  1822 fun GEN_ABS copt vlist hth thy =
  1823     let
  1824 	val _ = message "GEN_ABS:"
  1825 	val _ = case copt of
  1826 		    SOME c => if_debug prin c
  1827 		  | NONE => ()
  1828 	val _ = if_debug (app prin) vlist
  1829 	val _ = if_debug pth hth
  1830 	val (info,th) = disamb_thm hth
  1831 	val (info',vlist') = disamb_terms_from info vlist
  1832 	val th1 =
  1833 	    case copt of
  1834 		SOME (c as Const(cname,cty)) =>
  1835 		let
  1836 		    fun inst_type ty1 ty2 (TVar _) = raise ERR "GEN_ABS" "Type variable found!"
  1837 		      | inst_type ty1 ty2 (ty as TFree _) = if ty1 = ty
  1838 							    then ty2
  1839 							    else ty
  1840 		      | inst_type ty1 ty2 (ty as Type(name,tys)) =
  1841 			Type(name,map (inst_type ty1 ty2) tys)
  1842 		in
  1843 		    foldr (fn (v,th) =>
  1844 			      let
  1845 				  val cdom = fst (dom_rng (fst (dom_rng cty)))
  1846 				  val vty  = type_of v
  1847 				  val newcty = inst_type cdom vty cty
  1848 				  val cc = cterm_of thy (Const(cname,newcty))
  1849 			      in
  1850 				  mk_COMB (mk_REFL cc) (mk_ABS v th thy) thy
  1851 			      end) th vlist'
  1852 		end
  1853 	      | SOME _ => raise ERR "GEN_ABS" "Bad constant"
  1854 	      | NONE => 
  1855 		foldr (fn (v,th) => mk_ABS v th thy) th vlist'
  1856 	val res = HOLThm(rens_of info',th1)
  1857 	val _ = message "RESULT:"
  1858 	val _ = if_debug pth res
  1859     in
  1860 	(thy,res)
  1861     end
  1862 
  1863 fun NOT_INTRO (hth as HOLThm(rens,th)) thy =
  1864     let
  1865 	val _ = message "NOT_INTRO:"
  1866 	val _ = if_debug pth hth
  1867 	val th1 = implies_elim_all (beta_eta_thm th)
  1868 	val a = case concl_of th1 of
  1869 		    _ $ (Const("op -->",_) $ a $ Const("False",_)) => a
  1870 		  | _ => raise ERR "NOT_INTRO" "Conclusion of bad form"
  1871 	val ca = cterm_of thy a
  1872 	val th2 = equal_elim (Drule.instantiate' [] [SOME ca] not_intro_thm) th1
  1873 	val res = HOLThm(rens,implies_intr_hyps th2)
  1874 	val _ = message "RESULT:"
  1875 	val _ = if_debug pth res
  1876     in
  1877 	(thy,res)
  1878     end
  1879 
  1880 fun NOT_ELIM (hth as HOLThm(rens,th)) thy =
  1881     let
  1882 	val _ = message "NOT_INTRO:"
  1883 	val _ = if_debug pth hth
  1884 	val th1 = implies_elim_all (beta_eta_thm th)
  1885 	val a = case concl_of th1 of
  1886 		    _ $ (Const("Not",_) $ a) => a
  1887 		  | _ => raise ERR "NOT_ELIM" "Conclusion of bad form"
  1888 	val ca = cterm_of thy a
  1889 	val th2 = equal_elim (Drule.instantiate' [] [SOME ca] not_elim_thm) th1
  1890 	val res = HOLThm(rens,implies_intr_hyps th2)
  1891 	val _ = message "RESULT:"
  1892 	val _ = if_debug pth res
  1893     in
  1894 	(thy,res)
  1895     end
  1896 
  1897 fun DISCH tm hth thy =
  1898     let
  1899 	val _ = message "DISCH:"
  1900 	val _ = if_debug prin tm
  1901 	val _ = if_debug pth hth
  1902 	val (info,th) = disamb_thm hth
  1903 	val (info',tm') = disamb_term_from info tm
  1904 	val prems = prems_of th
  1905 	val th1 = beta_eta_thm th
  1906 	val th2 = implies_elim_all th1
  1907 	val th3 = implies_intr (cterm_of thy (HOLogic.mk_Trueprop tm')) th2
  1908 	val th4 = th3 COMP disch_thm
  1909 	val res = HOLThm(rens_of info',implies_intr_hyps th4)
  1910 	val _ = message "RESULT:"
  1911 	val _ = if_debug pth res
  1912     in
  1913 	(thy,res)
  1914     end
  1915 
  1916 val spaces = String.concat o separate " "
  1917 
  1918 fun new_definition thyname constname rhs thy =
  1919     let
  1920 	val constname = rename_const thyname thy constname
  1921         val redeclared = isSome (Sign.const_type thy (Sign.intern_const thy constname));
  1922 	val _ = warning ("Introducing constant " ^ constname)
  1923 	val (thmname,thy) = get_defname thyname constname thy
  1924 	val (info,rhs') = disamb_term rhs
  1925 	val ctype = type_of rhs'
  1926 	val csyn = mk_syn thy constname
  1927 	val thy1 = case HOL4DefThy.get thy of
  1928 		       Replaying _ => thy
  1929 		     | _ => (ImportRecorder.add_consts [(constname, ctype, csyn)]; Theory.add_consts_i [(constname,ctype,csyn)] thy)
  1930 	val eq = mk_defeq constname rhs' thy1
  1931 	val (thms, thy2) = PureThy.add_defs_i false [((thmname,eq),[])] thy1
  1932 	val _ = ImportRecorder.add_defs thmname eq
  1933 	val def_thm = hd thms
  1934 	val thm' = def_thm RS meta_eq_to_obj_eq_thm
  1935 	val (thy',th) = (thy2, thm')
  1936 	val fullcname = Sign.intern_const thy' constname
  1937 	val thy'' = add_hol4_const_mapping thyname constname true fullcname thy'
  1938 	val _ = ImportRecorder.add_hol_const_mapping thyname constname fullcname
  1939 	val (linfo,tm24) = disamb_term (mk_teq constname rhs' thy'')
  1940 	val rew = rewrite_hol4_term eq thy''
  1941 	val crhs = cterm_of thy'' (#2 (Logic.dest_equals (prop_of rew)))
  1942 	val thy22 = if (def_name constname) = thmname andalso not redeclared andalso csyn = NoSyn
  1943 		    then
  1944 			let
  1945 			    val p1 = quotename constname
  1946 			    val p2 = string_of_ctyp (ctyp_of thy'' ctype)
  1947 			    val p3 = Syntax.string_of_mixfix csyn
  1948 			    val p4 = smart_string_of_cterm crhs
  1949 			in
  1950 			    add_dump ("constdefs\n  " ^p1^ " :: \"" ^p2^ "\" "^p3^ "\n  " ^p4) thy''  
  1951 			end
  1952 		    else
  1953 			(add_dump ("consts\n  " ^ (quotename constname) ^ " :: \"" ^ string_of_ctyp (ctyp_of thy'' ctype) ^
  1954 				   "\" " ^ (Syntax.string_of_mixfix csyn) ^ "\n\ndefs\n  " ^ (quotename thmname) ^ ": " ^ (smart_string_of_cterm crhs))
  1955 				  thy'')
  1956 	val hth = case Shuffler.set_prop thy22 (HOLogic.mk_Trueprop tm24) [("",th)] of
  1957 		      SOME (_,res) => HOLThm(rens_of linfo,res)
  1958 		    | NONE => raise ERR "new_definition" "Bad conclusion"
  1959 	val fullname = Sign.full_name thy22 thmname
  1960 	val thy22' = case opt_get_output_thy thy22 of
  1961 			 "" => (ImportRecorder.add_hol_mapping thyname thmname fullname; 
  1962 				add_hol4_mapping thyname thmname fullname thy22)
  1963 		       | output_thy =>
  1964 			 let
  1965 			     val moved_thmname = output_thy ^ "." ^ thyname ^ "." ^ thmname
  1966 			     val _ = ImportRecorder.add_hol_move fullname moved_thmname
  1967 			     val _ = ImportRecorder.add_hol_mapping thyname thmname moved_thmname
  1968 			 in
  1969 			     thy22 |> add_hol4_move fullname moved_thmname
  1970 				   |> add_hol4_mapping thyname thmname moved_thmname
  1971 			 end
  1972 	val _ = message "new_definition:"
  1973 	val _ = if_debug pth hth
  1974     in
  1975 	(thy22',hth)
  1976     end
  1977     handle e => (message "exception in new_definition"; print_exn e)
  1978 
  1979 local
  1980     val helper = thm "termspec_help"
  1981 in
  1982 fun new_specification thyname thmname names hth thy =
  1983     case HOL4DefThy.get thy of
  1984 	Replaying _ => (thy,hth)
  1985       | _ => 
  1986 	let
  1987 	    val _ = message "NEW_SPEC:"
  1988 	    val _ = if_debug pth hth
  1989 	    val names = map (rename_const thyname thy) names
  1990 	    val _ = warning ("Introducing constants " ^ commas names)
  1991 	    val (HOLThm(rens,th)) = norm_hthm thy hth
  1992 	    val thy1 = case HOL4DefThy.get thy of
  1993 			   Replaying _ => thy
  1994 			 | _ =>
  1995 			   let
  1996 			       fun dest_eta_abs (Abs(x,xT,body)) = (x,xT,body)
  1997 				 | dest_eta_abs body =
  1998 				   let
  1999 				       val (dT,rT) = dom_rng (type_of body)
  2000 				   in
  2001 				       ("x",dT,body $ Bound 0)
  2002 				   end
  2003 				   handle TYPE _ => raise ERR "new_specification" "not an abstraction type"
  2004 			       fun dest_exists (Const("Ex",_) $ abody) =
  2005 				   dest_eta_abs abody
  2006 				 | dest_exists tm =
  2007 				   raise ERR "new_specification" "Bad existential formula"
  2008 					 
  2009 			       val (consts,_) = Library.foldl (fn ((cs,ex),cname) =>
  2010 							  let
  2011 							      val (_,cT,p) = dest_exists ex
  2012 							  in
  2013 							      ((cname,cT,mk_syn thy cname)::cs,p)
  2014 							  end) (([],HOLogic.dest_Trueprop (concl_of th)),names)
  2015 			       val str = Library.foldl (fn (acc,(c,T,csyn)) =>
  2016 						   acc ^ "\n  " ^ (quotename c) ^ " :: \"" ^ string_of_ctyp (ctyp_of thy T) ^ "\" " ^ (Syntax.string_of_mixfix csyn)) ("consts",consts)
  2017 			       val thy' = add_dump str thy
  2018 			       val _ = ImportRecorder.add_consts consts
  2019 			   in
  2020 			       Theory.add_consts_i consts thy'
  2021 			   end
  2022 
  2023 	    val thy1 = foldr (fn(name,thy)=>
  2024 				snd (get_defname thyname name thy)) thy1 names
  2025 	    fun new_name name = fst (get_defname thyname name thy1)
  2026 	    val names' = map (fn name => (new_name name,name,false)) names
  2027 	    val (thy',res) = SpecificationPackage.add_specification NONE
  2028 				 names'
  2029 				 (thy1,th)
  2030 	    val _ = ImportRecorder.add_specification names' th
  2031 	    val res' = Drule.freeze_all res
  2032 	    val hth = HOLThm(rens,res')
  2033 	    val rew = rewrite_hol4_term (concl_of res') thy'
  2034 	    val th  = equal_elim rew res'
  2035 	    fun handle_const (name,thy) =
  2036 		let
  2037 		    val defname = def_name name
  2038 		    val (newname,thy') = get_defname thyname name thy
  2039 		in
  2040 		    (if defname = newname
  2041 		     then quotename name
  2042 		     else (quotename newname) ^ ": " ^ (quotename name),thy')
  2043 		end
  2044 	    val (new_names,thy') = foldr (fn(name,(names,thy)) =>
  2045 					    let
  2046 						val (name',thy') = handle_const (name,thy)
  2047 					    in
  2048 						(name'::names,thy')
  2049 					    end) ([],thy') names
  2050 	    val thy'' = add_dump ("specification (" ^ (spaces new_names) ^ ") " ^ thmname ^ ": " ^ (smart_string_of_thm th) ^
  2051 				  "\n  by (import " ^ thyname ^ " " ^ thmname ^ ")")
  2052 				 thy'
  2053 	    val _ = message "RESULT:"
  2054 	    val _ = if_debug pth hth
  2055 	in
  2056 	    intern_store_thm false thyname thmname hth thy''
  2057 	end
  2058 	handle e => (message "exception in new_specification"; print_exn e)
  2059 		    
  2060 end
  2061 			   
  2062 fun new_axiom name tm thy = raise ERR "new_axiom" ("Oh, no you don't! (" ^ name ^ ")")
  2063 				      
  2064 fun to_isa_thm (hth as HOLThm(_,th)) =
  2065     let
  2066 	val (HOLThm args) = norm_hthm (theory_of_thm th) hth
  2067     in
  2068 	apsnd strip_shyps args
  2069     end
  2070 
  2071 fun to_isa_term tm = tm
  2072 
  2073 local
  2074     val light_nonempty = thm "light_ex_imp_nonempty"
  2075     val ex_imp_nonempty = thm "ex_imp_nonempty"
  2076     val typedef_hol2hol4 = thm "typedef_hol2hol4"
  2077     val typedef_hol2hollight = thm "typedef_hol2hollight"
  2078 in
  2079 fun new_type_definition thyname thmname tycname hth thy =
  2080     case HOL4DefThy.get thy of
  2081 	Replaying _ => (thy,hth)
  2082       | _ => 
  2083 	let
  2084 	    val _ = message "TYPE_DEF:"
  2085 	    val _ = if_debug pth hth
  2086 	    val _ = warning ("Introducing type " ^ tycname)
  2087 	    val (HOLThm(rens,td_th)) = norm_hthm thy hth
  2088 	    val th2 = beta_eta_thm (td_th RS ex_imp_nonempty)
  2089 	    val c = case concl_of th2 of
  2090 			_ $ (Const("Ex",_) $ Abs(_,_,Const("op :",_) $ _ $ c)) => c
  2091 		      | _ => raise ERR "new_type_definition" "Bad type definition theorem"
  2092 	    val tfrees = term_tfrees c
  2093 	    val tnames = map fst tfrees
  2094 	    val tsyn = mk_syn thy tycname
  2095 	    val typ = (tycname,tnames,tsyn)
  2096 	    val (thy',typedef_info) = TypedefPackage.add_typedef_i false (SOME thmname) typ c NONE (rtac th2 1) thy	    
  2097             val _ = ImportRecorder.add_typedef (SOME thmname) typ c NONE th2
  2098 				      
  2099 	    val th3 = (#type_definition typedef_info) RS typedef_hol2hol4
  2100 
  2101 	    val fulltyname = Sign.intern_type thy' tycname
  2102 	    val thy'' = add_hol4_type_mapping thyname tycname true fulltyname thy'
  2103 	    val _ = ImportRecorder.add_hol_type_mapping thyname tycname fulltyname
  2104 
  2105 	    val (hth' as HOLThm args) = norm_hthm thy'' (HOLThm(rens,th3))
  2106 	    val _ = if has_ren hth' then warning ("Theorem " ^ thmname ^ " needs variable-disambiguating")
  2107 		    else ()
  2108 	    val thy4 = add_hol4_pending thyname thmname args thy''
  2109 	    val _ = ImportRecorder.add_hol_pending thyname thmname (hthm2thm hth')
  2110 
  2111 	    val rew = rewrite_hol4_term (concl_of td_th) thy4
  2112 	    val th  = equal_elim rew (Thm.transfer thy4 td_th)
  2113 	    val c   = case HOLogic.dest_Trueprop (prop_of th) of
  2114 			  Const("Ex",exT) $ P =>
  2115 			  let
  2116 			      val PT = domain_type exT
  2117 			  in
  2118 			      Const("Collect",PT-->HOLogic.mk_setT (domain_type PT)) $ P
  2119 			  end
  2120 			| _ => error "Internal error in ProofKernel.new_typedefinition"
  2121 	    val tnames_string = if null tnames
  2122 				then ""
  2123 				else "(" ^ commas tnames ^ ") "
  2124 	    val proc_prop = if null tnames
  2125 			    then smart_string_of_cterm
  2126 			    else Library.setmp show_all_types true smart_string_of_cterm
  2127 	    val thy5 = add_dump ("typedef (open) " ^ tnames_string ^ (quotename tycname) ^ " = " ^ (proc_prop (cterm_of thy4 c)) ^ " " 
  2128 				 ^ (Syntax.string_of_mixfix tsyn) ^ "\n  by (rule typedef_helper,import " ^ thyname ^ " " ^ thmname ^ ")") thy4
  2129 	    
  2130 	    val thy6 = add_dump ("lemmas " ^ thmname ^ " = typedef_hol2hol4 [OF type_definition_" ^ tycname ^ "]") thy5
  2131               
  2132 	    val _ = message "RESULT:"
  2133 	    val _ = if_debug pth hth'
  2134 	in
  2135 	    (thy6,hth')
  2136 	end
  2137 	handle e => (message "exception in new_type_definition"; print_exn e)
  2138 
  2139 fun add_dump_constdefs thy defname constname rhs ty =
  2140     let
  2141 	val n = quotename constname
  2142 	val t = string_of_ctyp (ctyp_of thy ty)
  2143 	val syn = Syntax.string_of_mixfix (mk_syn thy constname)
  2144 	(*val eq = smart_string_of_cterm (cterm_of thy (Const(rhs, ty)))*)
  2145         val eq = quote (constname ^ " == "^rhs)
  2146 	val d = case defname of NONE => "" | SOME defname => (quotename defname)^" : "
  2147     in
  2148 	add_dump ("constdefs\n  " ^ n ^ " :: \"" ^ t ^ "\" " ^ syn ^ "\n  " ^ d ^ eq) thy    
  2149     end
  2150 
  2151 fun add_dump_syntax thy name = 
  2152     let
  2153       val n = quotename name
  2154       val syn = Syntax.string_of_mixfix (mk_syn thy name)
  2155     in
  2156       add_dump ("syntax\n  "^n^" :: _ "^syn) thy
  2157     end
  2158       
  2159 (*val type_intro_replay_history = ref (Symtab.empty:unit Symtab.table)
  2160 fun choose_upon_replay_history thy s dth = 
  2161     case Symtab.lookup (!type_intro_replay_history) s of
  2162 	NONE => (type_intro_replay_history := Symtab.update (s, ()) (!type_intro_replay_history); dth)
  2163       | SOME _ => HOLThm([], PureThy.get_thm thy (PureThy.Name s))
  2164 *)
  2165 
  2166 fun type_introduction thyname thmname tycname abs_name rep_name (P,t) hth thy =
  2167     case HOL4DefThy.get thy of
  2168 	Replaying _ => (thy,
  2169           HOLThm([], PureThy.get_thm thy (PureThy.Name (thmname^"_@intern"))) handle ERROR _ => hth)
  2170       | _ => 
  2171 	let
  2172             val _ = message "TYPE_INTRO:"
  2173 	    val _ = if_debug pth hth
  2174 	    val _ = warning ("Introducing type " ^ tycname ^ " (with morphisms " ^ abs_name ^ " and " ^ rep_name ^ ")")
  2175 	    val (HOLThm(rens,td_th)) = norm_hthm thy hth
  2176 	    val tT = type_of t
  2177 	    val light_nonempty' =
  2178 		Drule.instantiate' [SOME (ctyp_of thy tT)]
  2179 				   [SOME (cterm_of thy P),
  2180 				    SOME (cterm_of thy t)] light_nonempty
  2181 	    val th2 = beta_eta_thm (td_th RS (beta_eta_thm light_nonempty'))
  2182 	    val c = case concl_of th2 of
  2183 			_ $ (Const("Ex",_) $ Abs(_,_,Const("op :",_) $ _ $ c)) => c
  2184 		      | _ => raise ERR "type_introduction" "Bad type definition theorem"
  2185 	    val tfrees = term_tfrees c
  2186 	    val tnames = sort string_ord (map fst tfrees)
  2187 	    val tsyn = mk_syn thy tycname
  2188 	    val typ = (tycname,tnames,tsyn)
  2189 	    val (thy', typedef_info) = TypedefPackage.add_typedef_i false NONE typ c (SOME(rep_name,abs_name)) (rtac th2 1) thy
  2190 	    val _ = ImportRecorder.add_typedef NONE typ c (SOME(rep_name,abs_name)) th2
  2191 	    val fulltyname = Sign.intern_type thy' tycname
  2192 	    val aty = Type (fulltyname, map mk_vartype tnames)
  2193 	    val abs_ty = tT --> aty
  2194 	    val rep_ty = aty --> tT
  2195             val typedef_hol2hollight' = 
  2196 		Drule.instantiate' 
  2197 		    [SOME (ctyp_of thy' aty), SOME (ctyp_of thy' tT)] 
  2198 		    [NONE, NONE, NONE, SOME (cterm_of thy' (Free ("a", aty))), SOME (cterm_of thy' (Free ("r", tT)))]
  2199                     typedef_hol2hollight
  2200 	    val th4 = (#type_definition typedef_info) RS typedef_hol2hollight'
  2201             val _ = if Drule.tvars_of th4 = [] then () else raise ERR "type_introduction" "no type variables expected any more" 
  2202             val _ = if Drule.vars_of th4 = [] then () else raise ERR "type_introduction" "no term variables expected any more"
  2203 	    val _ = message ("step 3: thyname="^thyname^", tycname="^tycname^", fulltyname="^fulltyname)
  2204             val thy'' = add_hol4_type_mapping thyname tycname true fulltyname thy'
  2205 	    val _ = ImportRecorder.add_hol_type_mapping thyname tycname fulltyname
  2206             val _ = message "step 4"
  2207 	    val (hth' as HOLThm args) = norm_hthm thy'' (HOLThm(rens,th4))
  2208 	    val thy4 = add_hol4_pending thyname thmname args thy''
  2209 	    val _ = ImportRecorder.add_hol_pending thyname thmname (hthm2thm hth')
  2210 	   
  2211 	    val P' = P (* why !? #2 (Logic.dest_equals (concl_of (rewrite_hol4_term P thy4))) *)
  2212 	    val c   =
  2213 		let
  2214 		    val PT = type_of P'
  2215 		in
  2216 		    Const("Collect",PT-->HOLogic.mk_setT (domain_type PT)) $ P'
  2217 		end
  2218 	    
  2219 	    val tnames_string = if null tnames
  2220 				then ""
  2221 				else "(" ^ commas tnames ^ ") "
  2222 	    val proc_prop = if null tnames
  2223 			    then smart_string_of_cterm
  2224 			    else Library.setmp show_all_types true smart_string_of_cterm
  2225 	    val thy = add_dump ("typedef (open) " ^ tnames_string ^ (quotename tycname) ^ 
  2226               " = " ^ (proc_prop (cterm_of thy4 c)) ^ " " ^ 
  2227 	      (Syntax.string_of_mixfix tsyn) ^ " morphisms "^
  2228               (quote rep_name)^" "^(quote abs_name)^"\n"^ 
  2229 	      ("  apply (rule light_ex_imp_nonempty[where t="^
  2230               (proc_prop (cterm_of thy4 t))^"])\n"^              
  2231 	      ("  by (import " ^ thyname ^ " " ^ (quotename thmname) ^ ")"))) thy4
  2232 	    val str_aty = string_of_ctyp (ctyp_of thy aty)
  2233             val thy = add_dump_syntax thy rep_name 
  2234             val thy = add_dump_syntax thy abs_name
  2235 	    val thy = add_dump ("lemmas " ^ (quote (thmname^"_@intern")) ^ 
  2236               " = typedef_hol2hollight \n"^
  2237               "  [where a=\"a :: "^str_aty^"\" and r=r" ^
  2238 	      " ,\n   OF "^(quotename ("type_definition_" ^ tycname)) ^ "]") thy 
  2239 	    val _ = message "RESULT:"
  2240 	    val _ = if_debug pth hth'
  2241 	in
  2242 	    (thy,hth')
  2243 	end
  2244 	handle e => (message "exception in type_introduction"; print_exn e)
  2245 end
  2246 
  2247 val prin = prin
  2248 
  2249 end