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