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