src/HOL/Tools/Sledgehammer/sledgehammer_proof_reconstruct.ML
author blanchet
Tue Apr 27 11:44:01 2010 +0200 (2010-04-27)
changeset 36474 fe9b37503db3
parent 36422 69004340f53c
child 36475 05209b869a6b
permissions -rw-r--r--
honor "shrink_proof" Sledgehammer option
blanchet@35826
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_proof_reconstruct.ML
wenzelm@33310
     2
    Author:     Lawrence C Paulson and Claire Quigley, Cambridge University Computer Laboratory
blanchet@36392
     3
    Author:     Jasmin Blanchette, TU Muenchen
paulson@21978
     4
wenzelm@33310
     5
Transfer of proofs from external provers.
wenzelm@33310
     6
*)
wenzelm@33310
     7
blanchet@35826
     8
signature SLEDGEHAMMER_PROOF_RECONSTRUCT =
paulson@24425
     9
sig
blanchet@36281
    10
  type minimize_command = string list -> string
blanchet@36393
    11
  type name_pool = Sledgehammer_FOL_Clause.name_pool
blanchet@36281
    12
paulson@25492
    13
  val chained_hint: string
paulson@24425
    14
  val invert_const: string -> string
paulson@24425
    15
  val invert_type_const: string -> string
wenzelm@33243
    16
  val num_typargs: theory -> string -> int
paulson@24425
    17
  val make_tvar: string -> typ
paulson@24425
    18
  val strip_prefix: string -> string -> string option
blanchet@36063
    19
  val metis_line: int -> int -> string list -> string
blanchet@36223
    20
  val metis_proof_text:
blanchet@36287
    21
    minimize_command * string * string vector * thm * int
blanchet@36281
    22
    -> string * string list
blanchet@36223
    23
  val isar_proof_text:
blanchet@36402
    24
    name_pool option * bool * int * bool * Proof.context * int list list
blanchet@36287
    25
    -> minimize_command * string * string vector * thm * int
blanchet@36287
    26
    -> string * string list
blanchet@36223
    27
  val proof_text:
blanchet@36402
    28
    bool -> name_pool option * bool * int * bool * Proof.context * int list list
blanchet@36287
    29
    -> minimize_command * string * string vector * thm * int
blanchet@36287
    30
    -> string * string list
paulson@24425
    31
end;
paulson@21978
    32
blanchet@35826
    33
structure Sledgehammer_Proof_Reconstruct : SLEDGEHAMMER_PROOF_RECONSTRUCT =
paulson@21978
    34
struct
paulson@21978
    35
blanchet@35865
    36
open Sledgehammer_FOL_Clause
blanchet@35865
    37
open Sledgehammer_Fact_Preprocessor
paulson@21978
    38
blanchet@36281
    39
type minimize_command = string list -> string
blanchet@36281
    40
blanchet@36291
    41
fun is_ident_char c = Char.isAlphaNum c orelse c = #"_"
blanchet@36392
    42
fun is_head_digit s = Char.isDigit (String.sub (s, 0))
blanchet@36291
    43
blanchet@36402
    44
fun is_axiom_clause_number thm_names num = num <= Vector.length thm_names
blanchet@36291
    45
blanchet@36393
    46
fun ugly_name NONE s = s
blanchet@36393
    47
  | ugly_name (SOME the_pool) s =
blanchet@36393
    48
    case Symtab.lookup (snd the_pool) s of
blanchet@36393
    49
      SOME s' => s'
blanchet@36393
    50
    | NONE => s
blanchet@36393
    51
paulson@21978
    52
(**** PARSING OF TSTP FORMAT ****)
paulson@21978
    53
blanchet@36291
    54
(* Syntax trees, either term list or formulae *)
blanchet@36392
    55
datatype stree = SInt of int | SBranch of string * stree list;
paulson@21978
    56
blanchet@36392
    57
fun atom x = SBranch (x, [])
paulson@21978
    58
blanchet@36392
    59
fun scons (x, y) = SBranch ("cons", [x, y])
blanchet@36392
    60
val slist_of = List.foldl scons (atom "nil")
paulson@21978
    61
paulson@21978
    62
(*Strings enclosed in single quotes, e.g. filenames*)
blanchet@36392
    63
val parse_quoted = $$ "'" |-- Scan.repeat (~$$ "'") --| $$ "'" >> implode;
paulson@21978
    64
paulson@21978
    65
(*Integer constants, typically proof line numbers*)
blanchet@36392
    66
val parse_integer = Scan.many1 is_head_digit >> (the o Int.fromString o implode)
paulson@21978
    67
blanchet@36369
    68
(* needed for SPASS's output format *)
blanchet@36393
    69
fun repair_bool_literal "true" = "c_True"
blanchet@36393
    70
  | repair_bool_literal "false" = "c_False"
blanchet@36393
    71
fun repair_name pool "equal" = "c_equal"
blanchet@36393
    72
  | repair_name pool s = ugly_name pool s
blanchet@36392
    73
(* Generalized first-order terms, which include file names, numbers, etc. *)
blanchet@36393
    74
(* The "x" argument is not strictly necessary, but without it Poly/ML loops
blanchet@36393
    75
   forever at compile time. *)
blanchet@36393
    76
fun parse_term pool x =
blanchet@36392
    77
  (parse_quoted >> atom
blanchet@36392
    78
   || parse_integer >> SInt
blanchet@36393
    79
   || $$ "$" |-- Symbol.scan_id >> (atom o repair_bool_literal)
blanchet@36393
    80
   || (Symbol.scan_id >> repair_name pool)
blanchet@36393
    81
      -- Scan.optional ($$ "(" |-- parse_terms pool --| $$ ")") [] >> SBranch
blanchet@36393
    82
   || $$ "(" |-- parse_term pool --| $$ ")"
blanchet@36393
    83
   || $$ "[" |-- Scan.optional (parse_terms pool) [] --| $$ "]" >> slist_of) x
blanchet@36393
    84
and parse_terms pool x =
blanchet@36393
    85
  (parse_term pool ::: Scan.repeat ($$ "," |-- parse_term pool)) x
paulson@21978
    86
blanchet@36392
    87
fun negate_stree t = SBranch ("c_Not", [t])
blanchet@36392
    88
fun equate_strees t1 t2 = SBranch ("c_equal", [t1, t2]);
paulson@21978
    89
blanchet@36392
    90
(* Apply equal or not-equal to a term. *)
blanchet@36393
    91
fun repair_predicate_term (t, NONE) = t
blanchet@36393
    92
  | repair_predicate_term (t1, SOME (NONE, t2)) = equate_strees t1 t2
blanchet@36393
    93
  | repair_predicate_term (t1, SOME (SOME _, t2)) =
blanchet@36393
    94
    negate_stree (equate_strees t1 t2)
blanchet@36393
    95
fun parse_predicate_term pool =
blanchet@36393
    96
  parse_term pool -- Scan.option (Scan.option ($$ "!") --| $$ "="
blanchet@36393
    97
                                  -- parse_term pool)
blanchet@36393
    98
  >> repair_predicate_term
paulson@21978
    99
(*Literals can involve negation, = and !=.*)
blanchet@36393
   100
fun parse_literal pool x =
blanchet@36393
   101
  ($$ "~" |-- parse_literal pool >> negate_stree || parse_predicate_term pool) x
paulson@21978
   102
blanchet@36393
   103
fun parse_literals pool =
blanchet@36393
   104
  parse_literal pool ::: Scan.repeat ($$ "|" |-- parse_literal pool)
paulson@21978
   105
blanchet@36402
   106
(* Clause: a list of literals separated by the disjunction sign. *)
blanchet@36393
   107
fun parse_clause pool =
blanchet@36393
   108
  $$ "(" |-- parse_literals pool --| $$ ")" || Scan.single (parse_literal pool)
blanchet@36291
   109
blanchet@36392
   110
fun ints_of_stree (SInt n) = cons n
blanchet@36392
   111
  | ints_of_stree (SBranch (_, ts)) = fold ints_of_stree ts
blanchet@36392
   112
val parse_tstp_annotations =
blanchet@36393
   113
  Scan.optional ($$ "," |-- parse_term NONE
blanchet@36393
   114
                   --| Scan.option ($$ "," |-- parse_terms NONE)
blanchet@36291
   115
                 >> (fn source => ints_of_stree source [])) []
blanchet@36291
   116
blanchet@36291
   117
(* <cnf_annotated> ::= cnf(<name>, <formula_role>, <cnf_formula> <annotations>).
blanchet@36291
   118
   The <name> could be an identifier, but we assume integers. *)
blanchet@36392
   119
fun retuple_tstp_line ((name, ts), deps) = (name, ts, deps)
blanchet@36393
   120
fun parse_tstp_line pool =
blanchet@36392
   121
  (Scan.this_string "cnf" -- $$ "(") |-- parse_integer --| $$ ","
blanchet@36393
   122
   --| Symbol.scan_id --| $$ "," -- parse_clause pool -- parse_tstp_annotations
blanchet@36392
   123
   --| $$ ")" --| $$ "."
blanchet@36291
   124
  >> retuple_tstp_line
blanchet@36291
   125
blanchet@36291
   126
(**** PARSING OF SPASS OUTPUT ****)
blanchet@36291
   127
blanchet@36392
   128
(* SPASS returns clause references of the form "x.y". We ignore "y", whose role
blanchet@36392
   129
   is not clear anyway. *)
blanchet@36392
   130
val parse_dot_name = parse_integer --| $$ "." --| parse_integer
paulson@21978
   131
blanchet@36392
   132
val parse_spass_annotations =
blanchet@36392
   133
  Scan.optional ($$ ":" |-- Scan.repeat (parse_dot_name
blanchet@36392
   134
                                         --| Scan.option ($$ ","))) []
blanchet@36291
   135
blanchet@36392
   136
(* It is not clear why some literals are followed by sequences of stars. We
blanchet@36392
   137
   ignore them. *)
blanchet@36393
   138
fun parse_starred_predicate_term pool =
blanchet@36393
   139
  parse_predicate_term pool --| Scan.repeat ($$ "*" || $$ " ")
blanchet@36291
   140
blanchet@36393
   141
fun parse_horn_clause pool =
blanchet@36393
   142
  Scan.repeat (parse_starred_predicate_term pool) --| $$ "-" --| $$ ">"
blanchet@36393
   143
  -- Scan.repeat (parse_starred_predicate_term pool)
blanchet@36392
   144
  >> (fn ([], []) => [atom "c_False"]
blanchet@36392
   145
       | (clauses1, clauses2) => map negate_stree clauses1 @ clauses2)
paulson@21978
   146
blanchet@36393
   147
(* Syntax: <name>[0:<inference><annotations>] ||
blanchet@36393
   148
           <cnf_formulas> -> <cnf_formulas>. *)
blanchet@36402
   149
fun retuple_spass_line ((name, deps), ts) = (name, ts, deps)
blanchet@36402
   150
fun parse_spass_line pool =
blanchet@36392
   151
  parse_integer --| $$ "[" --| $$ "0" --| $$ ":" --| Symbol.scan_id
blanchet@36392
   152
  -- parse_spass_annotations --| $$ "]" --| $$ "|" --| $$ "|"
blanchet@36393
   153
  -- parse_horn_clause pool --| $$ "."
blanchet@36402
   154
  >> retuple_spass_line
blanchet@36291
   155
blanchet@36402
   156
fun parse_line pool = fst o (parse_tstp_line pool || parse_spass_line pool)
paulson@21978
   157
paulson@21978
   158
(**** INTERPRETATION OF TSTP SYNTAX TREES ****)
paulson@21978
   159
paulson@21978
   160
exception STREE of stree;
paulson@21978
   161
paulson@21978
   162
(*If string s has the prefix s1, return the result of deleting it.*)
wenzelm@23139
   163
fun strip_prefix s1 s =
immler@31038
   164
  if String.isPrefix s1 s
blanchet@35865
   165
  then SOME (undo_ascii_of (String.extract (s, size s1, NONE)))
paulson@21978
   166
  else NONE;
paulson@21978
   167
paulson@21978
   168
(*Invert the table of translations between Isabelle and ATPs*)
paulson@21978
   169
val type_const_trans_table_inv =
blanchet@35865
   170
      Symtab.make (map swap (Symtab.dest type_const_trans_table));
paulson@21978
   171
paulson@21978
   172
fun invert_type_const c =
paulson@21978
   173
    case Symtab.lookup type_const_trans_table_inv c of
paulson@21978
   174
        SOME c' => c'
paulson@21978
   175
      | NONE => c;
paulson@21978
   176
blanchet@36285
   177
fun make_tvar s = TVar (("'" ^ s, 0), HOLogic.typeS);
blanchet@36285
   178
fun make_tparam s = TypeInfer.param 0 (s, HOLogic.typeS)
paulson@21978
   179
fun make_var (b,T) = Var((b,0),T);
paulson@21978
   180
paulson@21978
   181
(*Type variables are given the basic sort, HOL.type. Some will later be constrained
paulson@21978
   182
  by information from type literals, or by type inference.*)
paulson@21978
   183
fun type_of_stree t =
paulson@21978
   184
  case t of
blanchet@36392
   185
      SInt _ => raise STREE t
blanchet@36392
   186
    | SBranch (a,ts) =>
paulson@21978
   187
        let val Ts = map type_of_stree ts
wenzelm@23139
   188
        in
blanchet@35865
   189
          case strip_prefix tconst_prefix a of
paulson@21978
   190
              SOME b => Type(invert_type_const b, Ts)
wenzelm@23139
   191
            | NONE =>
paulson@21978
   192
                if not (null ts) then raise STREE t  (*only tconsts have type arguments*)
wenzelm@23139
   193
                else
blanchet@35865
   194
                case strip_prefix tfree_prefix a of
paulson@21978
   195
                    SOME b => TFree("'" ^ b, HOLogic.typeS)
wenzelm@23139
   196
                  | NONE =>
blanchet@35865
   197
                case strip_prefix tvar_prefix a of
paulson@21978
   198
                    SOME b => make_tvar b
blanchet@36285
   199
                  | NONE => make_tparam a  (* Variable from the ATP, say "X1" *)
paulson@21978
   200
        end;
paulson@21978
   201
paulson@21978
   202
(*Invert the table of translations between Isabelle and ATPs*)
paulson@21978
   203
val const_trans_table_inv =
blanchet@36402
   204
  Symtab.update ("fequal", @{const_name "op ="})
blanchet@36402
   205
                (Symtab.make (map swap (Symtab.dest const_trans_table)))
paulson@21978
   206
blanchet@36402
   207
fun invert_const c = c |> Symtab.lookup const_trans_table_inv |> the_default c
paulson@21978
   208
paulson@21978
   209
(*The number of type arguments of a constant, zero if it's monomorphic*)
paulson@21978
   210
fun num_typargs thy s = length (Sign.const_typargs thy (s, Sign.the_const_type thy s));
paulson@21978
   211
paulson@21978
   212
(*Generates a constant, given its type arguments*)
paulson@21978
   213
fun const_of thy (a,Ts) = Const(a, Sign.const_instance thy (a,Ts));
paulson@21978
   214
paulson@21978
   215
(*First-order translation. No types are known for variables. HOLogic.typeT should allow
paulson@21978
   216
  them to be inferred.*)
paulson@22428
   217
fun term_of_stree args thy t =
paulson@21978
   218
  case t of
blanchet@36392
   219
      SInt _ => raise STREE t
blanchet@36392
   220
    | SBranch ("hBOOL", [t]) => term_of_stree [] thy t  (*ignore hBOOL*)
blanchet@36392
   221
    | SBranch ("hAPP", [t, u]) => term_of_stree (u::args) thy t
blanchet@36392
   222
    | SBranch (a, ts) =>
blanchet@35865
   223
        case strip_prefix const_prefix a of
wenzelm@23139
   224
            SOME "equal" =>
blanchet@35865
   225
              list_comb(Const (@{const_name "op ="}, HOLogic.typeT), List.map (term_of_stree [] thy) ts)
wenzelm@23139
   226
          | SOME b =>
paulson@21978
   227
              let val c = invert_const b
paulson@21978
   228
                  val nterms = length ts - num_typargs thy c
paulson@22428
   229
                  val us = List.map (term_of_stree [] thy) (List.take(ts,nterms) @ args)
paulson@22428
   230
                  (*Extra args from hAPP come AFTER any arguments given directly to the
paulson@22428
   231
                    constant.*)
paulson@21978
   232
                  val Ts = List.map type_of_stree (List.drop(ts,nterms))
paulson@21978
   233
              in  list_comb(const_of thy (c, Ts), us)  end
paulson@21978
   234
          | NONE => (*a variable, not a constant*)
paulson@21978
   235
              let val T = HOLogic.typeT
paulson@21978
   236
                  val opr = (*a Free variable is typically a Skolem function*)
blanchet@35865
   237
                    case strip_prefix fixed_var_prefix a of
paulson@21978
   238
                        SOME b => Free(b,T)
wenzelm@23139
   239
                      | NONE =>
blanchet@35865
   240
                    case strip_prefix schematic_var_prefix a of
paulson@21978
   241
                        SOME b => make_var (b,T)
blanchet@36291
   242
                      | NONE => make_var (a,T)  (* Variable from the ATP, say "X1" *)
paulson@23519
   243
              in  list_comb (opr, List.map (term_of_stree [] thy) (ts@args))  end;
paulson@21978
   244
blanchet@36392
   245
(* Type class literal applied to a type. Returns triple of polarity, class,
blanchet@36392
   246
   type. *)
blanchet@36392
   247
fun constraint_of_stree pol (SBranch ("c_Not", [t])) =
blanchet@36392
   248
    constraint_of_stree (not pol) t
paulson@21978
   249
  | constraint_of_stree pol t = case t of
blanchet@36392
   250
        SInt _ => raise STREE t
blanchet@36392
   251
      | SBranch (a, ts) =>
blanchet@35865
   252
            (case (strip_prefix class_prefix a, map type_of_stree ts) of
paulson@21978
   253
                 (SOME b, [T]) => (pol, b, T)
paulson@21978
   254
               | _ => raise STREE t);
paulson@21978
   255
paulson@21978
   256
(** Accumulate type constraints in a clause: negative type literals **)
paulson@21978
   257
paulson@21978
   258
fun addix (key,z)  = Vartab.map_default (key,[]) (cons z);
paulson@21978
   259
paulson@21978
   260
fun add_constraint ((false, cl, TFree(a,_)), vt) = addix ((a,~1),cl) vt
paulson@21978
   261
  | add_constraint ((false, cl, TVar(ix,_)), vt) = addix (ix,cl) vt
paulson@21978
   262
  | add_constraint (_, vt) = vt;
paulson@21978
   263
blanchet@36402
   264
fun is_positive_literal (@{const Trueprop} $ t) = is_positive_literal t
blanchet@36402
   265
  | is_positive_literal (@{const Not} $ _) = false
blanchet@36402
   266
  | is_positive_literal t = true
blanchet@36402
   267
blanchet@36402
   268
fun negate_term thy (@{const Trueprop} $ t) =
blanchet@36402
   269
    @{const Trueprop} $ negate_term thy t
blanchet@36402
   270
  | negate_term thy (Const (@{const_name All}, T) $ Abs (s, T', t')) =
blanchet@36402
   271
    Const (@{const_name Ex}, T) $ Abs (s, T', negate_term thy t')
blanchet@36402
   272
  | negate_term thy (Const (@{const_name Ex}, T) $ Abs (s, T', t')) =
blanchet@36402
   273
    Const (@{const_name All}, T) $ Abs (s, T', negate_term thy t')
blanchet@36402
   274
  | negate_term thy (@{const "op -->"} $ t1 $ t2) =
blanchet@36402
   275
    @{const "op &"} $ t1 $ negate_term thy t2
blanchet@36402
   276
  | negate_term thy (@{const "op &"} $ t1 $ t2) =
blanchet@36402
   277
    @{const "op |"} $ negate_term thy t1 $ negate_term thy t2
blanchet@36402
   278
  | negate_term thy (@{const "op |"} $ t1 $ t2) =
blanchet@36402
   279
    @{const "op &"} $ negate_term thy t1 $ negate_term thy t2
blanchet@36402
   280
  | negate_term thy (@{const Not} $ t) = t
blanchet@36402
   281
  | negate_term thy t =
blanchet@36402
   282
    if fastype_of t = @{typ prop} then
blanchet@36402
   283
      HOLogic.mk_Trueprop (negate_term thy (Object_Logic.atomize_term thy t))
blanchet@36402
   284
    else
blanchet@36402
   285
      @{const Not} $ t
blanchet@36402
   286
blanchet@36402
   287
fun clause_for_literals _ [] = HOLogic.false_const
blanchet@36402
   288
  | clause_for_literals _ [lit] = lit
blanchet@36402
   289
  | clause_for_literals thy lits =
blanchet@36402
   290
    case List.partition is_positive_literal lits of
blanchet@36402
   291
      (pos_lits as _ :: _, neg_lits as _ :: _) =>
blanchet@36402
   292
      @{const "op -->"}
blanchet@36402
   293
          $ foldr1 HOLogic.mk_conj (map (negate_term thy) neg_lits)
blanchet@36402
   294
          $ foldr1 HOLogic.mk_disj pos_lits
blanchet@36402
   295
    | _ => foldr1 HOLogic.mk_disj lits
blanchet@36402
   296
blanchet@36402
   297
(* Final treatment of the list of "real" literals from a clause.
blanchet@36402
   298
   No "real" literals means only type information. *)
blanchet@36402
   299
fun finish_clause _ [] = HOLogic.true_const
blanchet@36402
   300
  | finish_clause thy lits =
blanchet@36402
   301
    lits |> filter_out (curry (op =) HOLogic.false_const) |> rev
blanchet@36402
   302
         |> clause_for_literals thy
paulson@22491
   303
paulson@21978
   304
(*Accumulate sort constraints in vt, with "real" literals in lits.*)
blanchet@36402
   305
fun lits_of_strees thy (vt, lits) [] = (vt, finish_clause thy lits)
blanchet@36402
   306
  | lits_of_strees thy (vt, lits) (t :: ts) =
blanchet@36402
   307
    lits_of_strees thy (add_constraint (constraint_of_stree true t, vt), lits)
blanchet@36402
   308
                   ts
blanchet@36402
   309
    handle STREE _ => lits_of_strees thy (vt, term_of_stree [] thy t :: lits) ts
paulson@21978
   310
paulson@21978
   311
(*Update TVars/TFrees with detected sort constraints.*)
blanchet@36393
   312
fun repair_sorts vt =
paulson@21978
   313
  let fun tysubst (Type (a, Ts)) = Type (a, map tysubst Ts)
wenzelm@33035
   314
        | tysubst (TVar (xi, s)) = TVar (xi, the_default s (Vartab.lookup vt xi))
wenzelm@33035
   315
        | tysubst (TFree (x, s)) = TFree (x, the_default s (Vartab.lookup vt (x, ~1)))
paulson@21978
   316
      fun tmsubst (Const (a, T)) = Const (a, tysubst T)
paulson@21978
   317
        | tmsubst (Free (a, T)) = Free (a, tysubst T)
paulson@21978
   318
        | tmsubst (Var (xi, T)) = Var (xi, tysubst T)
paulson@21978
   319
        | tmsubst (t as Bound _) = t
paulson@21978
   320
        | tmsubst (Abs (a, T, t)) = Abs (a, tysubst T, tmsubst t)
paulson@21978
   321
        | tmsubst (t $ u) = tmsubst t $ tmsubst u;
blanchet@36285
   322
  in not (Vartab.is_empty vt) ? tmsubst end;
paulson@21978
   323
paulson@21978
   324
(*Interpret a list of syntax trees as a clause, given by "real" literals and sort constraints.
paulson@21978
   325
  vt0 holds the initial sort constraints, from the conjecture clauses.*)
blanchet@36393
   326
fun clause_of_strees ctxt vt ts =
blanchet@36402
   327
  let val (vt, dt) = lits_of_strees (ProofContext.theory_of ctxt) (vt, []) ts in
blanchet@36393
   328
    dt |> repair_sorts vt |> TypeInfer.constrain HOLogic.boolT
blanchet@36393
   329
       |> Syntax.check_term ctxt
blanchet@36285
   330
  end
paulson@21978
   331
wenzelm@29268
   332
fun gen_all_vars t = fold_rev Logic.all (OldTerm.term_vars t) t;
paulson@21978
   333
blanchet@36402
   334
fun decode_line vt0 (name, ts, deps) ctxt =
blanchet@36291
   335
  let val cl = clause_of_strees ctxt vt0 ts in
blanchet@36291
   336
    ((name, cl, deps), fold Variable.declare_term (OldTerm.term_frees cl) ctxt)
blanchet@36291
   337
  end
paulson@21978
   338
paulson@21978
   339
(** Global sort constraints on TFrees (from tfree_tcs) are positive unit clauses. **)
paulson@21978
   340
paulson@21978
   341
fun add_tfree_constraint ((true, cl, TFree(a,_)), vt) = addix ((a,~1),cl) vt
paulson@21978
   342
  | add_tfree_constraint (_, vt) = vt;
paulson@21978
   343
paulson@21978
   344
fun tfree_constraints_of_clauses vt [] = vt
wenzelm@23139
   345
  | tfree_constraints_of_clauses vt ([lit]::tss) =
paulson@21978
   346
      (tfree_constraints_of_clauses (add_tfree_constraint (constraint_of_stree true lit, vt)) tss
paulson@21978
   347
       handle STREE _ => (*not a positive type constraint: ignore*)
paulson@21978
   348
       tfree_constraints_of_clauses vt tss)
paulson@21978
   349
  | tfree_constraints_of_clauses vt (_::tss) = tfree_constraints_of_clauses vt tss;
paulson@21978
   350
paulson@21978
   351
paulson@21978
   352
(**** Translation of TSTP files to Isar Proofs ****)
paulson@21978
   353
blanchet@36402
   354
fun decode_lines ctxt tuples =
blanchet@36291
   355
  let val vt0 = tfree_constraints_of_clauses Vartab.empty (map #2 tuples) in
blanchet@36402
   356
    #1 (fold_map (decode_line vt0) tuples ctxt)
blanchet@36291
   357
  end
paulson@21978
   358
blanchet@35869
   359
fun unequal t (_, t', _) = not (t aconv t');
paulson@21978
   360
paulson@22491
   361
(*No "real" literals means only type information*)
paulson@23519
   362
fun eq_types t = t aconv HOLogic.true_const;
paulson@21978
   363
blanchet@36395
   364
fun replace_dep (old, new) dep = if dep = old then new else [dep]
blanchet@36395
   365
fun replace_deps p (num, t, deps) =
blanchet@36395
   366
  (num, t, fold (union (op =) o replace_dep p) deps [])
paulson@21978
   367
paulson@22491
   368
(*Discard axioms; consolidate adjacent lines that prove the same clause, since they differ
paulson@22491
   369
  only in type information.*)
blanchet@36402
   370
fun add_line thm_names (num, t, []) lines =
blanchet@36291
   371
      (* No dependencies: axiom or conjecture clause *)
blanchet@36395
   372
      if is_axiom_clause_number thm_names num then
blanchet@36291
   373
        (* Axioms are not proof lines *)
blanchet@36291
   374
        if eq_types t then
blanchet@36291
   375
          (* Must be clsrel/clsarity: type information, so delete refs to it *)
blanchet@36395
   376
          map (replace_deps (num, [])) lines
blanchet@36291
   377
        else
blanchet@36291
   378
          (case take_prefix (unequal t) lines of
blanchet@36291
   379
             (_,[]) => lines                  (*no repetition of proof line*)
blanchet@36395
   380
           | (pre, (num', _, _) :: post) =>   (*repetition: replace later line by earlier one*)
blanchet@36395
   381
               pre @ map (replace_deps (num', [num])) post)
paulson@22470
   382
      else
blanchet@36395
   383
        (num, t, []) :: lines
blanchet@36402
   384
  | add_line _ (num, t, deps) lines =
blanchet@36395
   385
      if eq_types t then (num, t, deps) :: lines
paulson@22491
   386
      (*Type information will be deleted later; skip repetition test.*)
paulson@22491
   387
      else (*FIXME: Doesn't this code risk conflating proofs involving different types??*)
blanchet@35869
   388
      case take_prefix (unequal t) lines of
blanchet@36395
   389
         (_,[]) => (num, t, deps) :: lines  (*no repetition of proof line*)
blanchet@36395
   390
       | (pre, (num', t', _) :: post) =>
blanchet@36395
   391
           (num, t', deps) ::               (*repetition: replace later line by earlier one*)
blanchet@36395
   392
           (pre @ map (replace_deps (num', [num])) post);
paulson@22044
   393
paulson@22470
   394
(*Recursively delete empty lines (type information) from the proof.*)
blanchet@36402
   395
fun add_nonnull_line (num, t, []) lines = (*no dependencies, so a conjecture clause*)
blanchet@36402
   396
    if eq_types t then
blanchet@36402
   397
      (*must be type information, tfree_tcs, clsrel, clsarity: delete refs to it*)
blanchet@36402
   398
      delete_dep num lines
blanchet@36402
   399
    else
blanchet@36402
   400
      (num, t, []) :: lines
blanchet@36402
   401
  | add_nonnull_line (num, t, deps) lines = (num, t, deps) :: lines
blanchet@36395
   402
and delete_dep num lines =
blanchet@36402
   403
  fold_rev add_nonnull_line (map (replace_deps (num, [])) lines) []
paulson@22470
   404
blanchet@35865
   405
fun bad_free (Free (a,_)) = String.isPrefix skolem_prefix a
paulson@22731
   406
  | bad_free _ = false;
paulson@22731
   407
blanchet@36474
   408
fun add_desired_line ctxt _ (num, t, []) (j, lines) =
blanchet@36402
   409
    (j, (num, t, []) :: lines)  (* conjecture clauses must be kept *)
blanchet@36474
   410
  | add_desired_line ctxt shrink_factor (num, t, deps) (j, lines) =
blanchet@36402
   411
    (j + 1,
blanchet@36402
   412
     if eq_types t orelse not (null (Term.add_tvars t [])) orelse
blanchet@36474
   413
        exists_subterm bad_free t orelse
blanchet@36474
   414
        (length deps < 2 orelse j mod shrink_factor <> 0) then
blanchet@36402
   415
       map (replace_deps (num, deps)) lines  (* delete line *)
blanchet@36402
   416
     else
blanchet@36402
   417
       (num, t, deps) :: lines)
paulson@21978
   418
blanchet@36402
   419
(* ### *)
paulson@21999
   420
(*Replace numeric proof lines by strings, either from thm_names or sequential line numbers*)
paulson@21978
   421
fun stringify_deps thm_names deps_map [] = []
blanchet@36395
   422
  | stringify_deps thm_names deps_map ((num, t, deps) :: lines) =
blanchet@36395
   423
    if is_axiom_clause_number thm_names num then
blanchet@36395
   424
      (Vector.sub (thm_names, num - 1), t, []) ::
blanchet@36395
   425
      stringify_deps thm_names deps_map lines
blanchet@36395
   426
    else
blanchet@36395
   427
      let
blanchet@36396
   428
        val label = Int.toString (length deps_map)
blanchet@36396
   429
        fun string_for_num num =
blanchet@36396
   430
          if is_axiom_clause_number thm_names num then
blanchet@36396
   431
            SOME (Vector.sub (thm_names, num - 1))
blanchet@36396
   432
          else
blanchet@36396
   433
            AList.lookup (op =) deps_map num
blanchet@36395
   434
      in
blanchet@36396
   435
        (label, t, map_filter string_for_num (distinct (op=) deps)) ::
blanchet@36396
   436
        stringify_deps thm_names ((num, label) :: deps_map) lines
blanchet@36395
   437
      end
paulson@21978
   438
blanchet@36402
   439
(** EXTRACTING LEMMAS **)
paulson@21979
   440
blanchet@36223
   441
(* A list consisting of the first number in each line is returned.
blanchet@36395
   442
   TSTP: Interesting lines have the form "cnf(108, axiom, ...)", where the
blanchet@36223
   443
   number (108) is extracted.
blanchet@36395
   444
   SPASS: Lines have the form "108[0:Inp] ...", where the first number (108) is
blanchet@36223
   445
   extracted. *)
blanchet@36402
   446
fun extract_clause_numbers_in_atp_proof atp_proof =
blanchet@35865
   447
  let
blanchet@36395
   448
    val tokens_of = String.tokens (not o is_ident_char)
blanchet@36402
   449
    fun extract_num ("cnf" :: num :: "axiom" :: _) = Int.fromString num
blanchet@36402
   450
      | extract_num ("cnf" :: num :: "negated_conjecture" :: _) =
blanchet@36402
   451
        Int.fromString num
blanchet@36395
   452
      | extract_num (num :: "0" :: "Inp" :: _) = Int.fromString num
blanchet@36395
   453
      | extract_num _ = NONE
blanchet@36402
   454
  in atp_proof |> split_lines |> map_filter (extract_num o tokens_of) end
wenzelm@33310
   455
  
blanchet@36395
   456
(* Used to label theorems chained into the Sledgehammer call (or rather
blanchet@36395
   457
   goal?) *)
blanchet@36395
   458
val chained_hint = "sledgehammer_chained"
blanchet@35865
   459
blanchet@36063
   460
fun apply_command _ 1 = "by "
blanchet@36063
   461
  | apply_command 1 _ = "apply "
blanchet@36063
   462
  | apply_command i _ = "prefer " ^ string_of_int i ^ " apply "
blanchet@36063
   463
fun metis_command i n [] =
blanchet@36063
   464
    apply_command i n ^ "metis"
blanchet@36063
   465
  | metis_command i n xs =
blanchet@36063
   466
    apply_command i n ^ "(metis " ^ space_implode " " xs ^ ")"
blanchet@36063
   467
fun metis_line i n xs =
blanchet@36063
   468
  "Try this command: " ^
blanchet@36063
   469
  Markup.markup Markup.sendback (metis_command i n xs) ^ ".\n" 
blanchet@36281
   470
fun minimize_line _ [] = ""
blanchet@36281
   471
  | minimize_line minimize_command facts =
blanchet@36281
   472
    case minimize_command facts of
blanchet@36281
   473
      "" => ""
blanchet@36281
   474
    | command =>
blanchet@36065
   475
      "To minimize the number of lemmas, try this command: " ^
blanchet@36281
   476
      Markup.markup Markup.sendback command ^ ".\n"
immler@31840
   477
blanchet@36402
   478
fun metis_proof_text (minimize_command, atp_proof, thm_names, goal, i) =
blanchet@36063
   479
  let
blanchet@36231
   480
    val lemmas =
blanchet@36402
   481
      atp_proof |> extract_clause_numbers_in_atp_proof
blanchet@36402
   482
                |> filter (is_axiom_clause_number thm_names)
blanchet@36402
   483
                |> map (fn i => Vector.sub (thm_names, i - 1))
blanchet@36402
   484
                |> filter_out (fn s => s = "??.unknown" orelse s = chained_hint)
blanchet@36402
   485
                |> sort_distinct string_ord
blanchet@36063
   486
    val n = Logic.count_prems (prop_of goal)
blanchet@36395
   487
  in (metis_line i n lemmas ^ minimize_line minimize_command lemmas, lemmas) end
immler@31037
   488
blanchet@36402
   489
val is_valid_line = String.isPrefix "cnf(" orf String.isSubstring "||"
blanchet@36402
   490
blanchet@36402
   491
(** NEW PROOF RECONSTRUCTION CODE **)
blanchet@36402
   492
blanchet@36402
   493
type label = string * int
blanchet@36402
   494
type facts = label list * string list
blanchet@36402
   495
blanchet@36402
   496
fun merge_fact_sets (ls1, ss1) (ls2, ss2) =
blanchet@36402
   497
  (union (op =) ls1 ls2, union (op =) ss1 ss2)
blanchet@36402
   498
blanchet@36402
   499
datatype qualifier = Show | Then | Moreover | Ultimately
blanchet@36291
   500
blanchet@36402
   501
datatype step =
blanchet@36402
   502
  Fix of term list |
blanchet@36402
   503
  Assume of label * term |
blanchet@36402
   504
  Have of qualifier list * label * term * byline
blanchet@36402
   505
and byline =
blanchet@36402
   506
  Facts of facts |
blanchet@36402
   507
  CaseSplit of step list list * facts
blanchet@36402
   508
blanchet@36402
   509
val raw_prefix = "X"
blanchet@36402
   510
val assum_prefix = "A"
blanchet@36402
   511
val fact_prefix = "F"
blanchet@36402
   512
blanchet@36402
   513
(* ###
blanchet@36402
   514
fun add_fact_from_dep s =
blanchet@36402
   515
  case Int.fromString s of
blanchet@36402
   516
    SOME n => apfst (cons (raw_prefix, n))
blanchet@36402
   517
  | NONE => apsnd (cons s)
blanchet@36402
   518
*)
blanchet@36402
   519
blanchet@36402
   520
val add_fact_from_dep = apfst o cons o pair raw_prefix
blanchet@36402
   521
blanchet@36402
   522
fun step_for_tuple _ (label, t, []) = Assume ((raw_prefix, label), t)
blanchet@36402
   523
  | step_for_tuple j (label, t, deps) =
blanchet@36402
   524
    Have (if j = 1 then [Show] else [], (raw_prefix, label), t,
blanchet@36402
   525
          Facts (fold add_fact_from_dep deps ([], [])))
blanchet@36291
   526
blanchet@36291
   527
fun strip_spaces_in_list [] = ""
blanchet@36402
   528
  | strip_spaces_in_list [c1] = if Char.isSpace c1 then "" else str c1
blanchet@36402
   529
  | strip_spaces_in_list [c1, c2] =
blanchet@36402
   530
    strip_spaces_in_list [c1] ^ strip_spaces_in_list [c2]
blanchet@36291
   531
  | strip_spaces_in_list (c1 :: c2 :: c3 :: cs) =
blanchet@36291
   532
    if Char.isSpace c1 then
blanchet@36291
   533
      strip_spaces_in_list (c2 :: c3 :: cs)
blanchet@36291
   534
    else if Char.isSpace c2 then
blanchet@36291
   535
      if Char.isSpace c3 then
blanchet@36291
   536
        strip_spaces_in_list (c1 :: c3 :: cs)
blanchet@36291
   537
      else
blanchet@36402
   538
        str c1 ^ (if forall is_ident_char [c1, c3] then " " else "") ^
blanchet@36291
   539
        strip_spaces_in_list (c3 :: cs)
blanchet@36291
   540
    else
blanchet@36291
   541
      str c1 ^ strip_spaces_in_list (c2 :: c3 :: cs)
blanchet@36291
   542
val strip_spaces = strip_spaces_in_list o String.explode
blanchet@36291
   543
blanchet@36474
   544
fun proof_from_atp_proof pool ctxt shrink_factor atp_proof thm_names frees =
blanchet@36402
   545
  let
blanchet@36402
   546
    val tuples =
blanchet@36402
   547
      atp_proof |> split_lines |> map strip_spaces
blanchet@36402
   548
                |> filter is_valid_line
blanchet@36402
   549
                |> map (parse_line pool o explode)
blanchet@36402
   550
                |> decode_lines ctxt
blanchet@36402
   551
    val tuples = fold_rev (add_line thm_names) tuples []
blanchet@36402
   552
    val tuples = fold_rev add_nonnull_line tuples []
blanchet@36474
   553
    val tuples = fold_rev (add_desired_line ctxt shrink_factor) tuples (0, [])
blanchet@36474
   554
                 |> snd
blanchet@36402
   555
  in
blanchet@36402
   556
    (if null frees then [] else [Fix frees]) @
blanchet@36402
   557
    map2 step_for_tuple (length tuples downto 1) tuples
blanchet@36402
   558
  end
blanchet@36402
   559
blanchet@36402
   560
val indent_size = 2
blanchet@36402
   561
val no_label = ("", ~1)
blanchet@36402
   562
blanchet@36402
   563
fun no_show qs = not (member (op =) qs Show)
blanchet@36402
   564
blanchet@36402
   565
(* When redirecting proofs, we keep information about the labels seen so far in
blanchet@36402
   566
   the "backpatches" data structure. The first component indicates which facts
blanchet@36402
   567
   should be associated with forthcoming proof steps. The second component is a
blanchet@36402
   568
   pair ("keep_ls", "drop_ls"), where "keep_ls" are the labels to keep and
blanchet@36402
   569
   "drop_ls" are those that should be dropped in a case split. *)
blanchet@36402
   570
type backpatches = (label * facts) list * (label list * label list)
blanchet@36402
   571
blanchet@36402
   572
fun using_of_step (Have (_, _, _, by)) =
blanchet@36402
   573
    (case by of
blanchet@36402
   574
       Facts (ls, _) => ls
blanchet@36402
   575
     | CaseSplit (proofs, (ls, _)) => fold (union (op =) o using_of) proofs ls)
blanchet@36402
   576
  | using_of_step _ = []
blanchet@36402
   577
and using_of proof = fold (union (op =) o using_of_step) proof []
blanchet@36402
   578
blanchet@36402
   579
fun new_labels_of_step (Fix _) = []
blanchet@36402
   580
  | new_labels_of_step (Assume (l, _)) = [l]
blanchet@36402
   581
  | new_labels_of_step (Have (_, l, _, _)) = [l]
blanchet@36402
   582
val new_labels_of = maps new_labels_of_step
blanchet@36402
   583
blanchet@36402
   584
val join_proofs =
blanchet@36402
   585
  let
blanchet@36402
   586
    fun aux _ [] = NONE
blanchet@36402
   587
      | aux proof_tail (proofs as (proof1 :: _)) =
blanchet@36402
   588
        if exists null proofs then
blanchet@36402
   589
          NONE
blanchet@36402
   590
        else if forall (curry (op =) (hd proof1) o hd) (tl proofs) then
blanchet@36402
   591
          aux (hd proof1 :: proof_tail) (map tl proofs)
blanchet@36402
   592
        else case hd proof1 of
blanchet@36402
   593
          Have ([], l, t, by) =>
blanchet@36402
   594
          if forall (fn Have ([], l', t', _) :: _ => (l, t) = (l', t')
blanchet@36402
   595
                      | _ => false) (tl proofs) andalso
blanchet@36402
   596
             not (exists (member (op =) (maps new_labels_of proofs))
blanchet@36402
   597
                         (using_of proof_tail)) then
blanchet@36402
   598
            SOME (l, t, map rev proofs, proof_tail)
blanchet@36402
   599
          else
blanchet@36402
   600
            NONE
blanchet@36402
   601
        | _ => NONE
blanchet@36402
   602
  in aux [] o map rev end
blanchet@36402
   603
blanchet@36402
   604
fun case_split_qualifiers proofs =
blanchet@36402
   605
  case length proofs of
blanchet@36402
   606
    0 => []
blanchet@36402
   607
  | 1 => [Then]
blanchet@36402
   608
  | _ => [Ultimately]
blanchet@36402
   609
blanchet@36402
   610
val index_in_shape = find_index o exists o curry (op =)
blanchet@36402
   611
blanchet@36402
   612
fun direct_proof thy conjecture_shape hyp_ts concl_t proof =
wenzelm@33310
   613
  let
blanchet@36402
   614
    val concl_ls = map (pair raw_prefix) (List.last conjecture_shape)
blanchet@36402
   615
    fun find_hyp (_, j) = nth hyp_ts (index_in_shape j conjecture_shape)
blanchet@36402
   616
    fun first_pass ([], contra) = ([], contra)
blanchet@36402
   617
      | first_pass ((ps as Fix _) :: proof, contra) =
blanchet@36402
   618
        first_pass (proof, contra) |>> cons ps
blanchet@36402
   619
      | first_pass ((ps as Assume (l, t)) :: proof, contra) =
blanchet@36402
   620
        if member (op =) concl_ls l then
blanchet@36402
   621
          first_pass (proof, contra ||> cons ps)
blanchet@36402
   622
        else
blanchet@36402
   623
          first_pass (proof, contra) |>> cons (Assume (l, find_hyp l))
blanchet@36402
   624
      | first_pass ((ps as Have (qs, l, t, Facts (ls, ss))) :: proof, contra) =
blanchet@36402
   625
        if exists (member (op =) (fst contra)) ls then
blanchet@36402
   626
          first_pass (proof, contra |>> cons l ||> cons ps)
blanchet@36402
   627
        else
blanchet@36402
   628
          first_pass (proof, contra) |>> cons ps
blanchet@36402
   629
      | first_pass _ = raise Fail "malformed proof"
blanchet@36402
   630
    val (proof_top, (contra_ls, contra_proof)) =
blanchet@36402
   631
      first_pass (proof, (concl_ls, []))
blanchet@36402
   632
    val backpatch_label = the_default ([], []) oo AList.lookup (op =) o fst
blanchet@36402
   633
    fun backpatch_labels patches ls =
blanchet@36402
   634
      fold merge_fact_sets (map (backpatch_label patches) ls) ([], [])
blanchet@36402
   635
    fun second_pass end_qs ([], assums, patches) =
blanchet@36402
   636
        ([Have (end_qs, no_label,
blanchet@36402
   637
                if length assums < length concl_ls then
blanchet@36402
   638
                  clause_for_literals thy (map (negate_term thy o fst) assums)
blanchet@36402
   639
                else
blanchet@36402
   640
                  concl_t,
blanchet@36402
   641
                Facts (backpatch_labels patches (map snd assums)))], patches)
blanchet@36402
   642
      | second_pass end_qs (Assume (l, t) :: proof, assums, patches) =
blanchet@36402
   643
        second_pass end_qs (proof, (t, l) :: assums, patches)
blanchet@36402
   644
      | second_pass end_qs (Have (qs, l, t, Facts (ls, ss)) :: proof, assums,
blanchet@36402
   645
                            patches) =
blanchet@36402
   646
        if member (op =) (snd (snd patches)) l andalso
blanchet@36402
   647
           not (AList.defined (op =) (fst patches) l) then
blanchet@36402
   648
          second_pass end_qs (proof, assums, patches ||> apsnd (append ls))
blanchet@36402
   649
        else
blanchet@36402
   650
          (case List.partition (member (op =) contra_ls) ls of
blanchet@36402
   651
             ([contra_l], co_ls) =>
blanchet@36402
   652
             if no_show qs then
blanchet@36402
   653
               second_pass end_qs
blanchet@36402
   654
                           (proof, assums,
blanchet@36402
   655
                            patches |>> cons (contra_l, (l :: co_ls, ss)))
blanchet@36402
   656
               |>> cons (if member (op =) (fst (snd patches)) l then
blanchet@36402
   657
                           Assume (l, negate_term thy t)
blanchet@36402
   658
                         else
blanchet@36402
   659
                           Have (qs, l, negate_term thy t,
blanchet@36402
   660
                                 Facts (backpatch_label patches l)))
blanchet@36402
   661
             else
blanchet@36402
   662
               second_pass end_qs (proof, assums,
blanchet@36402
   663
                                   patches |>> cons (contra_l, (co_ls, ss)))
blanchet@36402
   664
           | (contra_ls as _ :: _, co_ls) =>
blanchet@36402
   665
             let
blanchet@36402
   666
               val proofs =
blanchet@36402
   667
                 map_filter
blanchet@36402
   668
                     (fn l =>
blanchet@36402
   669
                         if member (op =) concl_ls l then
blanchet@36402
   670
                           NONE
blanchet@36402
   671
                         else
blanchet@36402
   672
                           let
blanchet@36402
   673
                             val drop_ls = filter (curry (op <>) l) contra_ls
blanchet@36402
   674
                           in
blanchet@36402
   675
                             second_pass []
blanchet@36402
   676
                                 (proof, assums,
blanchet@36402
   677
                                  patches ||> apfst (insert (op =) l)
blanchet@36402
   678
                                          ||> apsnd (union (op =) drop_ls))
blanchet@36402
   679
                             |> fst |> SOME
blanchet@36402
   680
                           end) contra_ls
blanchet@36402
   681
               val facts = (co_ls, [])
blanchet@36402
   682
             in
blanchet@36402
   683
               (case join_proofs proofs of
blanchet@36402
   684
                  SOME (l, t, proofs, proof_tail) =>
blanchet@36402
   685
                  Have (case_split_qualifiers proofs @
blanchet@36402
   686
                        (if null proof_tail then end_qs else []), l, t,
blanchet@36402
   687
                        CaseSplit (proofs, facts)) :: proof_tail
blanchet@36402
   688
                | NONE =>
blanchet@36402
   689
                  [Have (case_split_qualifiers proofs @ end_qs, no_label,
blanchet@36402
   690
                         concl_t, CaseSplit (proofs, facts))],
blanchet@36402
   691
                patches)
blanchet@36402
   692
             end
blanchet@36402
   693
           | _ => raise Fail "malformed proof")
blanchet@36402
   694
       | second_pass _ _ = raise Fail "malformed proof"
blanchet@36402
   695
    val (proof_bottom, _) =
blanchet@36402
   696
      second_pass [Show] (contra_proof, [], ([], ([], [])))
blanchet@36402
   697
  in proof_top @ proof_bottom end
blanchet@36402
   698
blanchet@36402
   699
val kill_duplicate_assumptions_in_proof =
blanchet@36402
   700
  let
blanchet@36402
   701
    fun relabel_facts subst =
blanchet@36402
   702
      apfst (map (fn l => AList.lookup (op =) subst l |> the_default l))
blanchet@36402
   703
    fun do_step (ps as Fix _) (proof, subst, assums) =
blanchet@36402
   704
        (ps :: proof, subst, assums)
blanchet@36402
   705
      | do_step (ps as Assume (l, t)) (proof, subst, assums) =
blanchet@36402
   706
        (case AList.lookup (op aconv) assums t of
blanchet@36402
   707
           SOME l' => (proof, (l', l) :: subst, assums)
blanchet@36402
   708
         | NONE => (ps :: proof, subst, (t, l) :: assums))
blanchet@36402
   709
      | do_step (Have (qs, l, t, by)) (proof, subst, assums) =
blanchet@36402
   710
        (Have (qs, l, t,
blanchet@36402
   711
               case by of
blanchet@36402
   712
                 Facts facts => Facts (relabel_facts subst facts)
blanchet@36402
   713
               | CaseSplit (proofs, facts) =>
blanchet@36402
   714
                 CaseSplit (map do_proof proofs, relabel_facts subst facts)) ::
blanchet@36402
   715
         proof, subst, assums)
blanchet@36402
   716
    and do_proof proof = fold do_step proof ([], [], []) |> #1 |> rev
blanchet@36402
   717
  in do_proof end
blanchet@36402
   718
blanchet@36402
   719
val then_chain_proof =
blanchet@36402
   720
  let
blanchet@36402
   721
    fun aux _ [] = []
blanchet@36402
   722
      | aux _ ((ps as Fix _) :: proof) = ps :: aux no_label proof
blanchet@36402
   723
      | aux _ ((ps as Assume (l, _)) :: proof) = ps :: aux l proof
blanchet@36402
   724
      | aux l' (Have (qs, l, t, by) :: proof) =
blanchet@36402
   725
        (case by of
blanchet@36402
   726
           Facts (ls, ss) =>
blanchet@36402
   727
           Have (if member (op =) ls l' then
blanchet@36402
   728
                   (Then :: qs, l, t,
blanchet@36402
   729
                    Facts (filter_out (curry (op =) l') ls, ss))
blanchet@36402
   730
                 else
blanchet@36402
   731
                   (qs, l, t, Facts (ls, ss)))
blanchet@36402
   732
         | CaseSplit (proofs, facts) =>
blanchet@36402
   733
           Have (qs, l, t, CaseSplit (map (aux no_label) proofs, facts))) ::
blanchet@36402
   734
        aux l proof
blanchet@36402
   735
  in aux no_label end
blanchet@36402
   736
blanchet@36402
   737
fun kill_useless_labels_in_proof proof =
blanchet@36402
   738
  let
blanchet@36402
   739
    val used_ls = using_of proof
blanchet@36402
   740
    fun do_label l = if member (op =) used_ls l then l else no_label
blanchet@36402
   741
    fun kill (Fix ts) = Fix ts
blanchet@36402
   742
      | kill (Assume (l, t)) = Assume (do_label l, t)
blanchet@36402
   743
      | kill (Have (qs, l, t, by)) =
blanchet@36402
   744
        Have (qs, do_label l, t,
blanchet@36402
   745
              case by of
blanchet@36402
   746
                CaseSplit (proofs, facts) =>
blanchet@36402
   747
                CaseSplit (map (map kill) proofs, facts)
blanchet@36402
   748
              | _ => by)
blanchet@36402
   749
  in map kill proof end
blanchet@36402
   750
blanchet@36402
   751
fun prefix_for_depth n = replicate_string (n + 1)
blanchet@36402
   752
blanchet@36402
   753
val relabel_proof =
blanchet@36402
   754
  let
blanchet@36402
   755
    fun aux _ _ _ [] = []
blanchet@36402
   756
      | aux subst depth nextp ((ps as Fix _) :: proof) =
blanchet@36402
   757
        ps :: aux subst depth nextp proof
blanchet@36402
   758
      | aux subst depth (next_assum, next_fact) (Assume (l, t) :: proof) =
blanchet@36402
   759
        if l = no_label then
blanchet@36402
   760
          Assume (l, t) :: aux subst depth (next_assum, next_fact) proof
blanchet@36402
   761
        else
blanchet@36402
   762
          let val l' = (prefix_for_depth depth assum_prefix, next_assum) in
blanchet@36402
   763
            Assume (l', t) ::
blanchet@36402
   764
            aux ((l, l') :: subst) depth (next_assum + 1, next_fact) proof
blanchet@36402
   765
          end
blanchet@36402
   766
      | aux subst depth (next_assum, next_fact) (Have (qs, l, t, by) :: proof) =
blanchet@36402
   767
        let
blanchet@36402
   768
          val (l', subst, next_fact) =
blanchet@36402
   769
            if l = no_label then
blanchet@36402
   770
              (l, subst, next_fact)
blanchet@36402
   771
            else
blanchet@36402
   772
              let
blanchet@36402
   773
                val l' = (prefix_for_depth depth fact_prefix, next_fact)
blanchet@36402
   774
              in (l', (l, l') :: subst, next_fact + 1) end
blanchet@36402
   775
          val relabel_facts = apfst (map (the o AList.lookup (op =) subst))
blanchet@36402
   776
          val by =
blanchet@36402
   777
            case by of
blanchet@36402
   778
              Facts facts => Facts (relabel_facts facts)
blanchet@36402
   779
            | CaseSplit (proofs, facts) =>
blanchet@36402
   780
              CaseSplit (map (aux subst (depth + 1) (1, 1)) proofs,
blanchet@36402
   781
                         relabel_facts facts)
blanchet@36402
   782
        in
blanchet@36402
   783
          Have (qs, l', t, by) ::
blanchet@36402
   784
          aux subst depth (next_assum, next_fact) proof
blanchet@36402
   785
        end
blanchet@36402
   786
  in aux [] 0 (1, 1) end
blanchet@36402
   787
blanchet@36402
   788
fun string_for_proof ctxt sorts i n =
blanchet@36402
   789
  let
blanchet@36402
   790
    fun do_indent ind = replicate_string (ind * indent_size) " "
blanchet@36402
   791
    fun do_raw_label (s, j) = s ^ string_of_int j
blanchet@36402
   792
    fun do_label l = if l = no_label then "" else do_raw_label l ^ ": "
blanchet@36402
   793
    fun do_have qs =
blanchet@36402
   794
      (if member (op =) qs Moreover then "moreover " else "") ^
blanchet@36402
   795
      (if member (op =) qs Ultimately then "ultimately " else "") ^
blanchet@36402
   796
      (if member (op =) qs Then then
blanchet@36402
   797
         if member (op =) qs Show then "thus" else "hence"
blanchet@36402
   798
       else
blanchet@36402
   799
         if member (op =) qs Show then "show" else "have")
blanchet@36402
   800
    val do_term =
blanchet@36404
   801
      quote o PrintMode.setmp (filter (curry (op =) Symbol.xsymbolsN)
blanchet@36404
   802
                                      (print_mode_value ()))
blanchet@36404
   803
                              (Syntax.string_of_term ctxt)
blanchet@36402
   804
    fun do_using [] = ""
blanchet@36402
   805
      | do_using ls = "using " ^ (space_implode " " (map do_raw_label ls)) ^ " "
blanchet@36402
   806
    fun do_by_facts [] [] = "by blast"
blanchet@36402
   807
      | do_by_facts _ [] = "by metis"
blanchet@36402
   808
      | do_by_facts _ ss = "by (metis " ^ space_implode " " ss ^ ")"
blanchet@36402
   809
    fun do_facts ind (ls, ss) =
blanchet@36402
   810
      do_indent (ind + 1) ^ do_using ls ^ do_by_facts ls ss
blanchet@36402
   811
    and do_step ind (Fix ts) =
blanchet@36402
   812
        do_indent ind ^ "fix " ^ space_implode " and " (map do_term ts) ^ "\n"
blanchet@36402
   813
      | do_step ind (Assume (l, t)) =
blanchet@36402
   814
        do_indent ind ^ "assume " ^ do_label l ^ do_term t ^ "\n"
blanchet@36402
   815
      | do_step ind (Have (qs, l, t, Facts facts)) =
blanchet@36402
   816
        do_indent ind ^ do_have qs ^ " " ^
blanchet@36402
   817
        do_label l ^ do_term t ^ "\n" ^ do_facts ind facts ^ "\n"
blanchet@36402
   818
      | do_step ind (Have (qs, l, t, CaseSplit (proofs, facts))) =
blanchet@36402
   819
        space_implode (do_indent ind ^ "moreover\n")
blanchet@36402
   820
                      (map (do_block ind) proofs) ^
blanchet@36402
   821
        do_indent ind ^ do_have qs ^ " " ^ do_label l ^ do_term t ^ "\n" ^
blanchet@36402
   822
        do_facts ind facts ^ "\n"
blanchet@36402
   823
    and do_steps prefix suffix ind steps =
blanchet@36402
   824
      let val s = implode (map (do_step ind) steps) in
blanchet@36402
   825
        replicate_string (ind * indent_size - size prefix) " " ^ prefix ^
blanchet@36402
   826
        String.extract (s, ind * indent_size,
blanchet@36402
   827
                        SOME (size s - ind * indent_size - 1)) ^
blanchet@36402
   828
        suffix ^ "\n"
blanchet@36402
   829
      end
blanchet@36402
   830
    and do_block ind proof = do_steps "{ " " }" (ind + 1) proof
blanchet@36402
   831
    and do_proof proof =
blanchet@36402
   832
      (if i <> 1 then "prefer " ^ string_of_int i ^ "\n" else "") ^
blanchet@36402
   833
      do_indent 0 ^ "proof -\n" ^
blanchet@36402
   834
      do_steps "" "" 1 proof ^
blanchet@36402
   835
      do_indent 0 ^ (if n <> 1 then "next" else "qed") ^ "\n"
blanchet@36402
   836
  in setmp_CRITICAL show_sorts sorts do_proof end
blanchet@36402
   837
blanchet@36402
   838
fun isar_proof_text (pool, debug, shrink_factor, sorts, ctxt, conjecture_shape)
blanchet@36402
   839
                    (minimize_command, atp_proof, thm_names, goal, i) =
blanchet@36402
   840
  let
blanchet@36402
   841
    val thy = ProofContext.theory_of ctxt
blanchet@36402
   842
    val (frees, hyp_ts, concl_t) = strip_subgoal goal i
blanchet@36402
   843
    val n = Logic.count_prems (prop_of goal)
blanchet@36223
   844
    val (one_line_proof, lemma_names) =
blanchet@36402
   845
      metis_proof_text (minimize_command, atp_proof, thm_names, goal, i)
blanchet@36283
   846
    fun isar_proof_for () =
blanchet@36474
   847
      case proof_from_atp_proof pool ctxt shrink_factor atp_proof thm_names
blanchet@36474
   848
                                frees
blanchet@36402
   849
           |> direct_proof thy conjecture_shape hyp_ts concl_t
blanchet@36402
   850
           |> kill_duplicate_assumptions_in_proof
blanchet@36402
   851
           |> then_chain_proof
blanchet@36402
   852
           |> kill_useless_labels_in_proof
blanchet@36402
   853
           |> relabel_proof
blanchet@36402
   854
           |> string_for_proof ctxt sorts i n of
blanchet@36283
   855
        "" => ""
blanchet@36402
   856
      | proof => "\nStructured proof:\n" ^ Markup.markup Markup.sendback proof
blanchet@35868
   857
    val isar_proof =
blanchet@36402
   858
      if debug then
blanchet@36283
   859
        isar_proof_for ()
blanchet@36283
   860
      else
blanchet@36283
   861
        try isar_proof_for ()
blanchet@36287
   862
        |> the_default "Warning: The Isar proof construction failed.\n"
blanchet@36283
   863
  in (one_line_proof ^ isar_proof, lemma_names) end
paulson@21978
   864
blanchet@36422
   865
fun proof_text isar_proof isar_params =
blanchet@36422
   866
  if isar_proof then isar_proof_text isar_params else metis_proof_text
blanchet@36223
   867
immler@31038
   868
end;