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