src/Pure/tctical.ML
author wenzelm
Sat Mar 04 13:18:43 2000 +0100 (2000-03-04)
changeset 8341 8f0f0ae02b10
parent 8149 941afb897532
child 8366 a70c56d821c7
permissions -rw-r--r--
added REPEAT_ALL_NEW;
paulson@2244
     1
(*  Title:      tctical
clasohm@0
     2
    ID:         $Id$
paulson@2244
     3
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
clasohm@0
     4
    Copyright   1993  University of Cambridge
clasohm@0
     5
clasohm@0
     6
Tacticals
clasohm@0
     7
*)
clasohm@0
     8
wenzelm@4602
     9
infix 1 THEN THEN' THEN_ALL_NEW;
clasohm@0
    10
infix 0 ORELSE APPEND INTLEAVE ORELSE' APPEND' INTLEAVE';
lcp@671
    11
infix 0 THEN_ELSE;
lcp@671
    12
clasohm@0
    13
clasohm@0
    14
signature TACTICAL =
clasohm@0
    15
  sig
wenzelm@4270
    16
  type tactic  (* = thm -> thm Seq.seq*)
paulson@2244
    17
  val all_tac           : tactic
paulson@2244
    18
  val ALLGOALS          : (int -> tactic) -> tactic   
paulson@2244
    19
  val APPEND            : tactic * tactic -> tactic
paulson@2244
    20
  val APPEND'           : ('a -> tactic) * ('a -> tactic) -> 'a -> tactic
paulson@2244
    21
  val CHANGED           : tactic -> tactic
paulson@5141
    22
  val CHANGED_GOAL	: (int -> tactic) -> int -> tactic
paulson@2244
    23
  val COND              : (thm -> bool) -> tactic -> tactic -> tactic   
paulson@2244
    24
  val DETERM            : tactic -> tactic
paulson@2244
    25
  val EVERY             : tactic list -> tactic   
paulson@2244
    26
  val EVERY'            : ('a -> tactic) list -> 'a -> tactic
paulson@2244
    27
  val EVERY1            : (int -> tactic) list -> tactic
paulson@2244
    28
  val FILTER            : (thm -> bool) -> tactic -> tactic
paulson@2244
    29
  val FIRST             : tactic list -> tactic   
paulson@2244
    30
  val FIRST'            : ('a -> tactic) list -> 'a -> tactic
paulson@2244
    31
  val FIRST1            : (int -> tactic) list -> tactic
paulson@2244
    32
  val FIRSTGOAL         : (int -> tactic) -> tactic
paulson@2244
    33
  val goals_limit       : int ref
paulson@2244
    34
  val INTLEAVE          : tactic * tactic -> tactic
paulson@2244
    35
  val INTLEAVE'         : ('a -> tactic) * ('a -> tactic) -> 'a -> tactic
paulson@2244
    36
  val METAHYPS          : (thm list -> tactic) -> int -> tactic
paulson@2244
    37
  val no_tac            : tactic
paulson@2244
    38
  val ORELSE            : tactic * tactic -> tactic
paulson@2244
    39
  val ORELSE'           : ('a -> tactic) * ('a -> tactic) -> 'a -> tactic
paulson@2244
    40
  val pause_tac         : tactic
paulson@6041
    41
  val print_tac         : string -> tactic
paulson@2244
    42
  val REPEAT            : tactic -> tactic
paulson@2244
    43
  val REPEAT1           : tactic -> tactic
oheimb@8149
    44
  val REPEAT_FIRST      : (int -> tactic) -> tactic
oheimb@8149
    45
  val REPEAT_SOME       : (int -> tactic) -> tactic
paulson@2244
    46
  val REPEAT_DETERM_N   : int -> tactic -> tactic
paulson@2244
    47
  val REPEAT_DETERM     : tactic -> tactic
paulson@2244
    48
  val REPEAT_DETERM1    : tactic -> tactic
lcp@703
    49
  val REPEAT_DETERM_FIRST: (int -> tactic) -> tactic
lcp@703
    50
  val REPEAT_DETERM_SOME: (int -> tactic) -> tactic
oheimb@8149
    51
  val DETERM_UNTIL      : (thm -> bool) -> tactic -> tactic
paulson@2244
    52
  val SELECT_GOAL       : tactic -> int -> tactic
paulson@2244
    53
  val SOMEGOAL          : (int -> tactic) -> tactic   
paulson@2244
    54
  val strip_context     : term -> (string * typ) list * term list * term
paulson@2244
    55
  val SUBGOAL           : ((term*int) -> tactic) -> int -> tactic
paulson@2244
    56
  val suppress_tracing  : bool ref
paulson@2244
    57
  val THEN              : tactic * tactic -> tactic
paulson@2244
    58
  val THEN'             : ('a -> tactic) * ('a -> tactic) -> 'a -> tactic
wenzelm@4602
    59
  val THEN_ALL_NEW	: (int -> tactic) * (int -> tactic) -> int -> tactic
wenzelm@8341
    60
  val REPEAT_ALL_NEW	: (int -> tactic) -> int -> tactic
paulson@2244
    61
  val THEN_ELSE         : tactic * (tactic*tactic) -> tactic
wenzelm@4270
    62
  val traced_tac        : (thm -> (thm * thm Seq.seq) option) -> tactic
paulson@5141
    63
  val tracify           : bool ref -> tactic -> tactic
paulson@2244
    64
  val trace_REPEAT      : bool ref
paulson@2244
    65
  val TRY               : tactic -> tactic
paulson@2244
    66
  val TRYALL            : (int -> tactic) -> tactic   
clasohm@0
    67
  end;
clasohm@0
    68
clasohm@0
    69
paulson@1502
    70
structure Tactical : TACTICAL = 
clasohm@0
    71
struct
clasohm@0
    72
clasohm@0
    73
(**** Tactics ****)
clasohm@0
    74
clasohm@0
    75
(*A tactic maps a proof tree to a sequence of proof trees:
clasohm@0
    76
    if length of sequence = 0 then the tactic does not apply;
clasohm@0
    77
    if length > 1 then backtracking on the alternatives can occur.*)
clasohm@0
    78
wenzelm@4270
    79
type tactic = thm -> thm Seq.seq;
clasohm@0
    80
clasohm@0
    81
clasohm@0
    82
(*** LCF-style tacticals ***)
clasohm@0
    83
clasohm@0
    84
(*the tactical THEN performs one tactic followed by another*)
wenzelm@4270
    85
fun (tac1 THEN tac2) st = Seq.flat (Seq.map tac2 (tac1 st));
clasohm@0
    86
clasohm@0
    87
clasohm@0
    88
(*The tactical ORELSE uses the first tactic that returns a nonempty sequence.
clasohm@0
    89
  Like in LCF, ORELSE commits to either tac1 or tac2 immediately.
clasohm@0
    90
  Does not backtrack to tac2 if tac1 was initially chosen. *)
paulson@1502
    91
fun (tac1 ORELSE tac2) st =
wenzelm@4270
    92
    case Seq.pull(tac1 st) of
paulson@2244
    93
        None       => tac2 st
wenzelm@4270
    94
      | sequencecell => Seq.make(fn()=> sequencecell);
clasohm@0
    95
clasohm@0
    96
clasohm@0
    97
(*The tactical APPEND combines the results of two tactics.
clasohm@0
    98
  Like ORELSE, but allows backtracking on both tac1 and tac2.
clasohm@0
    99
  The tactic tac2 is not applied until needed.*)
paulson@1502
   100
fun (tac1 APPEND tac2) st = 
wenzelm@4270
   101
  Seq.append(tac1 st,
wenzelm@4270
   102
                  Seq.make(fn()=> Seq.pull (tac2 st)));
clasohm@0
   103
clasohm@0
   104
(*Like APPEND, but interleaves results of tac1 and tac2.*)
paulson@1502
   105
fun (tac1 INTLEAVE tac2) st = 
wenzelm@4270
   106
    Seq.interleave(tac1 st,
wenzelm@4270
   107
                        Seq.make(fn()=> Seq.pull (tac2 st)));
clasohm@0
   108
lcp@671
   109
(*Conditional tactic.
paulson@2244
   110
        tac1 ORELSE tac2 = tac1 THEN_ELSE (all_tac, tac2)
paulson@2244
   111
        tac1 THEN tac2   = tac1 THEN_ELSE (tac2, no_tac)
lcp@671
   112
*)
paulson@1502
   113
fun (tac THEN_ELSE (tac1, tac2)) st = 
wenzelm@4270
   114
    case Seq.pull(tac st) of
paulson@2244
   115
        None    => tac2 st              (*failed; try tactic 2*)
wenzelm@4270
   116
      | seqcell => Seq.flat       (*succeeded; use tactic 1*)
wenzelm@4270
   117
                    (Seq.map tac1 (Seq.make(fn()=> seqcell)));
lcp@671
   118
lcp@671
   119
clasohm@0
   120
(*Versions for combining tactic-valued functions, as in
clasohm@0
   121
     SOMEGOAL (resolve_tac rls THEN' assume_tac) *)
paulson@1502
   122
fun (tac1 THEN' tac2) x = tac1 x THEN tac2 x;
paulson@1502
   123
fun (tac1 ORELSE' tac2) x = tac1 x ORELSE tac2 x;
paulson@1502
   124
fun (tac1 APPEND' tac2) x = tac1 x APPEND tac2 x;
paulson@1502
   125
fun (tac1 INTLEAVE' tac2) x = tac1 x INTLEAVE tac2 x;
clasohm@0
   126
clasohm@0
   127
(*passes all proofs through unchanged;  identity of THEN*)
wenzelm@4270
   128
fun all_tac st = Seq.single st;
clasohm@0
   129
clasohm@0
   130
(*passes no proofs through;  identity of ORELSE and APPEND*)
wenzelm@4270
   131
fun no_tac st  = Seq.empty;
clasohm@0
   132
clasohm@0
   133
clasohm@0
   134
(*Make a tactic deterministic by chopping the tail of the proof sequence*)
paulson@1502
   135
fun DETERM tac st =  
wenzelm@4270
   136
      case Seq.pull (tac st) of
wenzelm@4270
   137
              None => Seq.empty
wenzelm@4270
   138
            | Some(x,_) => Seq.cons(x, Seq.empty);
clasohm@0
   139
clasohm@0
   140
clasohm@0
   141
(*Conditional tactical: testfun controls which tactic to use next.
clasohm@0
   142
  Beware: due to eager evaluation, both thentac and elsetac are evaluated.*)
paulson@1502
   143
fun COND testfun thenf elsef = (fn prf =>
clasohm@0
   144
    if testfun prf then  thenf prf   else  elsef prf);
clasohm@0
   145
clasohm@0
   146
(*Do the tactic or else do nothing*)
clasohm@0
   147
fun TRY tac = tac ORELSE all_tac;
clasohm@0
   148
paulson@2672
   149
(*** List-oriented tactics ***)
paulson@2672
   150
paulson@2672
   151
local
paulson@2672
   152
  (*This version of EVERY avoids backtracking over repeated states*)
paulson@2672
   153
paulson@2672
   154
  fun EVY (trail, []) st = 
wenzelm@4270
   155
	Seq.make (fn()=> Some(st, 
wenzelm@4270
   156
			Seq.make (fn()=> Seq.pull (evyBack trail))))
paulson@2672
   157
    | EVY (trail, tac::tacs) st = 
wenzelm@4270
   158
	  case Seq.pull(tac st) of
paulson@2672
   159
	      None    => evyBack trail              (*failed: backtrack*)
paulson@2672
   160
	    | Some(st',q) => EVY ((st',q,tacs)::trail, tacs) st'
wenzelm@4270
   161
  and evyBack [] = Seq.empty (*no alternatives*)
paulson@2672
   162
    | evyBack ((st',q,tacs)::trail) =
wenzelm@4270
   163
	  case Seq.pull q of
paulson@2672
   164
	      None        => evyBack trail
paulson@2672
   165
	    | Some(st,q') => if eq_thm (st',st) 
paulson@2672
   166
			     then evyBack ((st',q',tacs)::trail)
paulson@2672
   167
			     else EVY ((st,q',tacs)::trail, tacs) st
paulson@2672
   168
in
paulson@2672
   169
paulson@2672
   170
(* EVERY [tac1,...,tacn]   equals    tac1 THEN ... THEN tacn   *)
paulson@2672
   171
fun EVERY tacs = EVY ([], tacs);
paulson@2672
   172
end;
oheimb@2627
   173
clasohm@0
   174
paulson@1502
   175
(* EVERY' [tac1,...,tacn] i  equals    tac1 i THEN ... THEN tacn i   *)
paulson@2672
   176
fun EVERY' tacs i = EVERY (map (fn f => f i) tacs);
clasohm@0
   177
clasohm@0
   178
(*Apply every tactic to 1*)
paulson@1502
   179
fun EVERY1 tacs = EVERY' tacs 1;
clasohm@0
   180
clasohm@0
   181
(* FIRST [tac1,...,tacn]   equals    tac1 ORELSE ... ORELSE tacn   *)
clasohm@0
   182
fun FIRST tacs = foldr (op ORELSE) (tacs, no_tac);
clasohm@0
   183
paulson@1502
   184
(* FIRST' [tac1,...,tacn] i  equals    tac1 i ORELSE ... ORELSE tacn i   *)
paulson@1502
   185
fun FIRST' tacs = foldr (op ORELSE') (tacs, K no_tac);
clasohm@0
   186
clasohm@0
   187
(*Apply first tactic to 1*)
paulson@1502
   188
fun FIRST1 tacs = FIRST' tacs 1;
clasohm@0
   189
clasohm@0
   190
clasohm@0
   191
(*** Tracing tactics ***)
clasohm@0
   192
clasohm@0
   193
(*Max number of goals to print -- set by user*)
clasohm@0
   194
val goals_limit = ref 10;
clasohm@0
   195
clasohm@0
   196
(*Print the current proof state and pass it on.*)
paulson@6041
   197
fun print_tac msg = 
paulson@1502
   198
    (fn st => 
paulson@6041
   199
     (writeln msg;
paulson@6041
   200
      print_goals (!goals_limit) st; Seq.single st));
clasohm@0
   201
clasohm@0
   202
(*Pause until a line is typed -- if non-empty then fail. *)
paulson@1502
   203
fun pause_tac st =  
wenzelm@5957
   204
  (writeln "** Press RETURN to continue:";
wenzelm@4270
   205
   if TextIO.inputLine TextIO.stdIn = "\n" then Seq.single st
wenzelm@5956
   206
   else (writeln "Goodbye";  Seq.empty));
clasohm@0
   207
clasohm@0
   208
exception TRACE_EXIT of thm
clasohm@0
   209
and TRACE_QUIT;
clasohm@0
   210
lcp@631
   211
(*Tracing flags*)
lcp@631
   212
val trace_REPEAT= ref false
lcp@631
   213
and suppress_tracing = ref false;
lcp@631
   214
clasohm@0
   215
(*Handle all tracing commands for current state and tactic *)
paulson@1502
   216
fun exec_trace_command flag (tac, st) = 
paulson@2244
   217
   case TextIO.inputLine(TextIO.stdIn) of
paulson@1502
   218
       "\n" => tac st
wenzelm@4270
   219
     | "f\n" => Seq.empty
paulson@1502
   220
     | "o\n" => (flag:=false;  tac st)
paulson@1502
   221
     | "s\n" => (suppress_tracing:=true;  tac st)
wenzelm@5956
   222
     | "x\n" => (writeln "Exiting now";  raise (TRACE_EXIT st))
clasohm@0
   223
     | "quit\n" => raise TRACE_QUIT
wenzelm@5956
   224
     | _     => (writeln
clasohm@0
   225
"Type RETURN to continue or...\n\
clasohm@0
   226
\     f    - to fail here\n\
clasohm@0
   227
\     o    - to switch tracing off\n\
lcp@631
   228
\     s    - to suppress tracing until next entry to a tactical\n\
clasohm@0
   229
\     x    - to exit at this point\n\
clasohm@0
   230
\     quit - to abort this tracing run\n\
paulson@1502
   231
\** Well? "     ;  exec_trace_command flag (tac, st));
clasohm@0
   232
clasohm@0
   233
clasohm@0
   234
(*Extract from a tactic, a thm->thm seq function that handles tracing*)
paulson@1502
   235
fun tracify flag tac st =
lcp@631
   236
  if !flag andalso not (!suppress_tracing)
wenzelm@3669
   237
           then (print_goals (!goals_limit) st;
wenzelm@5957
   238
                 writeln "** Press RETURN to continue:";
paulson@2244
   239
                 exec_trace_command flag (tac,st))
paulson@1502
   240
  else tac st;
clasohm@0
   241
clasohm@0
   242
(*Create a tactic whose outcome is given by seqf, handling TRACE_EXIT*)
paulson@1502
   243
fun traced_tac seqf st = 
lcp@631
   244
    (suppress_tracing := false;
wenzelm@4270
   245
     Seq.make (fn()=> seqf st
wenzelm@4270
   246
                         handle TRACE_EXIT st' => Some(st', Seq.empty)));
clasohm@0
   247
clasohm@0
   248
oheimb@8149
   249
(*Deterministic DO..UNTIL: only retains the first outcome; tail recursive.
oheimb@8149
   250
  Forces repitition until predicate on state is fulfilled.*)
oheimb@8149
   251
fun DETERM_UNTIL p tac = 
oheimb@8149
   252
let val tac = tracify trace_REPEAT tac
oheimb@8149
   253
    fun drep st = if p st then Some (st, Seq.empty)
oheimb@8149
   254
                          else (case Seq.pull(tac st) of
oheimb@8149
   255
                                  None        => None
oheimb@8149
   256
                                | Some(st',_) => drep st')
oheimb@8149
   257
in  traced_tac drep  end;
oheimb@8149
   258
clasohm@0
   259
(*Deterministic REPEAT: only retains the first outcome; 
lcp@703
   260
  uses less space than REPEAT; tail recursive.
lcp@703
   261
  If non-negative, n bounds the number of repetitions.*)
lcp@703
   262
fun REPEAT_DETERM_N n tac = 
paulson@1502
   263
  let val tac = tracify trace_REPEAT tac
wenzelm@4270
   264
      fun drep 0 st = Some(st, Seq.empty)
paulson@2244
   265
        | drep n st =
wenzelm@4270
   266
           (case Seq.pull(tac st) of
wenzelm@4270
   267
                None       => Some(st, Seq.empty)
paulson@2244
   268
              | Some(st',_) => drep (n-1) st')
lcp@703
   269
  in  traced_tac (drep n)  end;
lcp@703
   270
lcp@703
   271
(*Allows any number of repetitions*)
lcp@703
   272
val REPEAT_DETERM = REPEAT_DETERM_N ~1;
clasohm@0
   273
clasohm@0
   274
(*General REPEAT: maintains a stack of alternatives; tail recursive*)
clasohm@0
   275
fun REPEAT tac = 
paulson@1502
   276
  let val tac = tracify trace_REPEAT tac
clasohm@0
   277
      fun rep qs st = 
wenzelm@4270
   278
        case Seq.pull(tac st) of
wenzelm@4270
   279
            None       => Some(st, Seq.make(fn()=> repq qs))
clasohm@0
   280
          | Some(st',q) => rep (q::qs) st'
clasohm@0
   281
      and repq [] = None
wenzelm@4270
   282
        | repq(q::qs) = case Seq.pull q of
paulson@2244
   283
            None       => repq qs
clasohm@0
   284
          | Some(st,q) => rep (q::qs) st
clasohm@0
   285
  in  traced_tac (rep [])  end;
clasohm@0
   286
clasohm@0
   287
(*Repeat 1 or more times*)
lcp@703
   288
fun REPEAT_DETERM1 tac = DETERM tac THEN REPEAT_DETERM tac;
clasohm@0
   289
fun REPEAT1 tac = tac THEN REPEAT tac;
clasohm@0
   290
clasohm@0
   291
clasohm@0
   292
(** Filtering tacticals **)
clasohm@0
   293
clasohm@0
   294
(*Returns all states satisfying the predicate*)
wenzelm@4270
   295
fun FILTER pred tac st = Seq.filter pred (tac st);
clasohm@0
   296
clasohm@0
   297
(*Returns all changed states*)
paulson@1643
   298
fun CHANGED tac st = 
paulson@1643
   299
    let fun diff st' = not (eq_thm(st,st'))
wenzelm@4270
   300
    in  Seq.filter diff (tac st)  end;
clasohm@0
   301
clasohm@0
   302
clasohm@0
   303
(*** Tacticals based on subgoal numbering ***)
clasohm@0
   304
paulson@1502
   305
(*For n subgoals, performs tac(n) THEN ... THEN tac(1) 
paulson@1502
   306
  Essential to work backwards since tac(i) may add/delete subgoals at i. *)
paulson@1502
   307
fun ALLGOALS tac st = 
paulson@1502
   308
  let fun doall 0 = all_tac
paulson@2244
   309
        | doall n = tac(n) THEN doall(n-1)
paulson@1502
   310
  in  doall(nprems_of st)st  end;
clasohm@0
   311
paulson@1502
   312
(*For n subgoals, performs tac(n) ORELSE ... ORELSE tac(1)  *)
paulson@1502
   313
fun SOMEGOAL tac st = 
paulson@1502
   314
  let fun find 0 = no_tac
paulson@2244
   315
        | find n = tac(n) ORELSE find(n-1)
paulson@1502
   316
  in  find(nprems_of st)st  end;
clasohm@0
   317
paulson@1502
   318
(*For n subgoals, performs tac(1) ORELSE ... ORELSE tac(n).
clasohm@0
   319
  More appropriate than SOMEGOAL in some cases.*)
paulson@1502
   320
fun FIRSTGOAL tac st = 
paulson@1502
   321
  let fun find (i,n) = if i>n then no_tac else  tac(i) ORELSE find (i+1,n)
paulson@1502
   322
  in  find(1, nprems_of st)st  end;
clasohm@0
   323
paulson@1502
   324
(*Repeatedly solve some using tac. *)
paulson@1502
   325
fun REPEAT_SOME tac = REPEAT1 (SOMEGOAL (REPEAT1 o tac));
paulson@1502
   326
fun REPEAT_DETERM_SOME tac = REPEAT_DETERM1 (SOMEGOAL (REPEAT_DETERM1 o tac));
clasohm@0
   327
paulson@1502
   328
(*Repeatedly solve the first possible subgoal using tac. *)
paulson@1502
   329
fun REPEAT_FIRST tac = REPEAT1 (FIRSTGOAL (REPEAT1 o tac));
paulson@1502
   330
fun REPEAT_DETERM_FIRST tac = REPEAT_DETERM1 (FIRSTGOAL (REPEAT_DETERM1 o tac));
clasohm@0
   331
paulson@1502
   332
(*For n subgoals, tries to apply tac to n,...1  *)
paulson@1502
   333
fun TRYALL tac = ALLGOALS (TRY o tac);
clasohm@0
   334
clasohm@0
   335
clasohm@0
   336
(*Make a tactic for subgoal i, if there is one.  *)
paulson@2580
   337
fun SUBGOAL goalfun i st = goalfun (List.nth(prems_of st, i-1),  i) st
wenzelm@4270
   338
                             handle Subscript => Seq.empty;
clasohm@0
   339
paulson@5141
   340
(*Returns all states that have changed in subgoal i, counted from the LAST
paulson@5141
   341
  subgoal.  For stac, for example.*)
paulson@5141
   342
fun CHANGED_GOAL tac i st = 
paulson@7686
   343
    let val np = nprems_of st
paulson@7686
   344
        val d = np-i                 (*distance from END*)
paulson@5141
   345
        val t = List.nth(prems_of st, i-1)
paulson@7686
   346
        fun diff st' = 
paulson@7686
   347
	    nprems_of st' - d <= 0   (*the subgoal no longer exists*)
paulson@7686
   348
	    orelse 
paulson@7686
   349
             not (Pattern.aeconv (t,
paulson@7686
   350
				  List.nth(prems_of st', 
paulson@7686
   351
					   nprems_of st' - d - 1)))
paulson@5141
   352
    in  Seq.filter diff (tac i st)  end
paulson@5141
   353
    handle Subscript => Seq.empty  (*no subgoal i*);
paulson@5141
   354
wenzelm@4602
   355
fun ALLGOALS_RANGE tac (i:int) j st =
wenzelm@4602
   356
  if i > j then all_tac st
wenzelm@4602
   357
  else (tac j THEN ALLGOALS_RANGE tac i (j - 1)) st;
wenzelm@4602
   358
wenzelm@4602
   359
fun (tac1 THEN_ALL_NEW tac2) i st =
wenzelm@4602
   360
  st |> (tac1 i THEN (fn st' => ALLGOALS_RANGE tac2 i (i + nprems_of st' - nprems_of st) st'));
wenzelm@4602
   361
wenzelm@8341
   362
(*repeatedly dig into any emerging subgoals*)
wenzelm@8341
   363
fun REPEAT_ALL_NEW tac =
wenzelm@8341
   364
  tac THEN_ALL_NEW (TRY o (fn i => REPEAT_ALL_NEW tac i));
wenzelm@8341
   365
paulson@2005
   366
paulson@2005
   367
(*** SELECT_GOAL ***)
paulson@2005
   368
clasohm@0
   369
(*Tactical for restricting the effect of a tactic to subgoal i.
paulson@1502
   370
  Works by making a new state from subgoal i, applying tac to it, and
clasohm@0
   371
  composing the resulting metathm with the original state.
clasohm@0
   372
  The "main goal" of the new state will not be atomic, some tactics may fail!
clasohm@0
   373
  DOES NOT work if tactic affects the main goal other than by instantiation.*)
clasohm@0
   374
paulson@2005
   375
(*SELECT_GOAL optimization: replace the conclusion by a variable X,
paulson@2005
   376
  to avoid copying.  Proof states have X==concl as an assuption.*)
paulson@2005
   377
wenzelm@6390
   378
val prop_equals = cterm_of (Theory.sign_of ProtoPure.thy) 
paulson@2005
   379
                    (Const("==", propT-->propT-->propT));
paulson@2005
   380
paulson@2005
   381
fun mk_prop_equals(t,u) = capply (capply prop_equals t) u;
paulson@2005
   382
paulson@2005
   383
(*Like trivial but returns [ct==X] ct==>X instead of ct==>ct, if possible.
paulson@2005
   384
  It is paired with a function to undo the transformation.  If ct contains
paulson@2005
   385
  Vars then it returns ct==>ct.*)
paulson@5312
   386
paulson@2005
   387
fun eq_trivial ct =
wenzelm@6390
   388
  let val xfree = cterm_of (Theory.sign_of ProtoPure.thy)
paulson@5312
   389
                           (Free (gensym"EQ_TRIVIAL_", propT))
paulson@2158
   390
      val ct_eq_x = mk_prop_equals (ct, xfree)
paulson@2005
   391
      and refl_ct = reflexive ct
paulson@2005
   392
      fun restore th = 
paulson@2244
   393
          implies_elim 
paulson@2244
   394
            (forall_elim ct (forall_intr xfree (implies_intr ct_eq_x th)))
paulson@2244
   395
            refl_ct
paulson@2005
   396
  in  (equal_elim
paulson@2005
   397
         (combination (combination refl_implies refl_ct) (assume ct_eq_x))
paulson@5312
   398
         (Drule.mk_triv_goal ct),
paulson@2005
   399
       restore)
paulson@2005
   400
  end  (*Fails if there are Vars or TVars*)
paulson@5312
   401
    handle THM _ => (Drule.mk_triv_goal ct, I);
paulson@5312
   402
paulson@2005
   403
paulson@2005
   404
(*Does the work of SELECT_GOAL. *)
paulson@5312
   405
fun select tac st i =
paulson@2580
   406
  let val (eq_cprem, restore) = (*we hope maxidx goes to ~1*)
paulson@5312
   407
	  eq_trivial (adjust_maxidx (List.nth(cprems_of st, i-1)))
paulson@5312
   408
      fun next st' = 
paulson@5312
   409
	  let val np' = nprems_of st'
paulson@5312
   410
              (*rename the ?A in rev_triv_goal*)
paulson@5312
   411
	      val {maxidx,...} = rep_thm st'
wenzelm@6390
   412
              val ct = cterm_of (Theory.sign_of ProtoPure.thy)
paulson@5312
   413
		                (Var(("A",maxidx+1), propT))
wenzelm@5906
   414
	      val rev_triv_goal' = instantiate' [] [Some ct] Drule.rev_triv_goal
paulson@5312
   415
              fun bic th = bicompose false (false, th, np')
paulson@5312
   416
          in  bic (Seq.hd (bic (restore st') 1 rev_triv_goal')) i st  end 
wenzelm@4270
   417
  in  Seq.flat (Seq.map next (tac eq_cprem))
paulson@2005
   418
  end;
paulson@2005
   419
paulson@1502
   420
fun SELECT_GOAL tac i st = 
paulson@5312
   421
  let val np = nprems_of st
paulson@5312
   422
  in  if 1<=i andalso i<=np then 
paulson@5312
   423
          (*If only one subgoal, then just apply tactic*)
paulson@5312
   424
	  if np=1 then tac st else select tac st i
paulson@5312
   425
      else Seq.empty
paulson@5312
   426
  end;
clasohm@0
   427
clasohm@0
   428
clasohm@0
   429
(*Strips assumptions in goal yielding  ( [x1,...,xm], [H1,...,Hn], B )
clasohm@0
   430
    H1,...,Hn are the hypotheses;  x1...xm are variants of the parameters. 
clasohm@0
   431
  Main difference from strip_assums concerns parameters: 
clasohm@0
   432
    it replaces the bound variables by free variables.  *)
clasohm@0
   433
fun strip_context_aux (params, Hs, Const("==>", _) $ H $ B) = 
paulson@2244
   434
        strip_context_aux (params, H::Hs, B)
clasohm@0
   435
  | strip_context_aux (params, Hs, Const("all",_)$Abs(a,T,t)) =
clasohm@0
   436
        let val (b,u) = variant_abs(a,T,t)
paulson@2244
   437
        in  strip_context_aux ((b,T)::params, Hs, u)  end
clasohm@0
   438
  | strip_context_aux (params, Hs, B) = (rev params, rev Hs, B);
clasohm@0
   439
clasohm@0
   440
fun strip_context A = strip_context_aux ([],[],A);
clasohm@0
   441
clasohm@0
   442
clasohm@0
   443
(**** METAHYPS -- tactical for using hypotheses as meta-level assumptions
paulson@1502
   444
       METAHYPS (fn prems => tac prems) i
clasohm@0
   445
clasohm@0
   446
converts subgoal i, of the form !!x1...xm. [| A1;...;An] ==> A into a new
clasohm@0
   447
proof state A==>A, supplying A1,...,An as meta-level assumptions (in
clasohm@0
   448
"prems").  The parameters x1,...,xm become free variables.  If the
clasohm@0
   449
resulting proof state is [| B1;...;Bk] ==> C (possibly assuming A1,...,An)
clasohm@0
   450
then it is lifted back into the original context, yielding k subgoals.
clasohm@0
   451
clasohm@0
   452
Replaces unknowns in the context by Frees having the prefix METAHYP_
clasohm@0
   453
New unknowns in [| B1;...;Bk] ==> C are lifted over x1,...,xm.
clasohm@0
   454
DOES NOT HANDLE TYPE UNKNOWNS.
clasohm@0
   455
****)
clasohm@0
   456
clasohm@0
   457
local 
clasohm@0
   458
clasohm@0
   459
  (*Left-to-right replacements: ctpairs = [...,(vi,ti),...].
clasohm@0
   460
    Instantiates distinct free variables by terms of same type.*)
clasohm@0
   461
  fun free_instantiate ctpairs = 
clasohm@0
   462
      forall_elim_list (map snd ctpairs) o forall_intr_list (map fst ctpairs);
clasohm@0
   463
clasohm@0
   464
  fun free_of s ((a,i), T) =
clasohm@0
   465
        Free(s ^ (case i of 0 => a | _ => a ^ "_" ^ string_of_int i),
paulson@2244
   466
             T)
clasohm@0
   467
clasohm@0
   468
  fun mk_inst (var as Var(v,T))  = (var,  free_of "METAHYP1_" (v,T))
clasohm@0
   469
in
clasohm@0
   470
paulson@1502
   471
fun metahyps_aux_tac tacf (prem,i) state = 
clasohm@0
   472
  let val {sign,maxidx,...} = rep_thm state
lcp@230
   473
      val cterm = cterm_of sign
clasohm@0
   474
      (*find all vars in the hyps -- should find tvars also!*)
paulson@1502
   475
      val hyps_vars = foldr add_term_vars (Logic.strip_assums_hyp prem, [])
clasohm@0
   476
      val insts = map mk_inst hyps_vars
clasohm@0
   477
      (*replace the hyps_vars by Frees*)
clasohm@0
   478
      val prem' = subst_atomic insts prem
clasohm@0
   479
      val (params,hyps,concl) = strip_context prem'
clasohm@0
   480
      val fparams = map Free params
clasohm@0
   481
      val cparams = map cterm fparams
clasohm@0
   482
      and chyps = map cterm hyps
clasohm@0
   483
      val hypths = map assume chyps
clasohm@0
   484
      fun swap_ctpair (t,u) = (cterm u, cterm t)
clasohm@0
   485
      (*Subgoal variables: make Free; lift type over params*)
clasohm@0
   486
      fun mk_subgoal_inst concl_vars (var as Var(v,T)) = 
clasohm@0
   487
          if var mem concl_vars 
paulson@2244
   488
          then (var, true, free_of "METAHYP2_" (v,T))
paulson@2244
   489
          else (var, false,
paulson@2244
   490
                free_of "METAHYP2_" (v, map #2 params --->T))
clasohm@0
   491
      (*Instantiate subgoal vars by Free applied to params*)
clasohm@0
   492
      fun mk_ctpair (t,in_concl,u) = 
paulson@2244
   493
          if in_concl then (cterm t,  cterm u)
clasohm@0
   494
          else (cterm t,  cterm (list_comb (u,fparams)))
clasohm@0
   495
      (*Restore Vars with higher type and index*)
clasohm@0
   496
      fun mk_subgoal_swap_ctpair 
paulson@2244
   497
                (t as Var((a,i),_), in_concl, u as Free(_,U)) = 
paulson@2244
   498
          if in_concl then (cterm u, cterm t)
clasohm@0
   499
          else (cterm u, cterm(Var((a, i+maxidx), U)))
clasohm@0
   500
      (*Embed B in the original context of params and hyps*)
paulson@1502
   501
      fun embed B = list_all_free (params, Logic.list_implies (hyps, B))
clasohm@0
   502
      (*Strip the context using elimination rules*)
clasohm@0
   503
      fun elim Bhyp = implies_elim_list (forall_elim_list cparams Bhyp) hypths
clasohm@0
   504
      (*Embed an ff pair in the original params*)
paulson@1502
   505
      fun embed_ff(t,u) = Logic.mk_flexpair (list_abs_free (params, t), 
paulson@2244
   506
                                             list_abs_free (params, u))
clasohm@0
   507
      (*Remove parameter abstractions from the ff pairs*)
clasohm@0
   508
      fun elim_ff ff = flexpair_abs_elim_list cparams ff
clasohm@0
   509
      (*A form of lifting that discharges assumptions.*)
clasohm@0
   510
      fun relift st = 
paulson@2244
   511
        let val prop = #prop(rep_thm st)
paulson@2244
   512
            val subgoal_vars = (*Vars introduced in the subgoals*)
paulson@2244
   513
                  foldr add_term_vars (Logic.strip_imp_prems prop, [])
paulson@2244
   514
            and concl_vars = add_term_vars (Logic.strip_imp_concl prop, [])
paulson@2244
   515
            val subgoal_insts = map (mk_subgoal_inst concl_vars) subgoal_vars
paulson@2244
   516
            val st' = instantiate ([], map mk_ctpair subgoal_insts) st
paulson@2244
   517
            val emBs = map (cterm o embed) (prems_of st')
clasohm@0
   518
            and ffs = map (cterm o embed_ff) (tpairs_of st')
paulson@2244
   519
            val Cth  = implies_elim_list st' 
paulson@2244
   520
                            (map (elim_ff o assume) ffs @
paulson@2244
   521
                             map (elim o assume) emBs)
paulson@2244
   522
        in  (*restore the unknowns to the hypotheses*)
paulson@2244
   523
            free_instantiate (map swap_ctpair insts @
paulson@2244
   524
                              map mk_subgoal_swap_ctpair subgoal_insts)
paulson@2244
   525
                (*discharge assumptions from state in same order*)
paulson@2244
   526
                (implies_intr_list (ffs@emBs)
paulson@2244
   527
                  (forall_intr_list cparams (implies_intr_list chyps Cth)))
paulson@2244
   528
        end
clasohm@0
   529
      val subprems = map (forall_elim_vars 0) hypths
clasohm@0
   530
      and st0 = trivial (cterm concl)
clasohm@0
   531
      (*function to replace the current subgoal*)
clasohm@0
   532
      fun next st = bicompose false (false, relift st, nprems_of st)
paulson@2244
   533
                    i state
wenzelm@4270
   534
  in  Seq.flat (Seq.map next (tacf subprems st0))
paulson@1502
   535
  end;
clasohm@0
   536
end;
clasohm@0
   537
clasohm@0
   538
fun METAHYPS tacf = SUBGOAL (metahyps_aux_tac tacf);
clasohm@0
   539
clasohm@0
   540
end;
paulson@1502
   541
paulson@1502
   542
open Tactical;