src/HOL/Matrix_LP/Compute_Oracle/compute.ML
author wenzelm
Fri Mar 06 15:58:56 2015 +0100 (2015-03-06)
changeset 59621 291934bac95e
parent 59586 ddf6deaadfe8
child 60336 f0b2457bf68e
permissions -rw-r--r--
Thm.cterm_of and Thm.ctyp_of operate on local context;
     1 (*  Title:      HOL/Matrix_LP/Compute_Oracle/compute.ML
     2     Author:     Steven Obua
     3 *)
     4 
     5 signature COMPUTE = sig
     6 
     7     type computer
     8     type theorem
     9     type naming = int -> string
    10 
    11     datatype machine = BARRAS | BARRAS_COMPILED | HASKELL | SML
    12 
    13     (* Functions designated with a ! in front of them actually update the computer parameter *)
    14 
    15     exception Make of string
    16     val make : machine -> theory -> thm list -> computer
    17     val make_with_cache : machine -> theory -> term list -> thm list -> computer
    18     val theory_of : computer -> theory
    19     val hyps_of : computer -> term list
    20     val shyps_of : computer -> sort list
    21     (* ! *) val update : computer -> thm list -> unit
    22     (* ! *) val update_with_cache : computer -> term list -> thm list -> unit
    23     
    24     (* ! *) val set_naming : computer -> naming -> unit
    25     val naming_of : computer -> naming
    26     
    27     exception Compute of string    
    28     val simplify : computer -> theorem -> thm 
    29     val rewrite : computer -> cterm -> thm 
    30 
    31     val make_theorem : computer -> thm -> string list -> theorem
    32     (* ! *) val instantiate : computer -> (string * cterm) list -> theorem -> theorem
    33     (* ! *) val evaluate_prem : computer -> int -> theorem -> theorem
    34     (* ! *) val modus_ponens : computer -> int -> thm -> theorem -> theorem
    35 
    36 end
    37 
    38 structure Compute :> COMPUTE = struct
    39 
    40 open Report;
    41 
    42 datatype machine = BARRAS | BARRAS_COMPILED | HASKELL | SML      
    43 
    44 (* Terms are mapped to integer codes *)
    45 structure Encode :> 
    46 sig
    47     type encoding
    48     val empty : encoding
    49     val insert : term -> encoding -> int * encoding
    50     val lookup_code : term -> encoding -> int option
    51     val lookup_term : int -> encoding -> term option
    52     val remove_code : int -> encoding -> encoding
    53     val remove_term : term -> encoding -> encoding
    54 end 
    55 = 
    56 struct
    57 
    58 type encoding = int * (int Termtab.table) * (term Inttab.table)
    59 
    60 val empty = (0, Termtab.empty, Inttab.empty)
    61 
    62 fun insert t (e as (count, term2int, int2term)) = 
    63     (case Termtab.lookup term2int t of
    64          NONE => (count, (count+1, Termtab.update_new (t, count) term2int, Inttab.update_new (count, t) int2term))
    65        | SOME code => (code, e))
    66 
    67 fun lookup_code t (_, term2int, _) = Termtab.lookup term2int t
    68 
    69 fun lookup_term c (_, _, int2term) = Inttab.lookup int2term c
    70 
    71 fun remove_code c (e as (count, term2int, int2term)) = 
    72     (case lookup_term c e of NONE => e | SOME t => (count, Termtab.delete t term2int, Inttab.delete c int2term))
    73 
    74 fun remove_term t (e as (count, term2int, int2term)) = 
    75     (case lookup_code t e of NONE => e | SOME c => (count, Termtab.delete t term2int, Inttab.delete c int2term))
    76 
    77 end
    78 
    79 exception Make of string;
    80 exception Compute of string;
    81 
    82 local
    83     fun make_constant t encoding = 
    84         let 
    85             val (code, encoding) = Encode.insert t encoding 
    86         in 
    87             (encoding, AbstractMachine.Const code)
    88         end
    89 in
    90 
    91 fun remove_types encoding t =
    92     case t of 
    93         Var _ => make_constant t encoding
    94       | Free _ => make_constant t encoding
    95       | Const _ => make_constant t encoding
    96       | Abs (_, _, t') => 
    97         let val (encoding, t'') = remove_types encoding t' in
    98             (encoding, AbstractMachine.Abs t'')
    99         end
   100       | a $ b => 
   101         let
   102             val (encoding, a) = remove_types encoding a
   103             val (encoding, b) = remove_types encoding b
   104         in
   105             (encoding, AbstractMachine.App (a,b))
   106         end
   107       | Bound b => (encoding, AbstractMachine.Var b)
   108 end
   109     
   110 local
   111     fun type_of (Free (_, ty)) = ty
   112       | type_of (Const (_, ty)) = ty
   113       | type_of (Var (_, ty)) = ty
   114       | type_of _ = raise Fail "infer_types: type_of error"
   115 in
   116 fun infer_types naming encoding =
   117     let
   118         fun infer_types _ bounds _ (AbstractMachine.Var v) = (Bound v, nth bounds v)
   119           | infer_types _ bounds _ (AbstractMachine.Const code) = 
   120             let
   121                 val c = the (Encode.lookup_term code encoding)
   122             in
   123                 (c, type_of c)
   124             end
   125           | infer_types level bounds _ (AbstractMachine.App (a, b)) = 
   126             let
   127                 val (a, aty) = infer_types level bounds NONE a
   128                 val (adom, arange) =
   129                     case aty of
   130                         Type ("fun", [dom, range]) => (dom, range)
   131                       | _ => raise Fail "infer_types: function type expected"
   132                 val (b, _) = infer_types level bounds (SOME adom) b
   133             in
   134                 (a $ b, arange)
   135             end
   136           | infer_types level bounds (SOME (ty as Type ("fun", [dom, range]))) (AbstractMachine.Abs m) =
   137             let
   138                 val (m, _) = infer_types (level+1) (dom::bounds) (SOME range) m
   139             in
   140                 (Abs (naming level, dom, m), ty)
   141             end
   142           | infer_types _ _ NONE (AbstractMachine.Abs _) =
   143               raise Fail "infer_types: cannot infer type of abstraction"
   144 
   145         fun infer ty term =
   146             let
   147                 val (term', _) = infer_types 0 [] (SOME ty) term
   148             in
   149                 term'
   150             end
   151     in
   152         infer
   153     end
   154 end
   155 
   156 datatype prog = 
   157          ProgBarras of AM_Interpreter.program 
   158        | ProgBarrasC of AM_Compiler.program
   159        | ProgHaskell of AM_GHC.program
   160        | ProgSML of AM_SML.program
   161 
   162 fun machine_of_prog (ProgBarras _) = BARRAS
   163   | machine_of_prog (ProgBarrasC _) = BARRAS_COMPILED
   164   | machine_of_prog (ProgHaskell _) = HASKELL
   165   | machine_of_prog (ProgSML _) = SML
   166 
   167 type naming = int -> string
   168 
   169 fun default_naming i = "v_" ^ string_of_int i
   170 
   171 datatype computer = Computer of
   172   (theory * Encode.encoding * term list * unit Sorttab.table * prog * unit Unsynchronized.ref * naming)
   173     option Unsynchronized.ref
   174 
   175 fun theory_of (Computer (Unsynchronized.ref (SOME (thy,_,_,_,_,_,_)))) = thy
   176 fun hyps_of (Computer (Unsynchronized.ref (SOME (_,_,hyps,_,_,_,_)))) = hyps
   177 fun shyps_of (Computer (Unsynchronized.ref (SOME (_,_,_,shyptable,_,_,_)))) = Sorttab.keys (shyptable)
   178 fun shyptab_of (Computer (Unsynchronized.ref (SOME (_,_,_,shyptable,_,_,_)))) = shyptable
   179 fun stamp_of (Computer (Unsynchronized.ref (SOME (_,_,_,_,_,stamp,_)))) = stamp
   180 fun prog_of (Computer (Unsynchronized.ref (SOME (_,_,_,_,prog,_,_)))) = prog
   181 fun encoding_of (Computer (Unsynchronized.ref (SOME (_,encoding,_,_,_,_,_)))) = encoding
   182 fun set_encoding (Computer (r as Unsynchronized.ref (SOME (p1,_,p2,p3,p4,p5,p6)))) encoding' = 
   183     (r := SOME (p1,encoding',p2,p3,p4,p5,p6))
   184 fun naming_of (Computer (Unsynchronized.ref (SOME (_,_,_,_,_,_,n)))) = n
   185 fun set_naming (Computer (r as Unsynchronized.ref (SOME (p1,p2,p3,p4,p5,p6,_)))) naming'= 
   186     (r := SOME (p1,p2,p3,p4,p5,p6,naming'))
   187 
   188 fun ref_of (Computer r) = r
   189 
   190 fun super_theory thy1 thy2 =
   191   if Theory.subthy (thy1, thy2) then thy2
   192   else raise THEORY ("Not a super theory", [thy1, thy2]);
   193 
   194 
   195 datatype cthm = ComputeThm of term list * sort list * term
   196 
   197 fun thm2cthm th = 
   198     let
   199         val {hyps, prop, tpairs, shyps, ...} = Thm.rep_thm th
   200         val _ = if not (null tpairs) then raise Make "theorems may not contain tpairs" else ()
   201     in
   202         ComputeThm (hyps, shyps, prop)
   203     end
   204 
   205 fun make_internal machine thy stamp encoding cache_pattern_terms raw_ths =
   206     let
   207         fun transfer (x:thm) = Thm.transfer thy x
   208         val ths = map (thm2cthm o Thm.strip_shyps o transfer) raw_ths
   209 
   210         fun make_pattern encoding n vars (AbstractMachine.Abs _) =
   211             raise (Make "no lambda abstractions allowed in pattern")
   212           | make_pattern encoding n vars (AbstractMachine.Var _) =
   213             raise (Make "no bound variables allowed in pattern")
   214           | make_pattern encoding n vars (AbstractMachine.Const code) =
   215             (case the (Encode.lookup_term code encoding) of
   216                  Var _ => ((n+1, Inttab.update_new (code, n) vars, AbstractMachine.PVar)
   217                            handle Inttab.DUP _ => raise (Make "no duplicate variable in pattern allowed"))
   218                | _ => (n, vars, AbstractMachine.PConst (code, [])))
   219           | make_pattern encoding n vars (AbstractMachine.App (a, b)) =
   220             let
   221                 val (n, vars, pa) = make_pattern encoding n vars a
   222                 val (n, vars, pb) = make_pattern encoding n vars b
   223             in
   224                 case pa of
   225                     AbstractMachine.PVar =>
   226                     raise (Make "patterns may not start with a variable")
   227                   | AbstractMachine.PConst (c, args) =>
   228                     (n, vars, AbstractMachine.PConst (c, args@[pb]))
   229             end
   230 
   231         fun thm2rule (encoding, hyptable, shyptable) th =
   232             let
   233                 val (ComputeThm (hyps, shyps, prop)) = th
   234                 val hyptable = fold (fn h => Termtab.update (h, ())) hyps hyptable
   235                 val shyptable = fold (fn sh => Sorttab.update (sh, ())) shyps shyptable
   236                 val (prems, prop) = (Logic.strip_imp_prems prop, Logic.strip_imp_concl prop)
   237                 val (a, b) = Logic.dest_equals prop
   238                   handle TERM _ => raise (Make "theorems must be meta-level equations (with optional guards)")
   239                 val a = Envir.eta_contract a
   240                 val b = Envir.eta_contract b
   241                 val prems = map Envir.eta_contract prems
   242 
   243                 val (encoding, left) = remove_types encoding a     
   244                 val (encoding, right) = remove_types encoding b  
   245                 fun remove_types_of_guard encoding g = 
   246                     (let
   247                          val (t1, t2) = Logic.dest_equals g 
   248                          val (encoding, t1) = remove_types encoding t1
   249                          val (encoding, t2) = remove_types encoding t2
   250                      in
   251                          (encoding, AbstractMachine.Guard (t1, t2))
   252                      end handle TERM _ => raise (Make "guards must be meta-level equations"))
   253                 val (encoding, prems) = fold_rev (fn p => fn (encoding, ps) => let val (e, p) = remove_types_of_guard encoding p in (e, p::ps) end) prems (encoding, [])
   254 
   255                 (* Principally, a check should be made here to see if the (meta-) hyps contain any of the variables of the rule.
   256                    As it is, all variables of the rule are schematic, and there are no schematic variables in meta-hyps, therefore
   257                    this check can be left out. *)
   258 
   259                 val (vcount, vars, pattern) = make_pattern encoding 0 Inttab.empty left
   260                 val _ = (case pattern of
   261                              AbstractMachine.PVar =>
   262                              raise (Make "patterns may not start with a variable")
   263                            | _ => ())
   264 
   265                 (* finally, provide a function for renaming the
   266                    pattern bound variables on the right hand side *)
   267 
   268                 fun rename level vars (var as AbstractMachine.Var _) = var
   269                   | rename level vars (c as AbstractMachine.Const code) =
   270                     (case Inttab.lookup vars code of 
   271                          NONE => c 
   272                        | SOME n => AbstractMachine.Var (vcount-n-1+level))
   273                   | rename level vars (AbstractMachine.App (a, b)) =
   274                     AbstractMachine.App (rename level vars a, rename level vars b)
   275                   | rename level vars (AbstractMachine.Abs m) =
   276                     AbstractMachine.Abs (rename (level+1) vars m)
   277                     
   278                 fun rename_guard (AbstractMachine.Guard (a,b)) = 
   279                     AbstractMachine.Guard (rename 0 vars a, rename 0 vars b)
   280             in
   281                 ((encoding, hyptable, shyptable), (map rename_guard prems, pattern, rename 0 vars right))
   282             end
   283 
   284         val ((encoding, hyptable, shyptable), rules) =
   285           fold_rev (fn th => fn (encoding_hyptable, rules) =>
   286             let
   287               val (encoding_hyptable, rule) = thm2rule encoding_hyptable th
   288             in (encoding_hyptable, rule::rules) end)
   289           ths ((encoding, Termtab.empty, Sorttab.empty), [])
   290 
   291         fun make_cache_pattern t (encoding, cache_patterns) =
   292             let
   293                 val (encoding, a) = remove_types encoding t
   294                 val (_,_,p) = make_pattern encoding 0 Inttab.empty a
   295             in
   296                 (encoding, p::cache_patterns)
   297             end
   298         
   299         val (encoding, _) = fold_rev make_cache_pattern cache_pattern_terms (encoding, [])
   300 
   301         val prog = 
   302             case machine of 
   303                 BARRAS => ProgBarras (AM_Interpreter.compile rules)
   304               | BARRAS_COMPILED => ProgBarrasC (AM_Compiler.compile rules)
   305               | HASKELL => ProgHaskell (AM_GHC.compile rules)
   306               | SML => ProgSML (AM_SML.compile rules)
   307 
   308         fun has_witness s = not (null (Sign.witness_sorts thy [] [s]))
   309 
   310         val shyptable = fold Sorttab.delete (filter has_witness (Sorttab.keys (shyptable))) shyptable
   311 
   312     in (thy, encoding, Termtab.keys hyptable, shyptable, prog, stamp, default_naming) end
   313 
   314 fun make_with_cache machine thy cache_patterns raw_thms =
   315   Computer (Unsynchronized.ref (SOME (make_internal machine thy (Unsynchronized.ref ()) Encode.empty cache_patterns raw_thms)))
   316 
   317 fun make machine thy raw_thms = make_with_cache machine thy [] raw_thms
   318 
   319 fun update_with_cache computer cache_patterns raw_thms =
   320     let 
   321         val c = make_internal (machine_of_prog (prog_of computer)) (theory_of computer) (stamp_of computer) 
   322                               (encoding_of computer) cache_patterns raw_thms
   323         val _ = (ref_of computer) := SOME c     
   324     in
   325         ()
   326     end
   327 
   328 fun update computer raw_thms = update_with_cache computer [] raw_thms
   329 
   330 fun runprog (ProgBarras p) = AM_Interpreter.run p
   331   | runprog (ProgBarrasC p) = AM_Compiler.run p
   332   | runprog (ProgHaskell p) = AM_GHC.run p
   333   | runprog (ProgSML p) = AM_SML.run p    
   334 
   335 (* ------------------------------------------------------------------------------------- *)
   336 (* An oracle for exporting theorems; must only be accessible from inside this structure! *)
   337 (* ------------------------------------------------------------------------------------- *)
   338 
   339 fun merge_hyps hyps1 hyps2 = 
   340 let
   341     fun add hyps tab = fold (fn h => fn tab => Termtab.update (h, ()) tab) hyps tab
   342 in
   343     Termtab.keys (add hyps2 (add hyps1 Termtab.empty))
   344 end
   345 
   346 fun add_shyps shyps tab = fold (fn h => fn tab => Sorttab.update (h, ()) tab) shyps tab
   347 
   348 fun merge_shyps shyps1 shyps2 = Sorttab.keys (add_shyps shyps2 (add_shyps shyps1 Sorttab.empty))
   349 
   350 val (_, export_oracle) = Context.>>> (Context.map_theory_result
   351   (Thm.add_oracle (@{binding compute}, fn (thy, hyps, shyps, prop) =>
   352     let
   353         val shyptab = add_shyps shyps Sorttab.empty
   354         fun delete s shyptab = Sorttab.delete s shyptab handle Sorttab.UNDEF _ => shyptab
   355         fun delete_term t shyptab = fold delete (Sorts.insert_term t []) shyptab
   356         fun has_witness s = not (null (Sign.witness_sorts thy [] [s]))
   357         val shyptab = fold Sorttab.delete (filter has_witness (Sorttab.keys (shyptab))) shyptab
   358         val shyps = if Sorttab.is_empty shyptab then [] else Sorttab.keys (fold delete_term (prop::hyps) shyptab)
   359         val _ =
   360           if not (null shyps) then
   361             raise Compute ("dangling sort hypotheses: " ^
   362               commas (map (Syntax.string_of_sort_global thy) shyps))
   363           else ()
   364     in
   365         Thm.global_cterm_of thy (fold_rev (fn hyp => fn p => Logic.mk_implies (hyp, p)) hyps prop)
   366     end)));
   367 
   368 fun export_thm thy hyps shyps prop =
   369     let
   370         val th = export_oracle (thy, hyps, shyps, prop)
   371         val hyps = map (fn h => Thm.assume (Thm.global_cterm_of thy h)) hyps
   372     in
   373         fold (fn h => fn p => Thm.implies_elim p h) hyps th 
   374     end
   375         
   376 (* --------- Rewrite ----------- *)
   377 
   378 fun rewrite computer ct =
   379     let
   380         val thy = Thm.theory_of_cterm ct
   381         val t' = Thm.term_of ct
   382         val ty = Thm.typ_of_cterm ct
   383         val _ = super_theory (theory_of computer) thy
   384         val naming = naming_of computer
   385         val (encoding, t) = remove_types (encoding_of computer) t'
   386         val t = runprog (prog_of computer) t
   387         val t = infer_types naming encoding ty t
   388         val eq = Logic.mk_equals (t', t)
   389     in
   390         export_thm thy (hyps_of computer) (Sorttab.keys (shyptab_of computer)) eq
   391     end
   392 
   393 (* --------- Simplify ------------ *)
   394 
   395 datatype prem = EqPrem of AbstractMachine.term * AbstractMachine.term * Term.typ * int 
   396               | Prem of AbstractMachine.term
   397 datatype theorem = Theorem of theory * unit Unsynchronized.ref * (int * typ) Symtab.table * (AbstractMachine.term option) Inttab.table  
   398                * prem list * AbstractMachine.term * term list * sort list
   399 
   400 
   401 exception ParamSimplify of computer * theorem
   402 
   403 fun make_theorem computer th vars =
   404 let
   405     val _ = super_theory (theory_of computer) (Thm.theory_of_thm th)
   406 
   407     val (ComputeThm (hyps, shyps, prop)) = thm2cthm th 
   408 
   409     val encoding = encoding_of computer
   410  
   411     (* variables in the theorem are identified upfront *)
   412     fun collect_vars (Abs (_, _, t)) tab = collect_vars t tab
   413       | collect_vars (a $ b) tab = collect_vars b (collect_vars a tab)
   414       | collect_vars (Const _) tab = tab
   415       | collect_vars (Free _) tab = tab
   416       | collect_vars (Var ((s, i), ty)) tab = 
   417             if List.find (fn x => x=s) vars = NONE then 
   418                 tab
   419             else                
   420                 (case Symtab.lookup tab s of
   421                      SOME ((s',i'),ty') => 
   422                      if s' <> s orelse i' <> i orelse ty <> ty' then 
   423                          raise Compute ("make_theorem: variable name '"^s^"' is not unique")
   424                      else 
   425                          tab
   426                    | NONE => Symtab.update (s, ((s, i), ty)) tab)
   427     val vartab = collect_vars prop Symtab.empty 
   428     fun encodevar (s, t as (_, ty)) (encoding, tab) = 
   429         let
   430             val (x, encoding) = Encode.insert (Var t) encoding
   431         in
   432             (encoding, Symtab.update (s, (x, ty)) tab)
   433         end
   434     val (encoding, vartab) = Symtab.fold encodevar vartab (encoding, Symtab.empty)                                                     
   435     val varsubst = Inttab.make (map (fn (_, (x, _)) => (x, NONE)) (Symtab.dest vartab))
   436 
   437     (* make the premises and the conclusion *)
   438     fun mk_prem encoding t = 
   439         (let
   440              val (a, b) = Logic.dest_equals t
   441              val ty = type_of a
   442              val (encoding, a) = remove_types encoding a
   443              val (encoding, b) = remove_types encoding b
   444              val (eq, encoding) =
   445               Encode.insert (Const (@{const_name Pure.eq}, ty --> ty --> @{typ "prop"})) encoding 
   446          in
   447              (encoding, EqPrem (a, b, ty, eq))
   448          end handle TERM _ => let val (encoding, t) = remove_types encoding t in (encoding, Prem t) end)
   449     val (encoding, prems) = 
   450         (fold_rev (fn t => fn (encoding, l) => 
   451             case mk_prem encoding t  of 
   452                 (encoding, t) => (encoding, t::l)) (Logic.strip_imp_prems prop) (encoding, []))
   453     val (encoding, concl) = remove_types encoding (Logic.strip_imp_concl prop)
   454     val _ = set_encoding computer encoding
   455 in
   456     Theorem (Thm.theory_of_thm th, stamp_of computer, vartab, varsubst, 
   457              prems, concl, hyps, shyps)
   458 end
   459     
   460 fun theory_of_theorem (Theorem (thy,_,_,_,_,_,_,_)) = thy
   461 fun update_theory thy (Theorem (_,p0,p1,p2,p3,p4,p5,p6)) = Theorem (thy,p0,p1,p2,p3,p4,p5,p6)
   462 fun stamp_of_theorem (Theorem (_,s, _, _, _, _, _, _)) = s     
   463 fun vartab_of_theorem (Theorem (_,_,vt,_,_,_,_,_)) = vt
   464 fun varsubst_of_theorem (Theorem (_,_,_,vs,_,_,_,_)) = vs 
   465 fun update_varsubst vs (Theorem (p0,p1,p2,_,p3,p4,p5,p6)) = Theorem (p0,p1,p2,vs,p3,p4,p5,p6)
   466 fun prems_of_theorem (Theorem (_,_,_,_,prems,_,_,_)) = prems
   467 fun update_prems prems (Theorem (p0,p1,p2,p3,_,p4,p5,p6)) = Theorem (p0,p1,p2,p3,prems,p4,p5,p6)
   468 fun concl_of_theorem (Theorem (_,_,_,_,_,concl,_,_)) = concl
   469 fun hyps_of_theorem (Theorem (_,_,_,_,_,_,hyps,_)) = hyps
   470 fun update_hyps hyps (Theorem (p0,p1,p2,p3,p4,p5,_,p6)) = Theorem (p0,p1,p2,p3,p4,p5,hyps,p6)
   471 fun shyps_of_theorem (Theorem (_,_,_,_,_,_,_,shyps)) = shyps
   472 fun update_shyps shyps (Theorem (p0,p1,p2,p3,p4,p5,p6,_)) = Theorem (p0,p1,p2,p3,p4,p5,p6,shyps)
   473 
   474 fun check_compatible computer th s = 
   475     if stamp_of computer <> stamp_of_theorem th then
   476         raise Compute (s^": computer and theorem are incompatible")
   477     else ()
   478 
   479 fun instantiate computer insts th =
   480 let
   481     val _ = check_compatible computer th
   482 
   483     val thy = theory_of computer
   484 
   485     val vartab = vartab_of_theorem th
   486 
   487     fun rewrite computer t =
   488     let  
   489         val (encoding, t) = remove_types (encoding_of computer) t
   490         val t = runprog (prog_of computer) t
   491         val _ = set_encoding computer encoding
   492     in
   493         t
   494     end
   495 
   496     fun assert_varfree vs t = 
   497         if AbstractMachine.forall_consts (fn x => Inttab.lookup vs x = NONE) t then
   498             ()
   499         else
   500             raise Compute "instantiate: assert_varfree failed"
   501 
   502     fun assert_closed t =
   503         if AbstractMachine.closed t then
   504             ()
   505         else 
   506             raise Compute "instantiate: not a closed term"
   507 
   508     fun compute_inst (s, ct) vs =
   509         let
   510             val _ = super_theory (Thm.theory_of_cterm ct) thy
   511             val ty = Thm.typ_of_cterm ct
   512         in          
   513             (case Symtab.lookup vartab s of 
   514                  NONE => raise Compute ("instantiate: variable '"^s^"' not found in theorem")
   515                | SOME (x, ty') => 
   516                  (case Inttab.lookup vs x of 
   517                       SOME (SOME _) => raise Compute ("instantiate: variable '"^s^"' has already been instantiated")
   518                     | SOME NONE => 
   519                       if ty <> ty' then 
   520                           raise Compute ("instantiate: wrong type for variable '"^s^"'")
   521                       else
   522                           let
   523                               val t = rewrite computer (Thm.term_of ct)
   524                               val _ = assert_varfree vs t 
   525                               val _ = assert_closed t
   526                           in
   527                               Inttab.update (x, SOME t) vs
   528                           end
   529                     | NONE => raise Compute "instantiate: internal error"))
   530         end
   531 
   532     val vs = fold compute_inst insts (varsubst_of_theorem th)
   533 in
   534     update_varsubst vs th
   535 end
   536 
   537 fun match_aterms subst =
   538     let 
   539         exception no_match
   540         open AbstractMachine
   541         fun match subst (b as (Const c)) a = 
   542             if a = b then subst
   543             else 
   544                 (case Inttab.lookup subst c of 
   545                      SOME (SOME a') => if a=a' then subst else raise no_match
   546                    | SOME NONE => if AbstractMachine.closed a then 
   547                                       Inttab.update (c, SOME a) subst 
   548                                   else raise no_match
   549                    | NONE => raise no_match)
   550           | match subst (b as (Var _)) a = if a=b then subst else raise no_match
   551           | match subst (App (u, v)) (App (u', v')) = match (match subst u u') v v'
   552           | match subst (Abs u) (Abs u') = match subst u u'
   553           | match subst _ _ = raise no_match
   554     in
   555         fn b => fn a => (SOME (match subst b a) handle no_match => NONE)
   556     end
   557 
   558 fun apply_subst vars_allowed subst =
   559     let
   560         open AbstractMachine
   561         fun app (t as (Const c)) = 
   562             (case Inttab.lookup subst c of 
   563                  NONE => t 
   564                | SOME (SOME t) => Computed t
   565                | SOME NONE => if vars_allowed then t else raise Compute "apply_subst: no vars allowed")
   566           | app (t as (Var _)) = t
   567           | app (App (u, v)) = App (app u, app v)
   568           | app (Abs m) = Abs (app m)
   569     in
   570         app
   571     end
   572 
   573 fun splicein n l L = List.take (L, n) @ l @ List.drop (L, n+1)
   574 
   575 fun evaluate_prem computer prem_no th =
   576 let
   577     val _ = check_compatible computer th
   578     val prems = prems_of_theorem th
   579     val varsubst = varsubst_of_theorem th
   580     fun run vars_allowed t = 
   581         runprog (prog_of computer) (apply_subst vars_allowed varsubst t)
   582 in
   583     case nth prems prem_no of
   584         Prem _ => raise Compute "evaluate_prem: no equality premise"
   585       | EqPrem (a, b, ty, _) =>         
   586         let
   587             val a' = run false a
   588             val b' = run true b
   589         in
   590             case match_aterms varsubst b' a' of
   591                 NONE => 
   592                 let
   593                     fun mk s = Syntax.string_of_term_global Pure.thy
   594                       (infer_types (naming_of computer) (encoding_of computer) ty s)
   595                     val left = "computed left side: "^(mk a')
   596                     val right = "computed right side: "^(mk b')
   597                 in
   598                     raise Compute ("evaluate_prem: cannot assign computed left to right hand side\n"^left^"\n"^right^"\n")
   599                 end
   600               | SOME varsubst => 
   601                 update_prems (splicein prem_no [] prems) (update_varsubst varsubst th)
   602         end
   603 end
   604 
   605 fun prem2term (Prem t) = t
   606   | prem2term (EqPrem (a,b,_,eq)) = 
   607     AbstractMachine.App (AbstractMachine.App (AbstractMachine.Const eq, a), b)
   608 
   609 fun modus_ponens computer prem_no th' th = 
   610 let
   611     val _ = check_compatible computer th
   612     val thy = 
   613         let
   614             val thy1 = theory_of_theorem th
   615             val thy2 = Thm.theory_of_thm th'
   616         in
   617             if Theory.subthy (thy1, thy2) then thy2 
   618             else if Theory.subthy (thy2, thy1) then thy1 else
   619             raise Compute "modus_ponens: theorems are not compatible with each other"
   620         end 
   621     val th' = make_theorem computer th' []
   622     val varsubst = varsubst_of_theorem th
   623     fun run vars_allowed t =
   624         runprog (prog_of computer) (apply_subst vars_allowed varsubst t)
   625     val prems = prems_of_theorem th
   626     val prem = run true (prem2term (nth prems prem_no))
   627     val concl = run false (concl_of_theorem th')    
   628 in
   629     case match_aterms varsubst prem concl of
   630         NONE => raise Compute "modus_ponens: conclusion does not match premise"
   631       | SOME varsubst =>
   632         let
   633             val th = update_varsubst varsubst th
   634             val th = update_prems (splicein prem_no (prems_of_theorem th') prems) th
   635             val th = update_hyps (merge_hyps (hyps_of_theorem th) (hyps_of_theorem th')) th
   636             val th = update_shyps (merge_shyps (shyps_of_theorem th) (shyps_of_theorem th')) th
   637         in
   638             update_theory thy th
   639         end
   640 end
   641                      
   642 fun simplify computer th =
   643 let
   644     val _ = check_compatible computer th
   645     val varsubst = varsubst_of_theorem th
   646     val encoding = encoding_of computer
   647     val naming = naming_of computer
   648     fun infer t = infer_types naming encoding @{typ "prop"} t
   649     fun run t = infer (runprog (prog_of computer) (apply_subst true varsubst t))
   650     fun runprem p = run (prem2term p)
   651     val prop = Logic.list_implies (map runprem (prems_of_theorem th), run (concl_of_theorem th))
   652     val hyps = merge_hyps (hyps_of computer) (hyps_of_theorem th)
   653     val shyps = merge_shyps (shyps_of_theorem th) (Sorttab.keys (shyptab_of computer))
   654 in
   655     export_thm (theory_of_theorem th) hyps shyps prop
   656 end
   657 
   658 end
   659