src/HOL/Tools/Predicate_Compile/code_prolog.ML
author bulwahn
Thu Aug 26 13:49:12 2010 +0200 (2010-08-26)
changeset 38789 d171840881fd
parent 38735 cb9031a9dccf
child 38790 499135eb21ec
permissions -rw-r--r--
added generation of predicates for size-limited enumeration of values
bulwahn@38073
     1
(*  Title:      HOL/Tools/Predicate_Compile/code_prolog.ML
bulwahn@38073
     2
    Author:     Lukas Bulwahn, TU Muenchen
bulwahn@38073
     3
bulwahn@38073
     4
Prototype of an code generator for logic programming languages (a.k.a. Prolog)
bulwahn@38073
     5
*)
bulwahn@38073
     6
bulwahn@38073
     7
signature CODE_PROLOG =
bulwahn@38073
     8
sig
bulwahn@38789
     9
  type code_options = {ensure_groundness : bool, limited_types : (typ * int) list}
bulwahn@38727
    10
  val options : code_options ref
bulwahn@38727
    11
bulwahn@38113
    12
  datatype arith_op = Plus | Minus
bulwahn@38112
    13
  datatype prol_term = Var of string | Cons of string | AppF of string * prol_term list
bulwahn@38113
    14
    | Number of int | ArithOp of arith_op * prol_term list;
bulwahn@38113
    15
  datatype prem = Conj of prem list
bulwahn@38113
    16
    | Rel of string * prol_term list | NotRel of string * prol_term list
bulwahn@38113
    17
    | Eq of prol_term * prol_term | NotEq of prol_term * prol_term
bulwahn@38727
    18
    | ArithEq of prol_term * prol_term | NotArithEq of prol_term * prol_term
bulwahn@38727
    19
    | Ground of string * typ;
bulwahn@38727
    20
bulwahn@38079
    21
  type clause = ((string * prol_term list) * prem);
bulwahn@38073
    22
  type logic_program = clause list;
bulwahn@38079
    23
  type constant_table = (string * string) list
bulwahn@38727
    24
    
bulwahn@38731
    25
  val generate : code_options -> Proof.context -> string -> (logic_program * constant_table)
bulwahn@38079
    26
  val write_program : logic_program -> string
bulwahn@38079
    27
  val run : logic_program -> string -> string list -> int option -> prol_term list list
bulwahn@38073
    28
bulwahn@38733
    29
  val quickcheck : Proof.context -> bool -> term -> int -> term list option * (bool list * bool)
bulwahn@38733
    30
bulwahn@38079
    31
  val trace : bool Unsynchronized.ref
bulwahn@38073
    32
end;
bulwahn@38073
    33
bulwahn@38073
    34
structure Code_Prolog : CODE_PROLOG =
bulwahn@38073
    35
struct
bulwahn@38073
    36
bulwahn@38079
    37
(* diagnostic tracing *)
bulwahn@38079
    38
bulwahn@38079
    39
val trace = Unsynchronized.ref false
bulwahn@38079
    40
bulwahn@38079
    41
fun tracing s = if !trace then Output.tracing s else () 
bulwahn@38727
    42
bulwahn@38727
    43
(* code generation options *)
bulwahn@38727
    44
bulwahn@38789
    45
type code_options = {ensure_groundness : bool, limited_types : (typ * int) list}
bulwahn@38727
    46
bulwahn@38789
    47
val options = Unsynchronized.ref {ensure_groundness = false, limited_types = []};
bulwahn@38727
    48
bulwahn@38073
    49
(* general string functions *)
bulwahn@38073
    50
bulwahn@38073
    51
val first_upper = implode o nth_map 0 Symbol.to_ascii_upper o explode;
bulwahn@38073
    52
val first_lower = implode o nth_map 0 Symbol.to_ascii_lower o explode;
bulwahn@38073
    53
bulwahn@38073
    54
(* internal program representation *)
bulwahn@38073
    55
bulwahn@38113
    56
datatype arith_op = Plus | Minus
bulwahn@38113
    57
bulwahn@38112
    58
datatype prol_term = Var of string | Cons of string | AppF of string * prol_term list
bulwahn@38113
    59
  | Number of int | ArithOp of arith_op * prol_term list;
bulwahn@38113
    60
bulwahn@38735
    61
fun dest_Var (Var v) = v
bulwahn@38735
    62
bulwahn@38735
    63
fun add_vars (Var v) = insert (op =) v
bulwahn@38735
    64
  | add_vars (ArithOp (_, ts)) = fold add_vars ts
bulwahn@38735
    65
  | add_vars (AppF (_, ts)) = fold add_vars ts
bulwahn@38735
    66
  | add_vars _ = I
bulwahn@38735
    67
bulwahn@38735
    68
fun map_vars f (Var v) = Var (f v)
bulwahn@38735
    69
  | map_vars f (ArithOp (opr, ts)) = ArithOp (opr, map (map_vars f) ts)
bulwahn@38735
    70
  | map_vars f (AppF (fs, ts)) = AppF (fs, map (map_vars f) ts)
bulwahn@38735
    71
  | map_vars f t = t
bulwahn@38735
    72
  
bulwahn@38728
    73
fun maybe_AppF (c, []) = Cons c
bulwahn@38728
    74
  | maybe_AppF (c, xs) = AppF (c, xs)
bulwahn@38728
    75
bulwahn@38113
    76
fun is_Var (Var _) = true
bulwahn@38113
    77
  | is_Var _ = false
bulwahn@38113
    78
bulwahn@38113
    79
fun is_arith_term (Var _) = true
bulwahn@38113
    80
  | is_arith_term (Number _) = true
bulwahn@38113
    81
  | is_arith_term (ArithOp (_, operands)) = forall is_arith_term operands
bulwahn@38113
    82
  | is_arith_term _ = false
bulwahn@38073
    83
bulwahn@38081
    84
fun string_of_prol_term (Var s) = "Var " ^ s
bulwahn@38075
    85
  | string_of_prol_term (Cons s) = "Cons " ^ s
bulwahn@38075
    86
  | string_of_prol_term (AppF (f, args)) = f ^ "(" ^ commas (map string_of_prol_term args) ^ ")" 
bulwahn@38112
    87
  | string_of_prol_term (Number n) = "Number " ^ string_of_int n
bulwahn@38075
    88
bulwahn@38113
    89
datatype prem = Conj of prem list
bulwahn@38113
    90
  | Rel of string * prol_term list | NotRel of string * prol_term list
bulwahn@38113
    91
  | Eq of prol_term * prol_term | NotEq of prol_term * prol_term
bulwahn@38727
    92
  | ArithEq of prol_term * prol_term | NotArithEq of prol_term * prol_term
bulwahn@38727
    93
  | Ground of string * typ;
bulwahn@38735
    94
bulwahn@38073
    95
fun dest_Rel (Rel (c, ts)) = (c, ts)
bulwahn@38735
    96
bulwahn@38735
    97
fun map_term_prem f (Conj prems) = Conj (map (map_term_prem f) prems)
bulwahn@38735
    98
  | map_term_prem f (Rel (r, ts)) = Rel (r, map f ts)
bulwahn@38735
    99
  | map_term_prem f (NotRel (r, ts)) = NotRel (r, map f ts)
bulwahn@38735
   100
  | map_term_prem f (Eq (l, r)) = Eq (f l, f r)
bulwahn@38735
   101
  | map_term_prem f (NotEq (l, r)) = NotEq (f l, f r)
bulwahn@38735
   102
  | map_term_prem f (ArithEq (l, r)) = ArithEq (f l, f r)
bulwahn@38735
   103
  | map_term_prem f (NotArithEq (l, r)) = NotArithEq (f l, f r)
bulwahn@38735
   104
  | map_term_prem f (Ground (v, T)) = Ground (dest_Var (f (Var v)), T)
bulwahn@38735
   105
bulwahn@38735
   106
fun fold_prem_terms f (Conj prems) = fold (fold_prem_terms f) prems
bulwahn@38735
   107
  | fold_prem_terms f (Rel (_, ts)) = fold f ts
bulwahn@38735
   108
  | fold_prem_terms f (NotRel (_, ts)) = fold f ts
bulwahn@38735
   109
  | fold_prem_terms f (Eq (l, r)) = f l #> f r
bulwahn@38735
   110
  | fold_prem_terms f (NotEq (l, r)) = f l #> f r
bulwahn@38735
   111
  | fold_prem_terms f (ArithEq (l, r)) = f l #> f r
bulwahn@38735
   112
  | fold_prem_terms f (NotArithEq (l, r)) = f l #> f r
bulwahn@38735
   113
  | fold_prem_terms f (Ground (v, T)) = f (Var v)
bulwahn@38735
   114
  
bulwahn@38079
   115
type clause = ((string * prol_term list) * prem);
bulwahn@38073
   116
bulwahn@38073
   117
type logic_program = clause list;
bulwahn@38073
   118
bulwahn@38073
   119
(* translation from introduction rules to internal representation *)
bulwahn@38073
   120
bulwahn@38079
   121
(** constant table **)
bulwahn@38079
   122
bulwahn@38079
   123
type constant_table = (string * string) list
bulwahn@38079
   124
bulwahn@38073
   125
(* assuming no clashing *)
bulwahn@38079
   126
fun mk_constant_table consts =
bulwahn@38079
   127
  AList.make (first_lower o Long_Name.base_name) consts
bulwahn@38079
   128
bulwahn@38079
   129
fun declare_consts consts constant_table =
bulwahn@38079
   130
  fold (fn c => AList.update (op =) (c, first_lower (Long_Name.base_name c))) consts constant_table
bulwahn@38079
   131
  
bulwahn@38079
   132
fun translate_const constant_table c =
bulwahn@38079
   133
  case AList.lookup (op =) constant_table c of
bulwahn@38079
   134
    SOME c' => c'
bulwahn@38079
   135
  | NONE => error ("No such constant: " ^ c)
bulwahn@38073
   136
bulwahn@38079
   137
fun inv_lookup _ [] _ = NONE
bulwahn@38079
   138
  | inv_lookup eq ((key, value)::xs) value' =
bulwahn@38079
   139
      if eq (value', value) then SOME key
bulwahn@38079
   140
      else inv_lookup eq xs value';
bulwahn@38079
   141
bulwahn@38079
   142
fun restore_const constant_table c =
bulwahn@38079
   143
  case inv_lookup (op =) constant_table c of
bulwahn@38079
   144
    SOME c' => c'
bulwahn@38079
   145
  | NONE => error ("No constant corresponding to "  ^ c)
bulwahn@38727
   146
bulwahn@38079
   147
(** translation of terms, literals, premises, and clauses **)
bulwahn@38079
   148
bulwahn@38113
   149
fun translate_arith_const @{const_name "Groups.plus_class.plus"} = SOME Plus
bulwahn@38113
   150
  | translate_arith_const @{const_name "Groups.minus_class.minus"} = SOME Minus
bulwahn@38113
   151
  | translate_arith_const _ = NONE
bulwahn@38113
   152
bulwahn@38734
   153
fun mk_nat_term constant_table n =
bulwahn@38734
   154
  let
bulwahn@38734
   155
    val zero = translate_const constant_table @{const_name "Groups.zero_class.zero"}
bulwahn@38734
   156
    val Suc = translate_const constant_table @{const_name "Suc"}
bulwahn@38734
   157
  in funpow n (fn t => AppF (Suc, [t])) (Cons zero) end
bulwahn@38734
   158
bulwahn@38079
   159
fun translate_term ctxt constant_table t =
bulwahn@38112
   160
  case try HOLogic.dest_number t of
bulwahn@38112
   161
    SOME (@{typ "int"}, n) => Number n
bulwahn@38734
   162
  | SOME (@{typ "nat"}, n) => mk_nat_term constant_table n
bulwahn@38112
   163
  | NONE =>
bulwahn@38112
   164
      (case strip_comb t of
bulwahn@38112
   165
        (Free (v, T), []) => Var v 
bulwahn@38112
   166
      | (Const (c, _), []) => Cons (translate_const constant_table c)
bulwahn@38112
   167
      | (Const (c, _), args) =>
bulwahn@38113
   168
        (case translate_arith_const c of
bulwahn@38113
   169
          SOME aop => ArithOp (aop, map (translate_term ctxt constant_table) args)
bulwahn@38113
   170
        | NONE =>                                                             
bulwahn@38113
   171
            AppF (translate_const constant_table c, map (translate_term ctxt constant_table) args))
bulwahn@38112
   172
      | _ => error ("illegal term for translation: " ^ Syntax.string_of_term ctxt t))
bulwahn@38073
   173
bulwahn@38079
   174
fun translate_literal ctxt constant_table t =
bulwahn@38073
   175
  case strip_comb t of
bulwahn@38079
   176
    (Const (@{const_name "op ="}, _), [l, r]) =>
bulwahn@38113
   177
      let
bulwahn@38113
   178
        val l' = translate_term ctxt constant_table l
bulwahn@38113
   179
        val r' = translate_term ctxt constant_table r
bulwahn@38113
   180
      in
bulwahn@38728
   181
        (if is_Var l' andalso is_arith_term r' andalso not (is_Var r') then ArithEq else Eq) (l', r')
bulwahn@38113
   182
      end
bulwahn@38079
   183
  | (Const (c, _), args) =>
bulwahn@38079
   184
      Rel (translate_const constant_table c, map (translate_term ctxt constant_table) args)
bulwahn@38073
   185
  | _ => error ("illegal literal for translation: " ^ Syntax.string_of_term ctxt t)
bulwahn@38073
   186
bulwahn@38073
   187
fun NegRel_of (Rel lit) = NotRel lit
bulwahn@38073
   188
  | NegRel_of (Eq eq) = NotEq eq
bulwahn@38113
   189
  | NegRel_of (ArithEq eq) = NotArithEq eq
bulwahn@38113
   190
bulwahn@38727
   191
fun mk_groundness_prems t = map Ground (Term.add_frees t [])
bulwahn@38727
   192
  
bulwahn@38727
   193
fun translate_prem options ctxt constant_table t =  
bulwahn@38073
   194
    case try HOLogic.dest_not t of
bulwahn@38727
   195
      SOME t =>
bulwahn@38727
   196
        if #ensure_groundness options then
bulwahn@38727
   197
          Conj (mk_groundness_prems t @ [NegRel_of (translate_literal ctxt constant_table t)])
bulwahn@38727
   198
        else
bulwahn@38727
   199
          NegRel_of (translate_literal ctxt constant_table t)
bulwahn@38079
   200
    | NONE => translate_literal ctxt constant_table t
bulwahn@38114
   201
    
bulwahn@38114
   202
fun imp_prems_conv cv ct =
bulwahn@38114
   203
  case Thm.term_of ct of
bulwahn@38114
   204
    Const ("==>", _) $ _ $ _ => Conv.combination_conv (Conv.arg_conv cv) (imp_prems_conv cv) ct
bulwahn@38114
   205
  | _ => Conv.all_conv ct
bulwahn@38114
   206
bulwahn@38114
   207
fun Trueprop_conv cv ct =
bulwahn@38114
   208
  case Thm.term_of ct of
haftmann@38558
   209
    Const (@{const_name Trueprop}, _) $ _ => Conv.arg_conv cv ct  
bulwahn@38114
   210
  | _ => raise Fail "Trueprop_conv"
bulwahn@38114
   211
bulwahn@38114
   212
fun preprocess_intro thy rule =
bulwahn@38114
   213
  Conv.fconv_rule
bulwahn@38114
   214
    (imp_prems_conv
bulwahn@38114
   215
      (Trueprop_conv (Conv.try_conv (Conv.rewr_conv @{thm Predicate.eq_is_eq}))))
bulwahn@38114
   216
    (Thm.transfer thy rule)
bulwahn@38114
   217
bulwahn@38727
   218
fun translate_intros options ctxt gr const constant_table =
bulwahn@38073
   219
  let
bulwahn@38114
   220
    val intros = map (preprocess_intro (ProofContext.theory_of ctxt)) (Graph.get_node gr const)
bulwahn@38073
   221
    val (intros', ctxt') = Variable.import_terms true (map prop_of intros) ctxt
bulwahn@38079
   222
    val constant_table' = declare_consts (fold Term.add_const_names intros' []) constant_table
bulwahn@38734
   223
      |> declare_consts [@{const_name "Groups.zero_class.zero"}, @{const_name "Suc"}]
bulwahn@38073
   224
    fun translate_intro intro =
bulwahn@38073
   225
      let
bulwahn@38073
   226
        val head = HOLogic.dest_Trueprop (Logic.strip_imp_concl intro)
bulwahn@38727
   227
        val prems = map HOLogic.dest_Trueprop (Logic.strip_imp_prems intro)
bulwahn@38727
   228
        val prems' = Conj (map (translate_prem options ctxt' constant_table') prems)
bulwahn@38079
   229
        val clause = (dest_Rel (translate_literal ctxt' constant_table' head), prems')
bulwahn@38073
   230
      in clause end
bulwahn@38079
   231
  in (map translate_intro intros', constant_table') end
bulwahn@38073
   232
bulwahn@38731
   233
val preprocess_options = Predicate_Compile_Aux.Options {
bulwahn@38731
   234
  expected_modes = NONE,
bulwahn@38731
   235
  proposed_modes = NONE,
bulwahn@38731
   236
  proposed_names = [],
bulwahn@38731
   237
  show_steps = false,
bulwahn@38731
   238
  show_intermediate_results = false,
bulwahn@38731
   239
  show_proof_trace = false,
bulwahn@38731
   240
  show_modes = false,
bulwahn@38731
   241
  show_mode_inference = false,
bulwahn@38731
   242
  show_compilation = false,
bulwahn@38731
   243
  show_caught_failures = false,
bulwahn@38731
   244
  skip_proof = true,
bulwahn@38731
   245
  no_topmost_reordering = false,
bulwahn@38731
   246
  function_flattening = true,
bulwahn@38731
   247
  specialise = false,
bulwahn@38731
   248
  fail_safe_function_flattening = false,
bulwahn@38731
   249
  no_higher_order_predicate = [],
bulwahn@38731
   250
  inductify = false,
bulwahn@38731
   251
  detect_switches = true,
bulwahn@38731
   252
  compilation = Predicate_Compile_Aux.Pred
bulwahn@38731
   253
}
bulwahn@38731
   254
bulwahn@38731
   255
fun depending_preds_of (key, intros) =
bulwahn@38731
   256
  fold Term.add_const_names (map Thm.prop_of intros) []
bulwahn@38731
   257
bulwahn@38731
   258
fun add_edges edges_of key G =
bulwahn@38731
   259
  let
bulwahn@38731
   260
    fun extend' key (G, visited) = 
bulwahn@38731
   261
      case try (Graph.get_node G) key of
bulwahn@38731
   262
          SOME v =>
bulwahn@38731
   263
            let
bulwahn@38731
   264
              val new_edges = filter (fn k => is_some (try (Graph.get_node G) k)) (edges_of (key, v))
bulwahn@38731
   265
              val (G', visited') = fold extend'
bulwahn@38731
   266
                (subtract (op =) (key :: visited) new_edges) (G, key :: visited)
bulwahn@38731
   267
            in
bulwahn@38731
   268
              (fold (Graph.add_edge o (pair key)) new_edges G', visited')
bulwahn@38731
   269
            end
bulwahn@38731
   270
        | NONE => (G, visited)
bulwahn@38731
   271
  in
bulwahn@38731
   272
    fst (extend' key (G, []))
bulwahn@38731
   273
  end
bulwahn@38731
   274
bulwahn@38727
   275
fun generate options ctxt const =
bulwahn@38073
   276
  let 
bulwahn@38731
   277
    fun strong_conn_of gr keys =
bulwahn@38073
   278
      Graph.strong_conn (Graph.subgraph (member (op =) (Graph.all_succs gr keys)) gr)
bulwahn@38732
   279
    val gr = Predicate_Compile_Core.intros_graph_of ctxt
bulwahn@38731
   280
    val gr' = add_edges depending_preds_of const gr
bulwahn@38731
   281
    val scc = strong_conn_of gr' [const]
bulwahn@38079
   282
    val constant_table = mk_constant_table (flat scc)
bulwahn@38073
   283
  in
bulwahn@38732
   284
    apfst flat (fold_map (translate_intros options ctxt gr) (flat scc) constant_table)
bulwahn@38073
   285
  end
bulwahn@38727
   286
  
bulwahn@38789
   287
(* implementation for fully enumerating predicates and
bulwahn@38789
   288
  for size-limited predicates for enumerating the values of a datatype upto a specific size *)
bulwahn@38073
   289
bulwahn@38727
   290
fun add_ground_typ (Conj prems) = fold add_ground_typ prems
bulwahn@38727
   291
  | add_ground_typ (Ground (_, T)) = insert (op =) T
bulwahn@38727
   292
  | add_ground_typ _ = I
bulwahn@38073
   293
bulwahn@38728
   294
fun mk_relname (Type (Tcon, Targs)) =
bulwahn@38728
   295
  first_lower (Long_Name.base_name Tcon) ^ space_implode "_" (map mk_relname Targs)
bulwahn@38728
   296
  | mk_relname _ = raise Fail "unexpected type"
bulwahn@38728
   297
bulwahn@38789
   298
fun mk_lim_relname T = "lim_" ^  mk_relname T
bulwahn@38789
   299
bulwahn@38728
   300
(* This is copied from "pat_completeness.ML" *)
bulwahn@38728
   301
fun inst_constrs_of thy (T as Type (name, _)) =
bulwahn@38728
   302
  map (fn (Cn,CT) =>
bulwahn@38728
   303
    Envir.subst_term_types (Sign.typ_match thy (body_type CT, T) Vartab.empty) (Const (Cn, CT)))
bulwahn@38728
   304
    (the (Datatype.get_constrs thy name))
bulwahn@38728
   305
  | inst_constrs_of thy T = raise TYPE ("inst_constrs_of", [T], [])
bulwahn@38789
   306
bulwahn@38789
   307
fun is_recursive_constr T (Const (constr_name, T')) = member (op =) (binder_types T') T
bulwahn@38728
   308
  
bulwahn@38789
   309
fun mk_ground_impl ctxt limited_types (T as Type (Tcon, Targs)) (seen, constant_table) =
bulwahn@38728
   310
  if member (op =) seen T then ([], (seen, constant_table))
bulwahn@38728
   311
  else
bulwahn@38728
   312
    let
bulwahn@38789
   313
      val (limited, size) = case AList.lookup (op =) limited_types T of
bulwahn@38789
   314
        SOME s => (true, s)
bulwahn@38789
   315
      | NONE => (false, 0)      
bulwahn@38789
   316
      val rel_name = (if limited then mk_lim_relname else mk_relname) T
bulwahn@38789
   317
      fun mk_impl (Const (constr_name, cT), recursive) (seen, constant_table) =
bulwahn@38727
   318
        let
bulwahn@38727
   319
          val constant_table' = declare_consts [constr_name] constant_table
bulwahn@38789
   320
          val Ts = binder_types cT
bulwahn@38728
   321
          val (rec_clauses, (seen', constant_table'')) =
bulwahn@38789
   322
            fold_map (mk_ground_impl ctxt limited_types) Ts (seen, constant_table')
bulwahn@38789
   323
          val vars = map (fn i => Var ("x" ^ string_of_int i)) (1 upto (length Ts))
bulwahn@38789
   324
          val lim_var =
bulwahn@38789
   325
            if limited then
bulwahn@38789
   326
              if recursive then [AppF ("suc", [Var "Lim"])]              
bulwahn@38789
   327
              else [Var "Lim"]
bulwahn@38789
   328
            else [] 
bulwahn@38789
   329
          fun mk_prem v T' =
bulwahn@38789
   330
            if limited andalso T' = T then Rel (mk_lim_relname T', [Var "Lim", v])
bulwahn@38789
   331
            else Rel (mk_relname T', [v])
bulwahn@38728
   332
          val clause =
bulwahn@38789
   333
            ((rel_name, lim_var @ [maybe_AppF (translate_const constant_table'' constr_name, vars)]),
bulwahn@38789
   334
             Conj (map2 mk_prem vars Ts))
bulwahn@38727
   335
        in
bulwahn@38728
   336
          (clause :: flat rec_clauses, (seen', constant_table''))
bulwahn@38727
   337
        end
bulwahn@38728
   338
      val constrs = inst_constrs_of (ProofContext.theory_of ctxt) T
bulwahn@38789
   339
      val constrs' = (constrs ~~ map (is_recursive_constr T) constrs)
bulwahn@38789
   340
        |> (fn cs => filter_out snd cs @ filter snd cs)
bulwahn@38789
   341
      val (clauses, constant_table') =
bulwahn@38789
   342
        apfst flat (fold_map mk_impl constrs' (T :: seen, constant_table))
bulwahn@38789
   343
      val size_term = funpow size (fn t => AppF ("suc", [t])) (Cons "zero")
bulwahn@38789
   344
    in
bulwahn@38789
   345
      ((if limited then
bulwahn@38789
   346
        cons ((mk_relname T, [Var "x"]), Rel (mk_lim_relname T, [size_term, Var "x"]))
bulwahn@38789
   347
      else I) clauses, constant_table')
bulwahn@38789
   348
    end
bulwahn@38789
   349
 | mk_ground_impl ctxt _ T (seen, constant_table) =
bulwahn@38728
   350
   raise Fail ("unexpected type :" ^ Syntax.string_of_typ ctxt T)
bulwahn@38728
   351
bulwahn@38727
   352
fun replace_ground (Conj prems) = Conj (map replace_ground prems)
bulwahn@38728
   353
  | replace_ground (Ground (x, T)) =
bulwahn@38728
   354
    Rel (mk_relname T, [Var x])  
bulwahn@38727
   355
  | replace_ground p = p
bulwahn@38727
   356
  
bulwahn@38789
   357
fun add_ground_predicates ctxt limited_types (p, constant_table) =
bulwahn@38727
   358
  let
bulwahn@38727
   359
    val ground_typs = fold (add_ground_typ o snd) p []
bulwahn@38789
   360
    val (grs, (_, constant_table')) = fold_map (mk_ground_impl ctxt limited_types) ground_typs ([], constant_table)
bulwahn@38727
   361
    val p' = map (apsnd replace_ground) p
bulwahn@38073
   362
  in
bulwahn@38727
   363
    ((flat grs) @ p', constant_table')
bulwahn@38073
   364
  end
bulwahn@38789
   365
bulwahn@38789
   366
  
bulwahn@38735
   367
(* rename variables to prolog-friendly names *)
bulwahn@38735
   368
bulwahn@38735
   369
fun rename_vars_term renaming = map_vars (fn v => the (AList.lookup (op =) renaming v))
bulwahn@38735
   370
bulwahn@38735
   371
fun rename_vars_prem renaming = map_term_prem (rename_vars_term renaming)
bulwahn@38735
   372
bulwahn@38735
   373
fun dest_Char (Symbol.Char c) = c
bulwahn@38735
   374
bulwahn@38735
   375
fun is_prolog_conform v =
bulwahn@38735
   376
  forall (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s) (Symbol.explode v)
bulwahn@38735
   377
bulwahn@38735
   378
fun mk_conform avoid v =
bulwahn@38735
   379
  let 
bulwahn@38735
   380
    val v' = space_implode "" (map (dest_Char o Symbol.decode)
bulwahn@38735
   381
      (filter (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s)
bulwahn@38735
   382
        (Symbol.explode v)))
bulwahn@38735
   383
    val v' = if v' = "" then "var" else v'
bulwahn@38735
   384
  in Name.variant avoid (first_upper v') end
bulwahn@38735
   385
  
bulwahn@38735
   386
fun mk_renaming v renaming =
bulwahn@38735
   387
  (v, mk_conform (map snd renaming) v) :: renaming
bulwahn@38735
   388
bulwahn@38735
   389
fun rename_vars_clause ((rel, args), prem) =
bulwahn@38735
   390
  let
bulwahn@38735
   391
    val vars = fold_prem_terms add_vars prem (fold add_vars args [])
bulwahn@38735
   392
    val renaming = fold mk_renaming vars []
bulwahn@38735
   393
  in ((rel, map (rename_vars_term renaming) args), rename_vars_prem renaming prem) end
bulwahn@38735
   394
  
bulwahn@38735
   395
val rename_vars_program = map rename_vars_clause
bulwahn@38735
   396
  
bulwahn@38073
   397
(* code printer *)
bulwahn@38073
   398
bulwahn@38113
   399
fun write_arith_op Plus = "+"
bulwahn@38113
   400
  | write_arith_op Minus = "-"
bulwahn@38113
   401
bulwahn@38735
   402
fun write_term (Var v) = v
bulwahn@38079
   403
  | write_term (Cons c) = c
bulwahn@38113
   404
  | write_term (AppF (f, args)) = f ^ "(" ^ space_implode ", " (map write_term args) ^ ")"
bulwahn@38113
   405
  | write_term (ArithOp (oper, [a1, a2])) = write_term a1 ^ " " ^ write_arith_op oper ^ " " ^ write_term a2
bulwahn@38112
   406
  | write_term (Number n) = string_of_int n
bulwahn@38073
   407
bulwahn@38073
   408
fun write_rel (pred, args) =
bulwahn@38073
   409
  pred ^ "(" ^ space_implode ", " (map write_term args) ^ ")" 
bulwahn@38073
   410
bulwahn@38073
   411
fun write_prem (Conj prems) = space_implode ", " (map write_prem prems)
bulwahn@38073
   412
  | write_prem (Rel p) = write_rel p  
bulwahn@38073
   413
  | write_prem (NotRel p) = "not(" ^ write_rel p ^ ")"
bulwahn@38073
   414
  | write_prem (Eq (l, r)) = write_term l ^ " = " ^ write_term r
bulwahn@38073
   415
  | write_prem (NotEq (l, r)) = write_term l ^ " \\= " ^ write_term r
bulwahn@38113
   416
  | write_prem (ArithEq (l, r)) = write_term l ^ " is " ^ write_term r
bulwahn@38113
   417
  | write_prem (NotArithEq (l, r)) = write_term l ^ " =\\= " ^ write_term r
bulwahn@38073
   418
bulwahn@38073
   419
fun write_clause (head, prem) =
bulwahn@38073
   420
  write_rel head ^ (if prem = Conj [] then "." else " :- " ^ write_prem prem ^ ".")
bulwahn@38073
   421
bulwahn@38073
   422
fun write_program p =
bulwahn@38073
   423
  cat_lines (map write_clause p) 
bulwahn@38073
   424
bulwahn@38078
   425
(** query templates **)
bulwahn@38078
   426
bulwahn@38073
   427
fun query_first rel vnames =
bulwahn@38073
   428
  "eval :- once("  ^ rel ^ "(" ^ space_implode ", " vnames ^ ")),\n" ^
bulwahn@38082
   429
  "writef('" ^ space_implode ";" (map (fn v => v ^ " = %w") vnames) ^
bulwahn@38082
   430
  "\\n', [" ^ space_implode ", " vnames ^ "]).\n"
bulwahn@38077
   431
  
bulwahn@38077
   432
fun query_firstn n rel vnames =
bulwahn@38077
   433
  "eval :- findnsols(" ^ string_of_int n ^ ", (" ^ space_implode ", " vnames ^ "), " ^
bulwahn@38077
   434
    rel ^ "(" ^ space_implode ", " vnames ^ "), Sols), writelist(Sols).\n" ^
bulwahn@38077
   435
    "writelist([]).\n" ^
bulwahn@38077
   436
    "writelist([(" ^ space_implode ", " vnames ^ ")|T]) :- " ^
bulwahn@38079
   437
    "writef('" ^ space_implode ";" (map (fn v => v ^ " = %w") vnames) ^
bulwahn@38079
   438
    "\\n', [" ^ space_implode ", " vnames ^ "]), writelist(T).\n"
bulwahn@38077
   439
  
bulwahn@38073
   440
val prelude =
bulwahn@38073
   441
  "#!/usr/bin/swipl -q -t main -f\n\n" ^
bulwahn@38077
   442
  ":- use_module(library('dialect/ciao/aggregates')).\n" ^
bulwahn@38729
   443
  ":- style_check(-singleton).\n" ^
bulwahn@38729
   444
  ":- style_check(-discontiguous).\n" ^ 	
bulwahn@38729
   445
  ":- style_check(-atom).\n\n" ^
bulwahn@38073
   446
  "main :- catch(eval, E, (print_message(error, E), fail)), halt.\n" ^
bulwahn@38073
   447
  "main :- halt(1).\n"
bulwahn@38075
   448
bulwahn@38075
   449
(* parsing prolog solution *)
bulwahn@38115
   450
val scan_number =
bulwahn@38115
   451
  Scan.many1 Symbol.is_ascii_digit
bulwahn@38075
   452
bulwahn@38075
   453
val scan_atom =
bulwahn@38728
   454
  Scan.many1 (fn s => Symbol.is_ascii_lower s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38075
   455
bulwahn@38075
   456
val scan_var =
bulwahn@38078
   457
  Scan.many1
bulwahn@38078
   458
    (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38075
   459
bulwahn@38076
   460
val scan_ident =
bulwahn@38076
   461
  Scan.repeat (Scan.one
bulwahn@38076
   462
    (fn s => Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s))
bulwahn@38076
   463
bulwahn@38075
   464
fun dest_Char (Symbol.Char s) = s
bulwahn@38075
   465
bulwahn@38075
   466
val string_of = concat o map (dest_Char o Symbol.decode)
bulwahn@38075
   467
bulwahn@38076
   468
val is_atom_ident = forall Symbol.is_ascii_lower
bulwahn@38076
   469
bulwahn@38076
   470
val is_var_ident =
bulwahn@38076
   471
  forall (fn s => Symbol.is_ascii_upper s orelse Symbol.is_ascii_digit s orelse Symbol.is_ascii_quasi s)
bulwahn@38078
   472
bulwahn@38115
   473
fun int_of_symbol_list xs = fold (fn x => fn s => s * 10 + (ord x - ord "0")) xs 0
bulwahn@38115
   474
bulwahn@38078
   475
fun scan_terms xs = (((scan_term --| $$ ",") ::: scan_terms)
bulwahn@38078
   476
  || (scan_term >> single)) xs
bulwahn@38078
   477
and scan_term xs =
bulwahn@38115
   478
  ((scan_number >> (Number o int_of_symbol_list))
bulwahn@38115
   479
  || (scan_var >> (Var o string_of))
bulwahn@38078
   480
  || ((scan_atom -- ($$ "(" |-- scan_terms --| $$ ")"))
bulwahn@38079
   481
    >> (fn (f, ts) => AppF (string_of f, ts)))
bulwahn@38078
   482
  || (scan_atom >> (Cons o string_of))) xs
bulwahn@38079
   483
bulwahn@38075
   484
val parse_term = fst o Scan.finite Symbol.stopper
bulwahn@38077
   485
    (Scan.error (!! (fn _ => raise Fail "parsing prolog output failed")) scan_term)
bulwahn@38075
   486
  o explode
bulwahn@38075
   487
  
bulwahn@38079
   488
fun parse_solutions sol =
bulwahn@38075
   489
  let
bulwahn@38077
   490
    fun dest_eq s = case space_explode "=" s of
bulwahn@38075
   491
        (l :: r :: []) => parse_term (unprefix " " r)
bulwahn@38078
   492
      | _ => raise Fail "unexpected equation in prolog output"
bulwahn@38079
   493
    fun parse_solution s = map dest_eq (space_explode ";" s)
bulwahn@38075
   494
  in
bulwahn@38079
   495
    map parse_solution (fst (split_last (space_explode "\n" sol)))
bulwahn@38075
   496
  end 
bulwahn@38073
   497
  
bulwahn@38073
   498
(* calling external interpreter and getting results *)
bulwahn@38073
   499
bulwahn@38077
   500
fun run p query_rel vnames nsols =
bulwahn@38073
   501
  let
bulwahn@38073
   502
    val cmd = Path.named_root
bulwahn@38735
   503
    val query = case nsols of NONE => query_first | SOME n => query_firstn n
bulwahn@38735
   504
    val p' = rename_vars_program p
bulwahn@38735
   505
    val _ = tracing "Renaming variable names..."
bulwahn@38735
   506
    val renaming = fold mk_renaming vnames [] 
bulwahn@38735
   507
    val vnames' = map (fn v => the (AList.lookup (op =) renaming v)) vnames
bulwahn@38735
   508
    val prog = prelude ^ query query_rel vnames' ^ write_program p'
bulwahn@38079
   509
    val _ = tracing ("Generated prolog program:\n" ^ prog)
bulwahn@38073
   510
    val prolog_file = File.tmp_path (Path.basic "prolog_file")
bulwahn@38073
   511
    val _ = File.write prolog_file prog
bulwahn@38077
   512
    val (solution, _) = bash_output ("/usr/local/bin/swipl -f " ^ File.shell_path prolog_file)
bulwahn@38079
   513
    val _ = tracing ("Prolog returned solution(s):\n" ^ solution)
bulwahn@38079
   514
    val tss = parse_solutions solution
bulwahn@38073
   515
  in
bulwahn@38079
   516
    tss
bulwahn@38073
   517
  end
bulwahn@38073
   518
bulwahn@38075
   519
(* values command *)
bulwahn@38075
   520
bulwahn@38081
   521
fun restore_term ctxt constant_table (Var s, T) = Free (s, T)
bulwahn@38115
   522
  | restore_term ctxt constant_table (Number n, @{typ "int"}) = HOLogic.mk_number @{typ "int"} n
bulwahn@38115
   523
  | restore_term ctxt constant_table (Number n, _) = raise (Fail "unexpected type for number") 
bulwahn@38079
   524
  | restore_term ctxt constant_table (Cons s, T) = Const (restore_const constant_table s, T)
bulwahn@38079
   525
  | restore_term ctxt constant_table (AppF (f, args), T) =
bulwahn@38079
   526
    let
bulwahn@38079
   527
      val thy = ProofContext.theory_of ctxt
bulwahn@38079
   528
      val c = restore_const constant_table f
bulwahn@38079
   529
      val cT = Sign.the_const_type thy c
bulwahn@38079
   530
      val (argsT, resT) = strip_type cT
bulwahn@38079
   531
      val subst = Sign.typ_match thy (resT, T) Vartab.empty
bulwahn@38079
   532
      val argsT' = map (Envir.subst_type subst) argsT
bulwahn@38079
   533
    in
bulwahn@38079
   534
      list_comb (Const (c, Envir.subst_type subst cT),
bulwahn@38079
   535
        map (restore_term ctxt constant_table) (args ~~ argsT'))
bulwahn@38079
   536
    end
bulwahn@38079
   537
bulwahn@38075
   538
fun values ctxt soln t_compr =
bulwahn@38075
   539
  let
bulwahn@38727
   540
    val options = !options
bulwahn@38075
   541
    val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
bulwahn@38075
   542
      | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term ctxt t_compr);
bulwahn@38075
   543
    val (body, Ts, fp) = HOLogic.strip_psplits split;
bulwahn@38075
   544
    val output_names = Name.variant_list (Term.add_free_names body [])
bulwahn@38075
   545
      (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
bulwahn@38080
   546
    val output_frees = rev (map2 (curry Free) output_names Ts)
bulwahn@38075
   547
    val body = subst_bounds (output_frees, body)
bulwahn@38075
   548
    val (pred as Const (name, T), all_args) =
bulwahn@38075
   549
      case strip_comb body of
bulwahn@38075
   550
        (Const (name, T), all_args) => (Const (name, T), all_args)
bulwahn@38075
   551
      | (head, _) => error ("Not a constant: " ^ Syntax.string_of_term ctxt head)
bulwahn@38075
   552
    val vnames =
bulwahn@38075
   553
      case try (map (fst o dest_Free)) all_args of
bulwahn@38075
   554
        SOME vs => vs
bulwahn@38075
   555
      | NONE => error ("Not only free variables in " ^ commas (map (Syntax.string_of_term ctxt) all_args))
bulwahn@38732
   556
    val _ = tracing "Preprocessing specification..."
bulwahn@38732
   557
    val T = Sign.the_const_type (ProofContext.theory_of ctxt) name
bulwahn@38732
   558
    val t = Const (name, T)
bulwahn@38732
   559
    val ctxt' = ProofContext.theory (Context.copy_thy) ctxt
bulwahn@38732
   560
    val thy' = Predicate_Compile.preprocess preprocess_options t (ProofContext.theory_of ctxt')
bulwahn@38732
   561
    val ctxt'' = ProofContext.init_global thy'
bulwahn@38079
   562
    val _ = tracing "Generating prolog program..."
bulwahn@38732
   563
    val (p, constant_table) = generate options ctxt'' name
bulwahn@38789
   564
      |> (if #ensure_groundness options then
bulwahn@38789
   565
          add_ground_predicates ctxt'' (#limited_types options)
bulwahn@38789
   566
        else I)
bulwahn@38079
   567
    val _ = tracing "Running prolog program..."
bulwahn@38079
   568
    val tss = run p (translate_const constant_table name) (map first_upper vnames) soln
bulwahn@38079
   569
    val _ = tracing "Restoring terms..."
bulwahn@38115
   570
    val empty = Const("Orderings.bot_class.bot", fastype_of t_compr)
bulwahn@38115
   571
    fun mk_insert x S =
bulwahn@38115
   572
      Const (@{const_name "Set.insert"}, fastype_of x --> fastype_of S --> fastype_of S) $ x $ S 
bulwahn@38115
   573
    fun mk_set_compr in_insert [] xs =
bulwahn@38115
   574
       rev ((Free ("...", fastype_of t_compr)) ::
bulwahn@38115
   575
        (if null in_insert then xs else (fold mk_insert in_insert empty) :: xs))
bulwahn@38115
   576
      | mk_set_compr in_insert (t :: ts) xs =
bulwahn@38115
   577
        let
bulwahn@38115
   578
          val frees = Term.add_frees t []
bulwahn@38115
   579
        in
bulwahn@38115
   580
          if null frees then
bulwahn@38115
   581
            mk_set_compr (t :: in_insert) ts xs
bulwahn@38115
   582
          else
bulwahn@38115
   583
            let
bulwahn@38732
   584
              val uu as (uuN, uuT) = singleton (Variable.variant_frees ctxt'' [t]) ("uu", fastype_of t)
bulwahn@38115
   585
              val set_compr =
bulwahn@38115
   586
                HOLogic.mk_Collect (uuN, uuT, fold (fn (s, T) => fn t => HOLogic.mk_exists (s, T, t))
bulwahn@38115
   587
                  frees (HOLogic.mk_conj (HOLogic.mk_eq (Free uu, t), @{term "True"})))
bulwahn@38115
   588
            in
bulwahn@38729
   589
              mk_set_compr [] ts
bulwahn@38729
   590
                (set_compr :: (if null in_insert then xs else (fold mk_insert in_insert empty) :: xs))  
bulwahn@38115
   591
            end
bulwahn@38115
   592
        end
bulwahn@38075
   593
  in
bulwahn@38115
   594
      foldl1 (HOLogic.mk_binop @{const_name sup}) (mk_set_compr []
bulwahn@38732
   595
        (map (fn ts => HOLogic.mk_tuple (map (restore_term ctxt'' constant_table) (ts ~~ Ts))) tss) [])
bulwahn@38075
   596
  end
bulwahn@38075
   597
bulwahn@38075
   598
fun values_cmd print_modes soln raw_t state =
bulwahn@38075
   599
  let
bulwahn@38075
   600
    val ctxt = Toplevel.context_of state
bulwahn@38075
   601
    val t = Syntax.read_term ctxt raw_t
bulwahn@38075
   602
    val t' = values ctxt soln t
bulwahn@38075
   603
    val ty' = Term.type_of t'
bulwahn@38075
   604
    val ctxt' = Variable.auto_fixes t' ctxt
bulwahn@38115
   605
    val _ = tracing "Printing terms..."
bulwahn@38075
   606
    val p = Print_Mode.with_modes print_modes (fn () =>
bulwahn@38075
   607
      Pretty.block [Pretty.quote (Syntax.pretty_term ctxt' t'), Pretty.fbrk,
bulwahn@38075
   608
        Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt' ty')]) ();
bulwahn@38075
   609
  in Pretty.writeln p end;
bulwahn@38075
   610
bulwahn@38075
   611
bulwahn@38075
   612
(* renewing the values command for Prolog queries *)
bulwahn@38075
   613
bulwahn@38075
   614
val opt_print_modes =
bulwahn@38075
   615
  Scan.optional (Parse.$$$ "(" |-- Parse.!!! (Scan.repeat1 Parse.xname --| Parse.$$$ ")")) [];
bulwahn@38075
   616
bulwahn@38075
   617
val _ = Outer_Syntax.improper_command "values" "enumerate and print comprehensions" Keyword.diag
bulwahn@38077
   618
  (opt_print_modes -- Scan.optional (Parse.nat >> SOME) NONE -- Parse.term
bulwahn@38075
   619
   >> (fn ((print_modes, soln), t) => Toplevel.keep
haftmann@38504
   620
        (values_cmd print_modes soln t))); (*FIXME does not preserve the previous functionality*)
bulwahn@38075
   621
bulwahn@38733
   622
(* quickcheck generator *)
bulwahn@38733
   623
bulwahn@38733
   624
(* FIXME: large copy of Predicate_Compile_Quickcheck - refactor out commons *)
bulwahn@38733
   625
bulwahn@38733
   626
fun strip_imp_prems (Const(@{const_name "op -->"}, _) $ A $ B) = A :: strip_imp_prems B
bulwahn@38733
   627
  | strip_imp_prems _ = [];
bulwahn@38733
   628
bulwahn@38733
   629
fun strip_imp_concl (Const(@{const_name "op -->"}, _) $ A $ B) = strip_imp_concl B
bulwahn@38733
   630
  | strip_imp_concl A = A : term;
bulwahn@38733
   631
bulwahn@38733
   632
fun strip_horn A = (strip_imp_prems A, strip_imp_concl A);
bulwahn@38733
   633
bulwahn@38733
   634
fun quickcheck ctxt report t size =
bulwahn@38733
   635
  let
bulwahn@38733
   636
    val ctxt' = ProofContext.theory (Context.copy_thy) ctxt
bulwahn@38733
   637
    val thy = (ProofContext.theory_of ctxt')
bulwahn@38733
   638
    val (vs, t') = strip_abs t
bulwahn@38733
   639
    val vs' = Variable.variant_frees ctxt' [] vs
bulwahn@38733
   640
    val Ts = map snd vs'
bulwahn@38733
   641
    val t'' = subst_bounds (map Free (rev vs'), t')
bulwahn@38733
   642
    val (prems, concl) = strip_horn t''
bulwahn@38733
   643
    val constname = "quickcheck"
bulwahn@38733
   644
    val full_constname = Sign.full_bname thy constname
bulwahn@38733
   645
    val constT = Ts ---> @{typ bool}
bulwahn@38733
   646
    val thy1 = Sign.add_consts_i [(Binding.name constname, constT, NoSyn)] thy
bulwahn@38733
   647
    val const = Const (full_constname, constT)
bulwahn@38733
   648
    val t = Logic.list_implies
bulwahn@38733
   649
      (map HOLogic.mk_Trueprop (prems @ [HOLogic.mk_not concl]),
bulwahn@38733
   650
       HOLogic.mk_Trueprop (list_comb (Const (full_constname, constT), map Free vs')))
bulwahn@38733
   651
    val tac = fn _ => Skip_Proof.cheat_tac thy1
bulwahn@38733
   652
    val intro = Goal.prove (ProofContext.init_global thy1) (map fst vs') [] t tac
bulwahn@38733
   653
    val thy2 = Context.theory_map (Predicate_Compile_Alternative_Defs.add_thm intro) thy1
bulwahn@38733
   654
    val thy3 = Predicate_Compile.preprocess preprocess_options const thy2
bulwahn@38733
   655
    val ctxt'' = ProofContext.init_global thy3
bulwahn@38733
   656
    val _ = tracing "Generating prolog program..."
bulwahn@38789
   657
    val (p, constant_table) = generate {ensure_groundness = true, limited_types = []} ctxt'' full_constname
bulwahn@38789
   658
      |> add_ground_predicates ctxt'' (#limited_types (!options))
bulwahn@38733
   659
    val _ = tracing "Running prolog program..."
bulwahn@38735
   660
    val [ts] = run p (translate_const constant_table full_constname) (map fst vs')
bulwahn@38733
   661
      (SOME 1)
bulwahn@38733
   662
    val _ = tracing "Restoring terms..."
bulwahn@38733
   663
    val res = SOME (map (restore_term ctxt'' constant_table) (ts ~~ Ts))
bulwahn@38733
   664
    val empty_report = ([], false)
bulwahn@38733
   665
  in
bulwahn@38733
   666
    (res, empty_report)
bulwahn@38733
   667
  end; 
bulwahn@38732
   668
bulwahn@38073
   669
end;