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