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