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