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