src/HOL/Tools/res_reconstruct.ML
author immler@in.tum.de
Sat Apr 04 20:22:39 2009 +0200 (2009-04-04)
changeset 30874 34927a1e0ae8
parent 30857 3fb9345721e4
child 31037 ac8669134e7a
permissions -rw-r--r--
reverted to explicitly check the presence of a refutation
(compare to 479a2fce65e6);
simplified handling of errors in remote script
wenzelm@29268
     1
(*  Author:     L C Paulson and Claire Quigley, Cambridge University Computer Laboratory *)
paulson@21978
     2
paulson@21978
     3
(***************************************************************************)
paulson@21979
     4
(*  Code to deal with the transfer of proofs from a prover process         *)
paulson@21978
     5
(***************************************************************************)
paulson@21978
     6
signature RES_RECONSTRUCT =
paulson@24425
     7
sig
paulson@25492
     8
  val chained_hint: string
wenzelm@28477
     9
paulson@24425
    10
  val fix_sorts: sort Vartab.table -> term -> term
paulson@24425
    11
  val invert_const: string -> string
paulson@24425
    12
  val invert_type_const: string -> string
paulson@24425
    13
  val num_typargs: Context.theory -> string -> int
paulson@24425
    14
  val make_tvar: string -> typ
paulson@24425
    15
  val strip_prefix: string -> string -> string option
paulson@25710
    16
  val setup: Context.theory -> Context.theory
wenzelm@28477
    17
  (* extracting lemma list*)
immler@30874
    18
  val find_failure: string -> string option
wenzelm@28477
    19
  val lemma_list_dfg: string * string vector * Proof.context * Thm.thm * int -> string
wenzelm@28477
    20
  val lemma_list_tstp: string * string vector * Proof.context * Thm.thm * int -> string
wenzelm@28477
    21
  (* structured proofs *)
wenzelm@28477
    22
  val structured_proof: string * string vector * Proof.context * Thm.thm * int -> string
paulson@24425
    23
end;
paulson@21978
    24
paulson@24425
    25
structure ResReconstruct : RES_RECONSTRUCT =
paulson@21978
    26
struct
paulson@21978
    27
paulson@21978
    28
val trace_path = Path.basic "atp_trace";
paulson@21978
    29
wenzelm@23139
    30
fun trace s = if !Output.debugging then File.append (File.tmp_path trace_path) s
paulson@21978
    31
              else ();
paulson@21978
    32
wenzelm@26928
    33
val string_of_thm = PrintMode.setmp [] Display.string_of_thm;
paulson@26333
    34
paulson@25710
    35
(*For generating structured proofs: keep every nth proof line*)
paulson@26333
    36
val (modulus, modulus_setup) = Attrib.config_int "sledgehammer_modulus" 1;
paulson@21978
    37
paulson@25710
    38
(*Indicates whether to include sort information in generated proofs*)
paulson@26333
    39
val (recon_sorts, recon_sorts_setup) = Attrib.config_bool "sledgehammer_sorts" true;
paulson@22491
    40
wenzelm@28477
    41
(*Indicated whether to generate full proofs or just lemma lists - now via setup of atps*)
wenzelm@28477
    42
(* val (full_proofs, full_proofs_setup) = Attrib.config_bool "sledgehammer_full" false; *)
paulson@26333
    43
wenzelm@28477
    44
val setup = modulus_setup #> recon_sorts_setup;
paulson@22044
    45
paulson@21978
    46
(**** PARSING OF TSTP FORMAT ****)
paulson@21978
    47
paulson@21978
    48
(*Syntax trees, either termlist or formulae*)
paulson@21978
    49
datatype stree = Int of int | Br of string * stree list;
paulson@21978
    50
paulson@21978
    51
fun atom x = Br(x,[]);
paulson@21978
    52
paulson@21978
    53
fun scons (x,y) = Br("cons", [x,y]);
wenzelm@30190
    54
val listof = List.foldl scons (atom "nil");
paulson@21978
    55
paulson@21978
    56
(*Strings enclosed in single quotes, e.g. filenames*)
paulson@21978
    57
val quoted = $$"'" |-- Scan.repeat (~$$"'") --| $$"'" >> implode;
paulson@21978
    58
paulson@21978
    59
(*Intended for $true and $false*)
paulson@21978
    60
fun tf s = "c_" ^ str (Char.toUpper (String.sub(s,0))) ^ String.extract(s,1,NONE);
paulson@21978
    61
val truefalse = $$"$" |-- Symbol.scan_id >> (atom o tf);
paulson@21978
    62
paulson@21978
    63
(*Integer constants, typically proof line numbers*)
paulson@21978
    64
fun is_digit s = Char.isDigit (String.sub(s,0));
paulson@21978
    65
val integer = Scan.many1 is_digit >> (valOf o Int.fromString o implode);
paulson@21978
    66
paulson@21978
    67
(*Generalized FO terms, which include filenames, numbers, etc.*)
wenzelm@25999
    68
fun termlist x = (term ::: Scan.repeat ($$"," |-- term)) x
paulson@21978
    69
and term x = (quoted >> atom || integer>>Int || truefalse ||
paulson@21978
    70
              Symbol.scan_id -- Scan.optional ($$"(" |-- termlist --| $$")") [] >> Br ||
paulson@21978
    71
              $$"(" |-- term --| $$")" ||
paulson@24547
    72
              $$"[" |-- Scan.optional termlist [] --| $$"]" >> listof) x;
paulson@21978
    73
paulson@21978
    74
fun negate t = Br("c_Not", [t]);
paulson@21978
    75
fun equate (t1,t2) = Br("c_equal", [t1,t2]);
paulson@21978
    76
paulson@21978
    77
(*Apply equal or not-equal to a term*)
paulson@21978
    78
fun syn_equal (t, NONE) = t
paulson@21978
    79
  | syn_equal (t1, SOME (NONE, t2)) = equate (t1,t2)
paulson@21978
    80
  | syn_equal (t1, SOME (SOME _, t2)) = negate (equate (t1,t2));
paulson@21978
    81
paulson@21978
    82
(*Literals can involve negation, = and !=.*)
paulson@24547
    83
fun literal x = ($$"~" |-- literal >> negate ||
paulson@24547
    84
                 (term -- Scan.option (Scan.option ($$"!") --| $$"=" -- term) >> syn_equal)) x;
paulson@21978
    85
wenzelm@25999
    86
val literals = literal ::: Scan.repeat ($$"|" |-- literal);
paulson@21978
    87
paulson@21978
    88
(*Clause: a list of literals separated by the disjunction sign*)
paulson@24547
    89
val clause = $$"(" |-- literals --| $$")" || Scan.single literal;
paulson@21978
    90
paulson@21978
    91
val annotations = $$"," |-- term -- Scan.option ($$"," |-- termlist);
paulson@21978
    92
wenzelm@25718
    93
(*<cnf_annotated> ::= cnf(<name>,<formula_role>,<cnf_formula><annotations>).
paulson@21978
    94
  The <name> could be an identifier, but we assume integers.*)
wenzelm@23139
    95
val tstp_line = (Scan.this_string "cnf" -- $$"(") |--
wenzelm@23139
    96
                integer --| $$"," -- Symbol.scan_id --| $$"," --
paulson@21978
    97
                clause -- Scan.option annotations --| $$ ")";
paulson@21978
    98
paulson@21978
    99
paulson@21978
   100
(**** INTERPRETATION OF TSTP SYNTAX TREES ****)
paulson@21978
   101
paulson@21978
   102
exception STREE of stree;
paulson@21978
   103
paulson@21978
   104
(*If string s has the prefix s1, return the result of deleting it.*)
wenzelm@23139
   105
fun strip_prefix s1 s =
paulson@24182
   106
  if String.isPrefix s1 s 
paulson@24182
   107
  then SOME (ResClause.undo_ascii_of (String.extract (s, size s1, NONE)))
paulson@21978
   108
  else NONE;
paulson@21978
   109
paulson@21978
   110
(*Invert the table of translations between Isabelle and ATPs*)
paulson@21978
   111
val type_const_trans_table_inv =
paulson@21978
   112
      Symtab.make (map swap (Symtab.dest ResClause.type_const_trans_table));
paulson@21978
   113
paulson@21978
   114
fun invert_type_const c =
paulson@21978
   115
    case Symtab.lookup type_const_trans_table_inv c of
paulson@21978
   116
        SOME c' => c'
paulson@21978
   117
      | NONE => c;
paulson@21978
   118
paulson@21978
   119
fun make_tvar b = TVar(("'" ^ b, 0), HOLogic.typeS);
paulson@21978
   120
fun make_var (b,T) = Var((b,0),T);
paulson@21978
   121
paulson@21978
   122
(*Type variables are given the basic sort, HOL.type. Some will later be constrained
paulson@21978
   123
  by information from type literals, or by type inference.*)
paulson@21978
   124
fun type_of_stree t =
paulson@21978
   125
  case t of
paulson@21978
   126
      Int _ => raise STREE t
wenzelm@23139
   127
    | Br (a,ts) =>
paulson@21978
   128
        let val Ts = map type_of_stree ts
wenzelm@23139
   129
        in
paulson@21978
   130
          case strip_prefix ResClause.tconst_prefix a of
paulson@21978
   131
              SOME b => Type(invert_type_const b, Ts)
wenzelm@23139
   132
            | NONE =>
paulson@21978
   133
                if not (null ts) then raise STREE t  (*only tconsts have type arguments*)
wenzelm@23139
   134
                else
paulson@21978
   135
                case strip_prefix ResClause.tfree_prefix a of
paulson@21978
   136
                    SOME b => TFree("'" ^ b, HOLogic.typeS)
wenzelm@23139
   137
                  | NONE =>
paulson@21978
   138
                case strip_prefix ResClause.tvar_prefix a of
paulson@21978
   139
                    SOME b => make_tvar b
paulson@21978
   140
                  | NONE => make_tvar a   (*Variable from the ATP, say X1*)
paulson@21978
   141
        end;
paulson@21978
   142
paulson@21978
   143
(*Invert the table of translations between Isabelle and ATPs*)
paulson@21978
   144
val const_trans_table_inv =
wenzelm@23139
   145
      Symtab.update ("fequal", "op =")
paulson@22731
   146
        (Symtab.make (map swap (Symtab.dest ResClause.const_trans_table)));
paulson@21978
   147
paulson@21978
   148
fun invert_const c =
paulson@21978
   149
    case Symtab.lookup const_trans_table_inv c of
paulson@21978
   150
        SOME c' => c'
paulson@21978
   151
      | NONE => c;
paulson@21978
   152
paulson@21978
   153
(*The number of type arguments of a constant, zero if it's monomorphic*)
paulson@21978
   154
fun num_typargs thy s = length (Sign.const_typargs thy (s, Sign.the_const_type thy s));
paulson@21978
   155
paulson@21978
   156
(*Generates a constant, given its type arguments*)
paulson@21978
   157
fun const_of thy (a,Ts) = Const(a, Sign.const_instance thy (a,Ts));
paulson@21978
   158
paulson@21978
   159
(*First-order translation. No types are known for variables. HOLogic.typeT should allow
paulson@21978
   160
  them to be inferred.*)
paulson@22428
   161
fun term_of_stree args thy t =
paulson@21978
   162
  case t of
paulson@21978
   163
      Int _ => raise STREE t
paulson@22428
   164
    | Br ("hBOOL",[t]) => term_of_stree [] thy t  (*ignore hBOOL*)
paulson@22428
   165
    | Br ("hAPP",[t,u]) => term_of_stree (u::args) thy t
wenzelm@23139
   166
    | Br (a,ts) =>
paulson@21978
   167
        case strip_prefix ResClause.const_prefix a of
wenzelm@23139
   168
            SOME "equal" =>
paulson@22731
   169
              list_comb(Const ("op =", HOLogic.typeT), List.map (term_of_stree [] thy) ts)
wenzelm@23139
   170
          | SOME b =>
paulson@21978
   171
              let val c = invert_const b
paulson@21978
   172
                  val nterms = length ts - num_typargs thy c
paulson@22428
   173
                  val us = List.map (term_of_stree [] thy) (List.take(ts,nterms) @ args)
paulson@22428
   174
                  (*Extra args from hAPP come AFTER any arguments given directly to the
paulson@22428
   175
                    constant.*)
paulson@21978
   176
                  val Ts = List.map type_of_stree (List.drop(ts,nterms))
paulson@21978
   177
              in  list_comb(const_of thy (c, Ts), us)  end
paulson@21978
   178
          | NONE => (*a variable, not a constant*)
paulson@21978
   179
              let val T = HOLogic.typeT
paulson@21978
   180
                  val opr = (*a Free variable is typically a Skolem function*)
paulson@21978
   181
                    case strip_prefix ResClause.fixed_var_prefix a of
paulson@21978
   182
                        SOME b => Free(b,T)
wenzelm@23139
   183
                      | NONE =>
paulson@21978
   184
                    case strip_prefix ResClause.schematic_var_prefix a of
paulson@21978
   185
                        SOME b => make_var (b,T)
paulson@21978
   186
                      | NONE => make_var (a,T)    (*Variable from the ATP, say X1*)
paulson@23519
   187
              in  list_comb (opr, List.map (term_of_stree [] thy) (ts@args))  end;
paulson@21978
   188
wenzelm@23139
   189
(*Type class literal applied to a type. Returns triple of polarity, class, type.*)
paulson@21978
   190
fun constraint_of_stree pol (Br("c_Not",[t])) = constraint_of_stree (not pol) t
paulson@21978
   191
  | constraint_of_stree pol t = case t of
paulson@21978
   192
        Int _ => raise STREE t
wenzelm@23139
   193
      | Br (a,ts) =>
paulson@21978
   194
            (case (strip_prefix ResClause.class_prefix a, map type_of_stree ts) of
paulson@21978
   195
                 (SOME b, [T]) => (pol, b, T)
paulson@21978
   196
               | _ => raise STREE t);
paulson@21978
   197
paulson@21978
   198
(** Accumulate type constraints in a clause: negative type literals **)
paulson@21978
   199
paulson@21978
   200
fun addix (key,z)  = Vartab.map_default (key,[]) (cons z);
paulson@21978
   201
paulson@21978
   202
fun add_constraint ((false, cl, TFree(a,_)), vt) = addix ((a,~1),cl) vt
paulson@21978
   203
  | add_constraint ((false, cl, TVar(ix,_)), vt) = addix (ix,cl) vt
paulson@21978
   204
  | add_constraint (_, vt) = vt;
paulson@21978
   205
paulson@21978
   206
(*False literals (which E includes in its proofs) are deleted*)
paulson@21978
   207
val nofalses = filter (not o equal HOLogic.false_const);
paulson@21978
   208
paulson@22491
   209
(*Final treatment of the list of "real" literals from a clause.*)
paulson@22491
   210
fun finish [] = HOLogic.true_const  (*No "real" literals means only type information*)
wenzelm@23139
   211
  | finish lits =
paulson@22491
   212
      case nofalses lits of
paulson@22491
   213
          [] => HOLogic.false_const  (*The empty clause, since we started with real literals*)
paulson@22491
   214
        | xs => foldr1 HOLogic.mk_disj (rev xs);
paulson@22491
   215
paulson@21978
   216
(*Accumulate sort constraints in vt, with "real" literals in lits.*)
paulson@22491
   217
fun lits_of_strees ctxt (vt, lits) [] = (vt, finish lits)
wenzelm@23139
   218
  | lits_of_strees ctxt (vt, lits) (t::ts) =
paulson@22012
   219
      lits_of_strees ctxt (add_constraint (constraint_of_stree true t, vt), lits) ts
wenzelm@23139
   220
      handle STREE _ =>
paulson@22428
   221
      lits_of_strees ctxt (vt, term_of_stree [] (ProofContext.theory_of ctxt) t :: lits) ts;
paulson@21978
   222
paulson@21978
   223
(*Update TVars/TFrees with detected sort constraints.*)
paulson@21978
   224
fun fix_sorts vt =
paulson@21978
   225
  let fun tysubst (Type (a, Ts)) = Type (a, map tysubst Ts)
paulson@21978
   226
        | tysubst (TVar (xi, s)) = TVar (xi, getOpt (Vartab.lookup vt xi, s))
paulson@21978
   227
        | tysubst (TFree (x, s)) = TFree (x, getOpt (Vartab.lookup vt (x,~1), s))
paulson@21978
   228
      fun tmsubst (Const (a, T)) = Const (a, tysubst T)
paulson@21978
   229
        | tmsubst (Free (a, T)) = Free (a, tysubst T)
paulson@21978
   230
        | tmsubst (Var (xi, T)) = Var (xi, tysubst T)
paulson@21978
   231
        | tmsubst (t as Bound _) = t
paulson@21978
   232
        | tmsubst (Abs (a, T, t)) = Abs (a, tysubst T, tmsubst t)
paulson@21978
   233
        | tmsubst (t $ u) = tmsubst t $ tmsubst u;
paulson@21978
   234
  in fn t => if Vartab.is_empty vt then t else tmsubst t end;
paulson@21978
   235
paulson@21978
   236
(*Interpret a list of syntax trees as a clause, given by "real" literals and sort constraints.
paulson@21978
   237
  vt0 holds the initial sort constraints, from the conjecture clauses.*)
paulson@23519
   238
fun clause_of_strees ctxt vt0 ts =
wenzelm@22728
   239
  let val (vt, dt) = lits_of_strees ctxt (vt0,[]) ts in
wenzelm@24680
   240
    singleton (Syntax.check_terms ctxt) (TypeInfer.constrain HOLogic.boolT (fix_sorts vt dt))
wenzelm@22728
   241
  end;
paulson@21978
   242
wenzelm@29268
   243
fun gen_all_vars t = fold_rev Logic.all (OldTerm.term_vars t) t;
paulson@21978
   244
paulson@21978
   245
fun ints_of_stree_aux (Int n, ns) = n::ns
wenzelm@30190
   246
  | ints_of_stree_aux (Br(_,ts), ns) = List.foldl ints_of_stree_aux ns ts;
paulson@21978
   247
paulson@21978
   248
fun ints_of_stree t = ints_of_stree_aux (t, []);
paulson@21978
   249
paulson@25086
   250
fun decode_tstp vt0 (name, role, ts, annots) ctxt =
paulson@21978
   251
  let val deps = case annots of NONE => [] | SOME (source,_) => ints_of_stree source
paulson@25086
   252
      val cl = clause_of_strees ctxt vt0 ts
wenzelm@29268
   253
  in  ((name, role, cl, deps), fold Variable.declare_term (OldTerm.term_frees cl) ctxt)  end;
paulson@21978
   254
paulson@21978
   255
fun dest_tstp ((((name, role), ts), annots), chs) =
paulson@21978
   256
  case chs of
paulson@21978
   257
          "."::_ => (name, role, ts, annots)
paulson@21978
   258
        | _ => error ("TSTP line not terminated by \".\": " ^ implode chs);
paulson@21978
   259
paulson@21978
   260
paulson@21978
   261
(** Global sort constraints on TFrees (from tfree_tcs) are positive unit clauses. **)
paulson@21978
   262
paulson@21978
   263
fun add_tfree_constraint ((true, cl, TFree(a,_)), vt) = addix ((a,~1),cl) vt
paulson@21978
   264
  | add_tfree_constraint (_, vt) = vt;
paulson@21978
   265
paulson@21978
   266
fun tfree_constraints_of_clauses vt [] = vt
wenzelm@23139
   267
  | tfree_constraints_of_clauses vt ([lit]::tss) =
paulson@21978
   268
      (tfree_constraints_of_clauses (add_tfree_constraint (constraint_of_stree true lit, vt)) tss
paulson@21978
   269
       handle STREE _ => (*not a positive type constraint: ignore*)
paulson@21978
   270
       tfree_constraints_of_clauses vt tss)
paulson@21978
   271
  | tfree_constraints_of_clauses vt (_::tss) = tfree_constraints_of_clauses vt tss;
paulson@21978
   272
paulson@21978
   273
paulson@21978
   274
(**** Translation of TSTP files to Isar Proofs ****)
paulson@21978
   275
paulson@22012
   276
fun decode_tstp_list ctxt tuples =
paulson@21978
   277
  let val vt0 = tfree_constraints_of_clauses Vartab.empty (map #3 tuples)
paulson@25086
   278
  in  #1 (fold_map (decode_tstp vt0) tuples ctxt) end;
paulson@21978
   279
paulson@23519
   280
(** Finding a matching assumption. The literals may be permuted, and variable names
paulson@23519
   281
    may disagree. We have to try all combinations of literals (quadratic!) and 
paulson@23519
   282
    match up the variable names consistently. **)
paulson@23519
   283
paulson@23519
   284
fun strip_alls_aux n (Const("all",_)$Abs(a,T,t))  =  
paulson@23519
   285
      strip_alls_aux (n+1) (subst_bound (Var ((a,n), T), t))
paulson@23519
   286
  | strip_alls_aux _ t  =  t;
paulson@23519
   287
paulson@23519
   288
val strip_alls = strip_alls_aux 0;
paulson@23519
   289
paulson@23519
   290
exception MATCH_LITERAL;
paulson@22012
   291
paulson@23519
   292
(*Ignore types: they are not to be trusted...*)
paulson@23519
   293
fun match_literal (t1$u1) (t2$u2) env =
paulson@23519
   294
      match_literal t1 t2 (match_literal u1 u2 env)
paulson@23519
   295
  | match_literal (Abs (_,_,t1)) (Abs (_,_,t2)) env = 
paulson@23519
   296
      match_literal t1 t2 env
paulson@23519
   297
  | match_literal (Bound i1) (Bound i2) env = 
paulson@23519
   298
      if i1=i2 then env else raise MATCH_LITERAL
paulson@23519
   299
  | match_literal (Const(a1,_)) (Const(a2,_)) env = 
paulson@23519
   300
      if a1=a2 then env else raise MATCH_LITERAL
paulson@23519
   301
  | match_literal (Free(a1,_)) (Free(a2,_)) env = 
paulson@23519
   302
      if a1=a2 then env else raise MATCH_LITERAL
paulson@23519
   303
  | match_literal (Var(ix1,_)) (Var(ix2,_)) env = insert (op =) (ix1,ix2) env
paulson@23519
   304
  | match_literal _ _ env = raise MATCH_LITERAL;
paulson@23519
   305
paulson@23519
   306
(*Checking that all variable associations are unique. The list env contains no
paulson@23519
   307
  repetitions, but does it contain say (x,y) and (y,y)? *)
paulson@23519
   308
fun good env = 
paulson@23519
   309
  let val (xs,ys) = ListPair.unzip env
paulson@23519
   310
  in  not (has_duplicates (op=) xs orelse has_duplicates (op=) ys)  end;
paulson@23519
   311
paulson@23519
   312
(*Match one list of literals against another, ignoring types and the order of
paulson@23519
   313
  literals. Sorting is unreliable because we don't have types or variable names.*)
paulson@23519
   314
fun matches_aux _ [] [] = true
paulson@23519
   315
  | matches_aux env (lit::lits) ts =
paulson@23519
   316
      let fun match1 us [] = false
paulson@23519
   317
            | match1 us (t::ts) =
paulson@23519
   318
                let val env' = match_literal lit t env
paulson@23519
   319
                in  (good env' andalso matches_aux env' lits (us@ts)) orelse 
paulson@23519
   320
                    match1 (t::us) ts  
paulson@23519
   321
                end
paulson@23519
   322
                handle MATCH_LITERAL => match1 (t::us) ts
paulson@23519
   323
      in  match1 [] ts  end; 
paulson@23519
   324
paulson@23519
   325
(*Is this length test useful?*)
paulson@23519
   326
fun matches (lits1,lits2) = 
paulson@23519
   327
  length lits1 = length lits2  andalso  
paulson@23519
   328
  matches_aux [] (map Envir.eta_contract lits1) (map Envir.eta_contract lits2);
paulson@21999
   329
paulson@21999
   330
fun permuted_clause t =
paulson@24958
   331
  let val lits = HOLogic.disjuncts t
paulson@21999
   332
      fun perm [] = NONE
wenzelm@23139
   333
        | perm (ctm::ctms) =
paulson@24958
   334
            if matches (lits, HOLogic.disjuncts (HOLogic.dest_Trueprop (strip_alls ctm)))
paulson@23519
   335
            then SOME ctm else perm ctms
paulson@21999
   336
  in perm end;
paulson@21999
   337
paulson@22470
   338
fun have_or_show "show " lname = "show \""
paulson@22470
   339
  | have_or_show have lname = have ^ lname ^ ": \""
paulson@22470
   340
paulson@21999
   341
(*ctms is a list of conjecture clauses as yielded by Isabelle. Those returned by the
paulson@21999
   342
  ATP may have their literals reordered.*)
paulson@21999
   343
fun isar_lines ctxt ctms =
wenzelm@28572
   344
  let val string_of = PrintMode.setmp [] (fn term => Syntax.string_of_term ctxt term)
paulson@26333
   345
      val _ = trace ("\n\nisar_lines: start\n")
paulson@22470
   346
      fun doline have (lname, t, []) =  (*No deps: it's a conjecture clause, with no proof.*)
paulson@21999
   347
           (case permuted_clause t ctms of
paulson@21999
   348
                SOME u => "assume " ^ lname ^ ": \"" ^ string_of u ^ "\"\n"
paulson@21999
   349
              | NONE => "assume? " ^ lname ^ ": \"" ^ string_of t ^ "\"\n")  (*no match!!*)
paulson@22470
   350
        | doline have (lname, t, deps) =
paulson@23519
   351
            have_or_show have lname ^ string_of (gen_all_vars (HOLogic.mk_Trueprop t)) ^
paulson@22372
   352
            "\"\n  by (metis " ^ space_implode " " deps ^ ")\n"
paulson@21978
   353
      fun dolines [(lname, t, deps)] = [doline "show " (lname, t, deps)]
paulson@21978
   354
        | dolines ((lname, t, deps)::lines) = doline "have " (lname, t, deps) :: dolines lines
paulson@25710
   355
  in setmp show_sorts (Config.get ctxt recon_sorts) dolines end;
paulson@21978
   356
paulson@21978
   357
fun notequal t (_,t',_) = not (t aconv t');
paulson@21978
   358
paulson@22491
   359
(*No "real" literals means only type information*)
paulson@23519
   360
fun eq_types t = t aconv HOLogic.true_const;
paulson@21978
   361
paulson@22731
   362
fun replace_dep (old:int, new) dep = if dep=old then new else [dep];
paulson@21978
   363
wenzelm@23139
   364
fun replace_deps (old:int, new) (lno, t, deps) =
wenzelm@30190
   365
      (lno, t, List.foldl (op union_int) [] (map (replace_dep (old, new)) deps));
paulson@21978
   366
paulson@22491
   367
(*Discard axioms; consolidate adjacent lines that prove the same clause, since they differ
paulson@22491
   368
  only in type information.*)
paulson@21978
   369
fun add_prfline ((lno, "axiom", t, []), lines) =  (*axioms are not proof lines*)
paulson@22491
   370
      if eq_types t (*must be clsrel/clsarity: type information, so delete refs to it*)
wenzelm@23139
   371
      then map (replace_deps (lno, [])) lines
paulson@22470
   372
      else
paulson@22470
   373
       (case take_prefix (notequal t) lines of
paulson@22470
   374
           (_,[]) => lines                  (*no repetition of proof line*)
paulson@22470
   375
         | (pre, (lno',t',deps')::post) =>  (*repetition: replace later line by earlier one*)
paulson@22470
   376
             pre @ map (replace_deps (lno', [lno])) post)
paulson@21978
   377
  | add_prfline ((lno, role, t, []), lines) =  (*no deps: conjecture clause*)
paulson@22470
   378
      (lno, t, []) :: lines
paulson@21978
   379
  | add_prfline ((lno, role, t, deps), lines) =
paulson@22491
   380
      if eq_types t then (lno, t, deps) :: lines
paulson@22491
   381
      (*Type information will be deleted later; skip repetition test.*)
paulson@22491
   382
      else (*FIXME: Doesn't this code risk conflating proofs involving different types??*)
paulson@22044
   383
      case take_prefix (notequal t) lines of
paulson@22044
   384
         (_,[]) => (lno, t, deps) :: lines  (*no repetition of proof line*)
wenzelm@23139
   385
       | (pre, (lno',t',deps')::post) =>
paulson@22044
   386
           (lno, t', deps) ::               (*repetition: replace later line by earlier one*)
paulson@22044
   387
           (pre @ map (replace_deps (lno', [lno])) post);
paulson@22044
   388
paulson@22470
   389
(*Recursively delete empty lines (type information) from the proof.*)
paulson@22470
   390
fun add_nonnull_prfline ((lno, t, []), lines) = (*no dependencies, so a conjecture clause*)
paulson@22491
   391
     if eq_types t (*must be type information, tfree_tcs, clsrel, clsarity: delete refs to it*)
wenzelm@23139
   392
     then delete_dep lno lines
wenzelm@23139
   393
     else (lno, t, []) :: lines
paulson@22470
   394
  | add_nonnull_prfline ((lno, t, deps), lines) = (lno, t, deps) :: lines
wenzelm@30190
   395
and delete_dep lno lines = List.foldr add_nonnull_prfline [] (map (replace_deps (lno, [])) lines);
paulson@22470
   396
paulson@24937
   397
fun bad_free (Free (a,_)) = String.isPrefix "sko_" a
paulson@22731
   398
  | bad_free _ = false;
paulson@22731
   399
wenzelm@23139
   400
(*TVars are forbidden in goals. Also, we don't want lines with <2 dependencies.
paulson@22491
   401
  To further compress proofs, setting modulus:=n deletes every nth line, and nlines
paulson@22491
   402
  counts the number of proof lines processed so far.
paulson@22491
   403
  Deleted lines are replaced by their own dependencies. Note that the "add_nonnull_prfline"
paulson@22044
   404
  phase may delete some dependencies, hence this phase comes later.*)
paulson@25710
   405
fun add_wanted_prfline ctxt ((lno, t, []), (nlines, lines)) =
paulson@22491
   406
      (nlines, (lno, t, []) :: lines)   (*conjecture clauses must be kept*)
paulson@25710
   407
  | add_wanted_prfline ctxt ((lno, t, deps), (nlines, lines)) =
wenzelm@29272
   408
      if eq_types t orelse not (null (Term.add_tvars t [])) orelse
wenzelm@29268
   409
         exists_subterm bad_free t orelse
paulson@24937
   410
         (not (null lines) andalso   (*final line can't be deleted for these reasons*)
paulson@25710
   411
          (length deps < 2 orelse nlines mod (Config.get ctxt modulus) <> 0))   
paulson@22491
   412
      then (nlines+1, map (replace_deps (lno, deps)) lines) (*Delete line*)
paulson@22491
   413
      else (nlines+1, (lno, t, deps) :: lines);
paulson@21978
   414
paulson@21999
   415
(*Replace numeric proof lines by strings, either from thm_names or sequential line numbers*)
paulson@21978
   416
fun stringify_deps thm_names deps_map [] = []
paulson@21978
   417
  | stringify_deps thm_names deps_map ((lno, t, deps) :: lines) =
paulson@21978
   418
      if lno <= Vector.length thm_names  (*axiom*)
wenzelm@23139
   419
      then (Vector.sub(thm_names,lno-1), t, []) :: stringify_deps thm_names deps_map lines
paulson@21979
   420
      else let val lname = Int.toString (length deps_map)
wenzelm@23139
   421
               fun fix lno = if lno <= Vector.length thm_names
paulson@21978
   422
                             then SOME(Vector.sub(thm_names,lno-1))
paulson@21978
   423
                             else AList.lookup op= deps_map lno;
paulson@22731
   424
           in  (lname, t, List.mapPartial fix (distinct (op=) deps)) ::
paulson@21978
   425
               stringify_deps thm_names ((lno,lname)::deps_map) lines
paulson@21978
   426
           end;
paulson@21978
   427
paulson@24547
   428
val proofstart = "proof (neg_clausify)\n";
paulson@21979
   429
paulson@21979
   430
fun isar_header [] = proofstart
paulson@21999
   431
  | isar_header ts = proofstart ^ "fix " ^ space_implode " " ts ^ "\n";
paulson@21979
   432
paulson@22012
   433
fun decode_tstp_file cnfs ctxt th sgno thm_names =
paulson@26333
   434
  let val _ = trace "\ndecode_tstp_file: start\n"
paulson@26333
   435
      val tuples = map (dest_tstp o tstp_line o explode) cnfs
paulson@26333
   436
      val _ = trace (Int.toString (length tuples) ^ " tuples extracted\n")
paulson@24552
   437
      val ctxt = ProofContext.set_mode ProofContext.mode_schematic ctxt
wenzelm@30190
   438
      val raw_lines = List.foldr add_prfline [] (decode_tstp_list ctxt tuples)
paulson@26333
   439
      val _ = trace (Int.toString (length raw_lines) ^ " raw_lines extracted\n")
wenzelm@30190
   440
      val nonnull_lines = List.foldr add_nonnull_prfline [] raw_lines
paulson@26333
   441
      val _ = trace (Int.toString (length nonnull_lines) ^ " nonnull_lines extracted\n")
wenzelm@30190
   442
      val (_,lines) = List.foldr (add_wanted_prfline ctxt) (0,[]) nonnull_lines
paulson@26333
   443
      val _ = trace (Int.toString (length lines) ^ " lines extracted\n")
paulson@21999
   444
      val (ccls,fixes) = ResAxioms.neg_conjecture_clauses th sgno
paulson@26333
   445
      val _ = trace (Int.toString (length ccls) ^ " conjecture clauses\n")
paulson@21999
   446
      val ccls = map forall_intr_vars ccls
paulson@26333
   447
      val _ = if !Output.debugging then app (fn th => trace ("\nccl: " ^ string_of_thm th)) ccls
paulson@26333
   448
              else ()
paulson@26333
   449
      val ilines = isar_lines ctxt (map prop_of ccls) (stringify_deps thm_names [] lines)
paulson@26333
   450
      val _ = trace "\ndecode_tstp_file: finishing\n"
wenzelm@23139
   451
  in
paulson@26333
   452
    isar_header (map #1 fixes) ^ String.concat ilines ^ "qed\n"
paulson@24547
   453
  end
paulson@24547
   454
  handle e => (*FIXME: exn handler is too general!*)
paulson@26333
   455
    let val msg = "Translation of TSTP raised an exception: " ^ Toplevel.exn_message e
paulson@26333
   456
    in  trace msg; msg  end;
paulson@21978
   457
paulson@21978
   458
wenzelm@28477
   459
    
wenzelm@28477
   460
  (* ==== CHECK IF PROOF OF E OR VAMPIRE WAS SUCCESSFUL === *)
wenzelm@28477
   461
  
immler@30874
   462
  val failure_strings_E = ["SZS status: Satisfiable","SZS status Satisfiable",
immler@30874
   463
    "SZS status: ResourceOut","SZS status ResourceOut","# Cannot determine problem status"];
wenzelm@28477
   464
  val failure_strings_vampire = ["Satisfiability detected", "Refutation not found", "CANNOT PROVE"];
immler@30874
   465
  val failure_strings_SPASS = ["SPASS beiseite: Completion found.",
immler@30874
   466
    "SPASS beiseite: Ran out of time.", "SPASS beiseite: Maximal number of loops exceeded."];
immler@30874
   467
  val failure_strings_remote = ["Remote-script could not extract proof"];
immler@30874
   468
  fun find_failure proof =
immler@29597
   469
    let val failures =
immler@29597
   470
      map_filter (fn s => if String.isSubstring s proof then SOME s else NONE) 
immler@30874
   471
         (failure_strings_E @ failure_strings_vampire @ failure_strings_SPASS @ failure_strings_remote)
immler@29597
   472
    in if null failures then NONE else SOME (hd failures) end;
immler@29597
   473
    
wenzelm@28477
   474
  (*=== EXTRACTING PROOF-TEXT === *)
wenzelm@28477
   475
  
wenzelm@28477
   476
  val begin_proof_strings = ["# SZS output start CNFRefutation.",
wenzelm@28477
   477
      "=========== Refutation ==========",
wenzelm@28477
   478
  "Here is a proof"];
wenzelm@28477
   479
  val end_proof_strings = ["# SZS output end CNFRefutation",
wenzelm@28477
   480
      "======= End of refutation =======",
wenzelm@28477
   481
  "Formulae used in the proof"];
wenzelm@28477
   482
  fun get_proof_extract proof =
wenzelm@28477
   483
    let
wenzelm@28477
   484
    (*splits to_split by the first possible of a list of splitters*)                        
wenzelm@28477
   485
    fun first_field_any [] to_split = NONE
wenzelm@28477
   486
      | first_field_any (splitter::splitters) to_split =
wenzelm@28477
   487
      let
wenzelm@28477
   488
      val result = (first_field splitter to_split)
wenzelm@28477
   489
      in
wenzelm@28477
   490
        if isSome result then result else first_field_any splitters to_split
wenzelm@28477
   491
      end
wenzelm@28477
   492
    val (a:string, b:string) = valOf (first_field_any begin_proof_strings proof)
wenzelm@28477
   493
    val (proofextract:string, c:string) = valOf (first_field_any end_proof_strings b)
wenzelm@28477
   494
    in proofextract end;
wenzelm@28477
   495
  
wenzelm@28477
   496
  (* === EXTRACTING LEMMAS === *)    
wenzelm@28477
   497
  (* lines have the form "cnf(108, axiom, ...",
wenzelm@28477
   498
  the number (108) has to be extracted)*)
wenzelm@28477
   499
  fun get_step_nums_tstp proofextract = 
wenzelm@28477
   500
    let val toks = String.tokens (not o Char.isAlphaNum)
wenzelm@28477
   501
    fun inputno ("cnf"::ntok::"axiom"::_) = Int.fromString ntok
wenzelm@28477
   502
      | inputno _ = NONE
wenzelm@28477
   503
    val lines = split_lines proofextract
wenzelm@28477
   504
    in  List.mapPartial (inputno o toks) lines  end
wenzelm@28477
   505
    
wenzelm@28477
   506
    (*String contains multiple lines. We want those of the form
wenzelm@28477
   507
    "253[0:Inp] et cetera..."
wenzelm@28477
   508
    A list consisting of the first number in each line is returned. *)
wenzelm@28477
   509
  fun get_step_nums_dfg proofextract =
wenzelm@28477
   510
    let val toks = String.tokens (not o Char.isAlphaNum)
wenzelm@28477
   511
    fun inputno (ntok::"0"::"Inp"::_) = Int.fromString ntok
wenzelm@28477
   512
      | inputno _ = NONE
wenzelm@28477
   513
    val lines = split_lines proofextract
wenzelm@28477
   514
    in  List.mapPartial (inputno o toks) lines  end
wenzelm@28477
   515
    
wenzelm@28477
   516
  (*extracting lemmas from tstp-output between the lines from above*)                         
wenzelm@28477
   517
  fun extract_lemmas get_step_nums (proof, thm_names, _, _, _) = 
wenzelm@28477
   518
    let
wenzelm@28477
   519
    (* get the names of axioms from their numbers*)
wenzelm@28477
   520
    fun get_axiom_names thm_names step_nums =
wenzelm@28477
   521
      let
wenzelm@28477
   522
      fun is_axiom n = n <= Vector.length thm_names
wenzelm@28477
   523
      fun getname i = Vector.sub(thm_names, i-1)
wenzelm@28477
   524
      in 
wenzelm@28477
   525
        sort_distinct string_ord (filter (fn x => x <> "??.unknown") (map getname (filter is_axiom step_nums)))
wenzelm@28477
   526
      end
wenzelm@28477
   527
    val proofextract = get_proof_extract proof
wenzelm@28477
   528
    in 
wenzelm@28477
   529
      get_axiom_names thm_names (get_step_nums proofextract)
wenzelm@28477
   530
    end;
wenzelm@28477
   531
    
wenzelm@28477
   532
    (* metis-command *)
wenzelm@28477
   533
    fun metis_line [] = "apply metis"
wenzelm@28477
   534
      | metis_line xs = "apply (metis " ^ space_implode " " xs ^ ")"
wenzelm@28477
   535
    
wenzelm@28477
   536
    (*Used to label theorems chained into the sledgehammer call*)
wenzelm@28477
   537
    val chained_hint = "CHAINED";
wenzelm@28477
   538
    fun sendback_metis_nochained lemmas = 
wenzelm@28477
   539
      let val nochained = filter_out (fn y => y = chained_hint)
wenzelm@28477
   540
      in (Markup.markup Markup.sendback o metis_line) (nochained lemmas) end
wenzelm@28477
   541
    fun lemma_list_tstp result = sendback_metis_nochained (extract_lemmas get_step_nums_tstp result);
wenzelm@28477
   542
    fun lemma_list_dfg result = sendback_metis_nochained (extract_lemmas get_step_nums_dfg result);
wenzelm@28477
   543
           
wenzelm@28477
   544
    (* === Extracting structured Isar-proof === *)
wenzelm@28477
   545
    fun structured_proof (result as (proof, thm_names, ctxt, goal, subgoalno)) = 
wenzelm@28477
   546
      let
wenzelm@28477
   547
      (*Could use split_lines, but it can return blank lines...*)
wenzelm@28477
   548
      val lines = String.tokens (equal #"\n");
wenzelm@28477
   549
      val nospaces = String.translate (fn c => if Char.isSpace c then "" else str c)
wenzelm@28477
   550
      val proofextract = get_proof_extract proof
paulson@26333
   551
      val cnfs = filter (String.isPrefix "cnf(") (map nospaces (lines proofextract))
wenzelm@28477
   552
      val one_line_proof = lemma_list_tstp result
wenzelm@28477
   553
      val structured = if chained_hint mem_string (String.tokens (fn c => c = #" ") one_line_proof) then ""
wenzelm@28477
   554
                  else decode_tstp_file cnfs ctxt goal subgoalno thm_names
wenzelm@28477
   555
      in
wenzelm@28477
   556
      one_line_proof ^ "\n\n" ^ (Markup.markup Markup.sendback) structured
wenzelm@28477
   557
    end
paulson@21978
   558
wenzelm@28477
   559
 end;