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