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