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