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