src/HOL/Tools/Predicate_Compile/code_prolog.ML
author bulwahn
Thu Sep 16 13:49:10 2010 +0200 (2010-09-16)
changeset 39464 13493d3c28d0
parent 39462 3a86194d1534
child 39465 fcff6903595f
permissions -rw-r--r--
values command for prolog supports complex terms and not just variables
     1 (*  Title:      HOL/Tools/Predicate_Compile/code_prolog.ML
     2     Author:     Lukas Bulwahn, TU Muenchen
     3 
     4 Prototype of an code generator for logic programming languages (a.k.a. Prolog)
     5 *)
     6 
     7 signature CODE_PROLOG =
     8 sig
     9   datatype prolog_system = SWI_PROLOG | YAP
    10   type code_options =
    11     {ensure_groundness : bool,
    12      limited_types : (typ * int) list,
    13      limited_predicates : (string list * int) list,
    14      replacing : ((string * string) * string) list,
    15      manual_reorder : ((string * int) * int list) list}
    16   val set_ensure_groundness : code_options -> code_options
    17   val map_limit_predicates : ((string list * int) list -> (string list * int) list)
    18     -> code_options -> code_options
    19   val code_options_of : theory -> code_options 
    20   val map_code_options : (code_options -> code_options) -> theory -> theory
    21   
    22   datatype arith_op = Plus | Minus
    23   datatype prol_term = Var of string | Cons of string | AppF of string * prol_term list
    24     | Number of int | ArithOp of arith_op * prol_term list;
    25   datatype prem = Conj of prem list
    26     | Rel of string * prol_term list | NotRel of string * prol_term list
    27     | Eq of prol_term * prol_term | NotEq of prol_term * prol_term
    28     | ArithEq of prol_term * prol_term | NotArithEq of prol_term * prol_term
    29     | Ground of string * typ;
    30 
    31   type clause = ((string * prol_term list) * prem);
    32   type logic_program = clause list;
    33   type constant_table = (string * string) list
    34   
    35   val generate : Predicate_Compile_Aux.mode option * bool ->
    36     Proof.context -> string -> (logic_program * constant_table)
    37   val write_program : logic_program -> string
    38   val run : (Time.time * prolog_system) -> logic_program -> (string * prol_term list) -> string list -> int option -> prol_term list list
    39   
    40   val quickcheck : Proof.context -> term -> int -> term list option * (bool list * bool)
    41 
    42   val trace : bool Unsynchronized.ref
    43   
    44   val replace : ((string * string) * string) -> logic_program -> logic_program
    45 end;
    46 
    47 structure Code_Prolog : CODE_PROLOG =
    48 struct
    49 
    50 (* diagnostic tracing *)
    51 
    52 val trace = Unsynchronized.ref false
    53 
    54 fun tracing s = if !trace then Output.tracing s else () 
    55 
    56 (* code generation options *)
    57 
    58 
    59 type code_options =
    60   {ensure_groundness : bool,
    61    limited_types : (typ * int) list,
    62    limited_predicates : (string list * int) list,
    63    replacing : ((string * string) * string) list,
    64    manual_reorder : ((string * int) * int list) list}
    65 
    66 
    67 fun set_ensure_groundness {ensure_groundness, limited_types, limited_predicates,
    68   replacing, manual_reorder} =
    69   {ensure_groundness = true, limited_types = limited_types,
    70    limited_predicates = limited_predicates, replacing = replacing,
    71    manual_reorder = manual_reorder}
    72 
    73 fun map_limit_predicates f {ensure_groundness, limited_types, limited_predicates,
    74   replacing, manual_reorder} =
    75   {ensure_groundness = ensure_groundness, limited_types = limited_types,
    76    limited_predicates = f limited_predicates, replacing = replacing,
    77    manual_reorder = manual_reorder}
    78   
    79 structure Options = Theory_Data
    80 (
    81   type T = code_options
    82   val empty = {ensure_groundness = false,
    83     limited_types = [], limited_predicates = [], replacing = [], manual_reorder = []}
    84   val extend = I;
    85   fun merge
    86     ({ensure_groundness = ensure_groundness1, limited_types = limited_types1,
    87       limited_predicates = limited_predicates1, replacing = replacing1,
    88       manual_reorder = manual_reorder1},
    89      {ensure_groundness = ensure_groundness2, limited_types = limited_types2,
    90       limited_predicates = limited_predicates2, replacing = replacing2,
    91       manual_reorder = manual_reorder2}) =
    92     {ensure_groundness = ensure_groundness1 orelse ensure_groundness2,
    93      limited_types = AList.merge (op =) (K true) (limited_types1, limited_types2),
    94      limited_predicates = AList.merge (op =) (K true) (limited_predicates1, limited_predicates2),
    95      manual_reorder = AList.merge (op =) (K true) (manual_reorder1, manual_reorder2),
    96      replacing = Library.merge (op =) (replacing1, replacing2)};
    97 );
    98 
    99 val code_options_of = Options.get
   100 
   101 val map_code_options = Options.map
   102 
   103 (* system configuration *)
   104 
   105 datatype prolog_system = SWI_PROLOG | YAP
   106 
   107 fun string_of_system SWI_PROLOG = "swiprolog"
   108   | string_of_system YAP = "yap"
   109 
   110 type system_configuration = {timeout : Time.time, prolog_system : prolog_system}
   111                                                 
   112 structure System_Config = Generic_Data
   113 (
   114   type T = system_configuration
   115   val empty = {timeout = Time.fromSeconds 10, prolog_system = SWI_PROLOG}
   116   val extend = I;
   117   fun merge ({timeout = timeout1, prolog_system = prolog_system1},
   118         {timeout = timeout2, prolog_system = prolog_system2}) =
   119     {timeout = timeout1, prolog_system = prolog_system1}
   120 )
   121 
   122 (* general string functions *)
   123 
   124 val first_upper = implode o nth_map 0 Symbol.to_ascii_upper o explode;
   125 val first_lower = implode o nth_map 0 Symbol.to_ascii_lower o explode;
   126 
   127 (* internal program representation *)
   128 
   129 datatype arith_op = Plus | Minus
   130 
   131 datatype prol_term = Var of string | Cons of string | AppF of string * prol_term list
   132   | Number of int | ArithOp of arith_op * prol_term list;
   133 
   134 fun dest_Var (Var v) = v
   135 
   136 fun add_vars (Var v) = insert (op =) v
   137   | add_vars (ArithOp (_, ts)) = fold add_vars ts
   138   | add_vars (AppF (_, ts)) = fold add_vars ts
   139   | add_vars _ = I
   140 
   141 fun map_vars f (Var v) = Var (f v)
   142   | map_vars f (ArithOp (opr, ts)) = ArithOp (opr, map (map_vars f) ts)
   143   | map_vars f (AppF (fs, ts)) = AppF (fs, map (map_vars f) ts)
   144   | map_vars f t = t
   145   
   146 fun maybe_AppF (c, []) = Cons c
   147   | maybe_AppF (c, xs) = AppF (c, xs)
   148 
   149 fun is_Var (Var _) = true
   150   | is_Var _ = false
   151 
   152 fun is_arith_term (Var _) = true
   153   | is_arith_term (Number _) = true
   154   | is_arith_term (ArithOp (_, operands)) = forall is_arith_term operands
   155   | is_arith_term _ = false
   156 
   157 fun string_of_prol_term (Var s) = "Var " ^ s
   158   | string_of_prol_term (Cons s) = "Cons " ^ s
   159   | string_of_prol_term (AppF (f, args)) = f ^ "(" ^ commas (map string_of_prol_term args) ^ ")" 
   160   | string_of_prol_term (Number n) = "Number " ^ string_of_int n
   161 
   162 datatype prem = Conj of prem list
   163   | Rel of string * prol_term list | NotRel of string * prol_term list
   164   | Eq of prol_term * prol_term | NotEq of prol_term * prol_term
   165   | ArithEq of prol_term * prol_term | NotArithEq of prol_term * prol_term
   166   | Ground of string * typ;
   167 
   168 fun dest_Rel (Rel (c, ts)) = (c, ts)
   169 
   170 fun map_term_prem f (Conj prems) = Conj (map (map_term_prem f) prems)
   171   | map_term_prem f (Rel (r, ts)) = Rel (r, map f ts)
   172   | map_term_prem f (NotRel (r, ts)) = NotRel (r, map f ts)
   173   | map_term_prem f (Eq (l, r)) = Eq (f l, f r)
   174   | map_term_prem f (NotEq (l, r)) = NotEq (f l, f r)
   175   | map_term_prem f (ArithEq (l, r)) = ArithEq (f l, f r)
   176   | map_term_prem f (NotArithEq (l, r)) = NotArithEq (f l, f r)
   177   | map_term_prem f (Ground (v, T)) = Ground (dest_Var (f (Var v)), T)
   178 
   179 fun fold_prem_terms f (Conj prems) = fold (fold_prem_terms f) prems
   180   | fold_prem_terms f (Rel (_, ts)) = fold f ts
   181   | fold_prem_terms f (NotRel (_, ts)) = fold f ts
   182   | fold_prem_terms f (Eq (l, r)) = f l #> f r
   183   | fold_prem_terms f (NotEq (l, r)) = f l #> f r
   184   | fold_prem_terms f (ArithEq (l, r)) = f l #> f r
   185   | fold_prem_terms f (NotArithEq (l, r)) = f l #> f r
   186   | fold_prem_terms f (Ground (v, T)) = f (Var v)
   187   
   188 type clause = ((string * prol_term list) * prem);
   189 
   190 type logic_program = clause list;
   191 
   192 (* translation from introduction rules to internal representation *)
   193 
   194 fun mk_conform f empty avoid name =
   195   let
   196     fun dest_Char (Symbol.Char c) = c
   197     val name' = space_implode "" (map (dest_Char o Symbol.decode)
   198       (filter (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s)
   199         (Symbol.explode name)))
   200     val name'' = f (if name' = "" then empty else name')
   201   in (if member (op =) avoid name'' then Name.variant avoid name'' else name'') end
   202 
   203 (** constant table **)
   204 
   205 type constant_table = (string * string) list
   206 
   207 fun declare_consts consts constant_table =
   208   let
   209     fun update' c table =
   210       if AList.defined (op =) table c then table else
   211         let
   212           val c' = mk_conform first_lower "pred" (map snd table) (Long_Name.base_name c)
   213         in
   214           AList.update (op =) (c, c') table
   215         end
   216   in
   217     fold update' consts constant_table
   218   end
   219   
   220 fun translate_const constant_table c =
   221   case AList.lookup (op =) constant_table c of
   222     SOME c' => c'
   223   | NONE => error ("No such constant: " ^ c)
   224 
   225 fun inv_lookup _ [] _ = NONE
   226   | inv_lookup eq ((key, value)::xs) value' =
   227       if eq (value', value) then SOME key
   228       else inv_lookup eq xs value';
   229 
   230 fun restore_const constant_table c =
   231   case inv_lookup (op =) constant_table c of
   232     SOME c' => c'
   233   | NONE => error ("No constant corresponding to "  ^ c)
   234 
   235 (** translation of terms, literals, premises, and clauses **)
   236 
   237 fun translate_arith_const @{const_name "Groups.plus_class.plus"} = SOME Plus
   238   | translate_arith_const @{const_name "Groups.minus_class.minus"} = SOME Minus
   239   | translate_arith_const _ = NONE
   240 
   241 fun mk_nat_term constant_table n =
   242   let
   243     val zero = translate_const constant_table @{const_name "Groups.zero_class.zero"}
   244     val Suc = translate_const constant_table @{const_name "Suc"}
   245   in funpow n (fn t => AppF (Suc, [t])) (Cons zero) end
   246 
   247 fun translate_term ctxt constant_table t =
   248   case try HOLogic.dest_number t of
   249     SOME (@{typ "int"}, n) => Number n
   250   | SOME (@{typ "nat"}, n) => mk_nat_term constant_table n
   251   | NONE =>
   252       (case strip_comb t of
   253         (Free (v, T), []) => Var v 
   254       | (Const (c, _), []) => Cons (translate_const constant_table c)
   255       | (Const (c, _), args) =>
   256         (case translate_arith_const c of
   257           SOME aop => ArithOp (aop, map (translate_term ctxt constant_table) args)
   258         | NONE =>                                                             
   259             AppF (translate_const constant_table c, map (translate_term ctxt constant_table) args))
   260       | _ => error ("illegal term for translation: " ^ Syntax.string_of_term ctxt t))
   261 
   262 fun translate_literal ctxt constant_table t =
   263   case strip_comb t of
   264     (Const (@{const_name HOL.eq}, _), [l, r]) =>
   265       let
   266         val l' = translate_term ctxt constant_table l
   267         val r' = translate_term ctxt constant_table r
   268       in
   269         (if is_Var l' andalso is_arith_term r' andalso not (is_Var r') then ArithEq else Eq) (l', r')
   270       end
   271   | (Const (c, _), args) =>
   272       Rel (translate_const constant_table c, map (translate_term ctxt constant_table) args)
   273   | _ => error ("illegal literal for translation: " ^ Syntax.string_of_term ctxt t)
   274 
   275 fun NegRel_of (Rel lit) = NotRel lit
   276   | NegRel_of (Eq eq) = NotEq eq
   277   | NegRel_of (ArithEq eq) = NotArithEq eq
   278 
   279 fun mk_groundness_prems t = map Ground (Term.add_frees t [])
   280   
   281 fun translate_prem ensure_groundness ctxt constant_table t =  
   282     case try HOLogic.dest_not t of
   283       SOME t =>
   284         if ensure_groundness then
   285           Conj (mk_groundness_prems t @ [NegRel_of (translate_literal ctxt constant_table t)])
   286         else
   287           NegRel_of (translate_literal ctxt constant_table t)
   288     | NONE => translate_literal ctxt constant_table t
   289     
   290 fun imp_prems_conv cv ct =
   291   case Thm.term_of ct of
   292     Const ("==>", _) $ _ $ _ => Conv.combination_conv (Conv.arg_conv cv) (imp_prems_conv cv) ct
   293   | _ => Conv.all_conv ct
   294 
   295 fun Trueprop_conv cv ct =
   296   case Thm.term_of ct of
   297     Const (@{const_name Trueprop}, _) $ _ => Conv.arg_conv cv ct  
   298   | _ => raise Fail "Trueprop_conv"
   299 
   300 fun preprocess_intro thy rule =
   301   Conv.fconv_rule
   302     (imp_prems_conv
   303       (Trueprop_conv (Conv.try_conv (Conv.rewr_conv @{thm Predicate.eq_is_eq}))))
   304     (Thm.transfer thy rule)
   305 
   306 fun translate_intros ensure_groundness ctxt gr const constant_table =
   307   let
   308     val intros = map (preprocess_intro (ProofContext.theory_of ctxt)) (Graph.get_node gr const)
   309     val (intros', ctxt') = Variable.import_terms true (map prop_of intros) ctxt
   310     val constant_table' = declare_consts (fold Term.add_const_names intros' []) constant_table
   311     fun translate_intro intro =
   312       let
   313         val head = HOLogic.dest_Trueprop (Logic.strip_imp_concl intro)
   314         val prems = map HOLogic.dest_Trueprop (Logic.strip_imp_prems intro)
   315         val prems' = Conj (map (translate_prem ensure_groundness ctxt' constant_table') prems)
   316         val clause = (dest_Rel (translate_literal ctxt' constant_table' head), prems')
   317       in clause end
   318     val res = (map translate_intro intros', constant_table')
   319   in res end
   320 
   321 fun depending_preds_of (key, intros) =
   322   fold Term.add_const_names (map Thm.prop_of intros) []
   323 
   324 fun add_edges edges_of key G =
   325   let
   326     fun extend' key (G, visited) = 
   327       case try (Graph.get_node G) key of
   328           SOME v =>
   329             let
   330               val new_edges = filter (fn k => is_some (try (Graph.get_node G) k)) (edges_of (key, v))
   331               val (G', visited') = fold extend'
   332                 (subtract (op =) (key :: visited) new_edges) (G, key :: visited)
   333             in
   334               (fold (Graph.add_edge o (pair key)) new_edges G', visited')
   335             end
   336         | NONE => (G, visited)
   337   in
   338     fst (extend' key (G, []))
   339   end
   340 
   341 fun print_intros ctxt gr consts =
   342   tracing (cat_lines (map (fn const =>
   343     "Constant " ^ const ^ "has intros:\n" ^
   344     cat_lines (map (Display.string_of_thm ctxt) (Graph.get_node gr const))) consts))
   345 
   346 (* translation of moded predicates *)
   347 
   348 (** generating graph of moded predicates **)
   349 
   350 (* could be moved to Predicate_Compile_Core *)
   351 fun requires_modes polarity cls =
   352   let
   353     fun req_mode_of pol (t, derivation) =
   354       (case fst (strip_comb t) of
   355         Const (c, _) => SOME (c, (pol, Predicate_Compile_Core.head_mode_of derivation))
   356       | _ => NONE)
   357     fun req (Predicate_Compile_Aux.Prem t, derivation) = req_mode_of polarity (t, derivation)
   358       | req (Predicate_Compile_Aux.Negprem t, derivation) = req_mode_of (not polarity) (t, derivation)
   359       | req _ = NONE
   360   in      
   361     maps (fn (_, prems) => map_filter req prems) cls
   362   end
   363  
   364 structure Mode_Graph = Graph(type key = string * (bool * Predicate_Compile_Aux.mode)
   365   val ord = prod_ord fast_string_ord (prod_ord bool_ord Predicate_Compile_Aux.mode_ord));
   366 
   367 fun mk_moded_clauses_graph ctxt scc gr =
   368   let
   369     val options = Predicate_Compile_Aux.default_options
   370     val mode_analysis_options =
   371       {use_random = true, reorder_premises = true, infer_pos_and_neg_modes = true}
   372     fun infer prednames (gr, (pos_modes, neg_modes, random)) =
   373       let
   374         val (lookup_modes, lookup_neg_modes, needs_random) =
   375           ((fn s => the (AList.lookup (op =) pos_modes s)),
   376            (fn s => the (AList.lookup (op =) neg_modes s)),
   377            (fn s => member (op =) (the (AList.lookup (op =) random s))))
   378         val (preds, all_vs, param_vs, all_modes, clauses) =
   379           Predicate_Compile_Core.prepare_intrs options ctxt prednames
   380             (maps (Predicate_Compile_Core.intros_of ctxt) prednames)
   381         val ((moded_clauses, random'), _) =
   382           Predicate_Compile_Core.infer_modes mode_analysis_options options 
   383             (lookup_modes, lookup_neg_modes, needs_random) ctxt preds all_modes param_vs clauses
   384         val modes = map (fn (p, mps) => (p, map fst mps)) moded_clauses
   385         val pos_modes' = map (apsnd (map_filter (fn (true, m) => SOME m | _ => NONE))) modes
   386         val neg_modes' = map (apsnd (map_filter (fn (false, m) => SOME m | _ => NONE))) modes
   387         val _ = tracing ("Inferred modes:\n" ^
   388           cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map
   389             (fn (p, m) => Predicate_Compile_Aux.string_of_mode m ^ (if p then "pos" else "neg")) ms)) modes))
   390         val gr' = gr
   391           |> fold (fn (p, mps) => fold (fn (mode, cls) =>
   392                 Mode_Graph.new_node ((p, mode), cls)) mps)
   393             moded_clauses
   394           |> fold (fn (p, mps) => fold (fn (mode, cls) => fold (fn req =>
   395               Mode_Graph.add_edge ((p, mode), req)) (requires_modes (fst mode) cls)) mps)
   396             moded_clauses
   397       in
   398         (gr', (AList.merge (op =) (op =) (pos_modes, pos_modes'),
   399           AList.merge (op =) (op =) (neg_modes, neg_modes'),
   400           AList.merge (op =) (op =) (random, random')))
   401       end
   402   in  
   403     fst (fold infer (rev scc) (Mode_Graph.empty, ([], [], []))) 
   404   end
   405 
   406 fun declare_moded_predicate moded_preds table =
   407   let
   408     fun update' (p as (pred, (pol, mode))) table =
   409       if AList.defined (op =) table p then table else
   410         let
   411           val name = Long_Name.base_name pred ^ (if pol then "p" else "n")
   412             ^ Predicate_Compile_Aux.ascii_string_of_mode mode
   413           val p' = mk_conform first_lower "pred" (map snd table) name
   414         in
   415           AList.update (op =) (p, p') table
   416         end
   417   in
   418     fold update' moded_preds table
   419   end
   420 
   421 fun mk_program ctxt moded_gr moded_preds (prog, (moded_pred_table, constant_table)) =
   422   let
   423     val moded_pred_table' = declare_moded_predicate moded_preds moded_pred_table
   424     fun mk_literal pol derivation constant_table' t =
   425       let
   426         val (p, args) = strip_comb t
   427         val mode = Predicate_Compile_Core.head_mode_of derivation 
   428         val name = fst (dest_Const p)
   429         
   430         val p' = the (AList.lookup (op =) moded_pred_table' (name, (pol, mode)))
   431         val args' = map (translate_term ctxt constant_table') args
   432       in
   433         Rel (p', args')
   434       end
   435     fun mk_prem pol (indprem, derivation) constant_table =
   436       case indprem of
   437         Predicate_Compile_Aux.Generator (s, T) => (Ground (s, T), constant_table)
   438       | _ =>
   439         declare_consts (Term.add_const_names (Predicate_Compile_Aux.dest_indprem indprem) []) constant_table
   440         |> (fn constant_table' =>
   441           (case indprem of Predicate_Compile_Aux.Negprem t =>
   442             NegRel_of (mk_literal (not pol) derivation constant_table' t)
   443           | _ =>
   444             mk_literal pol derivation constant_table' (Predicate_Compile_Aux.dest_indprem indprem), constant_table'))
   445     fun mk_clause pred_name pol (ts, prems) (prog, constant_table) =
   446     let
   447       val constant_table' = declare_consts (fold Term.add_const_names ts []) constant_table
   448       val args = map (translate_term ctxt constant_table') ts
   449       val (prems', constant_table'') = fold_map (mk_prem pol) prems constant_table'
   450     in
   451       (((pred_name, args), Conj prems') :: prog, constant_table'')
   452     end
   453     fun mk_clauses (pred, mode as (pol, _)) =
   454       let
   455         val clauses = Mode_Graph.get_node moded_gr (pred, mode)
   456         val pred_name = the (AList.lookup (op =) moded_pred_table' (pred, mode))
   457       in
   458         fold (mk_clause pred_name pol) clauses
   459       end
   460   in
   461     apsnd (pair moded_pred_table') (fold mk_clauses moded_preds (prog, constant_table))
   462   end
   463 
   464 fun generate (use_modes, ensure_groundness) ctxt const =
   465   let 
   466     fun strong_conn_of gr keys =
   467       Graph.strong_conn (Graph.subgraph (member (op =) (Graph.all_succs gr keys)) gr)
   468     val gr = Predicate_Compile_Core.intros_graph_of ctxt
   469     val gr' = add_edges depending_preds_of const gr
   470     val scc = strong_conn_of gr' [const]
   471     val initial_constant_table = 
   472       declare_consts [@{const_name "Groups.zero_class.zero"}, @{const_name "Suc"}] []
   473   in
   474     case use_modes of
   475       SOME mode =>
   476         let
   477           val moded_gr = mk_moded_clauses_graph ctxt scc gr
   478           val moded_gr' = Mode_Graph.subgraph
   479             (member (op =) (Mode_Graph.all_succs moded_gr [(const, (true, mode))])) moded_gr
   480           val scc = Mode_Graph.strong_conn moded_gr' 
   481         in
   482           apfst rev (apsnd snd
   483             (fold (mk_program ctxt moded_gr') (rev scc) ([], ([], initial_constant_table))))
   484         end
   485       | NONE =>
   486         let 
   487           val _ = print_intros ctxt gr (flat scc)
   488           val constant_table = declare_consts (flat scc) initial_constant_table
   489         in
   490           apfst flat (fold_map (translate_intros ensure_groundness ctxt gr) (flat scc) constant_table)
   491         end
   492   end
   493   
   494 (* implementation for fully enumerating predicates and
   495   for size-limited predicates for enumerating the values of a datatype upto a specific size *)
   496 
   497 fun add_ground_typ (Conj prems) = fold add_ground_typ prems
   498   | add_ground_typ (Ground (_, T)) = insert (op =) T
   499   | add_ground_typ _ = I
   500 
   501 fun mk_relname (Type (Tcon, Targs)) =
   502   first_lower (Long_Name.base_name Tcon) ^ space_implode "_" (map mk_relname Targs)
   503   | mk_relname _ = raise Fail "unexpected type"
   504 
   505 fun mk_lim_relname T = "lim_" ^  mk_relname T
   506 
   507 (* This is copied from "pat_completeness.ML" *)
   508 fun inst_constrs_of thy (T as Type (name, _)) =
   509   map (fn (Cn,CT) =>
   510     Envir.subst_term_types (Sign.typ_match thy (body_type CT, T) Vartab.empty) (Const (Cn, CT)))
   511     (the (Datatype.get_constrs thy name))
   512   | inst_constrs_of thy T = raise TYPE ("inst_constrs_of", [T], [])
   513 
   514 fun is_recursive_constr T (Const (constr_name, T')) = member (op =) (binder_types T') T
   515   
   516 fun mk_ground_impl ctxt limited_types (T as Type (Tcon, Targs)) (seen, constant_table) =
   517   if member (op =) seen T then ([], (seen, constant_table))
   518   else
   519     let
   520       val (limited, size) = case AList.lookup (op =) limited_types T of
   521         SOME s => (true, s)
   522       | NONE => (false, 0)      
   523       val rel_name = (if limited then mk_lim_relname else mk_relname) T
   524       fun mk_impl (Const (constr_name, cT), recursive) (seen, constant_table) =
   525         let
   526           val constant_table' = declare_consts [constr_name] constant_table
   527           val Ts = binder_types cT
   528           val (rec_clauses, (seen', constant_table'')) =
   529             fold_map (mk_ground_impl ctxt limited_types) Ts (seen, constant_table')
   530           val vars = map (fn i => Var ("x" ^ string_of_int i)) (1 upto (length Ts))
   531           val lim_var =
   532             if limited then
   533               if recursive then [AppF ("suc", [Var "Lim"])]              
   534               else [Var "Lim"]
   535             else [] 
   536           fun mk_prem v T' =
   537             if limited andalso T' = T then Rel (mk_lim_relname T', [Var "Lim", v])
   538             else Rel (mk_relname T', [v])
   539           val clause =
   540             ((rel_name, lim_var @ [maybe_AppF (translate_const constant_table'' constr_name, vars)]),
   541              Conj (map2 mk_prem vars Ts))
   542         in
   543           (clause :: flat rec_clauses, (seen', constant_table''))
   544         end
   545       val constrs = inst_constrs_of (ProofContext.theory_of ctxt) T
   546       val constrs' = (constrs ~~ map (is_recursive_constr T) constrs)
   547         |> (fn cs => filter_out snd cs @ filter snd cs)
   548       val (clauses, constant_table') =
   549         apfst flat (fold_map mk_impl constrs' (T :: seen, constant_table))
   550       val size_term = funpow size (fn t => AppF ("suc", [t])) (Cons "zero")
   551     in
   552       ((if limited then
   553         cons ((mk_relname T, [Var "x"]), Rel (mk_lim_relname T, [size_term, Var "x"]))
   554       else I) clauses, constant_table')
   555     end
   556  | mk_ground_impl ctxt _ T (seen, constant_table) =
   557    raise Fail ("unexpected type :" ^ Syntax.string_of_typ ctxt T)
   558 
   559 fun replace_ground (Conj prems) = Conj (map replace_ground prems)
   560   | replace_ground (Ground (x, T)) =
   561     Rel (mk_relname T, [Var x])  
   562   | replace_ground p = p
   563   
   564 fun add_ground_predicates ctxt limited_types (p, constant_table) =
   565   let
   566     val ground_typs = fold (add_ground_typ o snd) p []
   567     val (grs, (_, constant_table')) = fold_map (mk_ground_impl ctxt limited_types) ground_typs ([], constant_table)
   568     val p' = map (apsnd replace_ground) p
   569   in
   570     ((flat grs) @ p', constant_table')
   571   end
   572 
   573 (* make depth-limited version of predicate *)
   574 
   575 fun mk_lim_rel_name rel_name = "lim_" ^ rel_name
   576 
   577 fun mk_depth_limited rel_names ((rel_name, ts), prem) =
   578   let
   579     fun has_positive_recursive_prems (Conj prems) = exists has_positive_recursive_prems prems
   580       | has_positive_recursive_prems (Rel (rel, ts)) = member (op =) rel_names rel
   581       | has_positive_recursive_prems _ = false
   582     fun mk_lim_prem (Conj prems) = Conj (map mk_lim_prem prems)
   583       | mk_lim_prem (p as Rel (rel, ts)) =
   584         if member (op =) rel_names rel then Rel (mk_lim_rel_name rel, Var "Lim" :: ts) else p
   585       | mk_lim_prem p = p
   586   in
   587     if has_positive_recursive_prems prem then
   588       ((mk_lim_rel_name rel_name, (AppF ("suc", [Var "Lim"]))  :: ts), mk_lim_prem prem)
   589     else
   590       ((mk_lim_rel_name rel_name, (Var "Lim") :: ts), prem)
   591   end
   592 
   593 fun add_limited_predicates limited_predicates =
   594   let                                     
   595     fun add (rel_names, limit) (p, constant_table) = 
   596       let
   597         val clauses = filter (fn ((rel, _), _) => member (op =) rel_names rel) p
   598         val clauses' = map (mk_depth_limited rel_names) clauses
   599         fun nat_term_of n = funpow n (fn t => AppF ("suc", [t])) (Cons "zero")
   600         fun mk_entry_clause rel_name =
   601           let
   602             val nargs = length (snd (fst
   603               (the (find_first (fn ((rel, _), _) => rel = rel_name) clauses))))
   604             val vars = map (fn i => Var ("x" ^ string_of_int i)) (1 upto nargs)        
   605           in
   606             (("limited_" ^ rel_name, vars), Rel ("lim_" ^ rel_name, nat_term_of limit :: vars))
   607           end
   608       in (p @ (map mk_entry_clause rel_names) @ clauses', constant_table) end
   609   in
   610     fold add limited_predicates
   611   end
   612 
   613 
   614 (* replace predicates in clauses *)
   615 
   616 (* replace (A, B, C) p = replace A by B in clauses of C *)
   617 fun replace ((from, to), location) p =
   618   let
   619     fun replace_prem (Conj prems) = Conj (map replace_prem prems)
   620       | replace_prem (r as Rel (rel, ts)) =
   621           if rel = from then Rel (to, ts) else r
   622       | replace_prem r = r
   623   in
   624     map (fn ((rel, args), prem) => ((rel, args), (if rel = location then replace_prem else I) prem)) p
   625   end
   626 
   627   
   628 (* reorder manually : reorder premises of ith clause of predicate p by a permutation perm *)
   629 
   630 fun reorder_manually reorder p =
   631   let
   632     fun reorder' (clause as ((rel, args), prem)) seen =
   633       let
   634         val seen' = AList.map_default (op =) (rel, 0) (fn x => x + 1) seen
   635         val i = the (AList.lookup (op =) seen' rel)
   636         val perm = AList.lookup (op =) reorder (rel, i)
   637         val prem' = (case perm of 
   638           SOME p => (case prem of Conj prems => Conj (map (nth prems) p) | _ => prem)
   639         | NONE => prem)
   640       in (((rel, args), prem'), seen') end
   641   in
   642     fst (fold_map reorder' p [])
   643   end
   644 
   645 (* rename variables to prolog-friendly names *)
   646 
   647 fun rename_vars_term renaming = map_vars (fn v => the (AList.lookup (op =) renaming v))
   648 
   649 fun rename_vars_prem renaming = map_term_prem (rename_vars_term renaming)
   650 
   651 fun is_prolog_conform v =
   652   forall (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s) (Symbol.explode v)
   653   
   654 fun mk_renaming v renaming =
   655   (v, mk_conform first_upper "Var" (map snd renaming) v) :: renaming
   656 
   657 fun rename_vars_clause ((rel, args), prem) =
   658   let
   659     val vars = fold_prem_terms add_vars prem (fold add_vars args [])
   660     val renaming = fold mk_renaming vars []
   661   in ((rel, map (rename_vars_term renaming) args), rename_vars_prem renaming prem) end
   662   
   663 val rename_vars_program = map rename_vars_clause
   664 
   665 (* code printer *)
   666 
   667 fun write_arith_op Plus = "+"
   668   | write_arith_op Minus = "-"
   669 
   670 fun write_term (Var v) = v
   671   | write_term (Cons c) = c
   672   | write_term (AppF (f, args)) = f ^ "(" ^ space_implode ", " (map write_term args) ^ ")"
   673   | write_term (ArithOp (oper, [a1, a2])) = write_term a1 ^ " " ^ write_arith_op oper ^ " " ^ write_term a2
   674   | write_term (Number n) = string_of_int n
   675 
   676 fun write_rel (pred, args) =
   677   pred ^ "(" ^ space_implode ", " (map write_term args) ^ ")" 
   678 
   679 fun write_prem (Conj prems) = space_implode ", " (map write_prem prems)
   680   | write_prem (Rel p) = write_rel p  
   681   | write_prem (NotRel p) = "not(" ^ write_rel p ^ ")"
   682   | write_prem (Eq (l, r)) = write_term l ^ " = " ^ write_term r
   683   | write_prem (NotEq (l, r)) = write_term l ^ " \\= " ^ write_term r
   684   | write_prem (ArithEq (l, r)) = write_term l ^ " is " ^ write_term r
   685   | write_prem (NotArithEq (l, r)) = write_term l ^ " =\\= " ^ write_term r
   686   | write_prem _ = raise Fail "Not a valid prolog premise"
   687 
   688 fun write_clause (head, prem) =
   689   write_rel head ^ (if prem = Conj [] then "." else " :- " ^ write_prem prem ^ ".")
   690 
   691 fun write_program p =
   692   cat_lines (map write_clause p) 
   693 
   694 (* query templates *)
   695 
   696 (** query and prelude for swi-prolog **)
   697 
   698 fun swi_prolog_query_first (rel, args) vnames =
   699   "eval :- once("  ^ rel ^ "(" ^ space_implode ", " (map write_term args) ^ ")),\n" ^
   700   "writef('" ^ space_implode ";" (map (fn v => v ^ " = %w") vnames) ^
   701   "\\n', [" ^ space_implode ", " vnames ^ "]).\n"
   702   
   703 fun swi_prolog_query_firstn n (rel, args) vnames =
   704   "eval :- findnsols(" ^ string_of_int n ^ ", (" ^ space_implode ", " vnames ^ "), " ^
   705     rel ^ "(" ^ space_implode ", " (map write_term args) ^ "), Sols), writelist(Sols).\n" ^
   706     "writelist([]).\n" ^
   707     "writelist([(" ^ space_implode ", " vnames ^ ")|T]) :- " ^
   708     "writef('" ^ space_implode ";" (map (fn v => v ^ " = %w") vnames) ^
   709     "\\n', [" ^ space_implode ", " vnames ^ "]), writelist(T).\n"
   710   
   711 val swi_prolog_prelude =
   712   "#!/usr/bin/swipl -q -t main -f\n\n" ^
   713   ":- use_module(library('dialect/ciao/aggregates')).\n" ^
   714   ":- style_check(-singleton).\n" ^
   715   ":- style_check(-discontiguous).\n" ^ 	
   716   ":- style_check(-atom).\n\n" ^
   717   "main :- catch(eval, E, (print_message(error, E), fail)), halt.\n" ^
   718   "main :- halt(1).\n"
   719 
   720 (** query and prelude for yap **)
   721 
   722 fun yap_query_first (rel, args) vnames =
   723   "eval :- once(" ^ rel ^ "(" ^ space_implode ", " (map write_term args) ^ ")),\n" ^
   724   "format('" ^ space_implode ";" (map (fn v => v ^ " = ~w") vnames) ^
   725   "\\n', [" ^ space_implode ", " vnames ^ "]).\n"
   726 
   727 val yap_prelude =
   728   "#!/usr/bin/yap -L\n\n" ^
   729   ":- initialization(eval).\n"
   730 
   731 (* system-dependent query, prelude and invocation *)
   732 
   733 fun query system nsols = 
   734   case system of
   735     SWI_PROLOG =>
   736       (case nsols of NONE => swi_prolog_query_first | SOME n => swi_prolog_query_firstn n)
   737   | YAP =>
   738       case nsols of NONE => yap_query_first | SOME n =>
   739         error "No support for querying multiple solutions in the prolog system yap"
   740 
   741 fun prelude system =
   742   case system of SWI_PROLOG => swi_prolog_prelude | YAP => yap_prelude
   743 
   744 fun invoke system file_name =
   745   let
   746     val env_var =
   747       (case system of SWI_PROLOG => "EXEC_SWIPL"| YAP => "EXEC_YAP")
   748     val prog = getenv env_var
   749     val cmd =
   750       case system of SWI_PROLOG => prog ^ " -f " | YAP => prog ^ " -L "
   751   in
   752     if prog = "" then
   753       (warning (env_var ^ " not set; could not execute code for " ^ string_of_system system); "")
   754     else fst (bash_output (cmd ^ file_name))
   755   end
   756 
   757 (* parsing prolog solution *)
   758 
   759 val scan_number =
   760   Scan.many1 Symbol.is_ascii_digit
   761 
   762 val scan_atom =
   763   Scan.many1 (fn s => Symbol.is_ascii_lower s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
   764 
   765 val scan_var =
   766   Scan.many1
   767     (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
   768 
   769 val scan_ident =
   770   Scan.repeat (Scan.one
   771     (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s))
   772 
   773 fun dest_Char (Symbol.Char s) = s
   774 
   775 val string_of = concat o map (dest_Char o Symbol.decode)
   776 
   777 val is_atom_ident = forall Symbol.is_ascii_lower
   778 
   779 val is_var_ident =
   780   forall (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
   781 
   782 fun int_of_symbol_list xs = fold (fn x => fn s => s * 10 + (ord x - ord "0")) xs 0
   783 
   784 fun scan_terms xs = (((scan_term --| $$ ",") ::: scan_terms)
   785   || (scan_term >> single)) xs
   786 and scan_term xs =
   787   ((scan_number >> (Number o int_of_symbol_list))
   788   || (scan_var >> (Var o string_of))
   789   || ((scan_atom -- ($$ "(" |-- scan_terms --| $$ ")"))
   790     >> (fn (f, ts) => AppF (string_of f, ts)))
   791   || (scan_atom >> (Cons o string_of))) xs
   792 
   793 val parse_term = fst o Scan.finite Symbol.stopper
   794     (Scan.error (!! (fn _ => raise Fail "parsing prolog output failed")) scan_term)
   795   o explode
   796   
   797 fun parse_solutions sol =
   798   let
   799     fun dest_eq s = case space_explode "=" s of
   800         (l :: r :: []) => parse_term (unprefix " " r)
   801       | _ => raise Fail "unexpected equation in prolog output"
   802     fun parse_solution s = map dest_eq (space_explode ";" s)
   803     val sols = case space_explode "\n" sol of [] => [] | s => fst (split_last s)  
   804   in
   805     map parse_solution sols
   806   end 
   807   
   808 (* calling external interpreter and getting results *)
   809 
   810 fun run (timeout, system) p (query_rel, args) vnames nsols =
   811   let
   812     val p' = rename_vars_program p
   813     val _ = tracing "Renaming variable names..."
   814     val renaming = fold mk_renaming (fold add_vars args vnames) [] 
   815     val vnames' = map (fn v => the (AList.lookup (op =) renaming v)) vnames
   816     val args' = map (rename_vars_term renaming) args
   817     val prog = prelude system ^ query system nsols (query_rel, args') vnames' ^ write_program p'
   818     val _ = tracing ("Generated prolog program:\n" ^ prog)
   819     val solution = TimeLimit.timeLimit timeout (fn prog => Cache_IO.with_tmp_file "prolog_file" (fn prolog_file =>
   820       (File.write prolog_file prog; invoke system (Path.implode prolog_file)))) prog
   821     val _ = tracing ("Prolog returned solution(s):\n" ^ solution)
   822     val tss = parse_solutions solution
   823   in
   824     tss
   825   end
   826 
   827 (* restoring types in terms *)
   828 
   829 fun restore_term ctxt constant_table (Var s, T) = Free (s, T)
   830   | restore_term ctxt constant_table (Number n, @{typ "int"}) = HOLogic.mk_number @{typ "int"} n
   831   | restore_term ctxt constant_table (Number n, _) = raise (Fail "unexpected type for number") 
   832   | restore_term ctxt constant_table (Cons s, T) = Const (restore_const constant_table s, T)
   833   | restore_term ctxt constant_table (AppF (f, args), T) =
   834     let
   835       val thy = ProofContext.theory_of ctxt
   836       val c = restore_const constant_table f
   837       val cT = Sign.the_const_type thy c
   838       val (argsT, resT) = strip_type cT
   839       val subst = Sign.typ_match thy (resT, T) Vartab.empty
   840       val argsT' = map (Envir.subst_type subst) argsT
   841     in
   842       list_comb (Const (c, Envir.subst_type subst cT),
   843         map (restore_term ctxt constant_table) (args ~~ argsT'))
   844     end
   845 
   846 (* values command *)
   847 
   848 val preprocess_options = Predicate_Compile_Aux.Options {
   849   expected_modes = NONE,
   850   proposed_modes = [],
   851   proposed_names = [],
   852   show_steps = false,
   853   show_intermediate_results = false,
   854   show_proof_trace = false,
   855   show_modes = false,
   856   show_mode_inference = false,
   857   show_compilation = false,
   858   show_caught_failures = false,
   859   show_invalid_clauses = false,
   860   skip_proof = true,
   861   no_topmost_reordering = false,
   862   function_flattening = true,
   863   specialise = false,
   864   fail_safe_function_flattening = false,
   865   no_higher_order_predicate = [],
   866   inductify = false,
   867   detect_switches = true,
   868   compilation = Predicate_Compile_Aux.Pred
   869 }
   870 
   871 fun values ctxt soln t_compr =
   872   let
   873     val options = code_options_of (ProofContext.theory_of ctxt)
   874     val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
   875       | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term ctxt t_compr);
   876     val (body, Ts, fp) = HOLogic.strip_psplits split;
   877     val output_names = Name.variant_list (Term.add_free_names body [])
   878       (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
   879     val output_frees = rev (map2 (curry Free) output_names Ts)
   880     val body = subst_bounds (output_frees, body)
   881     val (pred as Const (name, T), all_args) =
   882       case strip_comb body of
   883         (Const (name, T), all_args) => (Const (name, T), all_args)
   884       | (head, _) => error ("Not a constant: " ^ Syntax.string_of_term ctxt head)
   885     val _ = tracing "Preprocessing specification..."
   886     val T = Sign.the_const_type (ProofContext.theory_of ctxt) name
   887     val t = Const (name, T)
   888     val thy' =
   889       Theory.copy (ProofContext.theory_of ctxt)
   890       |> Predicate_Compile.preprocess preprocess_options t
   891     val ctxt' = ProofContext.init_global thy'
   892     val _ = tracing "Generating prolog program..."
   893     val (p, constant_table) = generate (NONE, #ensure_groundness options) ctxt' name (* FIXME *)
   894       |> (if #ensure_groundness options then
   895           add_ground_predicates ctxt' (#limited_types options)
   896         else I)
   897       |> add_limited_predicates (#limited_predicates options)
   898       |> apfst (fold replace (#replacing options))
   899       |> apfst (reorder_manually (#manual_reorder options))
   900     val constant_table' = declare_consts (fold Term.add_const_names all_args []) constant_table
   901     val args' = map (translate_term ctxt constant_table') all_args
   902     val _ = tracing "Running prolog program..."
   903     val system_config = System_Config.get (Context.Proof ctxt)
   904     val tss = run (#timeout system_config, #prolog_system system_config)
   905       p (translate_const constant_table' name, args') output_names soln
   906     val _ = tracing "Restoring terms..."
   907     val empty = Const("Orderings.bot_class.bot", fastype_of t_compr)
   908     fun mk_insert x S =
   909       Const (@{const_name "Set.insert"}, fastype_of x --> fastype_of S --> fastype_of S) $ x $ S 
   910     fun mk_set_compr in_insert [] xs =
   911        rev ((Free ("...", fastype_of t_compr)) ::
   912         (if null in_insert then xs else (fold mk_insert in_insert empty) :: xs))
   913       | mk_set_compr in_insert (t :: ts) xs =
   914         let
   915           val frees = Term.add_frees t []
   916         in
   917           if null frees then
   918             mk_set_compr (t :: in_insert) ts xs
   919           else
   920             let
   921               val uu as (uuN, uuT) = singleton (Variable.variant_frees ctxt' [t]) ("uu", fastype_of t)
   922               val set_compr =
   923                 HOLogic.mk_Collect (uuN, uuT, fold (fn (s, T) => fn t => HOLogic.mk_exists (s, T, t))
   924                   frees (HOLogic.mk_conj (HOLogic.mk_eq (Free uu, t), @{term "True"})))
   925             in
   926               mk_set_compr [] ts
   927                 (set_compr :: (if null in_insert then xs else (fold mk_insert in_insert empty) :: xs))  
   928             end
   929         end
   930   in
   931       foldl1 (HOLogic.mk_binop @{const_name sup}) (mk_set_compr []
   932         (map (fn ts => HOLogic.mk_tuple (map (restore_term ctxt' constant_table) (ts ~~ Ts))) tss) [])
   933   end
   934 
   935 fun values_cmd print_modes soln raw_t state =
   936   let
   937     val ctxt = Toplevel.context_of state
   938     val t = Syntax.read_term ctxt raw_t
   939     val t' = values ctxt soln t
   940     val ty' = Term.type_of t'
   941     val ctxt' = Variable.auto_fixes t' ctxt
   942     val _ = tracing "Printing terms..."
   943     val p = Print_Mode.with_modes print_modes (fn () =>
   944       Pretty.block [Pretty.quote (Syntax.pretty_term ctxt' t'), Pretty.fbrk,
   945         Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt' ty')]) ();
   946   in Pretty.writeln p end;
   947 
   948 
   949 (* renewing the values command for Prolog queries *)
   950 
   951 val opt_print_modes =
   952   Scan.optional (Parse.$$$ "(" |-- Parse.!!! (Scan.repeat1 Parse.xname --| Parse.$$$ ")")) [];
   953 
   954 val _ = Outer_Syntax.improper_command "values" "enumerate and print comprehensions" Keyword.diag
   955   (opt_print_modes -- Scan.optional (Parse.nat >> SOME) NONE -- Parse.term
   956    >> (fn ((print_modes, soln), t) => Toplevel.keep
   957         (values_cmd print_modes soln t))); (*FIXME does not preserve the previous functionality*)
   958 
   959 (* quickcheck generator *)
   960 
   961 (* FIXME: large copy of Predicate_Compile_Quickcheck - refactor out commons *)
   962 
   963 fun strip_imp_prems (Const(@{const_name HOL.implies}, _) $ A $ B) = A :: strip_imp_prems B
   964   | strip_imp_prems _ = [];
   965 
   966 fun strip_imp_concl (Const(@{const_name HOL.implies}, _) $ A $ B) = strip_imp_concl B
   967   | strip_imp_concl A = A : term;
   968 
   969 fun strip_horn A = (strip_imp_prems A, strip_imp_concl A);
   970 
   971 fun quickcheck ctxt t size =
   972   let
   973     val options = code_options_of (ProofContext.theory_of ctxt)
   974     val thy = Theory.copy (ProofContext.theory_of ctxt)
   975     val (vs, t') = strip_abs t
   976     val vs' = Variable.variant_frees ctxt [] vs
   977     val Ts = map snd vs'
   978     val t'' = subst_bounds (map Free (rev vs'), t')
   979     val (prems, concl) = strip_horn t''
   980     val constname = "quickcheck"
   981     val full_constname = Sign.full_bname thy constname
   982     val constT = Ts ---> @{typ bool}
   983     val thy1 = Sign.add_consts_i [(Binding.name constname, constT, NoSyn)] thy
   984     val const = Const (full_constname, constT)
   985     val t = Logic.list_implies
   986       (map HOLogic.mk_Trueprop (prems @ [HOLogic.mk_not concl]),
   987        HOLogic.mk_Trueprop (list_comb (Const (full_constname, constT), map Free vs')))
   988     val tac = fn _ => Skip_Proof.cheat_tac thy1
   989     val intro = Goal.prove (ProofContext.init_global thy1) (map fst vs') [] t tac
   990     val thy2 = Context.theory_map (Predicate_Compile_Alternative_Defs.add_thm intro) thy1
   991     val thy3 = Predicate_Compile.preprocess preprocess_options const thy2
   992     val ctxt' = ProofContext.init_global thy3
   993     val _ = tracing "Generating prolog program..."
   994     val (p, constant_table) = generate (NONE, true) ctxt' full_constname
   995       |> add_ground_predicates ctxt' (#limited_types options)
   996       |> add_limited_predicates (#limited_predicates options)
   997       |> apfst (fold replace (#replacing options))
   998       |> apfst (reorder_manually (#manual_reorder options))
   999     val _ = tracing "Running prolog program..."
  1000     val system_config = System_Config.get (Context.Proof ctxt)
  1001     val tss = run (#timeout system_config, #prolog_system system_config)
  1002       p (translate_const constant_table full_constname, map (Var o fst) vs') (map fst vs') (SOME 1)
  1003     val _ = tracing "Restoring terms..."
  1004     val res =
  1005       case tss of
  1006         [ts] => SOME (map (restore_term ctxt' constant_table) (ts ~~ Ts))
  1007       | _ => NONE
  1008     val empty_report = ([], false)
  1009   in
  1010     (res, empty_report)
  1011   end; 
  1012 
  1013 end;