Initial part of locale reimplementation.
authorballarin
Fri Nov 14 16:49:52 2008 +0100 (2008-11-14)
changeset 287956891e273c33b
parent 28794 4493633ab401
child 28796 56cb4130177a
Initial part of locale reimplementation.
src/Pure/IsaMakefile
src/Pure/Isar/ROOT.ML
src/Pure/Isar/expression.ML
src/Pure/Isar/new_locale.ML
     1.1 --- a/src/Pure/IsaMakefile	Fri Nov 14 14:00:52 2008 +0100
     1.2 +++ b/src/Pure/IsaMakefile	Fri Nov 14 16:49:52 2008 +0100
     1.3 @@ -44,6 +44,7 @@
     1.4    Isar/find_theorems.ML Isar/instance.ML Isar/isar.ML Isar/isar_cmd.ML	\
     1.5    Isar/isar_syn.ML Isar/local_defs.ML Isar/local_syntax.ML		\
     1.6    Isar/local_theory.ML Isar/locale.ML Isar/method.ML Isar/net_rules.ML	\
     1.7 +  Isar/new_locale.ML    \
     1.8    Isar/object_logic.ML Isar/obtain.ML Isar/outer_keyword.ML		\
     1.9    Isar/outer_lex.ML Isar/outer_parse.ML Isar/outer_syntax.ML		\
    1.10    Isar/overloading.ML Isar/proof.ML Isar/proof_context.ML		\
     2.1 --- a/src/Pure/Isar/ROOT.ML	Fri Nov 14 14:00:52 2008 +0100
     2.2 +++ b/src/Pure/Isar/ROOT.ML	Fri Nov 14 16:49:52 2008 +0100
     2.3 @@ -54,6 +54,7 @@
     2.4  use "local_theory.ML";
     2.5  use "overloading.ML";
     2.6  use "locale.ML";
     2.7 +use "new_locale.ML";
     2.8  use "expression.ML";
     2.9  use "class.ML";
    2.10  use "theory_target.ML";
     3.1 --- a/src/Pure/Isar/expression.ML	Fri Nov 14 14:00:52 2008 +0100
     3.2 +++ b/src/Pure/Isar/expression.ML	Fri Nov 14 16:49:52 2008 +0100
     3.3 @@ -2,21 +2,31 @@
     3.4      ID:         $Id$
     3.5      Author:     Clemens Ballarin, TU Muenchen
     3.6  
     3.7 -Locale expressions --- experimental.
     3.8 +New locale development --- experimental.
     3.9  *)
    3.10  
    3.11  signature EXPRESSION =
    3.12  sig
    3.13 +  type map
    3.14 +  type 'morph expr
    3.15  
    3.16 -type map
    3.17 -type 'morph expr
    3.18 +  val empty_expr: 'morph expr
    3.19 +
    3.20 +  type expression = (string * map) expr * (Name.binding * string option * mixfix) list
    3.21 +  type expression_i = Morphism.morphism expr * (Name.binding * typ option * mixfix) list
    3.22  
    3.23 -type expression = (string * map) expr * (Name.binding * string option * mixfix) list
    3.24 -type expression_i = Morphism.morphism expr * (Name.binding * typ option * mixfix) list
    3.25 +  (* Declaring locales *)
    3.26 +  val add_locale: string -> bstring -> expression -> Element.context list -> theory ->
    3.27 +    string * Proof.context
    3.28 +(*
    3.29 +  val add_locale_i: string -> bstring -> expression_i -> Element.context_i list -> theory ->
    3.30 +    string * Proof.context
    3.31 +*)
    3.32  
    3.33 -val parse_expr: OuterParse.token list -> expression * OuterParse.token list
    3.34 -val debug_parameters: expression -> Proof.context -> Proof.context
    3.35 -val debug_context: expression -> Proof.context -> Proof.context
    3.36 +  (* Debugging and development *)
    3.37 +  val parse_expression: OuterParse.token list -> expression * OuterParse.token list
    3.38 +  val debug_parameters: expression -> Proof.context -> Proof.context
    3.39 +  val debug_context: expression -> Proof.context -> Proof.context
    3.40  
    3.41  end;
    3.42  
    3.43 @@ -24,7 +34,10 @@
    3.44  structure Expression: EXPRESSION =
    3.45  struct
    3.46  
    3.47 -(* Locale expressions *)
    3.48 +datatype ctxt = datatype Element.ctxt;
    3.49 +
    3.50 +
    3.51 +(*** Expressions ***)
    3.52  
    3.53  datatype map =
    3.54    Positional of string option list |
    3.55 @@ -35,6 +48,8 @@
    3.56  type expression = (string * map) expr * (Name.binding * string option * mixfix) list;
    3.57  type expression_i = Morphism.morphism expr * (Name.binding * typ option * mixfix) list;
    3.58  
    3.59 +val empty_expr = Expr [];
    3.60 +
    3.61  
    3.62  (** Parsing and printing **)
    3.63  
    3.64 @@ -43,7 +58,7 @@
    3.65  structure P = OuterParse;
    3.66  
    3.67  val loc_keyword = P.$$$ "fixes" || P.$$$ "constrains" || P.$$$ "assumes" ||
    3.68 -   P.$$$ "defines" || P.$$$ "notes" || P.$$$ "includes";
    3.69 +   P.$$$ "defines" || P.$$$ "notes";
    3.70  fun plus1_unless test scan =
    3.71    scan ::: Scan.repeat (P.$$$ "+" |-- Scan.unless test (P.!!! scan));
    3.72  
    3.73 @@ -55,7 +70,7 @@
    3.74  
    3.75  in
    3.76  
    3.77 -val parse_expr =
    3.78 +val parse_expression =
    3.79    let
    3.80      fun expr2 x = P.xname x;
    3.81      fun expr1 x = (Scan.optional prefix "" -- expr2 --
    3.82 @@ -65,25 +80,42 @@
    3.83  
    3.84  end;
    3.85  
    3.86 -(*
    3.87 -fun pretty_expr thy (Locale loc) =
    3.88 -      [Pretty.str "Locale", Pretty.brk 1, Pretty.str (Locale.extern thy loc)]
    3.89 -  | pretty_expr thy (Instance (expr, (prfx, Positional insts))) =
    3.90 -      let
    3.91 -        val insts' = (* chop trailing NONEs *)
    3.92 -      
    3.93 -  | pretty_expr thy (Instance (expr, (prfx, Named insts))) =
    3.94 -*)
    3.95 +fun pretty_expr thy (Expr expr) =
    3.96 +  let
    3.97 +    fun pretty_pos NONE = Pretty.str "_"
    3.98 +      | pretty_pos (SOME x) = Pretty.str x;
    3.99 +    fun pretty_named (x, y) = [Pretty.str x, Pretty.brk 1, Pretty.str "=",
   3.100 +          Pretty.brk 1, Pretty.str y] |> Pretty.block;
   3.101 +    fun pretty_ren (Positional ps) = take_suffix is_none ps |> snd |>
   3.102 +          map pretty_pos |> Pretty.breaks
   3.103 +      | pretty_ren (Named []) = []
   3.104 +      | pretty_ren (Named ps) = Pretty.str "where" :: Pretty.brk 1 ::
   3.105 +          (ps |> map pretty_named |> Pretty.separate "and");
   3.106 +    fun pretty_rename (loc, ("", ren)) =
   3.107 +          Pretty.block (Pretty.str (NewLocale.extern thy loc) :: Pretty.brk 1 :: pretty_ren ren) 
   3.108 +      | pretty_rename (loc, (prfx, ren)) =
   3.109 +          Pretty.block (Pretty.str prfx :: Pretty.brk 1 :: Pretty.str (NewLocale.extern thy loc) ::
   3.110 +            Pretty.brk 1 :: pretty_ren ren);
   3.111 +  in Pretty.separate "+" (map pretty_rename expr) |> Pretty.block end;
   3.112 +
   3.113 +fun err_in_expr thy msg (Expr expr) =
   3.114 +  let
   3.115 +    val err_msg =
   3.116 +      if null expr then msg
   3.117 +      else msg ^ "\n" ^ Pretty.string_of (Pretty.block
   3.118 +        [Pretty.str "The above error(s) occurred in expression:", Pretty.brk 1,
   3.119 +          pretty_expr thy (Expr expr)])
   3.120 +  in error err_msg end;
   3.121  
   3.122  
   3.123 -(** Processing of locale expression **)
   3.124 +(** Internalise locale names **)
   3.125  
   3.126 -fun intern thy (Expr instances) = Expr (map (apfst (Locale.intern thy)) instances);
   3.127 +fun intern_expr thy (Expr instances) = Expr (map (apfst (NewLocale.intern thy)) instances);
   3.128  
   3.129  
   3.130 -(* Parameters of expression (not expression_i).
   3.131 +(** Parameters of expression (not expression_i).
   3.132     Sanity check of instantiations.
   3.133 -   Positional instantiations are extended to match full length of parameter list. *)
   3.134 +   Positional instantiations are extended to match full length of parameter list. **)
   3.135  
   3.136  fun parameters thy (expr, fixed : (Name.binding * string option * mixfix) list) =
   3.137    let
   3.138 @@ -93,63 +125,110 @@
   3.139          if null dups then () else error (message ^ commas dups)
   3.140        end;
   3.141  
   3.142 -    fun params2 loc =
   3.143 -          (Locale.parameters_of thy loc |> map (fn ((p, _), mx) => (p, mx)), loc) ;
   3.144 -    fun params1 (loc, (prfx, Positional insts)) =
   3.145 +    fun match_bind (n, b) = (n = Name.name_of b);
   3.146 +    fun bind_eq (b1, b2) = (Name.name_of b1 = Name.name_of b2);
   3.147 +      (* FIXME: cannot compare bindings for equality. *)
   3.148 +
   3.149 +    fun params_loc loc =
   3.150 +          (NewLocale.params_of thy loc |> map (fn (p, _, mx) => (p, mx)), loc)
   3.151 +            handle ERROR msg => err_in_expr thy msg (Expr [(loc, ("", Named []))]);
   3.152 +    fun params_inst (expr as (loc, (prfx, Positional insts))) =
   3.153            let
   3.154 -            val (ps, loc') = params2 loc;
   3.155 +            val (ps, loc') = params_loc loc;
   3.156  	    val d = length ps - length insts;
   3.157  	    val insts' =
   3.158 -	      if d < 0 then error ("More arguments than parameters in instantiation.")
   3.159 -(* FIXME print expr *)
   3.160 +	      if d < 0 then err_in_expr thy "More arguments than parameters in instantiation."
   3.161 +                (Expr [expr])
   3.162  	      else insts @ replicate d NONE;
   3.163              val ps' = (ps ~~ insts') |>
   3.164                map_filter (fn (p, NONE) => SOME p | (_, SOME _) => NONE);
   3.165            in
   3.166              (ps', (loc', (prfx, Positional insts')))
   3.167            end
   3.168 -      | params1 (loc, (prfx, Named insts)) =
   3.169 +      | params_inst (expr as (loc, (prfx, Named insts))) =
   3.170            let
   3.171              val _ = reject_dups "Duplicate instantiation of the following parameter(s): "
   3.172 -              (map fst insts);
   3.173 -(* FIXME print expr *)
   3.174 +              (map fst insts)
   3.175 +              handle ERROR msg => err_in_expr thy msg (Expr [expr]);
   3.176  
   3.177 -            val (ps, loc') = params2 loc;
   3.178 +            val (ps, loc') = params_loc loc;
   3.179              val ps' = fold (fn (p, _) => fn ps =>
   3.180 -              if AList.defined (op =) ps p then AList.delete (op =) p ps
   3.181 -              else error (quote p ^" not a parameter of instantiated expression.")) insts ps;
   3.182 -(* FIXME print expr *)
   3.183 -(* FIXME AList lacks a version of delete that signals the absence of the deleted item *)
   3.184 +              if AList.defined match_bind ps p then AList.delete match_bind p ps
   3.185 +              else err_in_expr thy (quote p ^" not a parameter of instantiated expression.")
   3.186 +                (Expr [expr])) insts ps;
   3.187            in
   3.188              (ps', (loc', (prfx, Named insts)))
   3.189            end;
   3.190 -    fun params0 (Expr is) =
   3.191 +    fun params_expr (Expr is) =
   3.192            let
   3.193              val (is', ps') = fold_map (fn i => fn ps =>
   3.194                let
   3.195 -                val (ps', i') = params1 i;
   3.196 -                val ps'' = AList.join (op =) (fn p => fn (mx1, mx2) =>
   3.197 +                val (ps', i') = params_inst i;
   3.198 +                val ps'' = AList.join bind_eq (fn p => fn (mx1, mx2) =>
   3.199 +                  (* FIXME: should check for bindings being the same.
   3.200 +                     Instead we check for equal name and syntax. *)
   3.201                    if mx1 = mx2 then mx1
   3.202 -                  else error ("Conflicting syntax for parameter" ^ quote p ^ " in expression.")) (ps, ps')
   3.203 -(* FIXME print Expr is *)
   3.204 +                  else err_in_expr thy ("Conflicting syntax for parameter" ^ quote (Name.name_of p) ^ " in expression.")
   3.205 +                    (Expr is)) (ps, ps')
   3.206                in (i', ps'') end) is []
   3.207            in
   3.208              (ps', Expr is')
   3.209            end;
   3.210  
   3.211 -    val (parms, expr') = params0 expr;
   3.212 +    val (parms, expr') = params_expr expr;
   3.213  
   3.214 -    val parms' = map fst parms;
   3.215 +    val parms' = map (fst #> Name.name_of) parms;
   3.216      val fixed' = map (#1 #> Name.name_of) fixed;
   3.217      val _ = reject_dups "Duplicate fixed parameter(s): " fixed';
   3.218      val _ = reject_dups "Parameter(s) declared simultaneously in expression and for clause: " (parms' @ fixed');
   3.219  
   3.220    in (expr', (parms, fixed)) end;
   3.221  
   3.222 +
   3.223 +(** Read instantiation **)
   3.224 +
   3.225 +fun read_inst parse_term parms (prfx, insts) ctxt =
   3.226 +  let
   3.227 +    (* parameters *)
   3.228 +    val (parm_names, parm_types) = split_list parms;
   3.229 +    val type_parm_names = fold Term.add_tfreesT parm_types [] |> map fst;
   3.230 +
   3.231 +    (* parameter instantiations *)
   3.232 +    val insts' = case insts of
   3.233 +      Positional insts => (insts ~~ parm_names) |> map (fn
   3.234 +        (NONE, p) => parse_term ctxt p |
   3.235 +        (SOME t, _) => parse_term ctxt t) |
   3.236 +      Named insts => parm_names |> map (fn
   3.237 +        p => case AList.lookup (op =) insts p of
   3.238 +          SOME t => parse_term ctxt t |
   3.239 +          NONE => parse_term ctxt p);
   3.240 +
   3.241 +    (* type inference and contexts *)
   3.242 +    val parm_types' = map (TypeInfer.paramify_vars o Logic.varifyT) parm_types;
   3.243 +    val type_parms = fold Term.add_tvarsT parm_types' [] |> map (Logic.mk_type o TVar);
   3.244 +    val arg = type_parms @ map2 TypeInfer.constrain parm_types' insts';
   3.245 +    val res = Syntax.check_terms ctxt arg;
   3.246 +    val ctxt' = ctxt |> fold Variable.auto_fixes res;
   3.247 +
   3.248 +    (* instantiation *)
   3.249 +    val (type_parms'', res') = chop (length type_parms) res;
   3.250 +    val insts'' = (parm_names ~~ res') |> map_filter
   3.251 +      (fn (inst as (x, Free (y, _))) => if x = y then NONE else SOME inst |
   3.252 +        inst => SOME inst);
   3.253 +    val instT = Symtab.make (type_parm_names ~~ map Logic.dest_type type_parms'');
   3.254 +    val inst = Symtab.make insts'';
   3.255 +  in
   3.256 +    (Element.inst_morphism (ProofContext.theory_of ctxt) (instT, inst) $>
   3.257 +      Morphism.name_morphism (Name.qualified prfx), ctxt')
   3.258 +  end;
   3.259 +        
   3.260 +        
   3.261 +(** Debugging **)
   3.262 +  
   3.263  fun debug_parameters raw_expr ctxt =
   3.264    let
   3.265      val thy = ProofContext.theory_of ctxt;
   3.266 -    val expr = apfst (intern thy) raw_expr;
   3.267 +    val expr = apfst (intern_expr thy) raw_expr;
   3.268      val (expr', (parms, fixed)) = parameters thy expr;
   3.269    in ctxt end;
   3.270  
   3.271 @@ -157,13 +236,13 @@
   3.272  fun debug_context (raw_expr, fixed) ctxt =
   3.273    let
   3.274      val thy = ProofContext.theory_of ctxt;
   3.275 -    val expr = intern thy raw_expr;
   3.276 +    val expr = intern_expr thy raw_expr;
   3.277      val (expr', (parms, fixed)) = parameters thy (expr, fixed);
   3.278  
   3.279      fun declare_parameters (parms, fixed) ctxt =
   3.280        let
   3.281        val (parms', ctxt') =
   3.282 -        ProofContext.add_fixes (map (fn (p, mx) => (Name.binding p, NONE, mx)) parms) ctxt;
   3.283 +        ProofContext.add_fixes (map (fn (p, mx) => (p, NONE, mx)) parms) ctxt;
   3.284        val (fixed', ctxt'') =
   3.285          ProofContext.add_fixes fixed ctxt';
   3.286        in
   3.287 @@ -173,8 +252,8 @@
   3.288      fun rough_inst loc prfx insts ctxt =
   3.289        let
   3.290          (* locale data *)
   3.291 -        val (parm_names, parm_types) = loc |> Locale.parameters_of thy |>
   3.292 -          map fst |> split_list;
   3.293 +        val (parm_names, parm_types) = loc |> NewLocale.params_of thy |>
   3.294 +          map (fn (b, SOME T, _) => (Name.name_of b, T)) |> split_list;
   3.295  
   3.296          (* type parameters *)
   3.297          val type_parm_names = fold Term.add_tfreesT parm_types [] |> map fst;
   3.298 @@ -211,8 +290,9 @@
   3.299      fun add_declarations loc morph ctxt =
   3.300        let
   3.301          (* locale data *)
   3.302 -        val parms = loc |> Locale.parameters_of thy;
   3.303 -        val (typ_decls, term_decls) = Locale.declarations_of thy loc;
   3.304 +        val parms = loc |> NewLocale.params_of thy |>
   3.305 +          map (fn (b, SOME T, mx) => ((Name.name_of b, T), mx));
   3.306 +        val (typ_decls, term_decls) = NewLocale.declarations_of thy loc;
   3.307  
   3.308          (* declarations from locale *)
   3.309  	val ctxt'' = ctxt |>
   3.310 @@ -227,7 +307,499 @@
   3.311      val (parms, ctxt') = declare_parameters (parms, fixed) ctxt0;
   3.312      val (morph1, ctxt'') = rough_inst loc1 prfx1 insts1 ctxt';
   3.313      val ctxt'' = add_declarations loc1 morph1 ctxt';
   3.314 -  in ctxt'' end;
   3.315 +  in ctxt0 end;
   3.316 +
   3.317 +
   3.318 +(*** Locale processing ***)
   3.319 +
   3.320 +(** Prepare locale elements **)
   3.321 +
   3.322 +local
   3.323 +
   3.324 +fun declare_elem prep_vars (Fixes fixes) ctxt =
   3.325 +      let val (vars, _) = prep_vars fixes ctxt
   3.326 +      in ([], ctxt |> ProofContext.add_fixes_i vars |> snd) end
   3.327 +  | declare_elem prep_vars (Constrains csts) ctxt =
   3.328 +      let val (_, ctxt') = prep_vars (map (fn (x, T) => (Name.binding x, SOME T, NoSyn)) csts) ctxt
   3.329 +      in ([], ctxt') end
   3.330 +  | declare_elem _ (Assumes asms) ctxt = (map #2 asms, ctxt)
   3.331 +  | declare_elem _ (Defines defs) ctxt = (map (fn (_, (t, ps)) => [(t, ps)]) defs, ctxt)
   3.332 +  | declare_elem _ (Notes _) ctxt = ([], ctxt);
   3.333 +
   3.334 +in
   3.335 +
   3.336 +fun declare_elems prep_vars raw_elems ctxt =
   3.337 +  fold_map (declare_elem prep_vars) raw_elems ctxt;
   3.338 +
   3.339 +end;
   3.340 +
   3.341 +local
   3.342 +
   3.343 +val norm_term = Envir.beta_norm oo Term.subst_atomic;
   3.344 +
   3.345 +fun abstract_thm thy eq =
   3.346 +  Thm.assume (Thm.cterm_of thy eq) |> Drule.gen_all |> Drule.abs_def;
   3.347 +
   3.348 +fun bind_def ctxt eq (xs, env, ths) =
   3.349 +  let
   3.350 +    val ((y, T), b) = LocalDefs.abs_def eq;
   3.351 +    val b' = norm_term env b;
   3.352 +    val th = abstract_thm (ProofContext.theory_of ctxt) eq;
   3.353 +    fun err msg = error (msg ^ ": " ^ quote y);
   3.354 +  in
   3.355 +    exists (fn (x, _) => x = y) xs andalso
   3.356 +      err "Attempt to define previously specified variable";
   3.357 +    exists (fn (Free (y', _), _) => y = y' | _ => false) env andalso
   3.358 +      err "Attempt to redefine variable";
   3.359 +    (Term.add_frees b' xs, (Free (y, T), b') :: env, th :: ths)
   3.360 +  end;
   3.361 +
   3.362 +fun eval_text _ (Fixes _) text = text
   3.363 +  | eval_text _ (Constrains _) text = text
   3.364 +  | eval_text _ (Assumes asms)
   3.365 +        (((exts, exts'), (ints, ints')), (xs, env, defs)) =
   3.366 +      let
   3.367 +        val ts = maps (map #1 o #2) asms;
   3.368 +        val ts' = map (norm_term env) ts;
   3.369 +        val spec' = ((exts @ ts, exts' @ ts'), (ints, ints'));
   3.370 +      in (spec', (fold Term.add_frees ts' xs, env, defs)) end
   3.371 +  | eval_text ctxt (Defines defs) (spec, binds) =
   3.372 +      (spec, fold (bind_def ctxt o #1 o #2) defs binds)
   3.373 +  | eval_text _ (Notes _) text = text;
   3.374 +
   3.375 +fun closeup _ false elem = elem
   3.376 +  | closeup ctxt true elem =
   3.377 +      let
   3.378 +        fun close_frees t =
   3.379 +          let
   3.380 +            val rev_frees =
   3.381 +              Term.fold_aterms (fn Free (x, T) =>
   3.382 +                if Variable.is_fixed ctxt x then I else insert (op =) (x, T) | _ => I) t [];
   3.383 +          in Term.list_all_free (rev rev_frees, t) end;
   3.384 +
   3.385 +        fun no_binds [] = []
   3.386 +          | no_binds _ = error "Illegal term bindings in locale element";
   3.387 +      in
   3.388 +        (case elem of
   3.389 +          Assumes asms => Assumes (asms |> map (fn (a, propps) =>
   3.390 +            (a, map (fn (t, ps) => (close_frees t, no_binds ps)) propps)))
   3.391 +        | Defines defs => Defines (defs |> map (fn (a, (t, ps)) =>
   3.392 +            (a, (close_frees (#2 (LocalDefs.cert_def ctxt t)), no_binds ps))))
   3.393 +        | e => e)
   3.394 +      end;
   3.395 +
   3.396 +fun finish_ext_elem parms _ (Fixes fixes, _) = Fixes (map (fn (binding, _, mx) =>
   3.397 +      let val x = Name.name_of binding
   3.398 +      in (binding, AList.lookup (op =) parms x, mx) end) fixes)
   3.399 +  | finish_ext_elem _ _ (Constrains _, _) = Constrains []
   3.400 +  | finish_ext_elem _ close (Assumes asms, propp) =
   3.401 +      close (Assumes (map #1 asms ~~ propp))
   3.402 +  | finish_ext_elem _ close (Defines defs, propp) =
   3.403 +      close (Defines (map #1 defs ~~ map (fn [(t, ps)] => (t, ps)) propp))
   3.404 +  | finish_ext_elem _ _ (Notes facts, _) = Notes facts;
   3.405 +
   3.406 +fun finish_elem ctxt parms do_close (elem, propp) text =
   3.407 +  let
   3.408 +    val elem' = finish_ext_elem parms (closeup ctxt do_close) (elem, propp);
   3.409 +    val text' = eval_text ctxt elem' text;
   3.410 +  in (elem', text') end
   3.411 +  
   3.412 +in
   3.413 +
   3.414 +fun finish_elems ctxt parms do_close elems text =
   3.415 +  fold_map (finish_elem ctxt parms do_close) elems text;
   3.416 +
   3.417 +end;
   3.418 +
   3.419 +
   3.420 +local
   3.421 +
   3.422 +fun param_types ps = map_filter (fn (_, NONE) => NONE | (x, SOME T) => SOME (x, T)) ps;
   3.423 +
   3.424 +fun frozen_tvars ctxt Ts =
   3.425 +  #1 (Variable.importT_inst (map Logic.mk_type Ts) ctxt)
   3.426 +  |> map (fn ((xi, S), T) => (xi, (S, T)));
   3.427 +
   3.428 +fun unify_frozen ctxt maxidx Ts Us =
   3.429 +  let
   3.430 +    fun paramify NONE i = (NONE, i)
   3.431 +      | paramify (SOME T) i = apfst SOME (TypeInfer.paramify_dummies T i);
   3.432 +
   3.433 +    val (Ts', maxidx') = fold_map paramify Ts maxidx;
   3.434 +    val (Us', maxidx'') = fold_map paramify Us maxidx';
   3.435 +    val thy = ProofContext.theory_of ctxt;
   3.436 +
   3.437 +    fun unify (SOME T, SOME U) env = (Sign.typ_unify thy (U, T) env
   3.438 +          handle Type.TUNIFY => raise TYPE ("unify_frozen: failed to unify types", [U, T], []))
   3.439 +      | unify _ env = env;
   3.440 +    val (unifier, _) = fold unify (Ts' ~~ Us') (Vartab.empty, maxidx'');
   3.441 +    val Vs = map (Option.map (Envir.norm_type unifier)) Us';
   3.442 +    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (map_filter I Vs));
   3.443 +  in map (Option.map (Envir.norm_type unifier')) Vs end;
   3.444 +
   3.445 +fun prep_elems prep_vars prepp do_close context raw_elems raw_concl =
   3.446 +  let
   3.447 +    val (raw_propps, raw_ctxt) = declare_elems prep_vars raw_elems context;
   3.448 +      (* raw_ctxt is context enriched by syntax from raw_elems *)
   3.449 +
   3.450 +    fun prep_prop raw_propp (raw_ctxt, raw_concl) =
   3.451 +      let
   3.452 +        (* process patterns (conclusion and external elements) *)
   3.453 +        val (ctxt, all_propp) = prepp (raw_ctxt, raw_concl @ raw_propp);
   3.454 +        (* add type information from conclusion and external elements to context *)
   3.455 +        val ctxt = fold Variable.declare_term (maps (map fst) all_propp) ctxt;
   3.456 +        (* resolve schematic variables (patterns) in conclusion and external elements. *)
   3.457 +        val all_propp' = map2 (curry (op ~~))
   3.458 +          (#1 (#2 (ProofContext.bind_propp_schematic_i (ctxt, all_propp)))) (map (map snd) all_propp);
   3.459 +        val (concl, propp) = chop (length raw_concl) all_propp';
   3.460 +      in (propp, (ctxt, concl)) end
   3.461 +
   3.462 +    val (propps, (ctxt, concl)) = fold_burrow prep_prop raw_propps (raw_ctxt, raw_concl);
   3.463 +
   3.464 +    (* Infer parameter types *) 
   3.465 +    val xs = fold (fn Fixes fixes => (fn ps => ps @ map (Name.name_of o #1) fixes) |
   3.466 +      _ => fn ps => ps) raw_elems [];
   3.467 +    val typing = unify_frozen ctxt 0
   3.468 +      (map (Variable.default_type raw_ctxt) xs)
   3.469 +      (map (Variable.default_type ctxt) xs);
   3.470 +    val parms = param_types (xs ~~ typing);
   3.471 +
   3.472 +    (* CB: extract information from assumes and defines elements
   3.473 +       (fixes, constrains and notes in raw_elemss don't have an effect on
   3.474 +       text and elemss), compute final form of context elements. *)
   3.475 +   val (elems, text) = finish_elems ctxt parms do_close
   3.476 +      (raw_elems ~~ propps) ((([], []), ([], [])), ([], [], []));
   3.477 +    (* CB: text has the following structure:
   3.478 +           (((exts, exts'), (ints, ints')), (xs, env, defs))
   3.479 +       where
   3.480 +         exts: external assumptions (terms in external assumes elements)
   3.481 +         exts': dito, normalised wrt. env
   3.482 +         ints: internal assumptions (terms in internal assumes elements)
   3.483 +         ints': dito, normalised wrt. env
   3.484 +         xs: the free variables in exts' and ints' and rhss of definitions,
   3.485 +           this includes parameters except defined parameters
   3.486 +         env: list of term pairs encoding substitutions, where the first term
   3.487 +           is a free variable; substitutions represent defines elements and
   3.488 +           the rhs is normalised wrt. the previous env
   3.489 +         defs: theorems representing the substitutions from defines elements
   3.490 +           (thms are normalised wrt. env).
   3.491 +       elems is an updated version of raw_elems:
   3.492 +         - type info added to Fixes and modified in Constrains
   3.493 +         - axiom and definition statement replaced by corresponding one
   3.494 +           from proppss in Assumes and Defines
   3.495 +         - Facts unchanged
   3.496 +       *)
   3.497 +   in ((parms, elems, concl), text) end
   3.498 +
   3.499 +in
   3.500 +
   3.501 +fun read_elems x = prep_elems ProofContext.read_vars ProofContext.read_propp_schematic x;
   3.502 +fun cert_elems x = prep_elems ProofContext.cert_vars ProofContext.cert_propp_schematic x;
   3.503 +
   3.504 +end;
   3.505 +
   3.506 +
   3.507 +(* facts and attributes *)
   3.508 +
   3.509 +local
   3.510 +
   3.511 +fun check_name name =
   3.512 +  if NameSpace.is_qualified name then error ("Illegal qualified name: " ^ quote name)
   3.513 +  else name;
   3.514 +
   3.515 +fun prep_facts prep_name get intern ctxt elem = elem |> Element.map_ctxt
   3.516 +     {var = I, typ = I, term = I,
   3.517 +      name = Name.map_name prep_name,
   3.518 +      fact = get ctxt,
   3.519 +      attrib = Args.assignable o intern (ProofContext.theory_of ctxt)};
   3.520 +
   3.521 +in
   3.522 +
   3.523 +fun read_facts x = prep_facts check_name ProofContext.get_fact Attrib.intern_src x;
   3.524 +fun cert_facts x = prep_facts I (K I) (K I) x;
   3.525 +
   3.526 +end;
   3.527 +
   3.528 +
   3.529 +(* activate elements in context, return elements and facts *)
   3.530 +
   3.531 +local
   3.532 +
   3.533 +fun axioms_export axs _ As =
   3.534 +  (Element.satisfy_thm axs #> Drule.implies_intr_list (Library.drop (length axs, As)), fn t => t);
   3.535  
   3.536  
   3.537 +(* NB: derived ids contain only facts at this stage *)
   3.538 +
   3.539 +fun activate_elem (Fixes fixes) ctxt =
   3.540 +      ([], ctxt |> ProofContext.add_fixes_i fixes |> snd)
   3.541 +  | activate_elem (Constrains _) ctxt =
   3.542 +      ([], ctxt)
   3.543 +  | activate_elem (Assumes asms) ctxt =
   3.544 +      let
   3.545 +        val asms' = Attrib.map_specs (Attrib.attribute_i (ProofContext.theory_of ctxt)) asms;
   3.546 +        val ts = maps (map #1 o #2) asms';
   3.547 +        val (_, ctxt') =
   3.548 +          ctxt |> fold Variable.auto_fixes ts
   3.549 +          |> ProofContext.add_assms_i (axioms_export []) asms';
   3.550 +      in ([], ctxt') end
   3.551 +  | activate_elem (Defines defs) ctxt =
   3.552 +      let
   3.553 +        val defs' = Attrib.map_specs (Attrib.attribute_i (ProofContext.theory_of ctxt)) defs;
   3.554 +        val asms = defs' |> map (fn ((name, atts), (t, ps)) =>
   3.555 +            let val ((c, _), t') = LocalDefs.cert_def ctxt t
   3.556 +            in (t', ((Name.map_name (Thm.def_name_optional c) name, atts), [(t', ps)])) end);
   3.557 +        val (_, ctxt') =
   3.558 +          ctxt |> fold (Variable.auto_fixes o #1) asms
   3.559 +          |> ProofContext.add_assms_i LocalDefs.def_export (map #2 asms);
   3.560 +      in ([], ctxt') end
   3.561 +  | activate_elem (Notes (kind, facts)) ctxt =
   3.562 +      let
   3.563 +        val facts' = Attrib.map_facts (Attrib.attribute_i (ProofContext.theory_of ctxt)) facts;
   3.564 +        val (res, ctxt') = ctxt |> ProofContext.note_thmss_i kind facts';
   3.565 +      in ((map (#1 o #1) facts' ~~ map #2 res), ctxt') end;
   3.566 +
   3.567 +in
   3.568 +
   3.569 +fun activate_elems prep_facts raw_elems ctxt =
   3.570 +  let
   3.571 +    val elems = map (prep_facts ctxt) raw_elems;
   3.572 +    val (res, ctxt') = fold_map activate_elem elems (ProofContext.qualified_names ctxt);
   3.573 +    val elems' = elems |> map (Element.map_ctxt_attrib Args.closure);
   3.574 +  in ((elems', flat res), ProofContext.restore_naming ctxt ctxt') end;
   3.575 +
   3.576  end;
   3.577 +
   3.578 +
   3.579 +(* full context statements: import + elements + conclusion *)
   3.580 +
   3.581 +local
   3.582 +
   3.583 +fun prep_context_statement prep_expr prep_elems prep_facts
   3.584 +    do_close imprt elements raw_concl context =
   3.585 +  let
   3.586 +    val thy = ProofContext.theory_of context;
   3.587 +
   3.588 +    val (expr, (params, fors)) = parameters thy (apfst (prep_expr thy) imprt);
   3.589 +    val ctxt = context |>
   3.590 +      ProofContext.add_fixes (map (fn (b, mx) => (b, NONE, mx)) params) |> snd |>
   3.591 +      ProofContext.add_fixes fors |> snd;
   3.592 +  in
   3.593 +    case expr of
   3.594 +        Expr [] => let
   3.595 +          val ((parms, elems, concl), (spec, (_, _, defs))) = prep_elems do_close
   3.596 +            context elements raw_concl;
   3.597 +          val ((elems', _), ctxt') =
   3.598 +            activate_elems prep_facts elems (ProofContext.set_stmt true ctxt);
   3.599 +        in
   3.600 +          (((ctxt', elems'), (parms, spec, defs)), concl)
   3.601 +        end
   3.602 +(*
   3.603 +        | Expr [(name, insts)] => let
   3.604 +          val parms = parameters_of thy name |> map (fn (b, SOME T, _) => (Name.name_of b, T));
   3.605 +          val (morph, ctxt') = read_inst parms insts context;
   3.606 +        in
   3.607 +          
   3.608 +        end
   3.609 +*)
   3.610 +end
   3.611 +
   3.612 +in
   3.613 +
   3.614 +fun read_context imprt body ctxt =
   3.615 +  #1 (prep_context_statement intern_expr read_elems read_facts true imprt body [] ctxt);
   3.616 +(*
   3.617 +fun cert_context imprt body ctxt =
   3.618 +  #1 (prep_context_statement (K I) cert_elems cert_facts true imprt body [] ctxt);
   3.619 +*)
   3.620 +end;
   3.621 +
   3.622 +
   3.623 +(** Dependencies **)
   3.624 +
   3.625 +
   3.626 +
   3.627 +(*** Locale declarations ***)
   3.628 +
   3.629 +local
   3.630 +
   3.631 +(* introN: name of theorems for introduction rules of locale and
   3.632 +     delta predicates;
   3.633 +   axiomsN: name of theorem set with destruct rules for locale predicates,
   3.634 +     also name suffix of delta predicates. *)
   3.635 +
   3.636 +val introN = "intro";
   3.637 +val axiomsN = "axioms";
   3.638 +
   3.639 +fun atomize_spec thy ts =
   3.640 +  let
   3.641 +    val t = Logic.mk_conjunction_balanced ts;
   3.642 +    val body = ObjectLogic.atomize_term thy t;
   3.643 +    val bodyT = Term.fastype_of body;
   3.644 +  in
   3.645 +    if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of thy t))
   3.646 +    else (body, bodyT, ObjectLogic.atomize (Thm.cterm_of thy t))
   3.647 +  end;
   3.648 +
   3.649 +(* achieve plain syntax for locale predicates (without "PROP") *)
   3.650 +
   3.651 +fun aprop_tr' n c = (Syntax.constN ^ c, fn ctxt => fn args =>
   3.652 +  if length args = n then
   3.653 +    Syntax.const "_aprop" $
   3.654 +      Term.list_comb (Syntax.free (Consts.extern (ProofContext.consts_of ctxt) c), args)
   3.655 +  else raise Match);
   3.656 +
   3.657 +(* CB: define one predicate including its intro rule and axioms
   3.658 +   - bname: predicate name
   3.659 +   - parms: locale parameters
   3.660 +   - defs: thms representing substitutions from defines elements
   3.661 +   - ts: terms representing locale assumptions (not normalised wrt. defs)
   3.662 +   - norm_ts: terms representing locale assumptions (normalised wrt. defs)
   3.663 +   - thy: the theory
   3.664 +*)
   3.665 +
   3.666 +fun def_pred bname parms defs ts norm_ts thy =
   3.667 +  let
   3.668 +    val name = Sign.full_name thy bname;
   3.669 +
   3.670 +    val (body, bodyT, body_eq) = atomize_spec thy norm_ts;
   3.671 +    val env = Term.add_term_free_names (body, []);
   3.672 +    val xs = filter (member (op =) env o #1) parms;
   3.673 +    val Ts = map #2 xs;
   3.674 +    val extraTs = (Term.term_tfrees body \\ fold Term.add_tfreesT Ts [])
   3.675 +      |> Library.sort_wrt #1 |> map TFree;
   3.676 +    val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
   3.677 +
   3.678 +    val args = map Logic.mk_type extraTs @ map Free xs;
   3.679 +    val head = Term.list_comb (Const (name, predT), args);
   3.680 +    val statement = ObjectLogic.ensure_propT thy head;
   3.681 +
   3.682 +    val ([pred_def], defs_thy) =
   3.683 +      thy
   3.684 +      |> bodyT = propT ? Sign.add_advanced_trfuns ([], [], [aprop_tr' (length args) name], [])
   3.685 +      |> Sign.declare_const [] ((Name.binding bname, predT), NoSyn) |> snd
   3.686 +      |> PureThy.add_defs false
   3.687 +        [((Thm.def_name bname, Logic.mk_equals (head, body)), [Thm.kind_internal])];
   3.688 +    val defs_ctxt = ProofContext.init defs_thy |> Variable.declare_term head;
   3.689 +
   3.690 +    val cert = Thm.cterm_of defs_thy;
   3.691 +
   3.692 +    val intro = Goal.prove_global defs_thy [] norm_ts statement (fn _ =>
   3.693 +      MetaSimplifier.rewrite_goals_tac [pred_def] THEN
   3.694 +      Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
   3.695 +      Tactic.compose_tac (false,
   3.696 +        Conjunction.intr_balanced (map (Thm.assume o cert) norm_ts), 0) 1);
   3.697 +
   3.698 +    val conjuncts =
   3.699 +      (Drule.equal_elim_rule2 OF [body_eq,
   3.700 +        MetaSimplifier.rewrite_rule [pred_def] (Thm.assume (cert statement))])
   3.701 +      |> Conjunction.elim_balanced (length ts);
   3.702 +    val axioms = ts ~~ conjuncts |> map (fn (t, ax) =>
   3.703 +      Element.prove_witness defs_ctxt t
   3.704 +       (MetaSimplifier.rewrite_goals_tac defs THEN
   3.705 +        Tactic.compose_tac (false, ax, 0) 1));
   3.706 +  in ((statement, intro, axioms), defs_thy) end;
   3.707 +
   3.708 +in
   3.709 +
   3.710 +(* CB: main predicate definition function *)
   3.711 +
   3.712 +fun define_preds pname (parms, ((exts, exts'), (ints, ints')), defs) thy =
   3.713 +  let
   3.714 +    val (a_pred, a_intro, a_axioms, thy'') =
   3.715 +      if null exts then (NONE, NONE, [], thy)
   3.716 +      else
   3.717 +        let
   3.718 +          val aname = if null ints then pname else pname ^ "_" ^ axiomsN;
   3.719 +          val ((statement, intro, axioms), thy') =
   3.720 +            thy
   3.721 +            |> def_pred aname parms defs exts exts';
   3.722 +          val (_, thy'') =
   3.723 +            thy'
   3.724 +            |> Sign.add_path aname
   3.725 +            |> Sign.no_base_names
   3.726 +            |> PureThy.note_thmss Thm.internalK [((Name.binding introN, []), [([intro], [])])]
   3.727 +            ||> Sign.restore_naming thy';
   3.728 +          in (SOME statement, SOME intro, axioms, thy'') end;
   3.729 +    val (b_pred, b_intro, b_axioms, thy'''') =
   3.730 +      if null ints then (NONE, NONE, [], thy'')
   3.731 +      else
   3.732 +        let
   3.733 +          val ((statement, intro, axioms), thy''') =
   3.734 +            thy''
   3.735 +            |> def_pred pname parms defs (ints @ the_list a_pred) (ints' @ the_list a_pred);
   3.736 +          val (_, thy'''') =
   3.737 +            thy'''
   3.738 +            |> Sign.add_path pname
   3.739 +            |> Sign.no_base_names
   3.740 +            |> PureThy.note_thmss Thm.internalK
   3.741 +                 [((Name.binding introN, []), [([intro], [])]),
   3.742 +                  ((Name.binding axiomsN, []),
   3.743 +                    [(map (Drule.standard o Element.conclude_witness) axioms, [])])]
   3.744 +            ||> Sign.restore_naming thy''';
   3.745 +        in (SOME statement, SOME intro, axioms, thy'''') end;
   3.746 +  in ((a_pred, a_intro, a_axioms), (b_pred, b_intro, b_axioms), thy'''') end;
   3.747 +
   3.748 +end;
   3.749 +
   3.750 +
   3.751 +local
   3.752 +
   3.753 +fun assumes_to_notes (Assumes asms) axms =
   3.754 +      fold_map (fn (a, spec) => fn axs =>
   3.755 +          let val (ps, qs) = chop (length spec) axs
   3.756 +          in ((a, [(ps, [])]), qs) end) asms axms
   3.757 +      |> apfst (curry Notes Thm.assumptionK)
   3.758 +  | assumes_to_notes e axms = (e, axms);
   3.759 +
   3.760 +fun defines_to_notes thy (Defines defs) defns =
   3.761 +    let
   3.762 +      val defs' = map (fn (_, (def, _)) => def) defs
   3.763 +      val notes = map (fn (a, (def, _)) =>
   3.764 +        (a, [([assume (cterm_of thy def)], [])])) defs
   3.765 +    in
   3.766 +      (Notes (Thm.definitionK, notes), defns @ defs')
   3.767 +    end
   3.768 +  | defines_to_notes _ e defns = (e, defns);
   3.769 +
   3.770 +fun gen_add_locale prep_ctxt
   3.771 +    bname predicate_name raw_imprt raw_body thy =
   3.772 +  let
   3.773 +    val thy_ctxt = ProofContext.init thy;
   3.774 +    val name = Sign.full_name thy bname;
   3.775 +    val _ = NewLocale.test_locale thy name andalso
   3.776 +      error ("Duplicate definition of locale " ^ quote name);
   3.777 +
   3.778 +    val ((body_ctxt, body_elems), text as (parms, ((_, exts'), _), defs)) =
   3.779 +      prep_ctxt raw_imprt raw_body thy_ctxt;
   3.780 +    val ((statement, intro, axioms), _, thy') =
   3.781 +      define_preds predicate_name text thy;
   3.782 +
   3.783 +    val extraTs = fold Term.add_tfrees exts' [] \\ fold Term.add_tfreesT (map snd parms) [];
   3.784 +    val _ = if null extraTs then ()
   3.785 +      else warning ("Additional type variable(s) in locale specification " ^ quote bname);
   3.786 +
   3.787 +    val params = body_elems |>
   3.788 +      map_filter (fn Fixes fixes => SOME fixes | _ => NONE) |> flat;
   3.789 +
   3.790 +    val (body_elems', defns) = fold_map (defines_to_notes thy) body_elems [];
   3.791 +
   3.792 +    val notes = body_elems' |>
   3.793 +      (fn elems => fold_map assumes_to_notes elems (map Element.conclude_witness axioms)) |>
   3.794 +      fst |>
   3.795 +      map_filter (fn Notes notes => SOME notes | _ => NONE);
   3.796 +
   3.797 +    val loc_ctxt = thy' |>
   3.798 +      NewLocale.register_locale name (extraTs, params) (statement, defns) ([], [])
   3.799 +        (map (fn n => (n, stamp ())) notes |> rev) [] |>
   3.800 +      NewLocale.init name
   3.801 +  in (name, loc_ctxt) end;
   3.802 +
   3.803 +in
   3.804 +
   3.805 +val add_locale = gen_add_locale read_context;
   3.806 +(* val add_locale_i = gen_add_locale cert_context; *)
   3.807 +
   3.808 +end;
   3.809 +
   3.810 +end;
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/src/Pure/Isar/new_locale.ML	Fri Nov 14 16:49:52 2008 +0100
     4.3 @@ -0,0 +1,234 @@
     4.4 +(*  Title:      Pure/Isar/expression.ML
     4.5 +    ID:         $Id$
     4.6 +    Author:     Clemens Ballarin, TU Muenchen
     4.7 +
     4.8 +New locale development --- experimental.
     4.9 +*)
    4.10 +
    4.11 +signature NEW_LOCALE =
    4.12 +sig
    4.13 +  type locale
    4.14 +
    4.15 +  val test_locale: theory -> string -> bool
    4.16 +  val register_locale: string ->
    4.17 +    (string * sort) list * (Name.binding * typ option * mixfix) list ->
    4.18 +    term option * term list ->
    4.19 +    (declaration * stamp) list * (declaration * stamp) list ->
    4.20 +    ((string * (Attrib.binding * (thm list * Attrib.src list) list) list) * stamp) list ->
    4.21 +    ((string * Morphism.morphism) * stamp) list -> theory -> theory
    4.22 +
    4.23 +  (* Locale name space *)
    4.24 +  val intern: theory -> xstring -> string
    4.25 +  val extern: theory -> string -> xstring
    4.26 +
    4.27 +  (* Specification *)
    4.28 +  val params_of: theory -> string -> (Name.binding * typ option * mixfix) list
    4.29 +  val declarations_of: theory -> string -> declaration list * declaration list;
    4.30 +
    4.31 +  (* Evaluate locales *)
    4.32 +  val init: string -> theory -> Proof.context
    4.33 +
    4.34 +  (* Diagnostic *)
    4.35 +  val print_locales: theory -> unit
    4.36 +  val print_locale: theory -> bool -> bstring -> unit
    4.37 +end;
    4.38 +
    4.39 +
    4.40 +structure NewLocale: NEW_LOCALE =
    4.41 +struct
    4.42 +
    4.43 +datatype ctxt = datatype Element.ctxt;
    4.44 +
    4.45 +
    4.46 +(*** Basics ***)
    4.47 +
    4.48 +datatype locale = Loc of {
    4.49 +  (* extensible lists are in reverse order: decls, notes, dependencies *)
    4.50 +  parameters: (string * sort) list * (Name.binding * typ option * mixfix) list,
    4.51 +    (* type and term parameters *)
    4.52 +  spec: term option * term list,
    4.53 +    (* assumptions (as a single predicate expression) and defines *)
    4.54 +  decls: (declaration * stamp) list * (declaration * stamp) list,
    4.55 +    (* type and term syntax declarations *)
    4.56 +  notes: ((string * (Attrib.binding * (thm list * Attrib.src list) list) list) * stamp) list,
    4.57 +    (* theorem declarations *)
    4.58 +  dependencies: ((string * Morphism.morphism) * stamp) list
    4.59 +    (* locale dependencies (sublocale relation) *)
    4.60 +}
    4.61 +
    4.62 +
    4.63 +(*** Theory data ***)
    4.64 +
    4.65 +structure LocalesData = TheoryDataFun
    4.66 +(
    4.67 +  type T = NameSpace.T * locale Symtab.table;
    4.68 +    (* locale namespace and locales of the theory *)
    4.69 +
    4.70 +  val empty = (NameSpace.empty, Symtab.empty);
    4.71 +  val copy = I;
    4.72 +  val extend = I;
    4.73 +
    4.74 +  fun join_locales _
    4.75 +    (Loc {parameters, spec, decls = (decls1, decls2), notes, dependencies},
    4.76 +      Loc {decls = (decls1', decls2'), notes = notes',
    4.77 +        dependencies = dependencies', ...}) =
    4.78 +        let fun s_merge x = merge (eq_snd (op =)) x in
    4.79 +          Loc {parameters = parameters,
    4.80 +            spec = spec,
    4.81 +            decls = (s_merge (decls1, decls1'), s_merge (decls2, decls2')),
    4.82 +            notes = s_merge (notes, notes'),
    4.83 +            dependencies = s_merge (dependencies, dependencies')
    4.84 +          }          
    4.85 +        end;
    4.86 +  fun merge _ ((space1, locs1), (space2, locs2)) =
    4.87 +    (NameSpace.merge (space1, space2), Symtab.join join_locales (locs1, locs2));
    4.88 +);
    4.89 +
    4.90 +val intern = NameSpace.intern o #1 o LocalesData.get;
    4.91 +val extern = NameSpace.extern o #1 o LocalesData.get;
    4.92 +
    4.93 +fun get_locale thy name = Symtab.lookup (#2 (LocalesData.get thy)) name;
    4.94 +
    4.95 +fun the_locale thy name = case get_locale thy name
    4.96 + of SOME loc => loc
    4.97 +  | NONE => error ("Unknown locale " ^ quote name);
    4.98 +
    4.99 +fun test_locale thy name = case get_locale thy name
   4.100 + of SOME _ => true | NONE => false;
   4.101 +
   4.102 +fun register_locale name parameters spec decls notes dependencies thy =
   4.103 +  thy |> LocalesData.map (fn (space, locs) =>
   4.104 +    (Sign.declare_name thy name space, Symtab.update (name,
   4.105 +      Loc {parameters = parameters, spec = spec, decls = decls, notes = notes,
   4.106 +        dependencies = dependencies}) locs));
   4.107 +
   4.108 +fun change_locale name f thy =
   4.109 +  let
   4.110 +    val Loc {parameters, spec, decls, notes, dependencies} =
   4.111 +        the_locale thy name;
   4.112 +    val (parameters', spec', decls', notes', dependencies') =
   4.113 +      f (parameters, spec, decls, notes, dependencies);
   4.114 +  in
   4.115 +    thy
   4.116 +    |> (LocalesData.map o apsnd) (Symtab.update (name, Loc {parameters = parameters',
   4.117 +      spec = spec', decls = decls', notes = notes', dependencies = dependencies'}))
   4.118 +  end;
   4.119 +
   4.120 +fun print_locales thy =
   4.121 +  let val (space, locs) = LocalesData.get thy in
   4.122 +    Pretty.strs ("locales:" :: map #1 (NameSpace.extern_table (space, locs)))
   4.123 +    |> Pretty.writeln
   4.124 +  end;
   4.125 +
   4.126 +
   4.127 +(*** Primitive operations ***)
   4.128 +
   4.129 +fun params_of thy name =
   4.130 +  let
   4.131 +    val Loc {parameters = (_, params), ...} = the_locale thy name
   4.132 +  in params end;
   4.133 +
   4.134 +fun declarations_of thy loc =
   4.135 +  let
   4.136 +    val Loc {decls, ...} = the_locale thy loc
   4.137 +  in
   4.138 +    decls |> apfst (map fst) |> apsnd (map fst)
   4.139 +  end;
   4.140 +
   4.141 +
   4.142 +(*** Target context ***)
   4.143 +
   4.144 +(* round up locale dependencies in a depth-first fashion *)
   4.145 +
   4.146 +local
   4.147 +
   4.148 +structure Idtab = TableFun(type key = string * term list
   4.149 +  val ord = prod_ord string_ord (list_ord Term.fast_term_ord));
   4.150 +
   4.151 +in
   4.152 +
   4.153 +fun roundup thy deps =
   4.154 +  let
   4.155 +    fun add (name, morph) (deps, marked) =
   4.156 +      let
   4.157 +        val Loc {parameters = (_, params), dependencies, ...} = the_locale thy name;
   4.158 +        val instance = params |>
   4.159 +          map ((fn (b, T, _) => Free (Name.name_of b, the T)) #> Morphism.term morph);
   4.160 +      in
   4.161 +        if Idtab.defined marked (name, instance)
   4.162 +        then (deps, marked)
   4.163 +        else
   4.164 +          let
   4.165 +            val dependencies' =
   4.166 +              map (fn ((name, morph'), _) => (name, morph' $>  morph)) dependencies;
   4.167 +            val marked' = Idtab.insert (op =) ((name, instance), ()) marked;
   4.168 +            val (deps', marked'') = fold_rev add dependencies' ([], marked');
   4.169 +          in
   4.170 +            (cons (name, morph) deps' @ deps, marked'')
   4.171 +          end
   4.172 +      end
   4.173 +  in fold_rev add deps ([], Idtab.empty) |> fst end;
   4.174 +
   4.175 +end;
   4.176 +
   4.177 +
   4.178 +(* full context *)
   4.179 +
   4.180 +fun make_asms NONE = []
   4.181 +  | make_asms (SOME asm) = [((Name.no_binding, []), [(asm, [])])];
   4.182 +
   4.183 +fun make_defs [] = []
   4.184 +  | make_defs defs = [((Name.no_binding, []), map (fn def => (def, [])) defs)];
   4.185 +
   4.186 +fun note_notes (name, morph) ctxt =
   4.187 +  let
   4.188 +    val thy = ProofContext.theory_of ctxt;
   4.189 +    val Loc {notes, ...} = the_locale (ProofContext.theory_of ctxt) name;
   4.190 +    fun activate ((kind, facts), _) ctxt =
   4.191 +      let
   4.192 +        val facts' = facts |> Element.facts_map (Element.morph_ctxt morph) |>
   4.193 +          Attrib.map_facts (Attrib.attribute_i thy);
   4.194 +      in fold (fn args => Locale.local_note_prefix kind args #> snd) facts' ctxt end;
   4.195 +  in
   4.196 +    fold_rev activate notes ctxt
   4.197 +  end;
   4.198 +
   4.199 +fun init name thy =
   4.200 +  let
   4.201 +    val Loc {parameters = (_, params), spec = (asm, defs), dependencies, ...} =
   4.202 +      the_locale thy name;
   4.203 +    val dependencies' =
   4.204 +      (intern thy name, Morphism.identity) :: roundup thy (map fst dependencies);
   4.205 +  in
   4.206 +    thy |> ProofContext.init |>
   4.207 +      ProofContext.add_fixes_i params |> snd |>
   4.208 +      (* FIXME type parameters *)
   4.209 +      fold Variable.auto_fixes (the_list asm) |>
   4.210 +      ProofContext.add_assms_i Assumption.assume_export (make_asms asm) |> snd |>
   4.211 +      fold Variable.auto_fixes defs |>
   4.212 +      ProofContext.add_assms_i LocalDefs.def_export (make_defs defs) |> snd |>
   4.213 +      fold_rev note_notes dependencies'
   4.214 +  end;
   4.215 +
   4.216 +fun print_locale thy show_facts name =
   4.217 +  let
   4.218 +    val Loc {parameters = (tparams, params), spec = (asm, defs), notes, ...} =
   4.219 +      the_locale thy (intern thy name);
   4.220 +
   4.221 +    val fixes = [Fixes params];
   4.222 +    val assumes = case asm of NONE => [] |
   4.223 +      SOME spec => [Assumes [(Attrib.no_binding, [(spec, [])])]];
   4.224 +    val defines = case defs of [] => [] |
   4.225 +      defs => [Defines (map (fn def => (Attrib.no_binding, (def, []))) defs)];
   4.226 +    val notes = if show_facts then map (Notes o fst) notes else [];
   4.227 +    val ctxt = ProofContext.init thy;
   4.228 +  in
   4.229 +    Pretty.big_list "locale elements:"
   4.230 +      (fixes @ assumes @ defines @ notes |> map (Element.pretty_ctxt ctxt) |>
   4.231 +        map Pretty.chunks) |> Pretty.writeln
   4.232 +  end;
   4.233 +
   4.234 +
   4.235 +end;
   4.236 +
   4.237 +