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