src/HOL/Statespace/state_space.ML
author wenzelm
Wed Mar 14 20:34:20 2012 +0100 (2012-03-14)
changeset 46925 98ffc3fe31cc
parent 45741 088256c289e7
child 46949 94aa7b81bcf6
permissions -rw-r--r--
locale expressions without source positions;
     1 (*  Title:      HOL/Statespace/state_space.ML
     2     Author:     Norbert Schirmer, TU Muenchen
     3 *)
     4 
     5 signature STATE_SPACE =
     6 sig
     7   val distinct_compsN : string
     8   val getN : string
     9   val putN : string
    10   val injectN : string
    11   val namespaceN : string
    12   val projectN : string
    13   val valuetypesN : string
    14 
    15   val namespace_definition :
    16      bstring ->
    17      typ ->
    18      (xstring, string) Expression.expr * (binding * string option * mixfix) list ->
    19      string list -> string list -> theory -> theory
    20 
    21   val define_statespace :
    22      string list ->
    23      string ->
    24      (string list * bstring * (string * string) list) list ->
    25      (string * string) list -> theory -> theory
    26   val define_statespace_i :
    27      string option ->
    28      string list ->
    29      string ->
    30      (typ list * bstring * (string * string) list) list ->
    31      (string * typ) list -> theory -> theory
    32 
    33   val statespace_decl :
    34      ((string list * bstring) *
    35        ((string list * xstring * (bstring * bstring) list) list *
    36         (bstring * string) list)) parser
    37 
    38 
    39   val neq_x_y : Proof.context -> term -> term -> thm option
    40   val distinctNameSolver : Simplifier.solver
    41   val distinctTree_tac : Proof.context -> int -> tactic
    42   val distinct_simproc : Simplifier.simproc
    43 
    44 
    45   val get_comp : Context.generic -> string -> (typ * string) Option.option
    46   val get_silent : Context.generic -> bool
    47   val set_silent : bool -> Context.generic -> Context.generic
    48 
    49   val gen_lookup_tr : Proof.context -> term -> string -> term
    50   val lookup_swap_tr : Proof.context -> term list -> term
    51   val lookup_tr : Proof.context -> term list -> term
    52   val lookup_tr' : Proof.context -> term list -> term
    53 
    54   val gen_update_tr :
    55      bool -> Proof.context -> string -> term -> term -> term
    56   val update_tr : Proof.context -> term list -> term
    57   val update_tr' : Proof.context -> term list -> term
    58 end;
    59 
    60 structure StateSpace : STATE_SPACE =
    61 struct
    62 
    63 (* Names *)
    64 
    65 val distinct_compsN = "distinct_names"
    66 val namespaceN = "_namespace"
    67 val valuetypesN = "_valuetypes"
    68 val projectN = "project"
    69 val injectN = "inject"
    70 val getN = "get"
    71 val putN = "put"
    72 val project_injectL = "StateSpaceLocale.project_inject";
    73 
    74 
    75 (* Library *)
    76 
    77 fun fold1 f xs = fold f (tl xs) (hd xs)
    78 fun fold1' f [] x = x
    79   | fold1' f xs _ = fold1 f xs
    80 
    81 fun sublist_idx eq xs ys =
    82   let
    83     fun sublist n xs ys =
    84          if is_prefix eq xs ys then SOME n
    85          else (case ys of [] => NONE
    86                | (y::ys') => sublist (n+1) xs ys')
    87   in sublist 0 xs ys end;
    88 
    89 fun is_sublist eq xs ys = is_some (sublist_idx eq xs ys);
    90 
    91 fun sorted_subset eq [] ys = true
    92   | sorted_subset eq (x::xs) [] = false
    93   | sorted_subset eq (x::xs) (y::ys) = if eq (x,y) then sorted_subset eq xs ys
    94                                        else sorted_subset eq (x::xs) ys;
    95 
    96 
    97 
    98 type namespace_info =
    99  {declinfo: (typ*string) Termtab.table, (* type, name of statespace *)
   100   distinctthm: thm Symtab.table,
   101   silent: bool
   102  };
   103 
   104 structure NameSpaceData = Generic_Data
   105 (
   106   type T = namespace_info;
   107   val empty = {declinfo = Termtab.empty, distinctthm = Symtab.empty, silent = false};
   108   val extend = I;
   109   fun merge
   110     ({declinfo=declinfo1, distinctthm=distinctthm1, silent=silent1},
   111       {declinfo=declinfo2, distinctthm=distinctthm2, silent=silent2}) : T =
   112     {declinfo = Termtab.merge (K true) (declinfo1, declinfo2),
   113      distinctthm = Symtab.merge (K true) (distinctthm1, distinctthm2),
   114      silent = silent1 andalso silent2 (* FIXME odd merge *)}
   115 );
   116 
   117 fun make_namespace_data declinfo distinctthm silent =
   118      {declinfo=declinfo,distinctthm=distinctthm,silent=silent};
   119 
   120 
   121 fun delete_declinfo n ctxt =
   122   let val {declinfo,distinctthm,silent} = NameSpaceData.get ctxt;
   123   in NameSpaceData.put
   124        (make_namespace_data (Termtab.delete_safe n declinfo) distinctthm silent) ctxt
   125   end;
   126 
   127 
   128 fun update_declinfo (n,v) ctxt =
   129   let val {declinfo,distinctthm,silent} = NameSpaceData.get ctxt;
   130   in NameSpaceData.put
   131       (make_namespace_data (Termtab.update (n,v) declinfo) distinctthm silent) ctxt
   132   end;
   133 
   134 fun set_silent silent ctxt =
   135   let val {declinfo,distinctthm,...} = NameSpaceData.get ctxt;
   136   in NameSpaceData.put
   137       (make_namespace_data declinfo distinctthm silent) ctxt
   138   end;
   139 
   140 val get_silent = #silent o NameSpaceData.get;
   141 
   142 fun expression_no_pos (expr, fixes) : Expression.expression =
   143   (map (fn (name, inst) => ((name, Position.none), inst)) expr, fixes);
   144 
   145 fun prove_interpretation_in ctxt_tac (name, expr) thy =
   146    thy
   147    |> Expression.sublocale_cmd I (name, Position.none) (expression_no_pos 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 (expression_no_pos 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.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 =
   229   mk_solver "distinctNameSolver" (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 =>
   236             Option.map (fn neq => DistinctTreeProver.neq_to_eq_False OF [neq])
   237               (neq_x_y ctxt x y)
   238         | NONE => NONE)
   239       | _ => NONE));
   240 
   241 local
   242   val ss = HOL_basic_ss
   243 in
   244 fun interprete_parent name dist_thm_name parent_expr thy =
   245   let
   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
   256     thy |> 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 assume =
   299       ((Binding.name dist_thm_name, [attr]),
   300         [(HOLogic.Trueprop $
   301           (Const (@{const_name all_distinct}, Type (@{type_name tree}, [nameT]) --> HOLogic.boolT) $
   302             DistinctTreeProver.mk_tree (fn n => Free (n, nameT)) nameT
   303               (sort fast_string_ord all_comps)), [])]);
   304   in
   305     thy
   306     |> add_locale name ([], vars) [Element.Assumes [assume]]
   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 =
   333   Const (@{const_name StateFun.lookup}, (V --> T) --> nT --> (nT --> V) --> T);
   334 
   335 fun update_const T nT V =
   336   Const (@{const_name StateFun.update},
   337     (V --> T) --> (T --> V) --> nT --> (T --> T) --> (nT --> V) --> (nT --> V));
   338 
   339 fun K_const T = Const (@{const_name K_statefun}, T --> T --> T);
   340 
   341 
   342 fun add_declaration name decl thy =
   343   thy
   344   |> Named_Target.init I name
   345   |> (fn lthy => Local_Theory.declaration {syntax = false, pervasive = false} (decl lthy) lthy)
   346   |> Local_Theory.exit_global;
   347 
   348 fun parent_components thy (Ts, pname, renaming) =
   349   let
   350     val ctxt = Context.Theory thy;
   351     fun rename [] xs = xs
   352       | rename (NONE::rs)  (x::xs) = x::rename rs xs
   353       | rename (SOME r::rs) ((x,T)::xs) = (r,T)::rename rs xs;
   354     val {args, parents, components, ...} = the (Symtab.lookup (StateSpaceData.get ctxt) pname);
   355     val inst = map fst args ~~ Ts;
   356     val subst = Term.map_type_tfree (the o AList.lookup (op =) inst o fst);
   357     val parent_comps =
   358       maps (fn (Ts',n,rs) => parent_components thy (map subst Ts',n,rs)) parents;
   359     val all_comps = rename renaming (parent_comps @ map (apsnd subst) components);
   360   in all_comps end;
   361 
   362 fun take_upto i xs = List.take(xs,i) handle General.Subscript => xs;
   363 
   364 fun statespace_definition state_type args name parents parent_comps components thy =
   365   let
   366     val full_name = Sign.full_bname thy name;
   367     val all_comps = parent_comps @ components;
   368 
   369     val components' = map (fn (n,T) => (n,(T,full_name))) components;
   370     val all_comps' = map (fn (n,T) => (n,(T,full_name))) all_comps;
   371 
   372     fun parent_expr (_,n,rs) = (suffix namespaceN n,((n,false),Expression.Positional rs));
   373         (* FIXME: a more specific renaming-prefix (including parameter names) may be nicer *)
   374     val parents_expr = map parent_expr parents;
   375     fun distinct_types Ts =
   376       let val tab = fold (fn T => fn tab => Typtab.update (T,()) tab) Ts Typtab.empty;
   377       in map fst (Typtab.dest tab) end;
   378 
   379     val Ts = distinct_types (map snd all_comps);
   380     val arg_names = map fst args;
   381     val valueN = singleton (Name.variant_list arg_names) "'value";
   382     val nameN = singleton (Name.variant_list (valueN :: arg_names)) "'name";
   383     val valueT = TFree (valueN, Sign.defaultS thy);
   384     val nameT = TFree (nameN, Sign.defaultS thy);
   385     val stateT = nameT --> valueT;
   386     fun projectT T = valueT --> T;
   387     fun injectT T = T --> valueT;
   388     val locinsts = map (fn T => (project_injectL,
   389                     (("",false),Expression.Positional
   390                              [SOME (Free (project_name T,projectT T)),
   391                               SOME (Free ((inject_name T,injectT T)))]))) Ts;
   392     val locs = maps (fn T => [(Binding.name (project_name T),NONE,NoSyn),
   393                                      (Binding.name (inject_name T),NONE,NoSyn)]) Ts;
   394     val constrains = maps (fn T => [(project_name T,projectT T),(inject_name T,injectT T)]) Ts;
   395 
   396     fun interprete_parent_valuetypes (Ts, pname, _) thy =
   397       let
   398         val {args,types,...} =
   399              the (Symtab.lookup (StateSpaceData.get (Context.Theory thy)) pname);
   400         val inst = map fst args ~~ Ts;
   401         val subst = Term.map_type_tfree (the o AList.lookup (op =) inst o fst);
   402         val pars = maps ((fn T => [project_name T,inject_name T]) o subst) types;
   403 
   404         val expr = ([(suffix valuetypesN name,
   405                      (("",false),Expression.Positional (map SOME pars)))],[]);
   406       in
   407         prove_interpretation_in (ALLGOALS o solve_tac o Assumption.all_prems_of)
   408           (suffix valuetypesN name, expr) thy
   409       end;
   410 
   411     fun interprete_parent (_, pname, rs) =
   412       let
   413         val expr = ([(pname, (("",false), Expression.Positional rs))],[])
   414       in prove_interpretation_in
   415            (fn ctxt => Locale.intro_locales_tac false ctxt [])
   416            (full_name, expr) end;
   417 
   418     fun declare_declinfo updates lthy phi ctxt =
   419       let
   420         fun upd_prf ctxt =
   421           let
   422             fun upd (n,v) =
   423               let
   424                 val nT = Proof_Context.infer_type (Local_Theory.target_of lthy) (n, dummyT)
   425               in Context.proof_map
   426                   (update_declinfo (Morphism.term phi (Free (n,nT)),v))
   427               end;
   428           in ctxt |> fold upd updates end;
   429 
   430       in Context.mapping I upd_prf ctxt end;
   431 
   432    fun string_of_typ T =
   433       Print_Mode.setmp []
   434         (Syntax.string_of_typ (Config.put show_sorts true (Syntax.init_pretty_global thy))) T;
   435    val fixestate = (case state_type of
   436          NONE => []
   437        | SOME s =>
   438           let
   439             val fx = Element.Fixes [(Binding.name s,SOME (string_of_typ stateT),NoSyn)];
   440             val cs = Element.Constrains
   441                        (map (fn (n,T) =>  (n,string_of_typ T))
   442                          ((map (fn (n,_) => (n,nameT)) all_comps) @
   443                           constrains))
   444           in [fx,cs] end
   445        )
   446 
   447 
   448   in thy
   449      |> namespace_definition
   450            (suffix namespaceN name) nameT (parents_expr,[])
   451            (map fst parent_comps) (map fst components)
   452      |> Context.theory_map (add_statespace full_name args parents components [])
   453      |> add_locale (suffix valuetypesN name) (locinsts,locs) []
   454      |> Proof_Context.theory_of
   455      |> fold interprete_parent_valuetypes parents
   456      |> add_locale_cmd name
   457               ([(suffix namespaceN full_name ,(("",false),Expression.Named [])),
   458                 (suffix valuetypesN full_name,(("",false),Expression.Named  []))],[]) fixestate
   459      |> Proof_Context.theory_of
   460      |> fold interprete_parent parents
   461      |> add_declaration full_name (declare_declinfo components')
   462   end;
   463 
   464 
   465 (* prepare arguments *)
   466 
   467 fun read_raw_parent ctxt raw_T =
   468   (case Proof_Context.read_typ_abbrev ctxt raw_T of
   469     Type (name, Ts) => (Ts, name)
   470   | T => error ("Bad parent statespace specification: " ^ Syntax.string_of_typ ctxt T));
   471 
   472 fun read_typ ctxt raw_T env =
   473   let
   474     val ctxt' = fold (Variable.declare_typ o TFree) env ctxt;
   475     val T = Syntax.read_typ ctxt' raw_T;
   476     val env' = Term.add_tfreesT T env;
   477   in (T, env') end;
   478 
   479 fun cert_typ ctxt raw_T env =
   480   let
   481     val thy = Proof_Context.theory_of ctxt;
   482     val T = Type.no_tvars (Sign.certify_typ thy raw_T)
   483       handle TYPE (msg, _, _) => error msg;
   484     val env' = Term.add_tfreesT T env;
   485   in (T, env') end;
   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 = Proof_Context.init_global 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 occurred 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 subtract (op =) 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 occurred 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 = maps (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 " ^ quote n ^ ": " ^
   571                 commas (map (Syntax.string_of_typ ctxt o snd) rs)])
   572 
   573     val err_dup_types = maps 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_quote 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 read_typ NONE;
   589 val define_statespace_i = gen_define_statespace cert_typ;
   590 
   591 
   592 
   593 (*** parse/print - translations ***)
   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 @{const_name StateFun.lookup} $
   612         Syntax.free (project_name T) $ Syntax.free n $ s
   613   | NONE =>
   614       if get_silent (Context.Proof ctxt)
   615       then Syntax.const @{const_name StateFun.lookup} $
   616         Syntax.const @{const_syntax undefined} $ Syntax.free n $ s
   617       else raise TERM ("StateSpace.gen_lookup_tr: component " ^ quote n ^ " not defined", []));
   618 
   619 fun lookup_tr ctxt [s, x] =
   620   (case Term_Position.strip_positions x of
   621     Free (n,_) => gen_lookup_tr ctxt s n
   622   | _ => raise Match);
   623 
   624 fun lookup_swap_tr ctxt [Free (n,_),s] = gen_lookup_tr ctxt s n;
   625 
   626 fun lookup_tr' ctxt [_ $ Free (prj, _), n as (_ $ Free (name, _)), s] =
   627       (case get_comp (Context.Proof ctxt) name of
   628         SOME (T, _) =>
   629           if prj = project_name T
   630           then Syntax.const "_statespace_lookup" $ s $ n
   631           else raise Match
   632       | NONE => raise Match)
   633   | lookup_tr' _ ts = raise Match;
   634 
   635 fun gen_update_tr id ctxt n v s =
   636   let
   637     fun pname T = if id then @{const_name Fun.id} else project_name T;
   638     fun iname T = if id then @{const_name Fun.id} else inject_name T;
   639   in
   640     (case get_comp (Context.Proof ctxt) n of
   641       SOME (T, _) =>
   642         Syntax.const @{const_name StateFun.update} $
   643           Syntax.free (pname T) $ Syntax.free (iname T) $
   644           Syntax.free n $ (Syntax.const @{const_name K_statefun} $ v) $ s
   645     | NONE =>
   646         if get_silent (Context.Proof ctxt) then
   647           Syntax.const @{const_name StateFun.update} $
   648             Syntax.const @{const_syntax undefined} $ Syntax.const @{const_syntax undefined} $
   649             Syntax.free n $ (Syntax.const @{const_name K_statefun} $ v) $ s
   650        else raise TERM ("StateSpace.gen_update_tr: component " ^ n ^ " not defined", []))
   651    end;
   652 
   653 fun update_tr ctxt [s, x, v] =
   654   (case Term_Position.strip_positions x of
   655     Free (n, _) => gen_update_tr false ctxt n v s
   656   | _ => raise Match);
   657 
   658 fun update_tr' ctxt
   659         [_ $ Free (prj, _), _ $ Free (inj, _), n as (_ $ Free (name, _)), (Const (k, _) $ v), s] =
   660       if Long_Name.base_name k = Long_Name.base_name @{const_name K_statefun} then
   661         (case get_comp (Context.Proof ctxt) name of
   662           SOME (T, _) =>
   663             if inj = inject_name T andalso prj = project_name T then
   664               Syntax.const "_statespace_update" $ s $ n $ v
   665             else raise Match
   666         | NONE => raise Match)
   667      else raise Match
   668   | update_tr' _ _ = raise Match;
   669 
   670 end;
   671 
   672 
   673 (*** outer syntax *)
   674 
   675 local
   676 
   677 val type_insts =
   678   Parse.typ >> single ||
   679   Parse.$$$ "(" |-- Parse.!!! (Parse.list1 Parse.typ --| Parse.$$$ ")")
   680 
   681 val comp = Parse.name -- (Parse.$$$ "::" |-- Parse.!!! Parse.typ);
   682 fun plus1_unless test scan =
   683   scan ::: Scan.repeat (Parse.$$$ "+" |-- Scan.unless test (Parse.!!! scan));
   684 
   685 val mapsto = Parse.$$$ "=";
   686 val rename = Parse.name -- (mapsto |-- Parse.name);
   687 val renames = Scan.optional (Parse.$$$ "[" |-- Parse.!!! (Parse.list1 rename --| Parse.$$$ "]")) [];
   688 
   689 val parent =
   690   ((type_insts -- Parse.xname) || (Parse.xname >> pair [])) -- renames
   691     >> (fn ((insts, name), renames) => (insts,name, renames));
   692 
   693 in
   694 
   695 val statespace_decl =
   696   Parse.type_args -- Parse.name --
   697     (Parse.$$$ "=" |--
   698       ((Scan.repeat1 comp >> pair []) ||
   699         (plus1_unless comp parent --
   700           Scan.optional (Parse.$$$ "+" |-- Parse.!!! (Scan.repeat1 comp)) [])));
   701 val _ =
   702   Outer_Syntax.command "statespace" "define state space" Keyword.thy_decl
   703     (statespace_decl >> (fn ((args, name), (parents, comps)) =>
   704       Toplevel.theory (define_statespace args name parents comps)));
   705 
   706 end;
   707 
   708 end;