src/HOL/Statespace/state_space.ML
author schirmer
Mon, 12 Nov 2007 11:07:22 +0100
changeset 25408 156f6f7082b8
parent 25171 4a9c25bffc9b
child 25696 c2058af6d9bc
permissions -rw-r--r--
added signatures; tuned

(*  Title:      state_space.ML
    ID:         $Id$
    Author:     Norbert Schirmer, TU Muenchen
*)

signature STATE_SPACE =
  sig
    val KN : string
    val distinct_compsN : string
    val getN : string
    val putN : string
    val injectN : string
    val namespaceN : string
    val projectN : string
    val valuetypesN : string

    val quiet_mode : bool ref

    val namespace_definition :
       bstring ->
       Term.typ ->
       Locale.expr ->
       string list -> string list -> Context.theory -> Context.theory

    val define_statespace :
       string list ->
       string ->
       (string list * bstring * (string * string) list) list ->
       (string * string) list -> Context.theory -> Context.theory
    val define_statespace_i :
       string option ->
       string list ->
       string ->
       (Term.typ list * bstring * (string * string) list) list ->
       (string * Term.typ) list -> Context.theory -> Context.theory

    val statespace_decl :
       OuterParse.token list -> 
       ((string list * bstring) *
         ((string list * xstring * (bstring * bstring) list) list *
          (bstring * string) list)) * OuterParse.token list


    val neq_x_y : Context.proof -> Term.term -> Term.term -> Thm.thm option
    val distinctNameSolver : MetaSimplifier.solver
    val distinctTree_tac :
       Context.proof -> Term.term * int -> Tactical.tactic
    val distinct_simproc : MetaSimplifier.simproc


    val change_simpset : (MetaSimplifier.simpset -> MetaSimplifier.simpset) ->
       Context.generic -> Context.generic

    val get_comp : Context.generic -> string -> (Term.typ * string) Option.option
    val get_silent : Context.generic -> bool
    val set_silent : bool -> Context.generic -> Context.generic

    val read_typ :
       Context.theory ->
       string ->
       (string * Term.sort) list -> Term.typ * (string * Term.sort) list

    val gen_lookup_tr : Context.proof -> Term.term -> string -> Term.term
    val lookup_swap_tr : Context.proof -> Term.term list -> Term.term
    val lookup_tr : Context.proof -> Term.term list -> Term.term
    val lookup_tr' : Context.proof -> Term.term list -> Term.term

    val gen_update_tr :
       bool -> Context.proof -> string -> Term.term -> Term.term -> Term.term
    val update_tr : Context.proof -> Term.term list -> Term.term
    val update_tr' : Context.proof -> Term.term list -> Term.term
  end;


structure StateSpace: STATE_SPACE =
struct

(* Theorems *)

(* Names *)
val distinct_compsN = "distinct_names"
val namespaceN = "_namespace"
val valuetypesN = "_valuetypes"
val projectN = "project"
val injectN = "inject"
val getN = "get"
val putN = "put"
val project_injectL = "StateSpaceLocale.project_inject";
val KN = "StateFun.K_statefun"


(* messages *)

val quiet_mode = ref false;
fun message s = if ! quiet_mode then () else writeln s;

(* Library *)

fun fold1 f xs = fold f (tl xs) (hd xs)
fun fold1' f [] x = x
  | fold1' f xs _ = fold1 f xs
 
fun sublist_idx eq xs ys = 
  let
    fun sublist n xs ys = 
         if is_prefix eq xs ys then SOME n
         else (case ys of [] => NONE
               | (y::ys') => sublist (n+1) xs ys')
  in sublist 0 xs ys end;

fun is_sublist eq xs ys = is_some (sublist_idx eq xs ys);

fun sorted_subset eq [] ys = true
  | sorted_subset eq (x::xs) [] = false
  | sorted_subset eq (x::xs) (y::ys) = if eq (x,y) then sorted_subset eq xs ys
                                       else sorted_subset eq (x::xs) ys;



type namespace_info =
 {declinfo: (typ*string) Termtab.table, (* type, name of statespace *)
  distinctthm: thm Symtab.table,
  silent: bool
 };
 
structure NameSpaceArgs =
struct
  type T = namespace_info; 
  val empty = {declinfo = Termtab.empty, distinctthm = Symtab.empty, silent = false};
  val extend = I;
  fun merge pp ({declinfo=declinfo1, distinctthm=distinctthm1, silent=silent1},
                {declinfo=declinfo2, distinctthm=distinctthm2, silent=silent2}) =
                {declinfo = Termtab.merge (K true) (declinfo1, declinfo2),
                 distinctthm = Symtab.merge (K true) (distinctthm1, distinctthm2),
                 silent = silent1 andalso silent2}
end;

structure NameSpaceData = GenericDataFun(NameSpaceArgs);

fun make_namespace_data declinfo distinctthm silent =
     {declinfo=declinfo,distinctthm=distinctthm,silent=silent};


fun delete_declinfo n ctxt =
  let val {declinfo,distinctthm,silent} = NameSpaceData.get ctxt;
  in NameSpaceData.put 
       (make_namespace_data (Termtab.delete_safe n declinfo) distinctthm silent) ctxt
  end;


fun update_declinfo (n,v) ctxt =
  let val {declinfo,distinctthm,silent} = NameSpaceData.get ctxt;
  in NameSpaceData.put 
      (make_namespace_data (Termtab.update (n,v) declinfo) distinctthm silent) ctxt
  end;

fun set_silent silent ctxt =
  let val {declinfo,distinctthm,...} = NameSpaceData.get ctxt;
  in NameSpaceData.put 
      (make_namespace_data declinfo distinctthm silent) ctxt
  end;

val get_silent = #silent o NameSpaceData.get;
 
fun prove_interpretation_in ctxt_tac (name, expr) thy =
   thy
   |> Locale.interpretation_in_locale I (name, expr)
   |> Proof.global_terminal_proof 
         (Method.Basic (fn ctxt => Method.SIMPLE_METHOD (ctxt_tac ctxt),Position.none), NONE)
   |> ProofContext.theory_of

type statespace_info =
 {args: (string * sort) list, (* type arguments *)
  parents: (typ list * string * string option list) list,
             (* type instantiation, state-space name, component renamings *)
  components: (string * typ) list,
  types: typ list (* range types of state space *)
 };

structure StateSpaceArgs =
struct
  val name = "HOL/StateSpace";
  type T = statespace_info Symtab.table;
  val empty = Symtab.empty;
  val extend = I;

  fun merge pp (nt1,nt2) = Symtab.merge (K true) (nt1, nt2);
end;

structure StateSpaceData = GenericDataFun(StateSpaceArgs);

fun add_statespace name args parents components types ctxt =
     StateSpaceData.put 
      (Symtab.update_new (name, {args=args,parents=parents,
                                components=components,types=types}) (StateSpaceData.get ctxt))
      ctxt; 

fun get_statespace ctxt name =
      Symtab.lookup (StateSpaceData.get ctxt) name;


fun lookupI eq xs n = 
  (case AList.lookup eq xs n of
     SOME v => v
   | NONE => n);
 
fun mk_free ctxt name =
  if Variable.is_fixed ctxt name orelse Variable.is_declared ctxt name 
  then
    let val n' = lookupI (op =) (Variable.fixes_of ctxt) name
    in SOME (Free (n',ProofContext.infer_type ctxt n')) end
  else NONE
  
     
fun get_dist_thm ctxt name = Symtab.lookup (#distinctthm (NameSpaceData.get ctxt)) name;
fun get_comp ctxt name = 
     Option.mapPartial 
       (Termtab.lookup (#declinfo (NameSpaceData.get ctxt))) 
       (mk_free (Context.proof_of ctxt) name);


(*** Tactics ***)

fun neq_x_y ctxt x y =
  (let
    val dist_thm = the (get_dist_thm (Context.Proof ctxt) (#1 (dest_Free x))); 
    val ctree = cprop_of dist_thm |> Thm.dest_comb |> #2 |> Thm.dest_comb |> #2;
    val tree = term_of ctree;
    val x_path = the (DistinctTreeProver.find_tree x tree);
    val y_path = the (DistinctTreeProver.find_tree y tree);
    val thm = DistinctTreeProver.distinctTreeProver dist_thm x_path y_path;
  in SOME thm  
  end handle Option => NONE)

fun distinctTree_tac ctxt 
      (Const ("Trueprop",_) $ 
        (Const ("Not", _) $ (Const ("op =", _) $ (x as Free _)$ (y as Free _))), i) =
  (case (neq_x_y ctxt x y) of
     SOME neq => rtac neq i
   | NONE => no_tac)
  | distinctTree_tac _ _ = no_tac;

val distinctNameSolver = mk_solver' "distinctNameSolver"
     (fn ss => case #context (#1 (rep_ss ss)) of
                 SOME ctxt => SUBGOAL (distinctTree_tac ctxt)
                | NONE => fn i => no_tac)

val distinct_simproc =
  Simplifier.simproc HOL.thy "StateSpace.distinct_simproc" ["x = y"]
    (fn thy => fn ss => (fn (Const ("op =",_)$(x as Free _)$(y as Free _)) =>
        (case #context (#1 (rep_ss ss)) of
          SOME ctxt => Option.map (fn neq => DistinctTreeProver.neq_to_eq_False OF [neq]) 
                       (neq_x_y ctxt x y) 
        | NONE => NONE)
      | _ => NONE))

fun change_simpset f = 
     Context.mapping 
       (fn thy  => (change_simpset_of thy f; thy))
       (fn ctxt => Simplifier.put_local_simpset (f (Simplifier.get_local_simpset ctxt)) ctxt);

fun read_typ thy s =
  Sign.read_typ thy s;

local
  val ss = HOL_basic_ss 
in    
fun interprete_parent name dist_thm_name parent_expr thy = 
  let

    fun solve_tac ctxt (_,i) st =
      let
        val distinct_thm = ProofContext.get_thm ctxt (Name dist_thm_name);
        val goal = List.nth (cprems_of st,i-1);
        val rule = DistinctTreeProver.distinct_implProver distinct_thm goal;
      in EVERY [rtac rule i] st
      end
        
    fun tac ctxt = EVERY [Locale.intro_locales_tac true ctxt [],
                          ALLGOALS (SUBGOAL (solve_tac ctxt))] 
        
  in thy 
     |> prove_interpretation_in tac (name,parent_expr)
  end;        

end;

fun namespace_definition name nameT parent_expr parent_comps new_comps thy = 
  let
    val all_comps = parent_comps @ new_comps;
    val vars = Locale.Merge 
                (map (fn n => Locale.Rename (Locale.Locale (Locale.intern thy "var")
                                            ,[SOME (n,NONE)])) all_comps);

    val full_name = Sign.full_name thy name;
    val dist_thm_name = distinct_compsN;
    val dist_thm_full_name =
        let val prefix = fold1' (fn name => fn prfx => prfx ^ "_" ^ name) all_comps "";
        in if prefix = "" then dist_thm_name else prefix ^ "." ^ dist_thm_name end;

    fun comps_of_thm thm = prop_of thm 
             |> (fn (_$(_$t)) => DistinctTreeProver.dest_tree t) |> map (fst o dest_Free);
 
    fun type_attr phi (ctxt,thm) =
      (case ctxt of Context.Theory _ => (ctxt,thm)
       | _ =>
        let 
          val {declinfo,distinctthm=tt,silent} = (NameSpaceData.get ctxt);
	  val all_names = comps_of_thm thm;
          fun upd name tt =
               (case (Symtab.lookup tt name) of
                 SOME dthm => if sorted_subset (op =) (comps_of_thm dthm) all_names
                              then Symtab.update (name,thm) tt else tt
                | NONE => Symtab.update (name,thm) tt)

          val tt' = tt |> fold upd all_names;
          val activate_simproc =
              Output.no_warnings 
               (change_simpset (fn ss => ss addsimprocs [distinct_simproc]));
          val ctxt' =
              ctxt 
              |> NameSpaceData.put {declinfo=declinfo,distinctthm=tt',silent=silent}
              |> activate_simproc
        in (ctxt',thm) 
        end)
        
    val attr = Attrib.internal type_attr;

    val assumes = Element.Assumes [((dist_thm_name,[attr]), 
                    [(HOLogic.Trueprop $
                      (Const ("DistinctTreeProver.all_distinct",
                                 Type ("DistinctTreeProver.tree",[nameT]) --> HOLogic.boolT) $
                      DistinctTreeProver.mk_tree (fn n => Free (n,nameT)) nameT 
                                (sort fast_string_ord all_comps)),
                      ([]))])];

  in thy 
     |> Locale.add_locale_i (SOME "") name vars [assumes]
     ||> ProofContext.theory_of 
     ||> interprete_parent name dist_thm_full_name parent_expr
     |> #2
  end;

structure Typetab = TableFun(type key=typ val ord = Term.typ_ord);

fun encode_dot x = if x= #"." then #"_" else x;

fun encode_type (TFree (s, _)) = s
  | encode_type (TVar ((s,i),_)) = "?" ^ s ^ string_of_int i
  | encode_type (Type (n,Ts)) = 
      let
        val Ts' = fold1' (fn x => fn y => x ^ "_" ^ y) (map encode_type Ts) "";
        val n' = String.map encode_dot n;
      in if Ts'="" then n' else Ts' ^ "_" ^ n' end;

fun project_name T = projectN ^"_"^encode_type T;
fun inject_name T = injectN ^"_"^encode_type T;

fun project_free T pT V = Free (project_name T, V --> pT);
fun inject_free T pT V = Free (inject_name T, pT --> V);

fun get_name n = getN ^ "_" ^ n;
fun put_name n = putN ^ "_" ^ n;
fun get_const n T nT V = Free (get_name n, (nT --> V) --> T);
fun put_const n T nT V = Free (put_name n, T --> (nT --> V) --> (nT --> V));

fun lookup_const T nT V = Const ("StateFun.lookup",(V --> T) --> nT --> (nT --> V) --> T);
fun update_const T nT V = 
 Const ("StateFun.update",
          (V --> T) --> (T --> V) --> nT --> (T --> T) --> (nT --> V) --> (nT --> V));

fun K_const T = Const ("StateFun.K_statefun",T --> T --> T);

val no_syn = #3 (Syntax.no_syn ((),()));


fun add_declaration name decl thy =
  thy
  |> TheoryTarget.init name
  |> (fn lthy => LocalTheory.declaration (decl lthy) lthy)
  |> LocalTheory.exit 
  |> ProofContext.theory_of;

fun parent_components thy (Ts, pname, renaming) =
  let
    val ctxt = Context.Theory thy;
    fun rename [] xs = xs
      | rename (NONE::rs)  (x::xs) = x::rename rs xs
      | rename (SOME r::rs) ((x,T)::xs) = (r,T)::rename rs xs;
    val {args,parents,components,...} = 
	      the (Symtab.lookup (StateSpaceData.get ctxt) pname);
    val inst = map fst args ~~ Ts;
    val subst = Term.map_type_tfree (the o AList.lookup (op =) inst o fst);
    val parent_comps = 
     List.concat (map (fn (Ts',n,rs) => parent_components thy (map subst Ts',n,rs)) parents);
    val all_comps = rename renaming (parent_comps @ map (apsnd subst) components);
  in all_comps end;

fun take_upto i xs = List.take(xs,i) handle Subscript => xs;

fun statespace_definition state_type args name parents parent_comps components thy =
  let 
    val full_name = Sign.full_name thy name;
    val all_comps = parent_comps @ components;

    val components' = map (fn (n,T) => (n,(T,full_name))) components;
    val all_comps' = map (fn (n,T) => (n,(T,full_name))) all_comps; 
    fun parent_expr (_,n,rs) = Locale.Rename 
                                (Locale.Locale (suffix namespaceN n),
                                 map (Option.map (fn s => (s,NONE))) rs);
    val parents_expr = Locale.Merge (fold (fn p => fn es => parent_expr p::es) parents []);

    fun distinct_types Ts =
      let val tab = fold (fn T => fn tab => Typetab.update (T,()) tab) Ts Typetab.empty;
      in map fst (Typetab.dest tab) end;

    val Ts = distinct_types (map snd all_comps);
    val arg_names = map fst args;
    val valueN = Name.variant arg_names "'value";
    val nameN = Name.variant (valueN::arg_names) "'name";
    val valueT = TFree (valueN, Sign.defaultS thy);
    val nameT = TFree (nameN, Sign.defaultS thy);
    val stateT = nameT --> valueT;
    fun projectT T = valueT --> T;
    fun injectT T = T --> valueT; 

    val locs = map (fn T => Locale.Rename (Locale.Locale project_injectL,
                             [SOME (project_name T,NONE),
                              SOME (inject_name T ,NONE)])) Ts;
    val constrains = List.concat 
         (map (fn T => [(project_name T,projectT T),(inject_name T,injectT T)]) Ts);

    fun interprete_parent_valuetypes (Ts, pname, _) = 
      let
        val {args,types,...} = 
             the (Symtab.lookup (StateSpaceData.get (Context.Theory thy)) pname);
        val inst = map fst args ~~ Ts;
        val subst = Term.map_type_tfree (the o AList.lookup (op =) inst o fst);
        val pars = List.concat (map ((fn T => [project_name T,inject_name T]) o subst) types);
        val expr = Locale.Rename (Locale.Locale (suffix valuetypesN name),
                                  map (fn n => SOME (n,NONE)) pars);
      in prove_interpretation_in (K all_tac) 
           (suffix valuetypesN name, expr) end;

    fun interprete_parent (_, pname, rs) =
      let
        val expr = Locale.Rename (Locale.Locale pname, map (Option.map (fn n => (n,NONE))) rs)
      in prove_interpretation_in 
           (fn ctxt => Locale.intro_locales_tac false ctxt []) 
           (full_name, expr) end;

    fun declare_declinfo updates lthy phi ctxt =
      let
        fun upd_prf ctxt = 
          let
            fun upd (n,v) =
              let
                val nT = ProofContext.infer_type (LocalTheory.target_of lthy) n
              in Context.proof_map 
                  (update_declinfo (Morphism.term phi (Free (n,nT)),v))  
              end;
          in ctxt |> fold upd updates end;

      in Context.mapping I upd_prf ctxt end;

   fun string_of_typ T = 
      setmp show_sorts true 
       (setmp print_mode [] (Syntax.string_of_typ (ProofContext.init thy))) T;
   val fixestate = (case state_type of
         NONE => []
       | SOME s => 
          let 
	    val fx = Element.Fixes [(s,SOME (string_of_typ stateT),NoSyn)];
            val cs = Element.Constrains 
                       (map (fn (n,T) =>  (n,string_of_typ T))
                         ((map (fn (n,_) => (n,nameT)) all_comps) @
                          constrains))
          in [fx,cs] end
       )

   
  in thy 
     |> namespace_definition 
           (suffix namespaceN name) nameT parents_expr 
           (map fst parent_comps) (map fst components)
     |> Context.theory_map (add_statespace full_name args parents components [])
     |> Locale.add_locale_i (SOME "") (suffix valuetypesN name) (Locale.Merge locs) 
            [Element.Constrains constrains]
     |> ProofContext.theory_of o #2
     |> fold interprete_parent_valuetypes parents 
     |> Locale.add_locale (SOME "") name 
              (Locale.Merge [Locale.Locale (suffix namespaceN full_name)
                            ,Locale.Locale (suffix valuetypesN full_name)]) fixestate
     |> ProofContext.theory_of o #2
     |> fold interprete_parent parents
     |> add_declaration (SOME full_name) (declare_declinfo components')
  end;


(* prepare arguments *)

fun read_raw_parent sg s =
  (case Sign.read_typ_abbrev sg s handle TYPE (msg, _, _) => error msg of
    Type (name, Ts) => (Ts, name)
  | _ => error ("Bad parent statespace specification: " ^ quote s));

fun read_typ sg s env  =
  let
    fun def_sort (x, ~1) = AList.lookup (op =) env x
      | def_sort _ = NONE;
    val T = Type.no_tvars (Sign.read_def_typ (sg, def_sort) s) handle TYPE (msg, _, _) => error msg;
  in (T, Term.add_typ_tfrees (T, env)) end;

fun cert_typ sg raw_T env =
  let val T = Type.no_tvars (Sign.certify_typ sg raw_T) handle TYPE (msg, _, _) => error msg
  in (T, Term.add_typ_tfrees (T, env)) end;




fun gen_define_statespace prep_typ state_space args name parents comps thy =
  let (* - args distinct
         - only args may occur in comps and parent-instantiations
         - number of insts must match parent args 
         - no duplicate renamings
         - renaming should occur in namespace
      *)
    val _ = message ("Defining statespace " ^ quote name ^ " ...");

    fun add_parent (Ts,pname,rs) env =
      let
        val full_pname = Sign.full_name thy pname;
        val {args,components,...} = 
              (case get_statespace (Context.Theory thy) full_pname of
                SOME r => r
               | NONE => error ("Undefined statespace " ^ quote pname));


        val (Ts',env') = fold_map (prep_typ thy) Ts env
            handle ERROR msg => cat_error msg 
                    ("The error(s) above occured in parent statespace specification " 
                    ^ quote pname);
        val err_insts = if length args <> length Ts' then
            ["number of type instantiation(s) does not match arguments of parent statespace "
              ^ quote pname]
            else [];
        
        val rnames = map fst rs
        val err_dup_renamings = (case duplicates (op =) rnames of
             [] => []
            | dups => ["Duplicate renaming(s) for " ^ commas dups])

        val cnames = map fst components;
        val err_rename_unknowns = (case (filter (fn n => not (n mem cnames))) rnames of
              [] => []
             | rs => ["Unknown components " ^ commas rs]);
              

        val rs' = map (AList.lookup (op =) rs o fst) components;
        val errs =err_insts @ err_dup_renamings @ err_rename_unknowns
      in if null errs then ((Ts',full_pname,rs'),env')
         else error (cat_lines (errs @ ["in parent statespace " ^ quote pname]))
      end;
 
    val (parents',env) = fold_map add_parent parents [];

    val err_dup_args =
         (case duplicates (op =) args of
            [] => []
          | dups => ["Duplicate type argument(s) " ^ commas dups]);
    

    val err_dup_components = 
         (case duplicates (op =) (map fst comps) of
           [] => []
          | dups => ["Duplicate state-space components " ^ commas dups]);

    fun prep_comp (n,T) env =
      let val (T', env') = prep_typ thy T env handle ERROR msg =>
       cat_error msg ("The error(s) above occured in component " ^ quote n)
      in ((n,T'), env') end;

    val (comps',env') = fold_map prep_comp comps env;

    val err_extra_frees =
      (case subtract (op =) args (map fst env') of
        [] => []
      | extras => ["Extra free type variable(s) " ^ commas extras]);

    val defaultS = Sign.defaultS thy;
    val args' = map (fn x => (x, AList.lookup (op =) env x |> the_default defaultS)) args;


    fun fst_eq ((x:string,_),(y,_)) = x = y;
    fun snd_eq ((_,t:typ),(_,u)) = t = u;              

    val raw_parent_comps = (List.concat (map (parent_components thy) parents'));
    fun check_type (n,T) = 
          (case distinct (snd_eq) (filter (curry fst_eq (n,T)) raw_parent_comps) of
             []  => []
           | [_] => []
           | rs  => ["Different types for component " ^ n ^": " ^ commas 
                       (map (Pretty.string_of o Display.pretty_ctyp o ctyp_of thy o snd) rs)])
                           
    val err_dup_types = List.concat (map check_type (duplicates fst_eq raw_parent_comps))

    val parent_comps = distinct (fst_eq) raw_parent_comps;
    val all_comps = parent_comps @ comps';
    val err_comp_in_parent = (case duplicates (op =) (map fst all_comps) of
               [] => []
             | xs => ["Components already defined in parents: " ^ commas xs]);
    val errs = err_dup_args @ err_dup_components @ err_extra_frees @
               err_dup_types @ err_comp_in_parent;

  in if null errs 
     then thy |> statespace_definition state_space args' name parents' parent_comps comps'
     else error (cat_lines errs) 
  end
  handle ERROR msg => cat_error msg ("Failed to define statespace " ^ quote name);
 

val define_statespace = gen_define_statespace read_typ NONE;
val define_statespace_i = gen_define_statespace cert_typ;
 

(*** parse/print - translations ***)


local
fun map_get_comp f ctxt (Free (name,_)) = 
      (case (get_comp ctxt name) of 
        SOME (T,_) => f T T dummyT 
      | NONE => (Syntax.free "arbitrary"(*; error "context not ready"*)))
  | map_get_comp _ _ _ = Syntax.free "arbitrary";

val get_comp_projection = map_get_comp project_free;
val get_comp_injection  = map_get_comp inject_free;

fun name_of (Free (n,_)) = n;
in

fun gen_lookup_tr ctxt s n = 
      (case get_comp (Context.Proof ctxt) n of
        SOME (T,_) => 
           Syntax.const "StateFun.lookup"$Syntax.free (project_name T)$Syntax.free n$s
       | NONE => 
           if get_silent (Context.Proof ctxt)
	   then Syntax.const "StateFun.lookup"$Syntax.const "arbitrary"$Syntax.free n$s
           else raise TERM ("StateSpace.gen_lookup_tr: component " ^ n ^ " not defined",[]));

fun lookup_tr ctxt [s,Free (n,_)] = gen_lookup_tr ctxt s n;
fun lookup_swap_tr ctxt [Free (n,_),s] = gen_lookup_tr ctxt s n;

fun lookup_tr' ctxt [_$Free (prj,_),n as (_$Free (name,_)),s] =
     ( case get_comp (Context.Proof ctxt) name of
         SOME (T,_) =>  if prj=project_name T then
                           Syntax.const "_statespace_lookup" $ s $ n  
                        else raise Match
      | NONE => raise Match)
  | lookup_tr' _ ts = raise Match;

fun gen_update_tr id ctxt n v s = 
  let
    fun pname T = if id then "Fun.id" else project_name T
    fun iname T = if id then "Fun.id" else inject_name T
   in
     (case get_comp (Context.Proof ctxt) n of
       SOME (T,_) => Syntax.const "StateFun.update"$
                   Syntax.free (pname T)$Syntax.free (iname T)$
                   Syntax.free n$(Syntax.const KN $ v)$s
      | NONE => 
         if get_silent (Context.Proof ctxt) 
         then Syntax.const "StateFun.update"$
                   Syntax.const "arbitrary"$Syntax.const "arbitrary"$
                   Syntax.free n$(Syntax.const KN $ v)$s
         else raise TERM ("StateSpace.gen_update_tr: component " ^ n ^ " not defined",[]))
   end;

fun update_tr ctxt [s,Free (n,_),v] = gen_update_tr false ctxt n v s;

fun update_tr' ctxt [_$Free (prj,_),_$Free (inj,_),n as (_$Free (name,_)),(Const (k,_)$v),s] =
     if NameSpace.base k = NameSpace.base KN then
        (case get_comp (Context.Proof ctxt) name of
          SOME (T,_) => if inj=inject_name T andalso prj=project_name T then
                           Syntax.const "_statespace_update" $ s $ n $ v  
                        else raise Match
         | NONE => raise Match)
     else raise Match
  | update_tr' _ _ = raise Match;

end;


(*** outer syntax *)

local structure P = OuterParse and K = OuterKeyword in

val type_insts =
  P.typ >> single ||
  P.$$$ "(" |-- P.!!! (P.list1 P.typ --| P.$$$ ")") 

val comp = P.name -- (P.$$$ "::" |-- P.!!! P.typ);
fun plus1_unless test scan =
  scan -- Scan.repeat (P.$$$ "+" |-- Scan.unless test (P.!!! scan)) >> op ::;

val mapsto = P.$$$ "=";
val rename = P.name -- (mapsto |-- P.name);
val renames =  Scan.optional (P.$$$ "[" |-- P.!!! (P.list1 rename --| P.$$$ "]")) [];


val parent = ((type_insts -- P.xname) || (P.xname >> pair [])) -- renames
             >> (fn ((insts,name),renames) => (insts,name,renames))


val statespace_decl =
   P.type_args -- P.name --
    (P.$$$ "=" |-- 
     ((Scan.repeat1 comp >> pair []) ||
      (plus1_unless comp parent --
        Scan.optional (P.$$$ "+" |-- P.!!! (Scan.repeat1 comp)) [])))

val statespace_command =
  OuterSyntax.command "statespace" "define state space" K.thy_decl
  (statespace_decl >> (fn ((args,name),(parents,comps)) => 
                           Toplevel.theory (define_statespace args name parents comps)))

end;

end;