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