src/Pure/tctical.ML
author lcp
Mon Oct 31 18:03:14 1994 +0100 (1994-10-31)
changeset 671 e0be228a9c5b
parent 631 8bc44f7bbab8
child 703 3a5cd2883581
permissions -rw-r--r--
Pure/tctical/THEN_ELSE: new
clasohm@0
     1
(*  Title: 	tctical
clasohm@0
     2
    ID:         $Id$
clasohm@0
     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
clasohm@0
     9
infix 1 THEN THEN' THEN_BEST_FIRST;
clasohm@0
    10
infix 0 ORELSE APPEND INTLEAVE ORELSE' APPEND' INTLEAVE';
clasohm@0
    11
lcp@671
    12
infix 0 THEN_ELSE;
lcp@671
    13
clasohm@0
    14
clasohm@0
    15
signature TACTICAL =
clasohm@0
    16
  sig
clasohm@0
    17
  structure Thm : THM
clasohm@0
    18
  local open Thm  in
clasohm@0
    19
  datatype tactic = Tactic of thm -> thm Sequence.seq
lcp@631
    20
  val all_tac		: tactic
lcp@631
    21
  val ALLGOALS		: (int -> tactic) -> tactic   
lcp@631
    22
  val APPEND		: tactic * tactic -> tactic
lcp@631
    23
  val APPEND'		: ('a -> tactic) * ('a -> tactic) -> 'a -> tactic
lcp@631
    24
  val BEST_FIRST	: (thm -> bool) * (thm -> int) -> tactic -> tactic
lcp@631
    25
  val BREADTH_FIRST	: (thm -> bool) -> tactic -> tactic
lcp@631
    26
  val CHANGED		: tactic -> tactic
lcp@631
    27
  val COND		: (thm -> bool) -> tactic -> tactic -> tactic   
lcp@631
    28
  val DEPTH_FIRST	: (thm -> bool) -> tactic -> tactic
lcp@631
    29
  val DEPTH_SOLVE	: tactic -> tactic
lcp@631
    30
  val DEPTH_SOLVE_1	: tactic -> tactic
lcp@631
    31
  val DETERM		: tactic -> tactic
lcp@631
    32
  val EVERY		: tactic list -> tactic   
lcp@631
    33
  val EVERY'		: ('a -> tactic) list -> 'a -> tactic
lcp@631
    34
  val EVERY1		: (int -> tactic) list -> tactic
lcp@631
    35
  val FILTER		: (thm -> bool) -> tactic -> tactic
lcp@631
    36
  val FIRST		: tactic list -> tactic   
lcp@631
    37
  val FIRST'		: ('a -> tactic) list -> 'a -> tactic
lcp@631
    38
  val FIRST1		: (int -> tactic) list -> tactic
lcp@631
    39
  val FIRSTGOAL		: (int -> tactic) -> tactic
lcp@631
    40
  val goals_limit	: int ref
lcp@631
    41
  val has_fewer_prems	: int -> thm -> bool   
lcp@631
    42
  val IF_UNSOLVED	: tactic -> tactic
lcp@631
    43
  val INTLEAVE		: tactic * tactic -> tactic
lcp@631
    44
  val INTLEAVE'		: ('a -> tactic) * ('a -> tactic) -> 'a -> tactic
lcp@631
    45
  val METAHYPS		: (thm list -> tactic) -> int -> tactic
lcp@631
    46
  val no_tac		: tactic
lcp@631
    47
  val ORELSE		: tactic * tactic -> tactic
lcp@631
    48
  val ORELSE'		: ('a -> tactic) * ('a -> tactic) -> 'a -> tactic
lcp@631
    49
  val pause_tac		: tactic
lcp@631
    50
  val print_tac		: tactic
lcp@631
    51
  val REPEAT1		: tactic -> tactic
lcp@631
    52
  val REPEAT		: tactic -> tactic
lcp@631
    53
  val REPEAT_DETERM	: tactic -> tactic
lcp@631
    54
  val REPEAT_FIRST	: (int -> tactic) -> tactic
lcp@631
    55
  val REPEAT_SOME	: (int -> tactic) -> tactic
lcp@631
    56
  val SELECT_GOAL	: tactic -> int -> tactic
lcp@631
    57
  val SOMEGOAL		: (int -> tactic) -> tactic   
lcp@631
    58
  val STATE		: (thm -> tactic) -> tactic
lcp@631
    59
  val strip_context	: term -> (string * typ) list * term list * term
lcp@631
    60
  val SUBGOAL		: ((term*int) -> tactic) -> int -> tactic
lcp@631
    61
  val suppress_tracing	: bool ref
lcp@631
    62
  val tapply		: tactic * thm -> thm Sequence.seq
lcp@631
    63
  val THEN		: tactic * tactic -> tactic
lcp@631
    64
  val THEN'		: ('a -> tactic) * ('a -> tactic) -> 'a -> tactic
lcp@631
    65
  val THEN_BEST_FIRST	: tactic * ((thm->bool) * (thm->int) * tactic) 
lcp@631
    66
			  -> tactic
lcp@671
    67
  val THEN_ELSE		: tactic * (tactic*tactic) -> tactic
lcp@631
    68
  val traced_tac	: (thm -> (thm * thm Sequence.seq) option) -> tactic
lcp@631
    69
  val tracify		: bool ref -> tactic -> thm -> thm Sequence.seq
lcp@631
    70
  val trace_BEST_FIRST	: bool ref
lcp@631
    71
  val trace_DEPTH_FIRST	: bool ref
lcp@631
    72
  val trace_REPEAT	: bool ref
lcp@631
    73
  val TRY		: tactic -> tactic
lcp@631
    74
  val TRYALL		: (int -> tactic) -> tactic   
clasohm@0
    75
  end
clasohm@0
    76
  end;
clasohm@0
    77
clasohm@0
    78
clasohm@0
    79
functor TacticalFun (structure Logic: LOGIC and Drule: DRULE) : TACTICAL = 
clasohm@0
    80
struct
clasohm@0
    81
structure Thm = Drule.Thm;
clasohm@0
    82
structure Sequence = Thm.Sequence;
clasohm@0
    83
structure Sign = Thm.Sign;
clasohm@0
    84
local open Drule Thm
clasohm@0
    85
in
clasohm@0
    86
clasohm@0
    87
(**** Tactics ****)
clasohm@0
    88
clasohm@0
    89
(*A tactic maps a proof tree to a sequence of proof trees:
clasohm@0
    90
    if length of sequence = 0 then the tactic does not apply;
clasohm@0
    91
    if length > 1 then backtracking on the alternatives can occur.*)
clasohm@0
    92
clasohm@0
    93
datatype tactic = Tactic of thm -> thm Sequence.seq;
clasohm@0
    94
clasohm@0
    95
fun tapply(Tactic tf, state) = tf (state);
clasohm@0
    96
clasohm@0
    97
(*Makes a tactic from one that uses the components of the state.*)
clasohm@0
    98
fun STATE tacfun = Tactic (fn state => tapply(tacfun state, state));
clasohm@0
    99
clasohm@0
   100
clasohm@0
   101
(*** LCF-style tacticals ***)
clasohm@0
   102
clasohm@0
   103
(*the tactical THEN performs one tactic followed by another*)
clasohm@0
   104
fun (Tactic tf1)  THEN  (Tactic tf2) = 
clasohm@0
   105
  Tactic (fn state => Sequence.flats (Sequence.maps tf2 (tf1 state)));
clasohm@0
   106
clasohm@0
   107
clasohm@0
   108
(*The tactical ORELSE uses the first tactic that returns a nonempty sequence.
clasohm@0
   109
  Like in LCF, ORELSE commits to either tac1 or tac2 immediately.
clasohm@0
   110
  Does not backtrack to tac2 if tac1 was initially chosen. *)
clasohm@0
   111
fun (Tactic tf1)  ORELSE  (Tactic tf2) = 
clasohm@0
   112
  Tactic (fn state =>  
clasohm@0
   113
    case Sequence.pull(tf1 state) of
clasohm@0
   114
	None       => tf2 state
clasohm@0
   115
      | sequencecell => Sequence.seqof(fn()=> sequencecell));
clasohm@0
   116
clasohm@0
   117
clasohm@0
   118
(*The tactical APPEND combines the results of two tactics.
clasohm@0
   119
  Like ORELSE, but allows backtracking on both tac1 and tac2.
clasohm@0
   120
  The tactic tac2 is not applied until needed.*)
clasohm@0
   121
fun (Tactic tf1)  APPEND  (Tactic tf2) = 
clasohm@0
   122
  Tactic (fn state =>  Sequence.append(tf1 state,
clasohm@0
   123
                          Sequence.seqof(fn()=> Sequence.pull (tf2 state))));
clasohm@0
   124
clasohm@0
   125
(*Like APPEND, but interleaves results of tac1 and tac2.*)
clasohm@0
   126
fun (Tactic tf1)  INTLEAVE  (Tactic tf2) = 
clasohm@0
   127
  Tactic (fn state =>  Sequence.interleave(tf1 state,
clasohm@0
   128
                          Sequence.seqof(fn()=> Sequence.pull (tf2 state))));
clasohm@0
   129
lcp@671
   130
(*Conditional tactic.
lcp@671
   131
	tac1 ORELSE tac2 = tac1 THEN_ELSE (all_tac, tac2)
lcp@671
   132
	tac1 THEN tac2   = tac1 THEN_ELSE (tac2, no_tac)
lcp@671
   133
*)
lcp@671
   134
fun (Tactic tf) THEN_ELSE (Tactic tf1, Tactic tf2) = 
lcp@671
   135
  Tactic (fn state =>  
lcp@671
   136
    case Sequence.pull(tf state) of
lcp@671
   137
	None    => tf2 state		(*failed; try tactic 2*)
lcp@671
   138
      | seqcell => Sequence.flats 	(*succeeded; use tactic 1*)
lcp@671
   139
	            (Sequence.maps tf1 (Sequence.seqof(fn()=> seqcell))));
lcp@671
   140
lcp@671
   141
clasohm@0
   142
(*Versions for combining tactic-valued functions, as in
clasohm@0
   143
     SOMEGOAL (resolve_tac rls THEN' assume_tac) *)
clasohm@0
   144
fun tac1 THEN' tac2 = fn x => tac1 x THEN tac2 x;
clasohm@0
   145
fun tac1 ORELSE' tac2 = fn x => tac1 x ORELSE tac2 x;
clasohm@0
   146
fun tac1 APPEND' tac2 = fn x => tac1 x APPEND tac2 x;
clasohm@0
   147
fun tac1 INTLEAVE' tac2 = fn x => tac1 x INTLEAVE tac2 x;
clasohm@0
   148
clasohm@0
   149
(*passes all proofs through unchanged;  identity of THEN*)
clasohm@0
   150
val all_tac = Tactic (fn state => Sequence.single state);
clasohm@0
   151
clasohm@0
   152
(*passes no proofs through;  identity of ORELSE and APPEND*)
clasohm@0
   153
val no_tac  = Tactic (fn state => Sequence.null);
clasohm@0
   154
clasohm@0
   155
clasohm@0
   156
(*Make a tactic deterministic by chopping the tail of the proof sequence*)
clasohm@0
   157
fun DETERM (Tactic tf) = Tactic (fn state => 
clasohm@0
   158
      case Sequence.pull (tf state) of
clasohm@0
   159
	      None => Sequence.null
clasohm@0
   160
            | Some(x,_) => Sequence.cons(x, Sequence.null));
clasohm@0
   161
clasohm@0
   162
clasohm@0
   163
(*Conditional tactical: testfun controls which tactic to use next.
clasohm@0
   164
  Beware: due to eager evaluation, both thentac and elsetac are evaluated.*)
clasohm@0
   165
fun COND testfun (Tactic thenf) (Tactic elsef) = Tactic (fn prf =>
clasohm@0
   166
    if testfun prf then  thenf prf   else  elsef prf);
clasohm@0
   167
clasohm@0
   168
(*Do the tactic or else do nothing*)
clasohm@0
   169
fun TRY tac = tac ORELSE all_tac;
clasohm@0
   170
clasohm@0
   171
clasohm@0
   172
(*** List-oriented tactics ***)
clasohm@0
   173
clasohm@0
   174
(* EVERY [tac1,...,tacn]   equals    tac1 THEN ... THEN tacn   *)
clasohm@0
   175
fun EVERY tacs = foldr (op THEN) (tacs, all_tac);
clasohm@0
   176
clasohm@0
   177
(* EVERY' [tf1,...,tfn] i  equals    tf1 i THEN ... THEN tfn i   *)
clasohm@0
   178
fun EVERY' tfs = foldr (op THEN') (tfs, K all_tac);
clasohm@0
   179
clasohm@0
   180
(*Apply every tactic to 1*)
clasohm@0
   181
fun EVERY1 tfs = EVERY' tfs 1;
clasohm@0
   182
clasohm@0
   183
(* FIRST [tac1,...,tacn]   equals    tac1 ORELSE ... ORELSE tacn   *)
clasohm@0
   184
fun FIRST tacs = foldr (op ORELSE) (tacs, no_tac);
clasohm@0
   185
clasohm@0
   186
(* FIRST' [tf1,...,tfn] i  equals    tf1 i ORELSE ... ORELSE tfn i   *)
clasohm@0
   187
fun FIRST' tfs = foldr (op ORELSE') (tfs, K no_tac);
clasohm@0
   188
clasohm@0
   189
(*Apply first tactic to 1*)
clasohm@0
   190
fun FIRST1 tfs = FIRST' tfs 1;
clasohm@0
   191
clasohm@0
   192
clasohm@0
   193
(*** Tracing tactics ***)
clasohm@0
   194
clasohm@0
   195
(*Max number of goals to print -- set by user*)
clasohm@0
   196
val goals_limit = ref 10;
clasohm@0
   197
clasohm@0
   198
(*Print the current proof state and pass it on.*)
lcp@67
   199
val print_tac = Tactic 
lcp@67
   200
    (fn state => 
lcp@67
   201
     (!print_goals_ref (!goals_limit) state;   Sequence.single state));
clasohm@0
   202
clasohm@0
   203
(*Pause until a line is typed -- if non-empty then fail. *)
clasohm@0
   204
val pause_tac = Tactic (fn state => 
clasohm@0
   205
  (prs"** Press RETURN to continue: ";
clasohm@0
   206
   if input(std_in,1) = "\n" then Sequence.single state
clasohm@0
   207
   else (prs"Goodbye\n";  Sequence.null)));
clasohm@0
   208
clasohm@0
   209
exception TRACE_EXIT of thm
clasohm@0
   210
and TRACE_QUIT;
clasohm@0
   211
lcp@631
   212
(*Tracing flags*)
lcp@631
   213
val trace_REPEAT= ref false
lcp@631
   214
and trace_DEPTH_FIRST = ref false
lcp@631
   215
and trace_BEST_FIRST = ref false
lcp@631
   216
and suppress_tracing = ref false;
lcp@631
   217
clasohm@0
   218
(*Handle all tracing commands for current state and tactic *)
clasohm@0
   219
fun exec_trace_command flag (tf, state) = 
clasohm@0
   220
   case input_line(std_in) of
clasohm@0
   221
       "\n" => tf state
clasohm@0
   222
     | "f\n" => Sequence.null
lcp@631
   223
     | "o\n" => (flag:=false;  tf state)
lcp@631
   224
     | "s\n" => (suppress_tracing:=true;  tf state)
clasohm@0
   225
     | "x\n" => (prs"Exiting now\n";  raise (TRACE_EXIT state))
clasohm@0
   226
     | "quit\n" => raise TRACE_QUIT
clasohm@0
   227
     | _     => (prs
clasohm@0
   228
"Type RETURN to continue or...\n\
clasohm@0
   229
\     f    - to fail here\n\
clasohm@0
   230
\     o    - to switch tracing off\n\
lcp@631
   231
\     s    - to suppress tracing until next entry to a tactical\n\
clasohm@0
   232
\     x    - to exit at this point\n\
clasohm@0
   233
\     quit - to abort this tracing run\n\
clasohm@0
   234
\** Well? "     ;  exec_trace_command flag (tf, state));
clasohm@0
   235
clasohm@0
   236
clasohm@0
   237
(*Extract from a tactic, a thm->thm seq function that handles tracing*)
clasohm@0
   238
fun tracify flag (Tactic tf) state =
lcp@631
   239
  if !flag andalso not (!suppress_tracing)
lcp@631
   240
           then (!print_goals_ref (!goals_limit) state;  
clasohm@0
   241
		 prs"** Press RETURN to continue: ";
clasohm@0
   242
		 exec_trace_command flag (tf,state))
clasohm@0
   243
  else tf state;
clasohm@0
   244
clasohm@0
   245
(*Create a tactic whose outcome is given by seqf, handling TRACE_EXIT*)
clasohm@0
   246
fun traced_tac seqf = Tactic (fn st =>
lcp@631
   247
    (suppress_tracing := false;
lcp@631
   248
     Sequence.seqof (fn()=> seqf st
lcp@631
   249
		         handle TRACE_EXIT st' => Some(st', Sequence.null))));
clasohm@0
   250
clasohm@0
   251
clasohm@0
   252
(*Deterministic REPEAT: only retains the first outcome; 
clasohm@0
   253
  uses less space than REPEAT; tail recursive*)
clasohm@0
   254
fun REPEAT_DETERM tac = 
clasohm@0
   255
  let val tf = tracify trace_REPEAT tac
clasohm@0
   256
      fun drep st =
clasohm@0
   257
        case Sequence.pull(tf st) of
clasohm@0
   258
  	    None       => Some(st, Sequence.null)
clasohm@0
   259
          | Some(st',_) => drep st'
clasohm@0
   260
  in  traced_tac drep  end;
clasohm@0
   261
clasohm@0
   262
(*General REPEAT: maintains a stack of alternatives; tail recursive*)
clasohm@0
   263
fun REPEAT tac = 
clasohm@0
   264
  let val tf = tracify trace_REPEAT tac
clasohm@0
   265
      fun rep qs st = 
clasohm@0
   266
	case Sequence.pull(tf st) of
clasohm@0
   267
  	    None       => Some(st, Sequence.seqof(fn()=> repq qs))
clasohm@0
   268
          | Some(st',q) => rep (q::qs) st'
clasohm@0
   269
      and repq [] = None
clasohm@0
   270
        | repq(q::qs) = case Sequence.pull q of
clasohm@0
   271
  	    None       => repq qs
clasohm@0
   272
          | Some(st,q) => rep (q::qs) st
clasohm@0
   273
  in  traced_tac (rep [])  end;
clasohm@0
   274
clasohm@0
   275
(*Repeat 1 or more times*)
clasohm@0
   276
fun REPEAT1 tac = tac THEN REPEAT tac;
clasohm@0
   277
clasohm@0
   278
clasohm@0
   279
(** Search tacticals **)
clasohm@0
   280
clasohm@0
   281
(*Seaarches "satp" reports proof tree as satisfied*)
clasohm@0
   282
fun DEPTH_FIRST satp tac = 
clasohm@0
   283
 let val tf = tracify trace_DEPTH_FIRST tac
clasohm@0
   284
     fun depth [] = None
clasohm@0
   285
       | depth(q::qs) =
clasohm@0
   286
	  case Sequence.pull q of
clasohm@0
   287
	      None         => depth qs
clasohm@0
   288
	    | Some(st,stq) => 
clasohm@0
   289
		if satp st then Some(st, Sequence.seqof(fn()=> depth(stq::qs)))
clasohm@0
   290
		else depth (tf st :: stq :: qs)
clasohm@0
   291
  in  traced_tac (fn st => depth([Sequence.single st]))  end;
clasohm@0
   292
clasohm@0
   293
clasohm@0
   294
(*Predicate: Does the rule have fewer than n premises?*)
clasohm@0
   295
fun has_fewer_prems n rule = (nprems_of rule < n);
clasohm@0
   296
clasohm@0
   297
(*Apply a tactic if subgoals remain, else do nothing.*)
clasohm@0
   298
val IF_UNSOLVED = COND (has_fewer_prems 1) all_tac;
clasohm@0
   299
clasohm@0
   300
(*Tactical to reduce the number of premises by 1.
clasohm@0
   301
  If no subgoals then it must fail! *)
clasohm@0
   302
fun DEPTH_SOLVE_1 tac = STATE
clasohm@0
   303
 (fn state => 
clasohm@0
   304
    (case nprems_of state of
clasohm@0
   305
	0 => no_tac
clasohm@0
   306
      | n => DEPTH_FIRST (has_fewer_prems n) tac));
clasohm@0
   307
clasohm@0
   308
(*Uses depth-first search to solve ALL subgoals*)
clasohm@0
   309
val DEPTH_SOLVE = DEPTH_FIRST (has_fewer_prems 1);
clasohm@0
   310
clasohm@0
   311
(*** Best-first search ***)
clasohm@0
   312
clasohm@0
   313
(*Insertion into priority queue of states *)
clasohm@0
   314
fun insert (nth: int*thm, []) = [nth]
clasohm@0
   315
  | insert ((m,th), (n,th')::nths) = 
clasohm@0
   316
      if  n<m then (n,th') :: insert ((m,th), nths)
clasohm@0
   317
      else if  n=m andalso eq_thm(th,th')
clasohm@0
   318
              then (n,th')::nths
clasohm@0
   319
              else (m,th)::(n,th')::nths;
clasohm@0
   320
clasohm@0
   321
(*For creating output sequence*)
clasohm@0
   322
fun some_of_list []     = None
clasohm@0
   323
  | some_of_list (x::l) = Some (x, Sequence.seqof (fn () => some_of_list l));
clasohm@0
   324
clasohm@0
   325
clasohm@0
   326
(* Best-first search for a state that satisfies satp (incl initial state)
clasohm@0
   327
  Function sizef estimates size of problem remaining (smaller means better).
clasohm@0
   328
  tactic tf0 sets up the initial priority queue, which is searched by tac. *)
clasohm@0
   329
fun (Tactic tf0) THEN_BEST_FIRST (satp, sizef, tac) = 
clasohm@0
   330
  let val tf = tracify trace_BEST_FIRST tac
clasohm@0
   331
      fun pairsize th = (sizef th, th);
clasohm@0
   332
      fun bfs (news,nprfs) =
clasohm@0
   333
	   (case  partition satp news  of
clasohm@0
   334
		([],nonsats) => next(foldr insert
clasohm@0
   335
					(map pairsize nonsats, nprfs)) 
clasohm@0
   336
	      | (sats,_)  => some_of_list sats)
clasohm@0
   337
      and next [] = None
clasohm@0
   338
        | next ((n,prf)::nprfs) =
clasohm@0
   339
	    (if !trace_BEST_FIRST 
clasohm@0
   340
	       then writeln("state size = " ^ string_of_int n ^ 
clasohm@0
   341
		         "  queue length =" ^ string_of_int (length nprfs))  
clasohm@0
   342
               else ();
clasohm@0
   343
	     bfs (Sequence.list_of_s (tf prf), nprfs))
clasohm@0
   344
      fun tf st = bfs (Sequence.list_of_s (tf0 st),  [])
clasohm@0
   345
  in traced_tac tf end;
clasohm@0
   346
clasohm@0
   347
(*Ordinary best-first search, with no initial tactic*)
clasohm@0
   348
fun BEST_FIRST (satp,sizef) tac = all_tac THEN_BEST_FIRST (satp,sizef,tac);
clasohm@0
   349
clasohm@0
   350
(*Breadth-first search to satisfy satpred (including initial state) 
clasohm@0
   351
  SLOW -- SHOULD NOT USE APPEND!*)
clasohm@0
   352
fun BREADTH_FIRST satpred (Tactic tf) = 
clasohm@0
   353
  let val tacf = Sequence.list_of_s o tf;
clasohm@0
   354
      fun bfs prfs =
clasohm@0
   355
	 (case  partition satpred prfs  of
clasohm@0
   356
	      ([],[]) => []
clasohm@0
   357
	    | ([],nonsats) => 
clasohm@0
   358
		  (prs("breadth=" ^ string_of_int(length nonsats) ^ "\n");
clasohm@0
   359
		   bfs (flat (map tacf nonsats)))
clasohm@0
   360
	    | (sats,_)  => sats)
clasohm@0
   361
  in Tactic (fn state => Sequence.s_of_list (bfs [state])) end;
clasohm@0
   362
clasohm@0
   363
clasohm@0
   364
(** Filtering tacticals **)
clasohm@0
   365
clasohm@0
   366
(*Returns all states satisfying the predicate*)
clasohm@0
   367
fun FILTER pred (Tactic tf) = Tactic
clasohm@0
   368
      (fn state => Sequence.filters pred (tf state));
clasohm@0
   369
clasohm@0
   370
(*Returns all changed states*)
clasohm@0
   371
fun CHANGED (Tactic tf)  = 
clasohm@0
   372
  Tactic (fn state => 
clasohm@0
   373
    let fun diff st = not (eq_thm(state,st))
clasohm@0
   374
    in  Sequence.filters diff (tf state)
clasohm@0
   375
    end );
clasohm@0
   376
clasohm@0
   377
clasohm@0
   378
(*** Tacticals based on subgoal numbering ***)
clasohm@0
   379
clasohm@0
   380
(*For n subgoals, performs tf(n) THEN ... THEN tf(1) 
clasohm@0
   381
  Essential to work backwards since tf(i) may add/delete subgoals at i. *)
clasohm@0
   382
fun ALLGOALS tf = 
clasohm@0
   383
  let fun tac 0 = all_tac
clasohm@0
   384
	| tac n = tf(n) THEN tac(n-1)
clasohm@0
   385
  in  Tactic(fn state => tapply(tac(nprems_of state), state))  end;
clasohm@0
   386
clasohm@0
   387
(*For n subgoals, performs tf(n) ORELSE ... ORELSE tf(1)  *)
clasohm@0
   388
fun SOMEGOAL tf = 
clasohm@0
   389
  let fun tac 0 = no_tac
clasohm@0
   390
	| tac n = tf(n) ORELSE tac(n-1)
clasohm@0
   391
  in  Tactic(fn state => tapply(tac(nprems_of state), state))  end;
clasohm@0
   392
clasohm@0
   393
(*For n subgoals, performs tf(1) ORELSE ... ORELSE tf(n).
clasohm@0
   394
  More appropriate than SOMEGOAL in some cases.*)
clasohm@0
   395
fun FIRSTGOAL tf = 
clasohm@0
   396
  let fun tac (i,n) = if i>n then no_tac else  tf(i) ORELSE tac (i+1,n)
clasohm@0
   397
  in  Tactic(fn state => tapply(tac(1, nprems_of state), state))  end;
clasohm@0
   398
clasohm@0
   399
(*Repeatedly solve some using tf. *)
clasohm@0
   400
fun REPEAT_SOME tf = REPEAT1 (SOMEGOAL (REPEAT1 o tf));
clasohm@0
   401
clasohm@0
   402
(*Repeatedly solve the first possible subgoal using tf. *)
clasohm@0
   403
fun REPEAT_FIRST tf = REPEAT1 (FIRSTGOAL (REPEAT1 o tf));
clasohm@0
   404
clasohm@0
   405
(*For n subgoals, tries to apply tf to n,...1  *)
clasohm@0
   406
fun TRYALL tf = ALLGOALS (TRY o tf);
clasohm@0
   407
clasohm@0
   408
clasohm@0
   409
(*Make a tactic for subgoal i, if there is one.  *)
clasohm@0
   410
fun SUBGOAL goalfun i = Tactic(fn state =>
clasohm@0
   411
  case drop(i-1, prems_of state) of
clasohm@0
   412
      [] => Sequence.null
clasohm@0
   413
    | prem::_ => tapply(goalfun (prem,i), state));
clasohm@0
   414
clasohm@0
   415
(*Tactical for restricting the effect of a tactic to subgoal i.
clasohm@0
   416
  Works by making a new state from subgoal i, applying tf to it, and
clasohm@0
   417
  composing the resulting metathm with the original state.
clasohm@0
   418
  The "main goal" of the new state will not be atomic, some tactics may fail!
clasohm@0
   419
  DOES NOT work if tactic affects the main goal other than by instantiation.*)
clasohm@0
   420
lcp@31
   421
(* (!!x. PROP ?V) ==> PROP ?V ;  contains NO TYPE VARIABLES.*)
clasohm@0
   422
val dummy_quant_rl = 
clasohm@0
   423
  standard (forall_elim_var 0 (assume 
lcp@230
   424
                  (read_cterm Sign.pure ("!!x::prop. PROP V",propT))));
clasohm@0
   425
clasohm@0
   426
(* Prevent the subgoal's assumptions from becoming additional subgoals in the
clasohm@0
   427
   new proof state by enclosing them by a universal quantification *)
clasohm@0
   428
fun protect_subgoal state i =
lcp@31
   429
  case Sequence.chop (1, bicompose false (false,dummy_quant_rl,1) i state) of
clasohm@0
   430
      ([state'],_) => state'
lcp@31
   431
    | _            => error"SELECT_GOAL -- impossible error???";
clasohm@0
   432
clasohm@0
   433
(*Does the work of SELECT_GOAL. *)
clasohm@0
   434
fun select (Tactic tf) state i =
clasohm@0
   435
  let val prem::_ = drop(i-1, prems_of state)
lcp@230
   436
      val st0 = trivial (cterm_of (#sign(rep_thm state)) prem);
clasohm@0
   437
      fun next st = bicompose false (false, st, nprems_of st) i state
clasohm@0
   438
  in  Sequence.flats (Sequence.maps next (tf st0))
clasohm@0
   439
  end;
clasohm@0
   440
clasohm@0
   441
fun SELECT_GOAL tac i = Tactic (fn state =>
clasohm@0
   442
  case (i, drop(i-1, prems_of state)) of
clasohm@0
   443
      (_,[]) => Sequence.null
lcp@31
   444
    | (1,[_]) => tapply(tac,state)  (*If i=1 and only one subgoal do nothing!*)
clasohm@0
   445
    | (_, (Const("==>",_)$_$_) :: _) => select tac (protect_subgoal state i) i
clasohm@0
   446
    | (_, _::_) => select tac state i);
clasohm@0
   447
clasohm@0
   448
clasohm@0
   449
(*Strips assumptions in goal yielding  ( [x1,...,xm], [H1,...,Hn], B )
clasohm@0
   450
    H1,...,Hn are the hypotheses;  x1...xm are variants of the parameters. 
clasohm@0
   451
  Main difference from strip_assums concerns parameters: 
clasohm@0
   452
    it replaces the bound variables by free variables.  *)
clasohm@0
   453
fun strip_context_aux (params, Hs, Const("==>", _) $ H $ B) = 
clasohm@0
   454
	strip_context_aux (params, H::Hs, B)
clasohm@0
   455
  | strip_context_aux (params, Hs, Const("all",_)$Abs(a,T,t)) =
clasohm@0
   456
        let val (b,u) = variant_abs(a,T,t)
clasohm@0
   457
	in  strip_context_aux ((b,T)::params, Hs, u)  end
clasohm@0
   458
  | strip_context_aux (params, Hs, B) = (rev params, rev Hs, B);
clasohm@0
   459
clasohm@0
   460
fun strip_context A = strip_context_aux ([],[],A);
clasohm@0
   461
clasohm@0
   462
clasohm@0
   463
(**** METAHYPS -- tactical for using hypotheses as meta-level assumptions
clasohm@0
   464
       METAHYPS (fn prems => tac (prems)) i
clasohm@0
   465
clasohm@0
   466
converts subgoal i, of the form !!x1...xm. [| A1;...;An] ==> A into a new
clasohm@0
   467
proof state A==>A, supplying A1,...,An as meta-level assumptions (in
clasohm@0
   468
"prems").  The parameters x1,...,xm become free variables.  If the
clasohm@0
   469
resulting proof state is [| B1;...;Bk] ==> C (possibly assuming A1,...,An)
clasohm@0
   470
then it is lifted back into the original context, yielding k subgoals.
clasohm@0
   471
clasohm@0
   472
Replaces unknowns in the context by Frees having the prefix METAHYP_
clasohm@0
   473
New unknowns in [| B1;...;Bk] ==> C are lifted over x1,...,xm.
clasohm@0
   474
DOES NOT HANDLE TYPE UNKNOWNS.
clasohm@0
   475
****)
clasohm@0
   476
clasohm@0
   477
local 
clasohm@0
   478
  open Logic 
clasohm@0
   479
clasohm@0
   480
  (*Left-to-right replacements: ctpairs = [...,(vi,ti),...].
clasohm@0
   481
    Instantiates distinct free variables by terms of same type.*)
clasohm@0
   482
  fun free_instantiate ctpairs = 
clasohm@0
   483
      forall_elim_list (map snd ctpairs) o forall_intr_list (map fst ctpairs);
clasohm@0
   484
clasohm@0
   485
  fun free_of s ((a,i), T) =
clasohm@0
   486
        Free(s ^ (case i of 0 => a | _ => a ^ "_" ^ string_of_int i),
clasohm@0
   487
	     T)
clasohm@0
   488
clasohm@0
   489
  fun mk_inst (var as Var(v,T))  = (var,  free_of "METAHYP1_" (v,T))
clasohm@0
   490
in
clasohm@0
   491
clasohm@0
   492
fun metahyps_aux_tac tacf (prem,i) = Tactic (fn state =>
clasohm@0
   493
  let val {sign,maxidx,...} = rep_thm state
lcp@230
   494
      val cterm = cterm_of sign
clasohm@0
   495
      (*find all vars in the hyps -- should find tvars also!*)
clasohm@0
   496
      val hyps_vars = foldr add_term_vars (strip_assums_hyp prem, [])
clasohm@0
   497
      val insts = map mk_inst hyps_vars
clasohm@0
   498
      (*replace the hyps_vars by Frees*)
clasohm@0
   499
      val prem' = subst_atomic insts prem
clasohm@0
   500
      val (params,hyps,concl) = strip_context prem'
clasohm@0
   501
      val fparams = map Free params
clasohm@0
   502
      val cparams = map cterm fparams
clasohm@0
   503
      and chyps = map cterm hyps
clasohm@0
   504
      val hypths = map assume chyps
clasohm@0
   505
      fun swap_ctpair (t,u) = (cterm u, cterm t)
clasohm@0
   506
      (*Subgoal variables: make Free; lift type over params*)
clasohm@0
   507
      fun mk_subgoal_inst concl_vars (var as Var(v,T)) = 
clasohm@0
   508
          if var mem concl_vars 
clasohm@0
   509
	  then (var, true, free_of "METAHYP2_" (v,T))
clasohm@0
   510
	  else (var, false,
clasohm@0
   511
		free_of "METAHYP2_" (v, map #2 params --->T))
clasohm@0
   512
      (*Instantiate subgoal vars by Free applied to params*)
clasohm@0
   513
      fun mk_ctpair (t,in_concl,u) = 
clasohm@0
   514
	  if in_concl then (cterm t,  cterm u)
clasohm@0
   515
          else (cterm t,  cterm (list_comb (u,fparams)))
clasohm@0
   516
      (*Restore Vars with higher type and index*)
clasohm@0
   517
      fun mk_subgoal_swap_ctpair 
clasohm@0
   518
		(t as Var((a,i),_), in_concl, u as Free(_,U)) = 
clasohm@0
   519
	  if in_concl then (cterm u, cterm t)
clasohm@0
   520
          else (cterm u, cterm(Var((a, i+maxidx), U)))
clasohm@0
   521
      (*Embed B in the original context of params and hyps*)
clasohm@0
   522
      fun embed B = list_all_free (params, list_implies (hyps, B))
clasohm@0
   523
      (*Strip the context using elimination rules*)
clasohm@0
   524
      fun elim Bhyp = implies_elim_list (forall_elim_list cparams Bhyp) hypths
clasohm@0
   525
      (*Embed an ff pair in the original params*)
clasohm@0
   526
      fun embed_ff(t,u) = 
clasohm@0
   527
	  mk_flexpair (list_abs_free (params, t), list_abs_free (params, u))
clasohm@0
   528
      (*Remove parameter abstractions from the ff pairs*)
clasohm@0
   529
      fun elim_ff ff = flexpair_abs_elim_list cparams ff
clasohm@0
   530
      (*A form of lifting that discharges assumptions.*)
clasohm@0
   531
      fun relift st = 
clasohm@0
   532
	let val prop = #prop(rep_thm st)
clasohm@0
   533
	    val subgoal_vars = (*Vars introduced in the subgoals*)
clasohm@0
   534
		  foldr add_term_vars (strip_imp_prems prop, [])
clasohm@0
   535
	    and concl_vars = add_term_vars (strip_imp_concl prop, [])
clasohm@0
   536
	    val subgoal_insts = map (mk_subgoal_inst concl_vars) subgoal_vars
clasohm@0
   537
	    val st' = instantiate ([], map mk_ctpair subgoal_insts) st
clasohm@0
   538
	    val emBs = map (cterm o embed) (prems_of st')
clasohm@0
   539
            and ffs = map (cterm o embed_ff) (tpairs_of st')
clasohm@0
   540
	    val Cth  = implies_elim_list st' 
clasohm@0
   541
			    (map (elim_ff o assume) ffs @
clasohm@0
   542
			     map (elim o assume) emBs)
clasohm@0
   543
	in  (*restore the unknowns to the hypotheses*)
clasohm@0
   544
	    free_instantiate (map swap_ctpair insts @
clasohm@0
   545
			      map mk_subgoal_swap_ctpair subgoal_insts)
clasohm@0
   546
		(*discharge assumptions from state in same order*)
clasohm@0
   547
		(implies_intr_list (ffs@emBs)
clasohm@0
   548
		  (forall_intr_list cparams (implies_intr_list chyps Cth)))
clasohm@0
   549
	end
clasohm@0
   550
      val subprems = map (forall_elim_vars 0) hypths
clasohm@0
   551
      and st0 = trivial (cterm concl)
clasohm@0
   552
      (*function to replace the current subgoal*)
clasohm@0
   553
      fun next st = bicompose false (false, relift st, nprems_of st)
clasohm@0
   554
	            i state
clasohm@0
   555
  in  Sequence.flats (Sequence.maps next (tapply(tacf subprems, st0)))
clasohm@0
   556
  end);
clasohm@0
   557
end;
clasohm@0
   558
clasohm@0
   559
fun METAHYPS tacf = SUBGOAL (metahyps_aux_tac tacf);
clasohm@0
   560
clasohm@0
   561
end;
clasohm@0
   562
end;