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