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