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