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