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