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