src/HOL/Statespace/state_space.ML
author schirmer
Mon Nov 12 11:07:22 2007 +0100 (2007-11-12)
changeset 25408 156f6f7082b8
parent 25171 4a9c25bffc9b
child 25696 c2058af6d9bc
permissions -rw-r--r--
added signatures;
tuned
schirmer@25171
     1
(*  Title:      state_space.ML
schirmer@25171
     2
    ID:         $Id$
schirmer@25171
     3
    Author:     Norbert Schirmer, TU Muenchen
schirmer@25171
     4
*)
schirmer@25171
     5
schirmer@25408
     6
signature STATE_SPACE =
schirmer@25408
     7
  sig
schirmer@25408
     8
    val KN : string
schirmer@25408
     9
    val distinct_compsN : string
schirmer@25408
    10
    val getN : string
schirmer@25408
    11
    val putN : string
schirmer@25408
    12
    val injectN : string
schirmer@25408
    13
    val namespaceN : string
schirmer@25408
    14
    val projectN : string
schirmer@25408
    15
    val valuetypesN : string
schirmer@25408
    16
schirmer@25408
    17
    val quiet_mode : bool ref
schirmer@25408
    18
schirmer@25408
    19
    val namespace_definition :
schirmer@25408
    20
       bstring ->
schirmer@25408
    21
       Term.typ ->
schirmer@25408
    22
       Locale.expr ->
schirmer@25408
    23
       string list -> string list -> Context.theory -> Context.theory
schirmer@25408
    24
schirmer@25408
    25
    val define_statespace :
schirmer@25408
    26
       string list ->
schirmer@25408
    27
       string ->
schirmer@25408
    28
       (string list * bstring * (string * string) list) list ->
schirmer@25408
    29
       (string * string) list -> Context.theory -> Context.theory
schirmer@25408
    30
    val define_statespace_i :
schirmer@25408
    31
       string option ->
schirmer@25408
    32
       string list ->
schirmer@25408
    33
       string ->
schirmer@25408
    34
       (Term.typ list * bstring * (string * string) list) list ->
schirmer@25408
    35
       (string * Term.typ) list -> Context.theory -> Context.theory
schirmer@25408
    36
schirmer@25408
    37
    val statespace_decl :
schirmer@25408
    38
       OuterParse.token list -> 
schirmer@25408
    39
       ((string list * bstring) *
schirmer@25408
    40
         ((string list * xstring * (bstring * bstring) list) list *
schirmer@25408
    41
          (bstring * string) list)) * OuterParse.token list
schirmer@25408
    42
schirmer@25408
    43
schirmer@25408
    44
    val neq_x_y : Context.proof -> Term.term -> Term.term -> Thm.thm option
schirmer@25408
    45
    val distinctNameSolver : MetaSimplifier.solver
schirmer@25408
    46
    val distinctTree_tac :
schirmer@25408
    47
       Context.proof -> Term.term * int -> Tactical.tactic
schirmer@25408
    48
    val distinct_simproc : MetaSimplifier.simproc
schirmer@25408
    49
schirmer@25408
    50
schirmer@25408
    51
    val change_simpset : (MetaSimplifier.simpset -> MetaSimplifier.simpset) ->
schirmer@25408
    52
       Context.generic -> Context.generic
schirmer@25408
    53
schirmer@25408
    54
    val get_comp : Context.generic -> string -> (Term.typ * string) Option.option
schirmer@25408
    55
    val get_silent : Context.generic -> bool
schirmer@25408
    56
    val set_silent : bool -> Context.generic -> Context.generic
schirmer@25408
    57
schirmer@25408
    58
    val read_typ :
schirmer@25408
    59
       Context.theory ->
schirmer@25408
    60
       string ->
schirmer@25408
    61
       (string * Term.sort) list -> Term.typ * (string * Term.sort) list
schirmer@25408
    62
schirmer@25408
    63
    val gen_lookup_tr : Context.proof -> Term.term -> string -> Term.term
schirmer@25408
    64
    val lookup_swap_tr : Context.proof -> Term.term list -> Term.term
schirmer@25408
    65
    val lookup_tr : Context.proof -> Term.term list -> Term.term
schirmer@25408
    66
    val lookup_tr' : Context.proof -> Term.term list -> Term.term
schirmer@25408
    67
schirmer@25408
    68
    val gen_update_tr :
schirmer@25408
    69
       bool -> Context.proof -> string -> Term.term -> Term.term -> Term.term
schirmer@25408
    70
    val update_tr : Context.proof -> Term.term list -> Term.term
schirmer@25408
    71
    val update_tr' : Context.proof -> Term.term list -> Term.term
schirmer@25408
    72
  end;
schirmer@25408
    73
schirmer@25408
    74
schirmer@25408
    75
structure StateSpace: STATE_SPACE =
schirmer@25171
    76
struct
schirmer@25171
    77
schirmer@25171
    78
(* Theorems *)
schirmer@25171
    79
schirmer@25171
    80
(* Names *)
schirmer@25171
    81
val distinct_compsN = "distinct_names"
schirmer@25171
    82
val namespaceN = "_namespace"
schirmer@25171
    83
val valuetypesN = "_valuetypes"
schirmer@25171
    84
val projectN = "project"
schirmer@25171
    85
val injectN = "inject"
schirmer@25171
    86
val getN = "get"
schirmer@25171
    87
val putN = "put"
schirmer@25171
    88
val project_injectL = "StateSpaceLocale.project_inject";
schirmer@25171
    89
val KN = "StateFun.K_statefun"
schirmer@25171
    90
schirmer@25171
    91
schirmer@25171
    92
(* messages *)
schirmer@25171
    93
schirmer@25171
    94
val quiet_mode = ref false;
schirmer@25171
    95
fun message s = if ! quiet_mode then () else writeln s;
schirmer@25171
    96
schirmer@25171
    97
(* Library *)
schirmer@25171
    98
schirmer@25171
    99
fun fold1 f xs = fold f (tl xs) (hd xs)
schirmer@25171
   100
fun fold1' f [] x = x
schirmer@25171
   101
  | fold1' f xs _ = fold1 f xs
schirmer@25171
   102
 
schirmer@25171
   103
fun sublist_idx eq xs ys = 
schirmer@25171
   104
  let
schirmer@25171
   105
    fun sublist n xs ys = 
schirmer@25171
   106
         if is_prefix eq xs ys then SOME n
schirmer@25171
   107
         else (case ys of [] => NONE
schirmer@25171
   108
               | (y::ys') => sublist (n+1) xs ys')
schirmer@25171
   109
  in sublist 0 xs ys end;
schirmer@25171
   110
schirmer@25171
   111
fun is_sublist eq xs ys = is_some (sublist_idx eq xs ys);
schirmer@25171
   112
schirmer@25171
   113
fun sorted_subset eq [] ys = true
schirmer@25171
   114
  | sorted_subset eq (x::xs) [] = false
schirmer@25171
   115
  | sorted_subset eq (x::xs) (y::ys) = if eq (x,y) then sorted_subset eq xs ys
schirmer@25171
   116
                                       else sorted_subset eq (x::xs) ys;
schirmer@25171
   117
schirmer@25171
   118
schirmer@25171
   119
schirmer@25171
   120
type namespace_info =
schirmer@25171
   121
 {declinfo: (typ*string) Termtab.table, (* type, name of statespace *)
schirmer@25171
   122
  distinctthm: thm Symtab.table,
schirmer@25171
   123
  silent: bool
schirmer@25171
   124
 };
schirmer@25171
   125
 
schirmer@25171
   126
structure NameSpaceArgs =
schirmer@25171
   127
struct
schirmer@25171
   128
  type T = namespace_info; 
schirmer@25171
   129
  val empty = {declinfo = Termtab.empty, distinctthm = Symtab.empty, silent = false};
schirmer@25171
   130
  val extend = I;
schirmer@25171
   131
  fun merge pp ({declinfo=declinfo1, distinctthm=distinctthm1, silent=silent1},
schirmer@25171
   132
                {declinfo=declinfo2, distinctthm=distinctthm2, silent=silent2}) =
schirmer@25171
   133
                {declinfo = Termtab.merge (K true) (declinfo1, declinfo2),
schirmer@25171
   134
                 distinctthm = Symtab.merge (K true) (distinctthm1, distinctthm2),
schirmer@25171
   135
                 silent = silent1 andalso silent2}
schirmer@25171
   136
end;
schirmer@25171
   137
schirmer@25171
   138
structure NameSpaceData = GenericDataFun(NameSpaceArgs);
schirmer@25171
   139
schirmer@25171
   140
fun make_namespace_data declinfo distinctthm silent =
schirmer@25171
   141
     {declinfo=declinfo,distinctthm=distinctthm,silent=silent};
schirmer@25171
   142
schirmer@25171
   143
schirmer@25171
   144
fun delete_declinfo n ctxt =
schirmer@25171
   145
  let val {declinfo,distinctthm,silent} = NameSpaceData.get ctxt;
schirmer@25171
   146
  in NameSpaceData.put 
schirmer@25171
   147
       (make_namespace_data (Termtab.delete_safe n declinfo) distinctthm silent) ctxt
schirmer@25171
   148
  end;
schirmer@25171
   149
schirmer@25171
   150
schirmer@25171
   151
fun update_declinfo (n,v) ctxt =
schirmer@25171
   152
  let val {declinfo,distinctthm,silent} = NameSpaceData.get ctxt;
schirmer@25171
   153
  in NameSpaceData.put 
schirmer@25171
   154
      (make_namespace_data (Termtab.update (n,v) declinfo) distinctthm silent) ctxt
schirmer@25171
   155
  end;
schirmer@25171
   156
schirmer@25171
   157
fun set_silent silent ctxt =
schirmer@25171
   158
  let val {declinfo,distinctthm,...} = NameSpaceData.get ctxt;
schirmer@25171
   159
  in NameSpaceData.put 
schirmer@25171
   160
      (make_namespace_data declinfo distinctthm silent) ctxt
schirmer@25171
   161
  end;
schirmer@25171
   162
schirmer@25171
   163
val get_silent = #silent o NameSpaceData.get;
schirmer@25171
   164
 
schirmer@25171
   165
fun prove_interpretation_in ctxt_tac (name, expr) thy =
schirmer@25171
   166
   thy
schirmer@25171
   167
   |> Locale.interpretation_in_locale I (name, expr)
schirmer@25171
   168
   |> Proof.global_terminal_proof 
schirmer@25171
   169
         (Method.Basic (fn ctxt => Method.SIMPLE_METHOD (ctxt_tac ctxt),Position.none), NONE)
schirmer@25171
   170
   |> ProofContext.theory_of
schirmer@25171
   171
schirmer@25171
   172
type statespace_info =
schirmer@25171
   173
 {args: (string * sort) list, (* type arguments *)
schirmer@25171
   174
  parents: (typ list * string * string option list) list,
schirmer@25171
   175
             (* type instantiation, state-space name, component renamings *)
schirmer@25171
   176
  components: (string * typ) list,
schirmer@25171
   177
  types: typ list (* range types of state space *)
schirmer@25171
   178
 };
schirmer@25171
   179
schirmer@25171
   180
structure StateSpaceArgs =
schirmer@25171
   181
struct
schirmer@25171
   182
  val name = "HOL/StateSpace";
schirmer@25171
   183
  type T = statespace_info Symtab.table;
schirmer@25171
   184
  val empty = Symtab.empty;
schirmer@25171
   185
  val extend = I;
schirmer@25171
   186
schirmer@25171
   187
  fun merge pp (nt1,nt2) = Symtab.merge (K true) (nt1, nt2);
schirmer@25171
   188
end;
schirmer@25171
   189
schirmer@25171
   190
structure StateSpaceData = GenericDataFun(StateSpaceArgs);
schirmer@25171
   191
schirmer@25171
   192
fun add_statespace name args parents components types ctxt =
schirmer@25171
   193
     StateSpaceData.put 
schirmer@25171
   194
      (Symtab.update_new (name, {args=args,parents=parents,
schirmer@25171
   195
                                components=components,types=types}) (StateSpaceData.get ctxt))
schirmer@25171
   196
      ctxt; 
schirmer@25171
   197
schirmer@25171
   198
fun get_statespace ctxt name =
schirmer@25171
   199
      Symtab.lookup (StateSpaceData.get ctxt) name;
schirmer@25171
   200
schirmer@25171
   201
schirmer@25171
   202
fun lookupI eq xs n = 
schirmer@25171
   203
  (case AList.lookup eq xs n of
schirmer@25171
   204
     SOME v => v
schirmer@25171
   205
   | NONE => n);
schirmer@25171
   206
 
schirmer@25171
   207
fun mk_free ctxt name =
schirmer@25171
   208
  if Variable.is_fixed ctxt name orelse Variable.is_declared ctxt name 
schirmer@25171
   209
  then
schirmer@25171
   210
    let val n' = lookupI (op =) (Variable.fixes_of ctxt) name
schirmer@25171
   211
    in SOME (Free (n',ProofContext.infer_type ctxt n')) end
schirmer@25171
   212
  else NONE
schirmer@25171
   213
  
schirmer@25171
   214
     
schirmer@25171
   215
fun get_dist_thm ctxt name = Symtab.lookup (#distinctthm (NameSpaceData.get ctxt)) name;
schirmer@25171
   216
fun get_comp ctxt name = 
schirmer@25171
   217
     Option.mapPartial 
schirmer@25171
   218
       (Termtab.lookup (#declinfo (NameSpaceData.get ctxt))) 
schirmer@25171
   219
       (mk_free (Context.proof_of ctxt) name);
schirmer@25171
   220
schirmer@25171
   221
schirmer@25171
   222
(*** Tactics ***)
schirmer@25171
   223
schirmer@25171
   224
fun neq_x_y ctxt x y =
schirmer@25171
   225
  (let
schirmer@25171
   226
    val dist_thm = the (get_dist_thm (Context.Proof ctxt) (#1 (dest_Free x))); 
schirmer@25171
   227
    val ctree = cprop_of dist_thm |> Thm.dest_comb |> #2 |> Thm.dest_comb |> #2;
schirmer@25171
   228
    val tree = term_of ctree;
schirmer@25171
   229
    val x_path = the (DistinctTreeProver.find_tree x tree);
schirmer@25171
   230
    val y_path = the (DistinctTreeProver.find_tree y tree);
schirmer@25171
   231
    val thm = DistinctTreeProver.distinctTreeProver dist_thm x_path y_path;
schirmer@25171
   232
  in SOME thm  
schirmer@25171
   233
  end handle Option => NONE)
schirmer@25171
   234
schirmer@25171
   235
fun distinctTree_tac ctxt 
schirmer@25171
   236
      (Const ("Trueprop",_) $ 
schirmer@25171
   237
        (Const ("Not", _) $ (Const ("op =", _) $ (x as Free _)$ (y as Free _))), i) =
schirmer@25171
   238
  (case (neq_x_y ctxt x y) of
schirmer@25171
   239
     SOME neq => rtac neq i
schirmer@25171
   240
   | NONE => no_tac)
schirmer@25171
   241
  | distinctTree_tac _ _ = no_tac;
schirmer@25171
   242
schirmer@25171
   243
val distinctNameSolver = mk_solver' "distinctNameSolver"
schirmer@25171
   244
     (fn ss => case #context (#1 (rep_ss ss)) of
schirmer@25171
   245
                 SOME ctxt => SUBGOAL (distinctTree_tac ctxt)
schirmer@25171
   246
                | NONE => fn i => no_tac)
schirmer@25171
   247
schirmer@25171
   248
val distinct_simproc =
schirmer@25171
   249
  Simplifier.simproc HOL.thy "StateSpace.distinct_simproc" ["x = y"]
schirmer@25171
   250
    (fn thy => fn ss => (fn (Const ("op =",_)$(x as Free _)$(y as Free _)) =>
schirmer@25171
   251
        (case #context (#1 (rep_ss ss)) of
schirmer@25171
   252
          SOME ctxt => Option.map (fn neq => DistinctTreeProver.neq_to_eq_False OF [neq]) 
schirmer@25171
   253
                       (neq_x_y ctxt x y) 
schirmer@25171
   254
        | NONE => NONE)
schirmer@25171
   255
      | _ => NONE))
schirmer@25171
   256
schirmer@25171
   257
fun change_simpset f = 
schirmer@25171
   258
     Context.mapping 
schirmer@25171
   259
       (fn thy  => (change_simpset_of thy f; thy))
schirmer@25171
   260
       (fn ctxt => Simplifier.put_local_simpset (f (Simplifier.get_local_simpset ctxt)) ctxt);
schirmer@25171
   261
schirmer@25171
   262
fun read_typ thy s =
schirmer@25171
   263
  Sign.read_typ thy s;
schirmer@25171
   264
schirmer@25171
   265
local
schirmer@25171
   266
  val ss = HOL_basic_ss 
schirmer@25171
   267
in    
schirmer@25171
   268
fun interprete_parent name dist_thm_name parent_expr thy = 
schirmer@25171
   269
  let
schirmer@25171
   270
schirmer@25171
   271
    fun solve_tac ctxt (_,i) st =
schirmer@25171
   272
      let
schirmer@25171
   273
        val distinct_thm = ProofContext.get_thm ctxt (Name dist_thm_name);
schirmer@25171
   274
        val goal = List.nth (cprems_of st,i-1);
schirmer@25171
   275
        val rule = DistinctTreeProver.distinct_implProver distinct_thm goal;
schirmer@25171
   276
      in EVERY [rtac rule i] st
schirmer@25171
   277
      end
schirmer@25171
   278
        
schirmer@25171
   279
    fun tac ctxt = EVERY [Locale.intro_locales_tac true ctxt [],
schirmer@25171
   280
                          ALLGOALS (SUBGOAL (solve_tac ctxt))] 
schirmer@25171
   281
        
schirmer@25171
   282
  in thy 
schirmer@25171
   283
     |> prove_interpretation_in tac (name,parent_expr)
schirmer@25171
   284
  end;        
schirmer@25171
   285
schirmer@25171
   286
end;
schirmer@25171
   287
schirmer@25171
   288
fun namespace_definition name nameT parent_expr parent_comps new_comps thy = 
schirmer@25171
   289
  let
schirmer@25171
   290
    val all_comps = parent_comps @ new_comps;
schirmer@25171
   291
    val vars = Locale.Merge 
schirmer@25171
   292
                (map (fn n => Locale.Rename (Locale.Locale (Locale.intern thy "var")
schirmer@25171
   293
                                            ,[SOME (n,NONE)])) all_comps);
schirmer@25171
   294
schirmer@25171
   295
    val full_name = Sign.full_name thy name;
schirmer@25171
   296
    val dist_thm_name = distinct_compsN;
schirmer@25171
   297
    val dist_thm_full_name =
schirmer@25171
   298
        let val prefix = fold1' (fn name => fn prfx => prfx ^ "_" ^ name) all_comps "";
schirmer@25171
   299
        in if prefix = "" then dist_thm_name else prefix ^ "." ^ dist_thm_name end;
schirmer@25171
   300
schirmer@25171
   301
    fun comps_of_thm thm = prop_of thm 
schirmer@25171
   302
             |> (fn (_$(_$t)) => DistinctTreeProver.dest_tree t) |> map (fst o dest_Free);
schirmer@25171
   303
 
schirmer@25171
   304
    fun type_attr phi (ctxt,thm) =
schirmer@25171
   305
      (case ctxt of Context.Theory _ => (ctxt,thm)
schirmer@25171
   306
       | _ =>
schirmer@25171
   307
        let 
schirmer@25171
   308
          val {declinfo,distinctthm=tt,silent} = (NameSpaceData.get ctxt);
schirmer@25171
   309
	  val all_names = comps_of_thm thm;
schirmer@25171
   310
          fun upd name tt =
schirmer@25171
   311
               (case (Symtab.lookup tt name) of
schirmer@25171
   312
                 SOME dthm => if sorted_subset (op =) (comps_of_thm dthm) all_names
schirmer@25171
   313
                              then Symtab.update (name,thm) tt else tt
schirmer@25171
   314
                | NONE => Symtab.update (name,thm) tt)
schirmer@25171
   315
schirmer@25171
   316
          val tt' = tt |> fold upd all_names;
schirmer@25171
   317
          val activate_simproc =
schirmer@25171
   318
              Output.no_warnings 
schirmer@25171
   319
               (change_simpset (fn ss => ss addsimprocs [distinct_simproc]));
schirmer@25171
   320
          val ctxt' =
schirmer@25171
   321
              ctxt 
schirmer@25171
   322
              |> NameSpaceData.put {declinfo=declinfo,distinctthm=tt',silent=silent}
schirmer@25171
   323
              |> activate_simproc
schirmer@25171
   324
        in (ctxt',thm) 
schirmer@25171
   325
        end)
schirmer@25171
   326
        
schirmer@25171
   327
    val attr = Attrib.internal type_attr;
schirmer@25171
   328
schirmer@25171
   329
    val assumes = Element.Assumes [((dist_thm_name,[attr]), 
schirmer@25171
   330
                    [(HOLogic.Trueprop $
schirmer@25171
   331
                      (Const ("DistinctTreeProver.all_distinct",
schirmer@25171
   332
                                 Type ("DistinctTreeProver.tree",[nameT]) --> HOLogic.boolT) $
schirmer@25171
   333
                      DistinctTreeProver.mk_tree (fn n => Free (n,nameT)) nameT 
schirmer@25171
   334
                                (sort fast_string_ord all_comps)),
schirmer@25171
   335
                      ([]))])];
schirmer@25171
   336
schirmer@25171
   337
  in thy 
schirmer@25171
   338
     |> Locale.add_locale_i (SOME "") name vars [assumes]
schirmer@25171
   339
     ||> ProofContext.theory_of 
schirmer@25171
   340
     ||> interprete_parent name dist_thm_full_name parent_expr
schirmer@25171
   341
     |> #2
schirmer@25171
   342
  end;
schirmer@25171
   343
schirmer@25171
   344
structure Typetab = TableFun(type key=typ val ord = Term.typ_ord);
schirmer@25171
   345
schirmer@25171
   346
fun encode_dot x = if x= #"." then #"_" else x;
schirmer@25171
   347
schirmer@25171
   348
fun encode_type (TFree (s, _)) = s
schirmer@25171
   349
  | encode_type (TVar ((s,i),_)) = "?" ^ s ^ string_of_int i
schirmer@25171
   350
  | encode_type (Type (n,Ts)) = 
schirmer@25171
   351
      let
schirmer@25171
   352
        val Ts' = fold1' (fn x => fn y => x ^ "_" ^ y) (map encode_type Ts) "";
schirmer@25171
   353
        val n' = String.map encode_dot n;
schirmer@25171
   354
      in if Ts'="" then n' else Ts' ^ "_" ^ n' end;
schirmer@25171
   355
schirmer@25171
   356
fun project_name T = projectN ^"_"^encode_type T;
schirmer@25171
   357
fun inject_name T = injectN ^"_"^encode_type T;
schirmer@25171
   358
schirmer@25171
   359
fun project_free T pT V = Free (project_name T, V --> pT);
schirmer@25171
   360
fun inject_free T pT V = Free (inject_name T, pT --> V);
schirmer@25171
   361
schirmer@25171
   362
fun get_name n = getN ^ "_" ^ n;
schirmer@25171
   363
fun put_name n = putN ^ "_" ^ n;
schirmer@25171
   364
fun get_const n T nT V = Free (get_name n, (nT --> V) --> T);
schirmer@25171
   365
fun put_const n T nT V = Free (put_name n, T --> (nT --> V) --> (nT --> V));
schirmer@25171
   366
schirmer@25171
   367
fun lookup_const T nT V = Const ("StateFun.lookup",(V --> T) --> nT --> (nT --> V) --> T);
schirmer@25171
   368
fun update_const T nT V = 
schirmer@25171
   369
 Const ("StateFun.update",
schirmer@25171
   370
          (V --> T) --> (T --> V) --> nT --> (T --> T) --> (nT --> V) --> (nT --> V));
schirmer@25171
   371
schirmer@25171
   372
fun K_const T = Const ("StateFun.K_statefun",T --> T --> T);
schirmer@25171
   373
schirmer@25171
   374
val no_syn = #3 (Syntax.no_syn ((),()));
schirmer@25171
   375
schirmer@25171
   376
schirmer@25171
   377
fun add_declaration name decl thy =
schirmer@25171
   378
  thy
schirmer@25171
   379
  |> TheoryTarget.init name
schirmer@25171
   380
  |> (fn lthy => LocalTheory.declaration (decl lthy) lthy)
schirmer@25171
   381
  |> LocalTheory.exit 
schirmer@25171
   382
  |> ProofContext.theory_of;
schirmer@25171
   383
schirmer@25171
   384
fun parent_components thy (Ts, pname, renaming) =
schirmer@25171
   385
  let
schirmer@25171
   386
    val ctxt = Context.Theory thy;
schirmer@25171
   387
    fun rename [] xs = xs
schirmer@25171
   388
      | rename (NONE::rs)  (x::xs) = x::rename rs xs
schirmer@25171
   389
      | rename (SOME r::rs) ((x,T)::xs) = (r,T)::rename rs xs;
schirmer@25171
   390
    val {args,parents,components,...} = 
schirmer@25171
   391
	      the (Symtab.lookup (StateSpaceData.get ctxt) pname);
schirmer@25171
   392
    val inst = map fst args ~~ Ts;
schirmer@25171
   393
    val subst = Term.map_type_tfree (the o AList.lookup (op =) inst o fst);
schirmer@25171
   394
    val parent_comps = 
schirmer@25171
   395
     List.concat (map (fn (Ts',n,rs) => parent_components thy (map subst Ts',n,rs)) parents);
schirmer@25171
   396
    val all_comps = rename renaming (parent_comps @ map (apsnd subst) components);
schirmer@25171
   397
  in all_comps end;
schirmer@25171
   398
schirmer@25171
   399
fun take_upto i xs = List.take(xs,i) handle Subscript => xs;
schirmer@25171
   400
schirmer@25171
   401
fun statespace_definition state_type args name parents parent_comps components thy =
schirmer@25171
   402
  let 
schirmer@25171
   403
    val full_name = Sign.full_name thy name;
schirmer@25171
   404
    val all_comps = parent_comps @ components;
schirmer@25171
   405
schirmer@25171
   406
    val components' = map (fn (n,T) => (n,(T,full_name))) components;
schirmer@25171
   407
    val all_comps' = map (fn (n,T) => (n,(T,full_name))) all_comps; 
schirmer@25171
   408
    fun parent_expr (_,n,rs) = Locale.Rename 
schirmer@25171
   409
                                (Locale.Locale (suffix namespaceN n),
schirmer@25171
   410
                                 map (Option.map (fn s => (s,NONE))) rs);
schirmer@25171
   411
    val parents_expr = Locale.Merge (fold (fn p => fn es => parent_expr p::es) parents []);
schirmer@25171
   412
schirmer@25171
   413
    fun distinct_types Ts =
schirmer@25171
   414
      let val tab = fold (fn T => fn tab => Typetab.update (T,()) tab) Ts Typetab.empty;
schirmer@25171
   415
      in map fst (Typetab.dest tab) end;
schirmer@25171
   416
schirmer@25171
   417
    val Ts = distinct_types (map snd all_comps);
schirmer@25171
   418
    val arg_names = map fst args;
schirmer@25171
   419
    val valueN = Name.variant arg_names "'value";
schirmer@25171
   420
    val nameN = Name.variant (valueN::arg_names) "'name";
schirmer@25171
   421
    val valueT = TFree (valueN, Sign.defaultS thy);
schirmer@25171
   422
    val nameT = TFree (nameN, Sign.defaultS thy);
schirmer@25171
   423
    val stateT = nameT --> valueT;
schirmer@25171
   424
    fun projectT T = valueT --> T;
schirmer@25171
   425
    fun injectT T = T --> valueT; 
schirmer@25171
   426
schirmer@25171
   427
    val locs = map (fn T => Locale.Rename (Locale.Locale project_injectL,
schirmer@25171
   428
                             [SOME (project_name T,NONE),
schirmer@25171
   429
                              SOME (inject_name T ,NONE)])) Ts;
schirmer@25171
   430
    val constrains = List.concat 
schirmer@25171
   431
         (map (fn T => [(project_name T,projectT T),(inject_name T,injectT T)]) Ts);
schirmer@25171
   432
schirmer@25171
   433
    fun interprete_parent_valuetypes (Ts, pname, _) = 
schirmer@25171
   434
      let
schirmer@25171
   435
        val {args,types,...} = 
schirmer@25171
   436
             the (Symtab.lookup (StateSpaceData.get (Context.Theory thy)) pname);
schirmer@25171
   437
        val inst = map fst args ~~ Ts;
schirmer@25171
   438
        val subst = Term.map_type_tfree (the o AList.lookup (op =) inst o fst);
schirmer@25171
   439
        val pars = List.concat (map ((fn T => [project_name T,inject_name T]) o subst) types);
schirmer@25171
   440
        val expr = Locale.Rename (Locale.Locale (suffix valuetypesN name),
schirmer@25171
   441
                                  map (fn n => SOME (n,NONE)) pars);
schirmer@25171
   442
      in prove_interpretation_in (K all_tac) 
schirmer@25171
   443
           (suffix valuetypesN name, expr) end;
schirmer@25171
   444
schirmer@25171
   445
    fun interprete_parent (_, pname, rs) =
schirmer@25171
   446
      let
schirmer@25171
   447
        val expr = Locale.Rename (Locale.Locale pname, map (Option.map (fn n => (n,NONE))) rs)
schirmer@25171
   448
      in prove_interpretation_in 
schirmer@25171
   449
           (fn ctxt => Locale.intro_locales_tac false ctxt []) 
schirmer@25171
   450
           (full_name, expr) end;
schirmer@25171
   451
schirmer@25171
   452
    fun declare_declinfo updates lthy phi ctxt =
schirmer@25171
   453
      let
schirmer@25171
   454
        fun upd_prf ctxt = 
schirmer@25171
   455
          let
schirmer@25171
   456
            fun upd (n,v) =
schirmer@25171
   457
              let
schirmer@25171
   458
                val nT = ProofContext.infer_type (LocalTheory.target_of lthy) n
schirmer@25171
   459
              in Context.proof_map 
schirmer@25171
   460
                  (update_declinfo (Morphism.term phi (Free (n,nT)),v))  
schirmer@25171
   461
              end;
schirmer@25171
   462
          in ctxt |> fold upd updates end;
schirmer@25171
   463
schirmer@25171
   464
      in Context.mapping I upd_prf ctxt end;
schirmer@25171
   465
schirmer@25171
   466
   fun string_of_typ T = 
schirmer@25171
   467
      setmp show_sorts true 
schirmer@25171
   468
       (setmp print_mode [] (Syntax.string_of_typ (ProofContext.init thy))) T;
schirmer@25171
   469
   val fixestate = (case state_type of
schirmer@25171
   470
         NONE => []
schirmer@25171
   471
       | SOME s => 
schirmer@25171
   472
          let 
schirmer@25171
   473
	    val fx = Element.Fixes [(s,SOME (string_of_typ stateT),NoSyn)];
schirmer@25171
   474
            val cs = Element.Constrains 
schirmer@25171
   475
                       (map (fn (n,T) =>  (n,string_of_typ T))
schirmer@25171
   476
                         ((map (fn (n,_) => (n,nameT)) all_comps) @
schirmer@25171
   477
                          constrains))
schirmer@25171
   478
          in [fx,cs] end
schirmer@25171
   479
       )
schirmer@25171
   480
schirmer@25171
   481
   
schirmer@25171
   482
  in thy 
schirmer@25171
   483
     |> namespace_definition 
schirmer@25171
   484
           (suffix namespaceN name) nameT parents_expr 
schirmer@25171
   485
           (map fst parent_comps) (map fst components)
schirmer@25171
   486
     |> Context.theory_map (add_statespace full_name args parents components [])
schirmer@25171
   487
     |> Locale.add_locale_i (SOME "") (suffix valuetypesN name) (Locale.Merge locs) 
schirmer@25171
   488
            [Element.Constrains constrains]
schirmer@25171
   489
     |> ProofContext.theory_of o #2
schirmer@25171
   490
     |> fold interprete_parent_valuetypes parents 
schirmer@25171
   491
     |> Locale.add_locale (SOME "") name 
schirmer@25171
   492
              (Locale.Merge [Locale.Locale (suffix namespaceN full_name)
schirmer@25171
   493
                            ,Locale.Locale (suffix valuetypesN full_name)]) fixestate
schirmer@25171
   494
     |> ProofContext.theory_of o #2
schirmer@25171
   495
     |> fold interprete_parent parents
schirmer@25171
   496
     |> add_declaration (SOME full_name) (declare_declinfo components')
schirmer@25171
   497
  end;
schirmer@25171
   498
schirmer@25171
   499
schirmer@25171
   500
(* prepare arguments *)
schirmer@25171
   501
schirmer@25171
   502
fun read_raw_parent sg s =
schirmer@25171
   503
  (case Sign.read_typ_abbrev sg s handle TYPE (msg, _, _) => error msg of
schirmer@25171
   504
    Type (name, Ts) => (Ts, name)
schirmer@25171
   505
  | _ => error ("Bad parent statespace specification: " ^ quote s));
schirmer@25171
   506
schirmer@25171
   507
fun read_typ sg s env  =
schirmer@25171
   508
  let
schirmer@25171
   509
    fun def_sort (x, ~1) = AList.lookup (op =) env x
schirmer@25171
   510
      | def_sort _ = NONE;
schirmer@25171
   511
    val T = Type.no_tvars (Sign.read_def_typ (sg, def_sort) s) handle TYPE (msg, _, _) => error msg;
schirmer@25171
   512
  in (T, Term.add_typ_tfrees (T, env)) end;
schirmer@25171
   513
schirmer@25171
   514
fun cert_typ sg raw_T env =
schirmer@25171
   515
  let val T = Type.no_tvars (Sign.certify_typ sg raw_T) handle TYPE (msg, _, _) => error msg
schirmer@25171
   516
  in (T, Term.add_typ_tfrees (T, env)) end;
schirmer@25171
   517
schirmer@25171
   518
schirmer@25171
   519
schirmer@25171
   520
schirmer@25171
   521
fun gen_define_statespace prep_typ state_space args name parents comps thy =
schirmer@25171
   522
  let (* - args distinct
schirmer@25171
   523
         - only args may occur in comps and parent-instantiations
schirmer@25171
   524
         - number of insts must match parent args 
schirmer@25171
   525
         - no duplicate renamings
schirmer@25171
   526
         - renaming should occur in namespace
schirmer@25171
   527
      *)
schirmer@25171
   528
    val _ = message ("Defining statespace " ^ quote name ^ " ...");
schirmer@25171
   529
schirmer@25171
   530
    fun add_parent (Ts,pname,rs) env =
schirmer@25171
   531
      let
schirmer@25171
   532
        val full_pname = Sign.full_name thy pname;
schirmer@25171
   533
        val {args,components,...} = 
schirmer@25171
   534
              (case get_statespace (Context.Theory thy) full_pname of
schirmer@25171
   535
                SOME r => r
schirmer@25171
   536
               | NONE => error ("Undefined statespace " ^ quote pname));
schirmer@25171
   537
schirmer@25171
   538
schirmer@25171
   539
        val (Ts',env') = fold_map (prep_typ thy) Ts env
schirmer@25171
   540
            handle ERROR msg => cat_error msg 
schirmer@25171
   541
                    ("The error(s) above occured in parent statespace specification " 
schirmer@25171
   542
                    ^ quote pname);
schirmer@25171
   543
        val err_insts = if length args <> length Ts' then
schirmer@25171
   544
            ["number of type instantiation(s) does not match arguments of parent statespace "
schirmer@25171
   545
              ^ quote pname]
schirmer@25171
   546
            else [];
schirmer@25171
   547
        
schirmer@25171
   548
        val rnames = map fst rs
schirmer@25171
   549
        val err_dup_renamings = (case duplicates (op =) rnames of
schirmer@25171
   550
             [] => []
schirmer@25171
   551
            | dups => ["Duplicate renaming(s) for " ^ commas dups])
schirmer@25171
   552
schirmer@25171
   553
        val cnames = map fst components;
schirmer@25171
   554
        val err_rename_unknowns = (case (filter (fn n => not (n mem cnames))) rnames of
schirmer@25171
   555
              [] => []
schirmer@25171
   556
             | rs => ["Unknown components " ^ commas rs]);
schirmer@25171
   557
              
schirmer@25171
   558
schirmer@25171
   559
        val rs' = map (AList.lookup (op =) rs o fst) components;
schirmer@25171
   560
        val errs =err_insts @ err_dup_renamings @ err_rename_unknowns
schirmer@25171
   561
      in if null errs then ((Ts',full_pname,rs'),env')
schirmer@25171
   562
         else error (cat_lines (errs @ ["in parent statespace " ^ quote pname]))
schirmer@25171
   563
      end;
schirmer@25171
   564
 
schirmer@25171
   565
    val (parents',env) = fold_map add_parent parents [];
schirmer@25171
   566
schirmer@25171
   567
    val err_dup_args =
schirmer@25171
   568
         (case duplicates (op =) args of
schirmer@25171
   569
            [] => []
schirmer@25171
   570
          | dups => ["Duplicate type argument(s) " ^ commas dups]);
schirmer@25171
   571
    
schirmer@25171
   572
schirmer@25171
   573
    val err_dup_components = 
schirmer@25171
   574
         (case duplicates (op =) (map fst comps) of
schirmer@25171
   575
           [] => []
schirmer@25171
   576
          | dups => ["Duplicate state-space components " ^ commas dups]);
schirmer@25171
   577
schirmer@25171
   578
    fun prep_comp (n,T) env =
schirmer@25171
   579
      let val (T', env') = prep_typ thy T env handle ERROR msg =>
schirmer@25171
   580
       cat_error msg ("The error(s) above occured in component " ^ quote n)
schirmer@25171
   581
      in ((n,T'), env') end;
schirmer@25171
   582
schirmer@25171
   583
    val (comps',env') = fold_map prep_comp comps env;
schirmer@25171
   584
schirmer@25171
   585
    val err_extra_frees =
schirmer@25171
   586
      (case subtract (op =) args (map fst env') of
schirmer@25171
   587
        [] => []
schirmer@25171
   588
      | extras => ["Extra free type variable(s) " ^ commas extras]);
schirmer@25171
   589
schirmer@25171
   590
    val defaultS = Sign.defaultS thy;
schirmer@25171
   591
    val args' = map (fn x => (x, AList.lookup (op =) env x |> the_default defaultS)) args;
schirmer@25171
   592
schirmer@25171
   593
schirmer@25171
   594
    fun fst_eq ((x:string,_),(y,_)) = x = y;
schirmer@25171
   595
    fun snd_eq ((_,t:typ),(_,u)) = t = u;              
schirmer@25171
   596
schirmer@25171
   597
    val raw_parent_comps = (List.concat (map (parent_components thy) parents'));
schirmer@25171
   598
    fun check_type (n,T) = 
schirmer@25171
   599
          (case distinct (snd_eq) (filter (curry fst_eq (n,T)) raw_parent_comps) of
schirmer@25171
   600
             []  => []
schirmer@25171
   601
           | [_] => []
schirmer@25171
   602
           | rs  => ["Different types for component " ^ n ^": " ^ commas 
schirmer@25171
   603
                       (map (Pretty.string_of o Display.pretty_ctyp o ctyp_of thy o snd) rs)])
schirmer@25171
   604
                           
schirmer@25171
   605
    val err_dup_types = List.concat (map check_type (duplicates fst_eq raw_parent_comps))
schirmer@25171
   606
schirmer@25171
   607
    val parent_comps = distinct (fst_eq) raw_parent_comps;
schirmer@25171
   608
    val all_comps = parent_comps @ comps';
schirmer@25171
   609
    val err_comp_in_parent = (case duplicates (op =) (map fst all_comps) of
schirmer@25171
   610
               [] => []
schirmer@25171
   611
             | xs => ["Components already defined in parents: " ^ commas xs]);
schirmer@25171
   612
    val errs = err_dup_args @ err_dup_components @ err_extra_frees @
schirmer@25171
   613
               err_dup_types @ err_comp_in_parent;
schirmer@25171
   614
schirmer@25171
   615
  in if null errs 
schirmer@25171
   616
     then thy |> statespace_definition state_space args' name parents' parent_comps comps'
schirmer@25171
   617
     else error (cat_lines errs) 
schirmer@25171
   618
  end
schirmer@25171
   619
  handle ERROR msg => cat_error msg ("Failed to define statespace " ^ quote name);
schirmer@25171
   620
 
schirmer@25171
   621
schirmer@25171
   622
val define_statespace = gen_define_statespace read_typ NONE;
schirmer@25171
   623
val define_statespace_i = gen_define_statespace cert_typ;
schirmer@25171
   624
 
schirmer@25171
   625
schirmer@25171
   626
(*** parse/print - translations ***)
schirmer@25171
   627
schirmer@25171
   628
schirmer@25171
   629
local
schirmer@25171
   630
fun map_get_comp f ctxt (Free (name,_)) = 
schirmer@25171
   631
      (case (get_comp ctxt name) of 
schirmer@25171
   632
        SOME (T,_) => f T T dummyT 
schirmer@25171
   633
      | NONE => (Syntax.free "arbitrary"(*; error "context not ready"*)))
schirmer@25171
   634
  | map_get_comp _ _ _ = Syntax.free "arbitrary";
schirmer@25171
   635
schirmer@25171
   636
val get_comp_projection = map_get_comp project_free;
schirmer@25171
   637
val get_comp_injection  = map_get_comp inject_free;
schirmer@25171
   638
schirmer@25171
   639
fun name_of (Free (n,_)) = n;
schirmer@25171
   640
in
schirmer@25171
   641
schirmer@25171
   642
fun gen_lookup_tr ctxt s n = 
schirmer@25171
   643
      (case get_comp (Context.Proof ctxt) n of
schirmer@25171
   644
        SOME (T,_) => 
schirmer@25171
   645
           Syntax.const "StateFun.lookup"$Syntax.free (project_name T)$Syntax.free n$s
schirmer@25171
   646
       | NONE => 
schirmer@25171
   647
           if get_silent (Context.Proof ctxt)
schirmer@25171
   648
	   then Syntax.const "StateFun.lookup"$Syntax.const "arbitrary"$Syntax.free n$s
schirmer@25171
   649
           else raise TERM ("StateSpace.gen_lookup_tr: component " ^ n ^ " not defined",[]));
schirmer@25171
   650
schirmer@25171
   651
fun lookup_tr ctxt [s,Free (n,_)] = gen_lookup_tr ctxt s n;
schirmer@25171
   652
fun lookup_swap_tr ctxt [Free (n,_),s] = gen_lookup_tr ctxt s n;
schirmer@25171
   653
schirmer@25171
   654
fun lookup_tr' ctxt [_$Free (prj,_),n as (_$Free (name,_)),s] =
schirmer@25171
   655
     ( case get_comp (Context.Proof ctxt) name of
schirmer@25171
   656
         SOME (T,_) =>  if prj=project_name T then
schirmer@25171
   657
                           Syntax.const "_statespace_lookup" $ s $ n  
schirmer@25171
   658
                        else raise Match
schirmer@25171
   659
      | NONE => raise Match)
schirmer@25171
   660
  | lookup_tr' _ ts = raise Match;
schirmer@25171
   661
schirmer@25171
   662
fun gen_update_tr id ctxt n v s = 
schirmer@25171
   663
  let
schirmer@25171
   664
    fun pname T = if id then "Fun.id" else project_name T
schirmer@25171
   665
    fun iname T = if id then "Fun.id" else inject_name T
schirmer@25171
   666
   in
schirmer@25171
   667
     (case get_comp (Context.Proof ctxt) n of
schirmer@25171
   668
       SOME (T,_) => Syntax.const "StateFun.update"$
schirmer@25171
   669
                   Syntax.free (pname T)$Syntax.free (iname T)$
schirmer@25171
   670
                   Syntax.free n$(Syntax.const KN $ v)$s
schirmer@25171
   671
      | NONE => 
schirmer@25171
   672
         if get_silent (Context.Proof ctxt) 
schirmer@25171
   673
         then Syntax.const "StateFun.update"$
schirmer@25171
   674
                   Syntax.const "arbitrary"$Syntax.const "arbitrary"$
schirmer@25171
   675
                   Syntax.free n$(Syntax.const KN $ v)$s
schirmer@25171
   676
         else raise TERM ("StateSpace.gen_update_tr: component " ^ n ^ " not defined",[]))
schirmer@25171
   677
   end;
schirmer@25171
   678
schirmer@25171
   679
fun update_tr ctxt [s,Free (n,_),v] = gen_update_tr false ctxt n v s;
schirmer@25171
   680
schirmer@25171
   681
fun update_tr' ctxt [_$Free (prj,_),_$Free (inj,_),n as (_$Free (name,_)),(Const (k,_)$v),s] =
schirmer@25171
   682
     if NameSpace.base k = NameSpace.base KN then
schirmer@25171
   683
        (case get_comp (Context.Proof ctxt) name of
schirmer@25171
   684
          SOME (T,_) => if inj=inject_name T andalso prj=project_name T then
schirmer@25171
   685
                           Syntax.const "_statespace_update" $ s $ n $ v  
schirmer@25171
   686
                        else raise Match
schirmer@25171
   687
         | NONE => raise Match)
schirmer@25171
   688
     else raise Match
schirmer@25171
   689
  | update_tr' _ _ = raise Match;
schirmer@25171
   690
schirmer@25171
   691
end;
schirmer@25171
   692
schirmer@25171
   693
schirmer@25171
   694
(*** outer syntax *)
schirmer@25171
   695
schirmer@25171
   696
local structure P = OuterParse and K = OuterKeyword in
schirmer@25171
   697
schirmer@25171
   698
val type_insts =
schirmer@25171
   699
  P.typ >> single ||
schirmer@25171
   700
  P.$$$ "(" |-- P.!!! (P.list1 P.typ --| P.$$$ ")") 
schirmer@25171
   701
schirmer@25171
   702
val comp = P.name -- (P.$$$ "::" |-- P.!!! P.typ);
schirmer@25171
   703
fun plus1_unless test scan =
schirmer@25171
   704
  scan -- Scan.repeat (P.$$$ "+" |-- Scan.unless test (P.!!! scan)) >> op ::;
schirmer@25171
   705
schirmer@25171
   706
val mapsto = P.$$$ "=";
schirmer@25171
   707
val rename = P.name -- (mapsto |-- P.name);
schirmer@25171
   708
val renames =  Scan.optional (P.$$$ "[" |-- P.!!! (P.list1 rename --| P.$$$ "]")) [];
schirmer@25171
   709
schirmer@25171
   710
schirmer@25171
   711
val parent = ((type_insts -- P.xname) || (P.xname >> pair [])) -- renames
schirmer@25171
   712
             >> (fn ((insts,name),renames) => (insts,name,renames))
schirmer@25171
   713
schirmer@25171
   714
schirmer@25171
   715
val statespace_decl =
schirmer@25171
   716
   P.type_args -- P.name --
schirmer@25171
   717
    (P.$$$ "=" |-- 
schirmer@25171
   718
     ((Scan.repeat1 comp >> pair []) ||
schirmer@25171
   719
      (plus1_unless comp parent --
schirmer@25171
   720
        Scan.optional (P.$$$ "+" |-- P.!!! (Scan.repeat1 comp)) [])))
schirmer@25171
   721
schirmer@25171
   722
val statespace_command =
schirmer@25171
   723
  OuterSyntax.command "statespace" "define state space" K.thy_decl
schirmer@25171
   724
  (statespace_decl >> (fn ((args,name),(parents,comps)) => 
schirmer@25171
   725
                           Toplevel.theory (define_statespace args name parents comps)))
schirmer@25171
   726
schirmer@25171
   727
end;
schirmer@25171
   728
schirmer@25171
   729
end;