src/Pure/Isar/expression.ML
author wenzelm
Wed Dec 31 18:53:17 2008 +0100 (2008-12-31)
changeset 29272 fb3ccf499df5
parent 29254 ef3e2c3399d7
child 29288 253bcf2a5854
permissions -rw-r--r--
use regular Term.add_XXX etc.;
ballarin@28697
     1
(*  Title:      Pure/Isar/expression.ML
ballarin@28697
     2
    Author:     Clemens Ballarin, TU Muenchen
ballarin@28697
     3
ballarin@28795
     4
New locale development --- experimental.
ballarin@28697
     5
*)
ballarin@28697
     6
ballarin@28697
     7
signature EXPRESSION =
ballarin@28697
     8
sig
ballarin@28885
     9
  datatype 'term map = Positional of 'term option list | Named of (string * 'term) list;
ballarin@29214
    10
  type 'term expr = (string * ((string * bool) * 'term map)) list;
haftmann@28965
    11
  type expression = string expr * (Binding.T * string option * mixfix) list;
haftmann@28965
    12
  type expression_i = term expr * (Binding.T * typ option * mixfix) list;
ballarin@28697
    13
ballarin@28898
    14
  (* Processing of context statements *)
ballarin@28879
    15
  val read_statement: Element.context list -> (string * string list) list list ->
ballarin@28879
    16
    Proof.context ->  (term * term list) list list * Proof.context;
ballarin@28879
    17
  val cert_statement: Element.context_i list -> (term * term list) list list ->
ballarin@28879
    18
    Proof.context -> (term * term list) list list * Proof.context;
ballarin@28879
    19
ballarin@28795
    20
  (* Declaring locales *)
ballarin@28902
    21
  val add_locale_cmd: string -> bstring -> expression -> Element.context list -> theory ->
ballarin@29028
    22
    (string * (string * (Attrib.binding * (thm list * Attrib.src list) list) list) list) *
ballarin@29028
    23
    Proof.context
ballarin@28902
    24
  val add_locale: string -> bstring -> expression_i -> Element.context_i list -> theory ->
ballarin@29028
    25
    (string * (string * (Attrib.binding * (thm list * Attrib.src list) list) list) list) *
ballarin@29028
    26
    Proof.context
ballarin@28885
    27
ballarin@28895
    28
  (* Interpretation *)
ballarin@28951
    29
  val sublocale_cmd: string -> expression -> theory -> Proof.state;
ballarin@28951
    30
  val sublocale: string -> expression_i -> theory -> Proof.state;
ballarin@29211
    31
  val interpretation_cmd: expression -> (Attrib.binding * string) list -> theory -> Proof.state;
ballarin@29211
    32
  val interpretation: expression_i -> (Attrib.binding * term) list -> theory -> Proof.state;
ballarin@29018
    33
  val interpret_cmd: expression -> bool -> Proof.state -> Proof.state;
ballarin@29018
    34
  val interpret: expression_i -> bool -> Proof.state -> Proof.state;
ballarin@28697
    35
end;
ballarin@28697
    36
ballarin@28697
    37
ballarin@28885
    38
structure Expression : EXPRESSION =
ballarin@28697
    39
struct
ballarin@28697
    40
ballarin@28795
    41
datatype ctxt = datatype Element.ctxt;
ballarin@28795
    42
ballarin@28795
    43
ballarin@28795
    44
(*** Expressions ***)
ballarin@28697
    45
ballarin@28872
    46
datatype 'term map =
ballarin@28872
    47
  Positional of 'term option list |
ballarin@28872
    48
  Named of (string * 'term) list;
ballarin@28697
    49
ballarin@29214
    50
type 'term expr = (string * ((string * bool) * 'term map)) list;
ballarin@28697
    51
haftmann@28965
    52
type expression = string expr * (Binding.T * string option * mixfix) list;
haftmann@28965
    53
type expression_i = term expr * (Binding.T * typ option * mixfix) list;
ballarin@28795
    54
ballarin@28697
    55
ballarin@28859
    56
(** Internalise locale names in expr **)
ballarin@28697
    57
ballarin@28885
    58
fun intern thy instances =  map (apfst (NewLocale.intern thy)) instances;
ballarin@28697
    59
ballarin@28697
    60
ballarin@28859
    61
(** Parameters of expression.
ballarin@28697
    62
ballarin@28895
    63
   Sanity check of instantiations and extraction of implicit parameters.
ballarin@28895
    64
   The latter only occurs iff strict = false.
ballarin@28895
    65
   Positional instantiations are extended to match full length of parameter list
ballarin@28895
    66
   of instantiated locale. **)
ballarin@28895
    67
ballarin@28895
    68
fun parameters_of thy strict (expr, fixed) =
ballarin@28697
    69
  let
ballarin@28697
    70
    fun reject_dups message xs =
ballarin@28697
    71
      let val dups = duplicates (op =) xs
ballarin@28697
    72
      in
ballarin@28697
    73
        if null dups then () else error (message ^ commas dups)
ballarin@28697
    74
      end;
ballarin@28697
    75
haftmann@29006
    76
    fun match_bind (n, b) = (n = Binding.base_name b);
ballarin@29030
    77
    fun parm_eq ((b1, mx1), (b2, mx2)) =
ballarin@29030
    78
      (* FIXME: cannot compare bindings for equality, instead check for equal name and syntax *)
ballarin@29030
    79
      (Binding.base_name b1 = Binding.base_name b2) andalso
ballarin@29030
    80
      (if mx1 = mx2 then true
ballarin@29030
    81
      else error ("Conflicting syntax for parameter" ^ quote (Binding.display b1) ^
ballarin@29030
    82
                    " in expression."));
ballarin@29030
    83
      
haftmann@29006
    84
    fun bind_eq (b1, b2) = (Binding.base_name b1 = Binding.base_name b2);
ballarin@28795
    85
      (* FIXME: cannot compare bindings for equality. *)
ballarin@28795
    86
ballarin@28795
    87
    fun params_loc loc =
ballarin@28859
    88
          (NewLocale.params_of thy loc |> map (fn (p, _, mx) => (p, mx)), loc);
ballarin@28795
    89
    fun params_inst (expr as (loc, (prfx, Positional insts))) =
ballarin@28697
    90
          let
ballarin@28795
    91
            val (ps, loc') = params_loc loc;
ballarin@28697
    92
	    val d = length ps - length insts;
ballarin@28697
    93
	    val insts' =
ballarin@28879
    94
	      if d < 0 then error ("More arguments than parameters in instantiation of locale " ^
ballarin@28879
    95
                quote (NewLocale.extern thy loc))
ballarin@28697
    96
	      else insts @ replicate d NONE;
ballarin@28697
    97
            val ps' = (ps ~~ insts') |>
ballarin@28697
    98
              map_filter (fn (p, NONE) => SOME p | (_, SOME _) => NONE);
ballarin@28885
    99
          in (ps', (loc', (prfx, Positional insts'))) end
ballarin@28795
   100
      | params_inst (expr as (loc, (prfx, Named insts))) =
ballarin@28697
   101
          let
ballarin@28697
   102
            val _ = reject_dups "Duplicate instantiation of the following parameter(s): "
ballarin@28859
   103
              (map fst insts);
ballarin@28697
   104
ballarin@28795
   105
            val (ps, loc') = params_loc loc;
ballarin@28697
   106
            val ps' = fold (fn (p, _) => fn ps =>
ballarin@28795
   107
              if AList.defined match_bind ps p then AList.delete match_bind p ps
ballarin@28859
   108
              else error (quote p ^" not a parameter of instantiated expression.")) insts ps;
ballarin@28885
   109
          in (ps', (loc', (prfx, Named insts))) end;
ballarin@28885
   110
    fun params_expr is =
ballarin@28697
   111
          let
ballarin@28697
   112
            val (is', ps') = fold_map (fn i => fn ps =>
ballarin@28697
   113
              let
ballarin@28795
   114
                val (ps', i') = params_inst i;
ballarin@29030
   115
                val ps'' = distinct parm_eq (ps @ ps');
ballarin@28697
   116
              in (i', ps'') end) is []
ballarin@28885
   117
          in (ps', is') end;
ballarin@28697
   118
ballarin@28895
   119
    val (implicit, expr') = params_expr expr;
ballarin@28697
   120
haftmann@29006
   121
    val implicit' = map (#1 #> Binding.base_name) implicit;
haftmann@29006
   122
    val fixed' = map (#1 #> Binding.base_name) fixed;
ballarin@28697
   123
    val _ = reject_dups "Duplicate fixed parameter(s): " fixed';
ballarin@28895
   124
    val implicit'' = if strict then []
ballarin@28895
   125
      else let val _ = reject_dups
ballarin@28895
   126
          "Parameter(s) declared simultaneously in expression and for clause: " (implicit' @ fixed')
ballarin@28895
   127
        in map (fn (b, mx) => (b, NONE, mx)) implicit end;
ballarin@28697
   128
ballarin@28895
   129
  in (expr', implicit'' @ fixed) end;
ballarin@28697
   130
ballarin@28795
   131
ballarin@28795
   132
(** Read instantiation **)
ballarin@28795
   133
ballarin@28872
   134
(* Parse positional or named instantiation *)
ballarin@28872
   135
ballarin@28859
   136
local
ballarin@28859
   137
ballarin@28872
   138
fun prep_inst parse_term parms (Positional insts) ctxt =
ballarin@28872
   139
      (insts ~~ parms) |> map (fn
ballarin@28872
   140
        (NONE, p) => Syntax.parse_term ctxt p |
ballarin@28872
   141
        (SOME t, _) => parse_term ctxt t)
ballarin@28872
   142
  | prep_inst parse_term parms (Named insts) ctxt =
ballarin@28872
   143
      parms |> map (fn p => case AList.lookup (op =) insts p of
ballarin@28872
   144
        SOME t => parse_term ctxt t |
ballarin@28872
   145
        NONE => Syntax.parse_term ctxt p);
ballarin@28872
   146
ballarin@28872
   147
in
ballarin@28872
   148
ballarin@28872
   149
fun parse_inst x = prep_inst Syntax.parse_term x;
ballarin@28872
   150
fun make_inst x = prep_inst (K I) x;
ballarin@28872
   151
ballarin@28872
   152
end;
ballarin@28872
   153
ballarin@28872
   154
ballarin@28872
   155
(* Instantiation morphism *)
ballarin@28872
   156
ballarin@29214
   157
fun inst_morph (parm_names, parm_types) ((prfx, strict), insts') ctxt =
ballarin@28795
   158
  let
ballarin@28795
   159
    (* parameters *)
ballarin@28795
   160
    val type_parm_names = fold Term.add_tfreesT parm_types [] |> map fst;
ballarin@28795
   161
ballarin@28795
   162
    (* type inference and contexts *)
ballarin@28795
   163
    val parm_types' = map (TypeInfer.paramify_vars o Logic.varifyT) parm_types;
ballarin@28795
   164
    val type_parms = fold Term.add_tvarsT parm_types' [] |> map (Logic.mk_type o TVar);
ballarin@28795
   165
    val arg = type_parms @ map2 TypeInfer.constrain parm_types' insts';
ballarin@28795
   166
    val res = Syntax.check_terms ctxt arg;
ballarin@28795
   167
    val ctxt' = ctxt |> fold Variable.auto_fixes res;
ballarin@28872
   168
    
ballarin@28795
   169
    (* instantiation *)
ballarin@28795
   170
    val (type_parms'', res') = chop (length type_parms) res;
ballarin@28795
   171
    val insts'' = (parm_names ~~ res') |> map_filter
ballarin@28795
   172
      (fn (inst as (x, Free (y, _))) => if x = y then NONE else SOME inst |
ballarin@28795
   173
        inst => SOME inst);
ballarin@28795
   174
    val instT = Symtab.make (type_parm_names ~~ map Logic.dest_type type_parms'');
ballarin@28795
   175
    val inst = Symtab.make insts'';
ballarin@28795
   176
  in
ballarin@28795
   177
    (Element.inst_morphism (ProofContext.theory_of ctxt) (instT, inst) $>
ballarin@29214
   178
      Morphism.binding_morphism (Binding.add_prefix strict prfx), ctxt')
ballarin@28795
   179
  end;
ballarin@28859
   180
ballarin@28795
   181
ballarin@28795
   182
(*** Locale processing ***)
ballarin@28795
   183
ballarin@28852
   184
(** Parsing **)
ballarin@28852
   185
ballarin@28852
   186
fun parse_elem prep_typ prep_term ctxt elem =
ballarin@29215
   187
  Element.map_ctxt' {binding = I, var = I, typ = prep_typ ctxt,
ballarin@29215
   188
  term = prep_term (ProofContext.set_mode ProofContext.mode_schematic ctxt), (* FIXME ?? *)
ballarin@29215
   189
  pat = prep_term (ProofContext.set_mode ProofContext.mode_pattern ctxt),
ballarin@29215
   190
  fact = I, attrib = I} elem;
ballarin@28852
   191
ballarin@28852
   192
fun parse_concl prep_term ctxt concl =
ballarin@28852
   193
  (map o map) (fn (t, ps) =>
ballarin@29215
   194
    (prep_term (ProofContext.set_mode ProofContext.mode_schematic ctxt) t, (* FIXME ?? *)
ballarin@29215
   195
      map (prep_term (ProofContext.set_mode ProofContext.mode_pattern ctxt)) ps)) concl;
ballarin@28852
   196
ballarin@28852
   197
ballarin@28885
   198
(** Simultaneous type inference: instantiations + elements + conclusion **)
ballarin@28885
   199
ballarin@28885
   200
local
ballarin@28885
   201
ballarin@28885
   202
fun mk_type T = (Logic.mk_type T, []);
ballarin@28885
   203
fun mk_term t = (t, []);
ballarin@28885
   204
fun mk_propp (p, pats) = (Syntax.type_constraint propT p, pats);
ballarin@28852
   205
ballarin@28885
   206
fun dest_type (T, []) = Logic.dest_type T;
ballarin@28885
   207
fun dest_term (t, []) = t;
ballarin@28885
   208
fun dest_propp (p, pats) = (p, pats);
ballarin@28885
   209
ballarin@28885
   210
fun extract_inst (_, (_, ts)) = map mk_term ts;
ballarin@28885
   211
fun restore_inst ((l, (p, _)), cs) = (l, (p, map dest_term cs));
ballarin@28885
   212
ballarin@28885
   213
fun extract_elem (Fixes fixes) = map (#2 #> the_list #> map mk_type) fixes
ballarin@28885
   214
  | extract_elem (Constrains csts) = map (#2 #> single #> map mk_type) csts
ballarin@28885
   215
  | extract_elem (Assumes asms) = map (#2 #> map mk_propp) asms
ballarin@28885
   216
  | extract_elem (Defines defs) = map (fn (_, (t, ps)) => [mk_propp (t, ps)]) defs
ballarin@28852
   217
  | extract_elem (Notes _) = [];
ballarin@28795
   218
ballarin@28885
   219
fun restore_elem (Fixes fixes, css) =
ballarin@28885
   220
      (fixes ~~ css) |> map (fn ((x, _, mx), cs) =>
ballarin@28885
   221
        (x, cs |> map dest_type |> try hd, mx)) |> Fixes
ballarin@28885
   222
  | restore_elem (Constrains csts, css) =
ballarin@28885
   223
      (csts ~~ css) |> map (fn ((x, _), cs) =>
ballarin@28885
   224
        (x, cs |> map dest_type |> hd)) |> Constrains
ballarin@28885
   225
  | restore_elem (Assumes asms, css) =
ballarin@28885
   226
      (asms ~~ css) |> map (fn ((b, _), cs) => (b, map dest_propp cs)) |> Assumes
ballarin@28885
   227
  | restore_elem (Defines defs, css) =
ballarin@28885
   228
      (defs ~~ css) |> map (fn ((b, _), [c]) => (b, dest_propp c)) |> Defines
ballarin@28852
   229
  | restore_elem (Notes notes, _) = Notes notes;
ballarin@28852
   230
ballarin@28885
   231
fun check cs context =
ballarin@28885
   232
  let
ballarin@28885
   233
    fun prep (_, pats) (ctxt, t :: ts) =
ballarin@28885
   234
      let val ctxt' = Variable.auto_fixes t ctxt
ballarin@28885
   235
      in
ballarin@28885
   236
        ((t, Syntax.check_props (ProofContext.set_mode ProofContext.mode_pattern ctxt') pats),
ballarin@28885
   237
          (ctxt', ts))
ballarin@28885
   238
      end
ballarin@28885
   239
    val (cs', (context', _)) = fold_map prep cs
ballarin@28885
   240
      (context, Syntax.check_terms
ballarin@28885
   241
        (ProofContext.set_mode ProofContext.mode_schematic context) (map fst cs));
ballarin@28885
   242
  in (cs', context') end;
ballarin@28885
   243
ballarin@28885
   244
in
ballarin@28885
   245
ballarin@28872
   246
fun check_autofix insts elems concl ctxt =
ballarin@28852
   247
  let
ballarin@28885
   248
    val inst_cs = map extract_inst insts;
ballarin@28885
   249
    val elem_css = map extract_elem elems;
ballarin@28885
   250
    val concl_cs = (map o map) mk_propp concl;
ballarin@28885
   251
    (* Type inference *)
ballarin@28885
   252
    val (inst_cs' :: css', ctxt') =
ballarin@28885
   253
      (fold_burrow o fold_burrow) check (inst_cs :: elem_css @ [concl_cs]) ctxt;
ballarin@28936
   254
    val (elem_css', [concl_cs']) = chop (length elem_css) css';
ballarin@28885
   255
  in
ballarin@28936
   256
    (map restore_inst (insts ~~ inst_cs'), map restore_elem (elems ~~ elem_css'),
ballarin@28936
   257
      concl_cs', ctxt')
ballarin@28885
   258
  end;
ballarin@28885
   259
ballarin@28885
   260
end;
ballarin@28852
   261
ballarin@28852
   262
ballarin@28852
   263
(** Prepare locale elements **)
ballarin@28795
   264
ballarin@28795
   265
fun declare_elem prep_vars (Fixes fixes) ctxt =
ballarin@28795
   266
      let val (vars, _) = prep_vars fixes ctxt
ballarin@28852
   267
      in ctxt |> ProofContext.add_fixes_i vars |> snd end
ballarin@28795
   268
  | declare_elem prep_vars (Constrains csts) ctxt =
haftmann@28965
   269
      ctxt |> prep_vars (map (fn (x, T) => (Binding.name x, SOME T, NoSyn)) csts) |> snd
ballarin@28872
   270
  | declare_elem _ (Assumes _) ctxt = ctxt
ballarin@28872
   271
  | declare_elem _ (Defines _) ctxt = ctxt
ballarin@28852
   272
  | declare_elem _ (Notes _) ctxt = ctxt;
ballarin@28795
   273
ballarin@29221
   274
(** Finish locale elements **)
ballarin@28795
   275
ballarin@28852
   276
fun closeup _ _ false elem = elem
ballarin@28852
   277
  | closeup ctxt parms true elem =
ballarin@28795
   278
      let
ballarin@28795
   279
        fun close_frees t =
ballarin@28795
   280
          let
ballarin@28795
   281
            val rev_frees =
ballarin@28795
   282
              Term.fold_aterms (fn Free (x, T) =>
ballarin@28852
   283
                if AList.defined (op =) parms x then I else insert (op =) (x, T) | _ => I) t [];
ballarin@29021
   284
          in Term.list_all_free (rev rev_frees, t) end; (* FIXME use fold Logic.all *)
ballarin@29019
   285
  (* FIXME consider closing in syntactic phase *)
ballarin@28795
   286
ballarin@28795
   287
        fun no_binds [] = []
ballarin@28852
   288
          | no_binds _ = error "Illegal term bindings in context element";
ballarin@28795
   289
      in
ballarin@28795
   290
        (case elem of
ballarin@28795
   291
          Assumes asms => Assumes (asms |> map (fn (a, propps) =>
ballarin@28795
   292
            (a, map (fn (t, ps) => (close_frees t, no_binds ps)) propps)))
ballarin@29022
   293
        | Defines defs => Defines (defs |> map (fn ((name, atts), (t, ps)) =>
ballarin@29022
   294
            let val ((c, _), t') = LocalDefs.cert_def ctxt (close_frees t)
ballarin@29022
   295
            in
ballarin@29022
   296
              ((Binding.map_base (Thm.def_name_optional c) name, atts), (t', no_binds ps))
ballarin@29022
   297
            end))
ballarin@28795
   298
        | e => e)
ballarin@28795
   299
      end;
ballarin@28795
   300
ballarin@28872
   301
fun finish_primitive parms _ (Fixes fixes) = Fixes (map (fn (binding, _, mx) =>
haftmann@29006
   302
      let val x = Binding.base_name binding
ballarin@28795
   303
      in (binding, AList.lookup (op =) parms x, mx) end) fixes)
ballarin@28872
   304
  | finish_primitive _ _ (Constrains _) = Constrains []
ballarin@28872
   305
  | finish_primitive _ close (Assumes asms) = close (Assumes asms)
ballarin@28872
   306
  | finish_primitive _ close (Defines defs) = close (Defines defs)
ballarin@28872
   307
  | finish_primitive _ _ (Notes facts) = Notes facts;
ballarin@28872
   308
ballarin@29221
   309
fun finish_inst ctxt parms do_close (loc, (prfx, inst)) =
ballarin@28872
   310
  let
ballarin@28872
   311
    val thy = ProofContext.theory_of ctxt;
ballarin@28872
   312
    val (parm_names, parm_types) = NewLocale.params_of thy loc |>
haftmann@29006
   313
      map (fn (b, SOME T, _) => (Binding.base_name b, T)) |> split_list;
ballarin@28872
   314
    val (morph, _) = inst_morph (parm_names, parm_types) (prfx, inst) ctxt;
ballarin@29221
   315
  in (loc, morph) end;
ballarin@28795
   316
ballarin@29221
   317
fun finish_elem ctxt parms do_close elem =
ballarin@28795
   318
  let
ballarin@28872
   319
    val elem' = finish_primitive parms (closeup ctxt parms do_close) elem;
ballarin@29221
   320
  in elem' end
ballarin@28795
   321
  
ballarin@29221
   322
fun finish ctxt parms do_close insts elems =
ballarin@28872
   323
  let
ballarin@29221
   324
    val deps = map (finish_inst ctxt parms do_close) insts;
ballarin@29221
   325
    val elems' = map (finish_elem ctxt parms do_close) elems;
ballarin@29221
   326
  in (deps, elems') end;
ballarin@28795
   327
ballarin@28795
   328
ballarin@28895
   329
(** Process full context statement: instantiations + elements + conclusion **)
ballarin@28895
   330
ballarin@28895
   331
(* Interleave incremental parsing and type inference over entire parsed stretch. *)
ballarin@28895
   332
ballarin@28795
   333
local
ballarin@28795
   334
ballarin@28895
   335
fun prep_full_context_statement parse_typ parse_prop parse_inst prep_vars prep_expr
ballarin@28895
   336
    strict do_close context raw_import raw_elems raw_concl =
ballarin@28795
   337
  let
ballarin@28872
   338
    val thy = ProofContext.theory_of context;
ballarin@28872
   339
ballarin@28895
   340
    val (raw_insts, fixed) = parameters_of thy strict (apfst (prep_expr thy) raw_import);
ballarin@28895
   341
ballarin@28951
   342
    fun prep_inst (loc, (prfx, inst)) (i, insts, ctxt) =
ballarin@28872
   343
      let
ballarin@28872
   344
        val (parm_names, parm_types) = NewLocale.params_of thy loc |>
haftmann@29006
   345
          map (fn (b, SOME T, _) => (Binding.base_name b, T)) |> split_list;
ballarin@28872
   346
        val inst' = parse_inst parm_names inst ctxt;
ballarin@28885
   347
        val parm_types' = map (TypeInfer.paramify_vars o
ballarin@28885
   348
          Term.map_type_tvar (fn ((x, _), S) => TVar ((x, i), S)) o Logic.varifyT) parm_types;
ballarin@28872
   349
        val inst'' = map2 TypeInfer.constrain parm_types' inst';
ballarin@28872
   350
        val insts' = insts @ [(loc, (prfx, inst''))];
ballarin@28951
   351
        val (insts'', _, _, ctxt' (* FIXME not used *) ) = check_autofix insts' [] [] ctxt;
ballarin@28872
   352
        val inst''' = insts'' |> List.last |> snd |> snd;
ballarin@28872
   353
        val (morph, _) = inst_morph (parm_names, parm_types) (prfx, inst''') ctxt;
ballarin@28951
   354
        val ctxt'' = NewLocale.activate_declarations thy (loc, morph) ctxt;
ballarin@28951
   355
      in (i+1, insts', ctxt'') end;
ballarin@28872
   356
  
ballarin@28872
   357
    fun prep_elem raw_elem (insts, elems, ctxt) =
ballarin@28852
   358
      let
ballarin@28852
   359
        val ctxt' = declare_elem prep_vars raw_elem ctxt;
ballarin@28852
   360
        val elems' = elems @ [parse_elem parse_typ parse_prop ctxt' raw_elem];
ballarin@28872
   361
        val (_, _, _, ctxt'') = check_autofix insts elems' [] ctxt';
ballarin@28872
   362
      in (insts, elems', ctxt') end;
ballarin@28795
   363
ballarin@28872
   364
    fun prep_concl raw_concl (insts, elems, ctxt) =
ballarin@28795
   365
      let
ballarin@29215
   366
        val concl = parse_concl parse_prop ctxt raw_concl;
ballarin@28872
   367
      in check_autofix insts elems concl ctxt end;
ballarin@28795
   368
ballarin@28872
   369
    val fors = prep_vars fixed context |> fst;
ballarin@28872
   370
    val ctxt = context |> ProofContext.add_fixes_i fors |> snd;
ballarin@29206
   371
    val (_, insts', ctxt') = fold prep_inst raw_insts (0, [], ctxt);
ballarin@28872
   372
    val (_, elems'', ctxt'') = fold prep_elem raw_elems (insts', [], ctxt');
ballarin@28872
   373
    val (insts, elems, concl, ctxt) = prep_concl raw_concl (insts', elems'', ctxt'');
ballarin@28795
   374
ballarin@28872
   375
    (* Retrieve parameter types *)
haftmann@29006
   376
    val xs = fold (fn Fixes fixes => (fn ps => ps @ map (Binding.base_name o #1) fixes) |
ballarin@28872
   377
      _ => fn ps => ps) (Fixes fors :: elems) [];
ballarin@28859
   378
    val (Ts, ctxt') = fold_map ProofContext.inferred_param xs ctxt; 
ballarin@28895
   379
    val parms = xs ~~ Ts;  (* params from expression and elements *)
ballarin@28795
   380
ballarin@28872
   381
    val Fixes fors' = finish_primitive parms I (Fixes fors);
ballarin@29221
   382
    val (deps, elems') = finish ctxt' parms do_close insts elems;
ballarin@28852
   383
ballarin@29221
   384
  in ((fors', deps, elems', concl), (parms, ctxt')) end
ballarin@28795
   385
ballarin@28795
   386
in
ballarin@28795
   387
ballarin@28895
   388
fun read_full_context_statement x =
ballarin@28895
   389
  prep_full_context_statement Syntax.parse_typ Syntax.parse_prop parse_inst
ballarin@28895
   390
  ProofContext.read_vars intern x;
ballarin@28895
   391
fun cert_full_context_statement x =
ballarin@28895
   392
  prep_full_context_statement (K I) (K I) make_inst ProofContext.cert_vars (K I) x;
ballarin@28795
   393
ballarin@28795
   394
end;
ballarin@28795
   395
ballarin@28795
   396
ballarin@28898
   397
(* Context statement: elements + conclusion *)
ballarin@28795
   398
ballarin@28795
   399
local
ballarin@28795
   400
ballarin@28898
   401
fun prep_statement prep activate raw_elems raw_concl context =
ballarin@28898
   402
  let
ballarin@28898
   403
     val ((_, _, elems, concl), _) = prep true false context ([], []) raw_elems raw_concl;
ballarin@28898
   404
     val (_, context') = activate elems (ProofContext.set_stmt true context);
ballarin@28898
   405
  in (concl, context') end;
ballarin@28898
   406
ballarin@28898
   407
in
ballarin@28898
   408
ballarin@28898
   409
fun read_statement x = prep_statement read_full_context_statement Element.activate x;
ballarin@28898
   410
fun cert_statement x = prep_statement cert_full_context_statement Element.activate_i x;
ballarin@28898
   411
ballarin@28898
   412
end;
ballarin@28898
   413
ballarin@28898
   414
ballarin@28898
   415
(* Locale declaration: import + elements *)
ballarin@28898
   416
ballarin@28898
   417
local
ballarin@28898
   418
ballarin@28898
   419
fun prep_declaration prep activate raw_import raw_elems context =
ballarin@28795
   420
  let
ballarin@29221
   421
    val ((fixed, deps, elems, _), (parms, ctxt')) = prep false true context raw_import raw_elems [];
ballarin@28898
   422
    (* Declare parameters and imported facts *)
ballarin@28898
   423
    val context' = context |>
ballarin@28898
   424
      ProofContext.add_fixes_i fixed |> snd |>
ballarin@29206
   425
      fold NewLocale.activate_local_facts deps;
ballarin@29217
   426
    val (elems', _) = activate elems (ProofContext.set_stmt true context');
ballarin@29221
   427
  in ((fixed, deps, elems'), (parms, ctxt')) end;
ballarin@28795
   428
ballarin@28795
   429
in
ballarin@28795
   430
ballarin@28898
   431
fun read_declaration x = prep_declaration read_full_context_statement Element.activate x;
ballarin@28898
   432
fun cert_declaration x = prep_declaration cert_full_context_statement Element.activate_i x;
ballarin@28898
   433
ballarin@28898
   434
end;
ballarin@28898
   435
ballarin@28898
   436
ballarin@28898
   437
(* Locale expression to set up a goal *)
ballarin@28898
   438
ballarin@28898
   439
local
ballarin@28898
   440
ballarin@28898
   441
fun props_of thy (name, morph) =
ballarin@28898
   442
  let
ballarin@28898
   443
    val (asm, defs) = NewLocale.specification_of thy name;
ballarin@28898
   444
  in
ballarin@28898
   445
    (case asm of NONE => defs | SOME asm => asm :: defs) |> map (Morphism.term morph)
ballarin@28898
   446
  end;
ballarin@28898
   447
ballarin@28898
   448
fun prep_goal_expression prep expression context =
ballarin@28898
   449
  let
ballarin@28898
   450
    val thy = ProofContext.theory_of context;
ballarin@28879
   451
ballarin@28898
   452
    val ((fixed, deps, _, _), _) = prep true true context expression [] [];
ballarin@28898
   453
    (* proof obligations *)
ballarin@28898
   454
    val propss = map (props_of thy) deps;
ballarin@28898
   455
ballarin@28898
   456
    val goal_ctxt = context |>
ballarin@28898
   457
      ProofContext.add_fixes_i fixed |> snd |>
ballarin@28898
   458
      (fold o fold) Variable.auto_fixes propss;
ballarin@28898
   459
ballarin@28898
   460
    val export = Variable.export_morphism goal_ctxt context;
ballarin@28898
   461
    val exp_fact = Drule.zero_var_indexes_list o map Thm.strip_shyps o Morphism.fact export;
ballarin@29245
   462
    val exp_term = TermSubst.zero_var_indexes o Morphism.term export;
ballarin@28898
   463
    val exp_typ = Logic.type_map exp_term;
ballarin@28898
   464
    val export' =
haftmann@28965
   465
      Morphism.morphism {binding = I, var = I, typ = exp_typ, term = exp_term, fact = exp_fact};
ballarin@28898
   466
  in ((propss, deps, export'), goal_ctxt) end;
ballarin@28898
   467
    
ballarin@28898
   468
in
ballarin@28898
   469
ballarin@28898
   470
fun read_goal_expression x = prep_goal_expression read_full_context_statement x;
ballarin@28898
   471
fun cert_goal_expression x = prep_goal_expression cert_full_context_statement x;
ballarin@28879
   472
ballarin@28795
   473
end;
ballarin@28795
   474
ballarin@28795
   475
ballarin@28795
   476
(*** Locale declarations ***)
ballarin@28795
   477
ballarin@29221
   478
(* extract specification text *)
ballarin@29221
   479
ballarin@29221
   480
val norm_term = Envir.beta_norm oo Term.subst_atomic;
ballarin@29221
   481
ballarin@29221
   482
fun bind_def ctxt eq (xs, env, eqs) =
ballarin@29221
   483
  let
ballarin@29221
   484
    val _ = LocalDefs.cert_def ctxt eq;
ballarin@29221
   485
    val ((y, T), b) = LocalDefs.abs_def eq;
ballarin@29221
   486
    val b' = norm_term env b;
ballarin@29221
   487
    fun err msg = error (msg ^ ": " ^ quote y);
ballarin@29221
   488
  in
ballarin@29250
   489
    case filter (fn (Free (y', _), _) => y = y' | _ => false) env of
ballarin@29250
   490
      [] => (Term.add_frees b' xs, (Free (y, T), b') :: env, eq :: eqs) |
ballarin@29250
   491
      dups => if forall (fn (_, b'') => b' aconv b'') dups
ballarin@29250
   492
        then (xs, env, eqs)
ballarin@29250
   493
        else err "Attempt to redefine variable"
ballarin@29221
   494
  end;
ballarin@29221
   495
ballarin@29221
   496
(* text has the following structure:
ballarin@29221
   497
       (((exts, exts'), (ints, ints')), (xs, env, defs))
ballarin@29221
   498
   where
ballarin@29221
   499
     exts: external assumptions (terms in assumes elements)
ballarin@29221
   500
     exts': dito, normalised wrt. env
ballarin@29221
   501
     ints: internal assumptions (terms in assumptions from insts)
ballarin@29221
   502
     ints': dito, normalised wrt. env
ballarin@29221
   503
     xs: the free variables in exts' and ints' and rhss of definitions,
ballarin@29221
   504
       this includes parameters except defined parameters
ballarin@29221
   505
     env: list of term pairs encoding substitutions, where the first term
ballarin@29221
   506
       is a free variable; substitutions represent defines elements and
ballarin@29221
   507
       the rhs is normalised wrt. the previous env
ballarin@29221
   508
     defs: the equations from the defines elements
ballarin@29221
   509
   *)
ballarin@29221
   510
ballarin@29221
   511
fun eval_text _ _ (Fixes _) text = text
ballarin@29221
   512
  | eval_text _ _ (Constrains _) text = text
ballarin@29221
   513
  | eval_text _ is_ext (Assumes asms)
ballarin@29221
   514
        (((exts, exts'), (ints, ints')), (xs, env, defs)) =
ballarin@29221
   515
      let
ballarin@29221
   516
        val ts = maps (map #1 o #2) asms;
ballarin@29221
   517
        val ts' = map (norm_term env) ts;
ballarin@29221
   518
        val spec' =
ballarin@29221
   519
          if is_ext then ((exts @ ts, exts' @ ts'), (ints, ints'))
ballarin@29221
   520
          else ((exts, exts'), (ints @ ts, ints' @ ts'));
ballarin@29221
   521
      in (spec', (fold Term.add_frees ts' xs, env, defs)) end
ballarin@29221
   522
  | eval_text ctxt _ (Defines defs) (spec, binds) =
ballarin@29221
   523
      (spec, fold (bind_def ctxt o #1 o #2) defs binds)
ballarin@29221
   524
  | eval_text _ _ (Notes _) text = text;
ballarin@29221
   525
ballarin@29221
   526
fun eval_inst ctxt (loc, morph) text =
ballarin@29221
   527
  let
ballarin@29221
   528
    val thy = ProofContext.theory_of ctxt;
ballarin@29221
   529
    val (asm, defs) = NewLocale.specification_of thy loc;
ballarin@29221
   530
    val asm' = Option.map (Morphism.term morph) asm;
ballarin@29221
   531
    val defs' = map (Morphism.term morph) defs;
ballarin@29221
   532
    val text' = text |>
ballarin@29221
   533
      (if is_some asm
ballarin@29221
   534
        then eval_text ctxt false (Assumes [(Attrib.empty_binding, [(the asm', [])])])
ballarin@29221
   535
        else I) |>
ballarin@29221
   536
      (if not (null defs)
ballarin@29221
   537
        then eval_text ctxt false (Defines (map (fn def => (Attrib.empty_binding, (def, []))) defs'))
ballarin@29221
   538
        else I)
ballarin@29221
   539
(* FIXME clone from new_locale.ML *)
ballarin@29221
   540
  in text' end;
ballarin@29221
   541
ballarin@29221
   542
fun eval_elem ctxt elem text =
ballarin@29221
   543
  let
ballarin@29221
   544
    val text' = eval_text ctxt true elem text;
ballarin@29221
   545
  in text' end;
ballarin@29221
   546
ballarin@29221
   547
fun eval ctxt deps elems =
ballarin@29221
   548
  let
ballarin@29221
   549
    val text' = fold (eval_inst ctxt) deps ((([], []), ([], [])), ([], [], []));
ballarin@29221
   550
    val ((spec, (_, _, defs))) = fold (eval_elem ctxt) elems text';
ballarin@29221
   551
  in (spec, defs) end;
ballarin@29221
   552
ballarin@28903
   553
(* axiomsN: name of theorem set with destruct rules for locale predicates,
ballarin@28903
   554
     also name suffix of delta predicates and assumptions. *)
ballarin@28903
   555
ballarin@28903
   556
val axiomsN = "axioms";
ballarin@28903
   557
ballarin@28795
   558
local
ballarin@28795
   559
ballarin@28795
   560
(* introN: name of theorems for introduction rules of locale and
ballarin@28903
   561
     delta predicates *)
ballarin@28795
   562
ballarin@28795
   563
val introN = "intro";
ballarin@28795
   564
ballarin@28795
   565
fun atomize_spec thy ts =
ballarin@28795
   566
  let
ballarin@28795
   567
    val t = Logic.mk_conjunction_balanced ts;
ballarin@28795
   568
    val body = ObjectLogic.atomize_term thy t;
ballarin@28795
   569
    val bodyT = Term.fastype_of body;
ballarin@28795
   570
  in
ballarin@28795
   571
    if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of thy t))
ballarin@28795
   572
    else (body, bodyT, ObjectLogic.atomize (Thm.cterm_of thy t))
ballarin@28795
   573
  end;
ballarin@28795
   574
ballarin@28795
   575
(* achieve plain syntax for locale predicates (without "PROP") *)
ballarin@28795
   576
ballarin@28795
   577
fun aprop_tr' n c = (Syntax.constN ^ c, fn ctxt => fn args =>
ballarin@28795
   578
  if length args = n then
ballarin@28795
   579
    Syntax.const "_aprop" $
ballarin@28795
   580
      Term.list_comb (Syntax.free (Consts.extern (ProofContext.consts_of ctxt) c), args)
ballarin@28795
   581
  else raise Match);
ballarin@28795
   582
ballarin@28898
   583
(* define one predicate including its intro rule and axioms
ballarin@28795
   584
   - bname: predicate name
ballarin@28795
   585
   - parms: locale parameters
ballarin@28795
   586
   - defs: thms representing substitutions from defines elements
ballarin@28795
   587
   - ts: terms representing locale assumptions (not normalised wrt. defs)
ballarin@28795
   588
   - norm_ts: terms representing locale assumptions (normalised wrt. defs)
ballarin@28795
   589
   - thy: the theory
ballarin@28795
   590
*)
ballarin@28795
   591
ballarin@28795
   592
fun def_pred bname parms defs ts norm_ts thy =
ballarin@28795
   593
  let
haftmann@28965
   594
    val name = Sign.full_bname thy bname;
ballarin@28795
   595
ballarin@28795
   596
    val (body, bodyT, body_eq) = atomize_spec thy norm_ts;
wenzelm@29272
   597
    val env = Term.add_free_names body [];
ballarin@28795
   598
    val xs = filter (member (op =) env o #1) parms;
ballarin@28795
   599
    val Ts = map #2 xs;
wenzelm@29272
   600
    val extraTs =
wenzelm@29272
   601
      (Term.add_tfrees body [] \\ fold Term.add_tfreesT Ts [])
ballarin@28795
   602
      |> Library.sort_wrt #1 |> map TFree;
ballarin@28795
   603
    val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
ballarin@28795
   604
ballarin@28795
   605
    val args = map Logic.mk_type extraTs @ map Free xs;
ballarin@28795
   606
    val head = Term.list_comb (Const (name, predT), args);
ballarin@28795
   607
    val statement = ObjectLogic.ensure_propT thy head;
ballarin@28795
   608
ballarin@28795
   609
    val ([pred_def], defs_thy) =
ballarin@28795
   610
      thy
ballarin@28795
   611
      |> bodyT = propT ? Sign.add_advanced_trfuns ([], [], [aprop_tr' (length args) name], [])
haftmann@28965
   612
      |> Sign.declare_const [] ((Binding.name bname, predT), NoSyn) |> snd
ballarin@28795
   613
      |> PureThy.add_defs false
ballarin@28795
   614
        [((Thm.def_name bname, Logic.mk_equals (head, body)), [Thm.kind_internal])];
ballarin@28795
   615
    val defs_ctxt = ProofContext.init defs_thy |> Variable.declare_term head;
ballarin@28795
   616
ballarin@28795
   617
    val cert = Thm.cterm_of defs_thy;
ballarin@28795
   618
ballarin@28795
   619
    val intro = Goal.prove_global defs_thy [] norm_ts statement (fn _ =>
ballarin@28795
   620
      MetaSimplifier.rewrite_goals_tac [pred_def] THEN
ballarin@28795
   621
      Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
ballarin@28795
   622
      Tactic.compose_tac (false,
ballarin@28795
   623
        Conjunction.intr_balanced (map (Thm.assume o cert) norm_ts), 0) 1);
ballarin@28795
   624
ballarin@28795
   625
    val conjuncts =
ballarin@28795
   626
      (Drule.equal_elim_rule2 OF [body_eq,
ballarin@28795
   627
        MetaSimplifier.rewrite_rule [pred_def] (Thm.assume (cert statement))])
ballarin@28795
   628
      |> Conjunction.elim_balanced (length ts);
ballarin@28795
   629
    val axioms = ts ~~ conjuncts |> map (fn (t, ax) =>
ballarin@28795
   630
      Element.prove_witness defs_ctxt t
ballarin@28795
   631
       (MetaSimplifier.rewrite_goals_tac defs THEN
ballarin@28795
   632
        Tactic.compose_tac (false, ax, 0) 1));
ballarin@28795
   633
  in ((statement, intro, axioms), defs_thy) end;
ballarin@28795
   634
ballarin@28795
   635
in
ballarin@28795
   636
ballarin@28795
   637
(* CB: main predicate definition function *)
ballarin@28795
   638
ballarin@29221
   639
fun define_preds pname parms (((exts, exts'), (ints, ints')), defs) thy =
ballarin@28795
   640
  let
ballarin@29031
   641
    val defs' = map (cterm_of thy #> Assumption.assume #> Drule.gen_all #> Drule.abs_def) defs;
ballarin@29031
   642
ballarin@28795
   643
    val (a_pred, a_intro, a_axioms, thy'') =
ballarin@28795
   644
      if null exts then (NONE, NONE, [], thy)
ballarin@28795
   645
      else
ballarin@28795
   646
        let
ballarin@28795
   647
          val aname = if null ints then pname else pname ^ "_" ^ axiomsN;
ballarin@28795
   648
          val ((statement, intro, axioms), thy') =
ballarin@28795
   649
            thy
ballarin@29031
   650
            |> def_pred aname parms defs' exts exts';
ballarin@28795
   651
          val (_, thy'') =
ballarin@28795
   652
            thy'
ballarin@28795
   653
            |> Sign.add_path aname
ballarin@28795
   654
            |> Sign.no_base_names
ballarin@28903
   655
            |> PureThy.note_thmss Thm.internalK
haftmann@28965
   656
              [((Binding.name introN, []), [([intro], [NewLocale.unfold_attrib])])]
ballarin@28795
   657
            ||> Sign.restore_naming thy';
ballarin@28795
   658
          in (SOME statement, SOME intro, axioms, thy'') end;
ballarin@28795
   659
    val (b_pred, b_intro, b_axioms, thy'''') =
ballarin@28795
   660
      if null ints then (NONE, NONE, [], thy'')
ballarin@28795
   661
      else
ballarin@28795
   662
        let
ballarin@28795
   663
          val ((statement, intro, axioms), thy''') =
ballarin@28795
   664
            thy''
ballarin@29031
   665
            |> def_pred pname parms defs' (ints @ the_list a_pred) (ints' @ the_list a_pred);
ballarin@28795
   666
          val (_, thy'''') =
ballarin@28795
   667
            thy'''
ballarin@28795
   668
            |> Sign.add_path pname
ballarin@28795
   669
            |> Sign.no_base_names
ballarin@28795
   670
            |> PureThy.note_thmss Thm.internalK
haftmann@28965
   671
                 [((Binding.name introN, []), [([intro], [NewLocale.intro_attrib])]),
haftmann@28965
   672
                  ((Binding.name axiomsN, []),
ballarin@28795
   673
                    [(map (Drule.standard o Element.conclude_witness) axioms, [])])]
ballarin@28795
   674
            ||> Sign.restore_naming thy''';
ballarin@28795
   675
        in (SOME statement, SOME intro, axioms, thy'''') end;
ballarin@28795
   676
  in ((a_pred, a_intro, a_axioms), (b_pred, b_intro, b_axioms), thy'''') end;
ballarin@28795
   677
ballarin@28795
   678
end;
ballarin@28795
   679
ballarin@28795
   680
ballarin@28795
   681
local
ballarin@28795
   682
ballarin@28795
   683
fun assumes_to_notes (Assumes asms) axms =
ballarin@28795
   684
      fold_map (fn (a, spec) => fn axs =>
ballarin@28795
   685
          let val (ps, qs) = chop (length spec) axs
ballarin@28795
   686
          in ((a, [(ps, [])]), qs) end) asms axms
ballarin@28795
   687
      |> apfst (curry Notes Thm.assumptionK)
ballarin@28795
   688
  | assumes_to_notes e axms = (e, axms);
ballarin@28795
   689
ballarin@29031
   690
fun defines_to_notes thy (Defines defs) =
ballarin@29031
   691
      Notes (Thm.definitionK, map (fn (a, (def, _)) =>
ballarin@29245
   692
        (a, [([Assumption.assume (cterm_of thy def)],
ballarin@29245
   693
          [(Attrib.internal o K) NewLocale.witness_attrib])])) defs)
ballarin@29031
   694
  | defines_to_notes _ e = e;
ballarin@28795
   695
ballarin@28898
   696
fun gen_add_locale prep_decl
ballarin@28795
   697
    bname predicate_name raw_imprt raw_body thy =
ballarin@28795
   698
  let
haftmann@28965
   699
    val name = Sign.full_bname thy bname;
ballarin@28795
   700
    val _ = NewLocale.test_locale thy name andalso
ballarin@28795
   701
      error ("Duplicate definition of locale " ^ quote name);
ballarin@28795
   702
ballarin@29221
   703
    val ((fixed, deps, body_elems), (parms, ctxt')) =
ballarin@29021
   704
      prep_decl raw_imprt raw_body (ProofContext.init thy);
ballarin@29221
   705
    val text as (((_, exts'), _), defs) = eval ctxt' deps body_elems;
ballarin@29221
   706
ballarin@28872
   707
    val ((a_statement, a_intro, a_axioms), (b_statement, b_intro, b_axioms), thy') =
ballarin@29221
   708
      define_preds predicate_name parms text thy;
ballarin@28795
   709
ballarin@28795
   710
    val extraTs = fold Term.add_tfrees exts' [] \\ fold Term.add_tfreesT (map snd parms) [];
ballarin@28795
   711
    val _ = if null extraTs then ()
ballarin@28795
   712
      else warning ("Additional type variable(s) in locale specification " ^ quote bname);
ballarin@28795
   713
ballarin@29035
   714
    val a_satisfy = Element.satisfy_morphism a_axioms;
ballarin@29035
   715
    val b_satisfy = Element.satisfy_morphism b_axioms;
ballarin@28903
   716
ballarin@28895
   717
    val params = fixed @
ballarin@28872
   718
      (body_elems |> map_filter (fn Fixes fixes => SOME fixes | _ => NONE) |> flat);
ballarin@28903
   719
    val asm = if is_some b_statement then b_statement else a_statement;
ballarin@29028
   720
ballarin@29035
   721
    (* These are added immediately. *)
ballarin@29028
   722
    val notes =
ballarin@29028
   723
        if is_some asm
ballarin@29028
   724
        then [(Thm.internalK, [((Binding.name (bname ^ "_" ^ axiomsN), []),
ballarin@29028
   725
          [([Assumption.assume (cterm_of thy' (the asm))],
ballarin@29028
   726
            [(Attrib.internal o K) NewLocale.witness_attrib])])])]
ballarin@29028
   727
        else [];
ballarin@28795
   728
ballarin@29035
   729
    (* These will be added in the local theory. *)
ballarin@29035
   730
    val notes' = body_elems |>
ballarin@29035
   731
      map (defines_to_notes thy') |>
ballarin@29035
   732
      map (Element.morph_ctxt a_satisfy) |>
ballarin@29035
   733
      (fn elems => fold_map assumes_to_notes elems (map Element.conclude_witness a_axioms)) |>
ballarin@29035
   734
      fst |>
ballarin@29035
   735
      map (Element.morph_ctxt b_satisfy) |>
ballarin@29035
   736
      map_filter (fn Notes notes => SOME notes | _ => NONE);
ballarin@29035
   737
ballarin@29035
   738
    val deps' = map (fn (l, morph) => (l, morph $> b_satisfy)) deps;
ballarin@28872
   739
ballarin@28795
   740
    val loc_ctxt = thy' |>
haftmann@28991
   741
      NewLocale.register_locale bname (extraTs, params)
ballarin@29032
   742
        (asm, rev defs) ([], [])
ballarin@28872
   743
        (map (fn n => (n, stamp ())) notes |> rev) (map (fn d => (d, stamp ())) deps' |> rev) |>
ballarin@29028
   744
      NewLocale.init name;
ballarin@29028
   745
ballarin@29028
   746
  in ((name, notes'), loc_ctxt) end;
ballarin@28795
   747
ballarin@28795
   748
in
ballarin@28795
   749
ballarin@28902
   750
val add_locale_cmd = gen_add_locale read_declaration;
ballarin@28902
   751
val add_locale = gen_add_locale cert_declaration;
ballarin@28795
   752
ballarin@28795
   753
end;
ballarin@28795
   754
ballarin@28895
   755
ballarin@28895
   756
(*** Interpretation ***)
ballarin@28895
   757
ballarin@28895
   758
(** Witnesses and goals **)
ballarin@28895
   759
ballarin@28895
   760
fun prep_propp propss = propss |> map (map (rpair [] o Element.mark_witness));
ballarin@28895
   761
wenzelm@29254
   762
val prep_result = map2 (fn props => fn thms =>
wenzelm@29254
   763
  map2 Element.make_witness props (map Thm.close_derivation thms));
ballarin@28895
   764
ballarin@28895
   765
ballarin@28895
   766
(** Interpretation between locales: declaring sublocale relationships **)
ballarin@28895
   767
ballarin@28895
   768
local
ballarin@28895
   769
ballarin@28902
   770
fun gen_sublocale prep_expr intern
ballarin@28951
   771
    raw_target expression thy =
ballarin@28895
   772
  let
ballarin@28902
   773
    val target = intern thy raw_target;
ballarin@28895
   774
    val target_ctxt = NewLocale.init target thy;
ballarin@28895
   775
ballarin@28903
   776
    val ((propss, deps, export), goal_ctxt) = prep_expr expression target_ctxt;
ballarin@28898
   777
    
ballarin@28902
   778
    fun store_dep ((name, morph), thms) =
ballarin@28903
   779
      NewLocale.add_dependency target (name, morph $> Element.satisfy_morphism thms $> export);
ballarin@28895
   780
ballarin@28993
   781
    fun after_qed results =
ballarin@28993
   782
      ProofContext.theory (
ballarin@28993
   783
        (* store dependencies *)
ballarin@28993
   784
        fold store_dep (deps ~~ prep_result propss results) #>
ballarin@28993
   785
        (* propagate registrations *)
ballarin@28993
   786
        (fn thy => fold_rev (fn reg => NewLocale.activate_global_facts reg)
ballarin@28993
   787
          (NewLocale.get_global_registrations thy) thy));
ballarin@28895
   788
  in
ballarin@28895
   789
    goal_ctxt |>
ballarin@28951
   790
      Proof.theorem_i NONE after_qed (prep_propp propss) |>
ballarin@28895
   791
      Element.refine_witness |> Seq.hd
ballarin@28895
   792
  end;
ballarin@28895
   793
ballarin@28895
   794
in
ballarin@28895
   795
ballarin@28902
   796
fun sublocale_cmd x = gen_sublocale read_goal_expression NewLocale.intern x;
ballarin@28902
   797
fun sublocale x = gen_sublocale cert_goal_expression (K I) x;
ballarin@28895
   798
ballarin@28795
   799
end;
ballarin@28895
   800
ballarin@29018
   801
ballarin@28993
   802
(** Interpretation in theories **)
ballarin@28993
   803
ballarin@28993
   804
local
ballarin@28993
   805
ballarin@29211
   806
datatype goal = Reg of string * Morphism.morphism | Eqns of Attrib.binding list;
ballarin@29211
   807
ballarin@29211
   808
fun gen_interpretation prep_expr parse_prop prep_attr
ballarin@29210
   809
    expression equations thy =
ballarin@28993
   810
  let
ballarin@28993
   811
    val ctxt = ProofContext.init thy;
ballarin@28993
   812
ballarin@29211
   813
    val ((propss, regs, export), expr_ctxt) = prep_expr expression ctxt;
ballarin@29211
   814
    
ballarin@29211
   815
    val eqns = map (parse_prop expr_ctxt o snd) equations |> Syntax.check_terms expr_ctxt;
ballarin@29211
   816
    val eq_attns = map ((apsnd o map) (prep_attr thy) o fst) equations;
ballarin@29211
   817
    val goal_ctxt = fold Variable.auto_fixes eqns expr_ctxt;
ballarin@29211
   818
    val export' = Variable.export_morphism goal_ctxt expr_ctxt;
ballarin@29210
   819
ballarin@29211
   820
    fun store (Reg (name, morph), thms) (regs, thy) =
ballarin@29211
   821
        let
ballarin@29211
   822
          val thms' = map (Element.morph_witness export') thms;
ballarin@29211
   823
          val morph' = morph $> Element.satisfy_morphism thms';
ballarin@29211
   824
          val add = NewLocale.add_global_registration (name, (morph', export));
ballarin@29211
   825
        in ((name, morph') :: regs, add thy) end
ballarin@29211
   826
      | store (Eqns [], []) (regs, thy) =
ballarin@29211
   827
        let val add = fold_rev (fn (name, morph) =>
ballarin@29211
   828
              NewLocale.activate_global_facts (name, morph $> export)) regs;
ballarin@29211
   829
        in (regs, add thy) end
ballarin@29211
   830
      | store (Eqns attns, thms) (regs, thy) =
ballarin@29211
   831
        let
ballarin@29211
   832
          val thms' = thms |> map (Element.conclude_witness #>
ballarin@29211
   833
            Morphism.thm (export' $> export) #>
ballarin@29211
   834
            LocalDefs.meta_rewrite_rule (ProofContext.init thy) #>
ballarin@29211
   835
            Drule.abs_def);
ballarin@29211
   836
          val eq_morph =
ballarin@29211
   837
            Morphism.term_morphism (MetaSimplifier.rewrite_term thy thms' []) $>
ballarin@29211
   838
            Morphism.thm_morphism (MetaSimplifier.rewrite_rule thms');
ballarin@29211
   839
          val attns' = map ((apsnd o map) (Attrib.attribute_i thy)) attns;
ballarin@29211
   840
          val add =
ballarin@29211
   841
            fold_rev (fn (name, morph) =>
ballarin@29211
   842
              NewLocale.amend_global_registration eq_morph (name, morph) #>
ballarin@29211
   843
              NewLocale.activate_global_facts (name, morph $> eq_morph $> export)) regs #>
ballarin@29211
   844
            PureThy.note_thmss Thm.lemmaK (attns' ~~ map (fn th => [([th], [])]) thms') #>
ballarin@29211
   845
            snd
ballarin@29211
   846
        in (regs, add thy) end;
ballarin@28993
   847
ballarin@28993
   848
    fun after_qed results =
ballarin@29211
   849
      ProofContext.theory (fn thy =>
ballarin@29211
   850
        fold store (map Reg regs @ [Eqns eq_attns] ~~
ballarin@29211
   851
          prep_result (propss @ [eqns]) results) ([], thy) |> snd);
ballarin@28993
   852
  in
ballarin@28993
   853
    goal_ctxt |>
ballarin@29211
   854
      Proof.theorem_i NONE after_qed (prep_propp (propss @ [eqns])) |>
ballarin@28993
   855
      Element.refine_witness |> Seq.hd
ballarin@28993
   856
  end;
ballarin@28993
   857
ballarin@28993
   858
in
ballarin@28993
   859
ballarin@29210
   860
fun interpretation_cmd x = gen_interpretation read_goal_expression
ballarin@29211
   861
  Syntax.parse_prop Attrib.intern_src x;
ballarin@29211
   862
fun interpretation x = gen_interpretation cert_goal_expression (K I) (K I) x;
ballarin@28895
   863
ballarin@28895
   864
end;
ballarin@28903
   865
ballarin@29018
   866
ballarin@29018
   867
(** Interpretation in proof contexts **)
ballarin@29018
   868
ballarin@29018
   869
local
ballarin@29018
   870
ballarin@29018
   871
fun gen_interpret prep_expr
ballarin@29018
   872
    expression int state =
ballarin@29018
   873
  let
ballarin@29018
   874
    val _ = Proof.assert_forward_or_chain state;
ballarin@29018
   875
    val ctxt = Proof.context_of state;
ballarin@29018
   876
ballarin@29018
   877
    val ((propss, regs, export), goal_ctxt) = prep_expr expression ctxt;
ballarin@29018
   878
    
ballarin@29018
   879
    fun store_reg ((name, morph), thms) =
ballarin@29018
   880
      let
ballarin@29018
   881
        val morph' = morph $> Element.satisfy_morphism thms $> export;
ballarin@29018
   882
      in
ballarin@29018
   883
        NewLocale.activate_local_facts (name, morph')
ballarin@29018
   884
      end;
ballarin@29018
   885
ballarin@29018
   886
    fun after_qed results =
ballarin@29018
   887
      Proof.map_context (fold store_reg (regs ~~ prep_result propss results)) #> Seq.single;
ballarin@29018
   888
  in
ballarin@29018
   889
    state |> Proof.map_context (K goal_ctxt) |>
ballarin@29018
   890
      Proof.local_goal (ProofDisplay.print_results int) (K I) ProofContext.bind_propp_i
ballarin@29018
   891
      "interpret" NONE after_qed (map (pair (Binding.empty, [])) (prep_propp propss)) |>
ballarin@29018
   892
      Element.refine_witness |> Seq.hd
ballarin@29018
   893
  end;
ballarin@29018
   894
ballarin@29018
   895
in
ballarin@29018
   896
ballarin@29018
   897
fun interpret_cmd x = gen_interpret read_goal_expression x;
ballarin@29018
   898
fun interpret x = gen_interpret cert_goal_expression x;
ballarin@29018
   899
ballarin@28993
   900
end;
ballarin@28993
   901
ballarin@29018
   902
end;
ballarin@29018
   903