src/Pure/Isar/expression.ML
author haftmann
Sun Apr 21 20:08:13 2013 +0200 (2013-04-21)
changeset 51731 f27e22880cc3
parent 51730 dffc57bfc653
child 51734 d504e349e951
permissions -rw-r--r--
more sharing
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@49819
   290
fun finish_inst ctxt (loc, (prfx, inst)) =
wenzelm@49819
   291
  let
wenzelm@49819
   292
    val thy = Proof_Context.theory_of ctxt;
wenzelm@49819
   293
    val (parm_names, parm_types) = Locale.params_of thy loc |> map #1 |> split_list;
wenzelm@49819
   294
    val (morph, _) = inst_morph (parm_names, parm_types) (prfx, inst) ctxt;
wenzelm@49819
   295
  in (loc, morph) end;
wenzelm@49819
   296
wenzelm@49818
   297
fun finish_fixes (parms: (string * typ) list) = map (fn (binding, _, mx) =>
wenzelm@49818
   298
  let val x = Binding.name_of binding
wenzelm@49818
   299
  in (binding, AList.lookup (op =) parms x, mx) end);
wenzelm@49817
   300
wenzelm@49817
   301
local
wenzelm@49817
   302
ballarin@28852
   303
fun closeup _ _ false elem = elem
wenzelm@49819
   304
  | closeup (outer_ctxt, ctxt) parms true elem =
ballarin@28795
   305
      let
wenzelm@30725
   306
        (* FIXME consider closing in syntactic phase -- before type checking *)
ballarin@28795
   307
        fun close_frees t =
ballarin@28795
   308
          let
ballarin@28795
   309
            val rev_frees =
ballarin@28795
   310
              Term.fold_aterms (fn Free (x, T) =>
wenzelm@49819
   311
                if Variable.is_fixed outer_ctxt x orelse AList.defined (op =) parms x then I
wenzelm@49819
   312
                else insert (op =) (x, T) | _ => I) t [];
wenzelm@30725
   313
          in fold (Logic.all o Free) rev_frees t end;
ballarin@28795
   314
ballarin@28795
   315
        fun no_binds [] = []
ballarin@28852
   316
          | no_binds _ = error "Illegal term bindings in context element";
ballarin@28795
   317
      in
ballarin@28795
   318
        (case elem of
ballarin@28795
   319
          Assumes asms => Assumes (asms |> map (fn (a, propps) =>
ballarin@28795
   320
            (a, map (fn (t, ps) => (close_frees t, no_binds ps)) propps)))
ballarin@29022
   321
        | Defines defs => Defines (defs |> map (fn ((name, atts), (t, ps)) =>
wenzelm@35624
   322
            let val ((c, _), t') = Local_Defs.cert_def ctxt (close_frees t)
wenzelm@30434
   323
            in ((Thm.def_binding_optional (Binding.name c) name, atts), (t', no_binds ps)) end))
ballarin@28795
   324
        | e => e)
ballarin@28795
   325
      end;
ballarin@28795
   326
wenzelm@49819
   327
in
wenzelm@49819
   328
wenzelm@49818
   329
fun finish_elem _ parms _ (Fixes fixes) = Fixes (finish_fixes parms fixes)
wenzelm@49818
   330
  | finish_elem _ _ _ (Constrains _) = Constrains []
wenzelm@49819
   331
  | finish_elem ctxts parms do_close (Assumes asms) = closeup ctxts parms do_close (Assumes asms)
wenzelm@49819
   332
  | finish_elem ctxts parms do_close (Defines defs) = closeup ctxts parms do_close (Defines defs)
wenzelm@49818
   333
  | finish_elem _ _ _ (Notes facts) = Notes facts;
ballarin@28872
   334
wenzelm@49817
   335
end;
wenzelm@49817
   336
ballarin@28795
   337
ballarin@28895
   338
(** Process full context statement: instantiations + elements + conclusion **)
ballarin@28895
   339
ballarin@28895
   340
(* Interleave incremental parsing and type inference over entire parsed stretch. *)
ballarin@28895
   341
ballarin@28795
   342
local
ballarin@28795
   343
wenzelm@46922
   344
fun prep_full_context_statement
wenzelm@46922
   345
    parse_typ parse_prop prep_vars_elem prep_inst prep_vars_inst prep_expr
wenzelm@30786
   346
    {strict, do_close, fixed_frees} raw_import init_body raw_elems raw_concl ctxt1 =
ballarin@28795
   347
  let
wenzelm@42360
   348
    val thy = Proof_Context.theory_of ctxt1;
ballarin@28872
   349
ballarin@28895
   350
    val (raw_insts, fixed) = parameters_of thy strict (apfst (prep_expr thy) raw_import);
ballarin@28895
   351
wenzelm@30778
   352
    fun prep_insts_cumulative (loc, (prfx, inst)) (i, insts, ctxt) =
ballarin@28872
   353
      let
wenzelm@30755
   354
        val (parm_names, parm_types) = Locale.params_of thy loc |> map #1 |> split_list;
haftmann@29797
   355
        val inst' = prep_inst ctxt parm_names inst;
wenzelm@45587
   356
        val parm_types' = parm_types
wenzelm@45587
   357
          |> map (Type_Infer.paramify_vars o
wenzelm@45587
   358
              Term.map_type_tvar (fn ((x, _), S) => TVar ((x, i), S)) o Logic.varifyT_global);
wenzelm@39288
   359
        val inst'' = map2 Type.constraint parm_types' inst';
ballarin@28872
   360
        val insts' = insts @ [(loc, (prfx, inst''))];
wenzelm@47315
   361
        val (insts'', _, _, _) = check_autofix insts' [] [] ctxt;
ballarin@28872
   362
        val inst''' = insts'' |> List.last |> snd |> snd;
ballarin@28872
   363
        val (morph, _) = inst_morph (parm_names, parm_types) (prfx, inst''') ctxt;
wenzelm@30764
   364
        val ctxt'' = Locale.activate_declarations (loc, morph) ctxt;
wenzelm@30725
   365
      in (i + 1, insts', ctxt'') end;
wenzelm@30344
   366
haftmann@51729
   367
    fun prep_elem raw_elem ctxt =
ballarin@28852
   368
      let
wenzelm@47315
   369
        val ctxt' = ctxt
wenzelm@47315
   370
          |> Context_Position.set_visible false
wenzelm@47315
   371
          |> declare_elem prep_vars_elem raw_elem
wenzelm@47315
   372
          |> Context_Position.restore_visible ctxt;
wenzelm@47315
   373
        val elems' = parse_elem parse_typ parse_prop ctxt' raw_elem;
haftmann@29501
   374
      in (elems', ctxt') end;
ballarin@28795
   375
ballarin@28872
   376
    fun prep_concl raw_concl (insts, elems, ctxt) =
ballarin@28795
   377
      let
ballarin@29215
   378
        val concl = parse_concl parse_prop ctxt raw_concl;
ballarin@28872
   379
      in check_autofix insts elems concl ctxt end;
ballarin@28795
   380
haftmann@29501
   381
    val fors = prep_vars_inst fixed ctxt1 |> fst;
wenzelm@42360
   382
    val ctxt2 = ctxt1 |> Proof_Context.add_fixes fors |> snd;
wenzelm@30778
   383
    val (_, insts', ctxt3) = fold prep_insts_cumulative raw_insts (0, [], ctxt2);
wenzelm@30786
   384
wenzelm@30786
   385
    val _ =
wenzelm@30786
   386
      if fixed_frees then ()
wenzelm@30786
   387
      else
wenzelm@42482
   388
        (case fold (fold (Variable.add_frees ctxt3) o snd o snd) insts' [] of
wenzelm@30786
   389
          [] => ()
wenzelm@30786
   390
        | frees => error ("Illegal free variables in expression: " ^
wenzelm@30786
   391
            commas_quote (map (Syntax.string_of_term ctxt3 o Free) (rev frees))));
wenzelm@30786
   392
haftmann@29702
   393
    val ctxt4 = init_body ctxt3;
haftmann@51729
   394
    val (elems, ctxt5) = fold_map prep_elem raw_elems ctxt4;
wenzelm@30778
   395
    val (insts, elems', concl, ctxt6) = prep_concl raw_concl (insts', elems, ctxt5);
ballarin@28795
   396
ballarin@28872
   397
    (* Retrieve parameter types *)
wenzelm@42494
   398
    val xs = fold (fn Fixes fixes => (fn ps => ps @ map (Variable.check_name o #1) fixes)
haftmann@29501
   399
      | _ => fn ps => ps) (Fixes fors :: elems') [];
wenzelm@42360
   400
    val (Ts, ctxt7) = fold_map Proof_Context.inferred_param xs ctxt6;
ballarin@28895
   401
    val parms = xs ~~ Ts;  (* params from expression and elements *)
ballarin@28795
   402
wenzelm@49818
   403
    val fors' = finish_fixes parms fors;
wenzelm@30755
   404
    val fixed = map (fn (b, SOME T, mx) => ((Binding.name_of b, T), mx)) fors';
wenzelm@49819
   405
    val deps = map (finish_inst ctxt6) insts;
wenzelm@49819
   406
    val elems'' = map (finish_elem (ctxt1, ctxt6) parms do_close) elems';
ballarin@28852
   407
wenzelm@30755
   408
  in ((fixed, deps, elems'', concl), (parms, ctxt7)) end
ballarin@28795
   409
ballarin@28795
   410
in
ballarin@28795
   411
haftmann@29501
   412
fun cert_full_context_statement x =
wenzelm@42360
   413
  prep_full_context_statement (K I) (K I) Proof_Context.cert_vars
wenzelm@42360
   414
  make_inst Proof_Context.cert_vars (K I) x;
wenzelm@30776
   415
haftmann@29501
   416
fun cert_read_full_context_statement x =
wenzelm@42360
   417
  prep_full_context_statement Syntax.parse_typ Syntax.parse_prop Proof_Context.read_vars
wenzelm@42360
   418
  make_inst Proof_Context.cert_vars (K I) x;
wenzelm@30776
   419
ballarin@28895
   420
fun read_full_context_statement x =
wenzelm@42360
   421
  prep_full_context_statement Syntax.parse_typ Syntax.parse_prop Proof_Context.read_vars
wenzelm@46922
   422
  parse_inst Proof_Context.read_vars check_expr x;
ballarin@28795
   423
ballarin@28795
   424
end;
ballarin@28795
   425
ballarin@28795
   426
ballarin@28898
   427
(* Context statement: elements + conclusion *)
ballarin@28795
   428
ballarin@28795
   429
local
ballarin@28795
   430
ballarin@28898
   431
fun prep_statement prep activate raw_elems raw_concl context =
ballarin@28898
   432
  let
wenzelm@49817
   433
    val ((_, _, elems, concl), _) =
wenzelm@49817
   434
      prep {strict = true, do_close = false, fixed_frees = true}
wenzelm@30786
   435
        ([], []) I raw_elems raw_concl context;
wenzelm@49817
   436
    val (_, context') = context
wenzelm@49817
   437
      |> Proof_Context.set_stmt true
wenzelm@49817
   438
      |> fold_map activate elems;
ballarin@28898
   439
  in (concl, context') end;
ballarin@28898
   440
ballarin@28898
   441
in
ballarin@28898
   442
haftmann@29501
   443
fun cert_statement x = prep_statement cert_full_context_statement Element.activate_i x;
ballarin@28898
   444
fun read_statement x = prep_statement read_full_context_statement Element.activate x;
ballarin@28898
   445
ballarin@28898
   446
end;
ballarin@28898
   447
ballarin@28898
   448
ballarin@28898
   449
(* Locale declaration: import + elements *)
ballarin@28898
   450
wenzelm@30755
   451
fun fix_params params =
wenzelm@42360
   452
  Proof_Context.add_fixes (map (fn ((x, T), mx) => (Binding.name x, SOME T, mx)) params) #> snd;
wenzelm@30755
   453
ballarin@28898
   454
local
ballarin@28898
   455
haftmann@29702
   456
fun prep_declaration prep activate raw_import init_body raw_elems context =
ballarin@28795
   457
  let
haftmann@29358
   458
    val ((fixed, deps, elems, _), (parms, ctxt')) =
wenzelm@30786
   459
      prep {strict = false, do_close = true, fixed_frees = false}
wenzelm@30786
   460
        raw_import init_body raw_elems [] context;
ballarin@28898
   461
    (* Declare parameters and imported facts *)
ballarin@28898
   462
    val context' = context |>
wenzelm@30755
   463
      fix_params fixed |>
ballarin@38316
   464
      fold (Context.proof_map o Locale.activate_facts NONE) deps;
wenzelm@47311
   465
    val (elems', context'') = context' |>
wenzelm@42360
   466
      Proof_Context.set_stmt true |>
wenzelm@30777
   467
      fold_map activate elems;
wenzelm@47311
   468
  in ((fixed, deps, elems', context''), (parms, ctxt')) end;
ballarin@28795
   469
ballarin@28795
   470
in
ballarin@28795
   471
haftmann@29501
   472
fun cert_declaration x = prep_declaration cert_full_context_statement Element.activate_i x;
haftmann@29501
   473
fun cert_read_declaration x = prep_declaration cert_read_full_context_statement Element.activate x;
ballarin@28898
   474
fun read_declaration x = prep_declaration read_full_context_statement Element.activate x;
ballarin@28898
   475
ballarin@28898
   476
end;
ballarin@28898
   477
ballarin@28898
   478
ballarin@28898
   479
(* Locale expression to set up a goal *)
ballarin@28898
   480
ballarin@28898
   481
local
ballarin@28898
   482
ballarin@28898
   483
fun props_of thy (name, morph) =
ballarin@28898
   484
  let
haftmann@29360
   485
    val (asm, defs) = Locale.specification_of thy name;
ballarin@28898
   486
  in
ballarin@28898
   487
    (case asm of NONE => defs | SOME asm => asm :: defs) |> map (Morphism.term morph)
ballarin@28898
   488
  end;
ballarin@28898
   489
ballarin@28898
   490
fun prep_goal_expression prep expression context =
ballarin@28898
   491
  let
wenzelm@42360
   492
    val thy = Proof_Context.theory_of context;
ballarin@28879
   493
haftmann@29358
   494
    val ((fixed, deps, _, _), _) =
wenzelm@30786
   495
      prep {strict = true, do_close = true, fixed_frees = true} expression I [] [] context;
ballarin@28898
   496
    (* proof obligations *)
ballarin@28898
   497
    val propss = map (props_of thy) deps;
ballarin@28898
   498
ballarin@28898
   499
    val goal_ctxt = context |>
wenzelm@30755
   500
      fix_params fixed |>
ballarin@28898
   501
      (fold o fold) Variable.auto_fixes propss;
ballarin@28898
   502
ballarin@28898
   503
    val export = Variable.export_morphism goal_ctxt context;
ballarin@28898
   504
    val exp_fact = Drule.zero_var_indexes_list o map Thm.strip_shyps o Morphism.fact export;
wenzelm@31977
   505
    val exp_term = Term_Subst.zero_var_indexes o Morphism.term export;
ballarin@28898
   506
    val exp_typ = Logic.type_map exp_term;
wenzelm@45289
   507
    val export' =
wenzelm@45289
   508
      Morphism.morphism {binding = [], typ = [exp_typ], term = [exp_term], fact = [exp_fact]};
ballarin@28898
   509
  in ((propss, deps, export'), goal_ctxt) end;
wenzelm@30344
   510
ballarin@28898
   511
in
ballarin@28898
   512
haftmann@29501
   513
fun cert_goal_expression x = prep_goal_expression cert_full_context_statement x;
ballarin@28898
   514
fun read_goal_expression x = prep_goal_expression read_full_context_statement x;
ballarin@28879
   515
ballarin@28795
   516
end;
ballarin@28795
   517
ballarin@28795
   518
ballarin@28795
   519
(*** Locale declarations ***)
ballarin@28795
   520
ballarin@29221
   521
(* extract specification text *)
ballarin@29221
   522
ballarin@29221
   523
val norm_term = Envir.beta_norm oo Term.subst_atomic;
ballarin@29221
   524
ballarin@29221
   525
fun bind_def ctxt eq (xs, env, eqs) =
ballarin@29221
   526
  let
wenzelm@35624
   527
    val _ = Local_Defs.cert_def ctxt eq;
wenzelm@35624
   528
    val ((y, T), b) = Local_Defs.abs_def eq;
ballarin@29221
   529
    val b' = norm_term env b;
ballarin@29221
   530
    fun err msg = error (msg ^ ": " ^ quote y);
ballarin@29221
   531
  in
wenzelm@49749
   532
    (case filter (fn (Free (y', _), _) => y = y' | _ => false) env of
wenzelm@49749
   533
      [] => (Term.add_frees b' xs, (Free (y, T), b') :: env, eq :: eqs)
wenzelm@49749
   534
    | dups =>
wenzelm@49749
   535
        if forall (fn (_, b'') => b' aconv b'') dups then (xs, env, eqs)
wenzelm@49749
   536
        else err "Attempt to redefine variable")
ballarin@29221
   537
  end;
ballarin@29221
   538
ballarin@29221
   539
(* text has the following structure:
ballarin@29221
   540
       (((exts, exts'), (ints, ints')), (xs, env, defs))
ballarin@29221
   541
   where
ballarin@29221
   542
     exts: external assumptions (terms in assumes elements)
ballarin@29221
   543
     exts': dito, normalised wrt. env
ballarin@29221
   544
     ints: internal assumptions (terms in assumptions from insts)
ballarin@29221
   545
     ints': dito, normalised wrt. env
ballarin@29221
   546
     xs: the free variables in exts' and ints' and rhss of definitions,
ballarin@29221
   547
       this includes parameters except defined parameters
ballarin@29221
   548
     env: list of term pairs encoding substitutions, where the first term
ballarin@29221
   549
       is a free variable; substitutions represent defines elements and
ballarin@29221
   550
       the rhs is normalised wrt. the previous env
ballarin@29221
   551
     defs: the equations from the defines elements
ballarin@29221
   552
   *)
ballarin@29221
   553
ballarin@29221
   554
fun eval_text _ _ (Fixes _) text = text
ballarin@29221
   555
  | eval_text _ _ (Constrains _) text = text
ballarin@29221
   556
  | eval_text _ is_ext (Assumes asms)
ballarin@29221
   557
        (((exts, exts'), (ints, ints')), (xs, env, defs)) =
ballarin@29221
   558
      let
ballarin@29221
   559
        val ts = maps (map #1 o #2) asms;
ballarin@29221
   560
        val ts' = map (norm_term env) ts;
ballarin@29221
   561
        val spec' =
ballarin@29221
   562
          if is_ext then ((exts @ ts, exts' @ ts'), (ints, ints'))
ballarin@29221
   563
          else ((exts, exts'), (ints @ ts, ints' @ ts'));
ballarin@29221
   564
      in (spec', (fold Term.add_frees ts' xs, env, defs)) end
ballarin@29221
   565
  | eval_text ctxt _ (Defines defs) (spec, binds) =
ballarin@29221
   566
      (spec, fold (bind_def ctxt o #1 o #2) defs binds)
ballarin@29221
   567
  | eval_text _ _ (Notes _) text = text;
ballarin@29221
   568
ballarin@29221
   569
fun eval_inst ctxt (loc, morph) text =
ballarin@29221
   570
  let
wenzelm@42360
   571
    val thy = Proof_Context.theory_of ctxt;
haftmann@29360
   572
    val (asm, defs) = Locale.specification_of thy loc;
ballarin@29221
   573
    val asm' = Option.map (Morphism.term morph) asm;
ballarin@29221
   574
    val defs' = map (Morphism.term morph) defs;
ballarin@29221
   575
    val text' = text |>
ballarin@29221
   576
      (if is_some asm
ballarin@29221
   577
        then eval_text ctxt false (Assumes [(Attrib.empty_binding, [(the asm', [])])])
ballarin@29221
   578
        else I) |>
ballarin@29221
   579
      (if not (null defs)
ballarin@29221
   580
        then eval_text ctxt false (Defines (map (fn def => (Attrib.empty_binding, (def, []))) defs'))
ballarin@29221
   581
        else I)
haftmann@29360
   582
(* FIXME clone from locale.ML *)
ballarin@29221
   583
  in text' end;
ballarin@29221
   584
ballarin@29221
   585
fun eval_elem ctxt elem text =
wenzelm@30725
   586
  eval_text ctxt true elem text;
ballarin@29221
   587
ballarin@29221
   588
fun eval ctxt deps elems =
ballarin@29221
   589
  let
ballarin@29221
   590
    val text' = fold (eval_inst ctxt) deps ((([], []), ([], [])), ([], [], []));
ballarin@29221
   591
    val ((spec, (_, _, defs))) = fold (eval_elem ctxt) elems text';
ballarin@29221
   592
  in (spec, defs) end;
ballarin@29221
   593
ballarin@28903
   594
(* axiomsN: name of theorem set with destruct rules for locale predicates,
ballarin@28903
   595
     also name suffix of delta predicates and assumptions. *)
ballarin@28903
   596
ballarin@28903
   597
val axiomsN = "axioms";
ballarin@28903
   598
ballarin@28795
   599
local
ballarin@28795
   600
ballarin@28795
   601
(* introN: name of theorems for introduction rules of locale and
ballarin@28903
   602
     delta predicates *)
ballarin@28795
   603
ballarin@28795
   604
val introN = "intro";
ballarin@28795
   605
ballarin@28795
   606
fun atomize_spec thy ts =
ballarin@28795
   607
  let
ballarin@28795
   608
    val t = Logic.mk_conjunction_balanced ts;
wenzelm@35625
   609
    val body = Object_Logic.atomize_term thy t;
ballarin@28795
   610
    val bodyT = Term.fastype_of body;
ballarin@28795
   611
  in
ballarin@28795
   612
    if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of thy t))
wenzelm@35625
   613
    else (body, bodyT, Object_Logic.atomize (Thm.cterm_of thy t))
ballarin@28795
   614
  end;
ballarin@28795
   615
ballarin@28795
   616
(* achieve plain syntax for locale predicates (without "PROP") *)
ballarin@28795
   617
wenzelm@49820
   618
fun aprop_tr' n c =
wenzelm@49820
   619
  let
wenzelm@49820
   620
    val c' = Lexicon.mark_const c;
wenzelm@49820
   621
    fun tr' T args =
wenzelm@49820
   622
      if T <> dummyT andalso length args = n
wenzelm@49820
   623
      then Syntax.const "_aprop" $ Term.list_comb (Syntax.const c', args)
wenzelm@49820
   624
      else raise Match;
wenzelm@49820
   625
  in (c', tr') end;
ballarin@28795
   626
ballarin@28898
   627
(* define one predicate including its intro rule and axioms
haftmann@33360
   628
   - binding: predicate name
ballarin@28795
   629
   - parms: locale parameters
ballarin@28795
   630
   - defs: thms representing substitutions from defines elements
ballarin@28795
   631
   - ts: terms representing locale assumptions (not normalised wrt. defs)
ballarin@28795
   632
   - norm_ts: terms representing locale assumptions (normalised wrt. defs)
ballarin@28795
   633
   - thy: the theory
ballarin@28795
   634
*)
ballarin@28795
   635
haftmann@33360
   636
fun def_pred binding parms defs ts norm_ts thy =
ballarin@28795
   637
  let
haftmann@33360
   638
    val name = Sign.full_name thy binding;
ballarin@28795
   639
ballarin@28795
   640
    val (body, bodyT, body_eq) = atomize_spec thy norm_ts;
wenzelm@29272
   641
    val env = Term.add_free_names body [];
ballarin@28795
   642
    val xs = filter (member (op =) env o #1) parms;
ballarin@28795
   643
    val Ts = map #2 xs;
wenzelm@29272
   644
    val extraTs =
haftmann@33040
   645
      (subtract (op =) (fold Term.add_tfreesT Ts []) (Term.add_tfrees body []))
ballarin@28795
   646
      |> Library.sort_wrt #1 |> map TFree;
ballarin@28795
   647
    val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
ballarin@28795
   648
ballarin@28795
   649
    val args = map Logic.mk_type extraTs @ map Free xs;
ballarin@28795
   650
    val head = Term.list_comb (Const (name, predT), args);
wenzelm@35625
   651
    val statement = Object_Logic.ensure_propT thy head;
ballarin@28795
   652
ballarin@28795
   653
    val ([pred_def], defs_thy) =
ballarin@28795
   654
      thy
wenzelm@49820
   655
      |> bodyT = propT ? Sign.add_trfunsT [aprop_tr' (length args) name]
wenzelm@42375
   656
      |> Sign.declare_const_global ((Binding.conceal binding, predT), NoSyn) |> snd
wenzelm@39557
   657
      |> Global_Theory.add_defs false
wenzelm@35238
   658
        [((Binding.conceal (Thm.def_binding binding), Logic.mk_equals (head, body)), [])];
wenzelm@42360
   659
    val defs_ctxt = Proof_Context.init_global defs_thy |> Variable.declare_term head;
ballarin@28795
   660
ballarin@28795
   661
    val cert = Thm.cterm_of defs_thy;
ballarin@28795
   662
ballarin@28795
   663
    val intro = Goal.prove_global defs_thy [] norm_ts statement (fn _ =>
wenzelm@41228
   664
      rewrite_goals_tac [pred_def] THEN
ballarin@28795
   665
      Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
ballarin@28795
   666
      Tactic.compose_tac (false,
ballarin@28795
   667
        Conjunction.intr_balanced (map (Thm.assume o cert) norm_ts), 0) 1);
ballarin@28795
   668
ballarin@28795
   669
    val conjuncts =
ballarin@28795
   670
      (Drule.equal_elim_rule2 OF [body_eq,
wenzelm@41228
   671
        Raw_Simplifier.rewrite_rule [pred_def] (Thm.assume (cert statement))])
ballarin@28795
   672
      |> Conjunction.elim_balanced (length ts);
ballarin@28795
   673
    val axioms = ts ~~ conjuncts |> map (fn (t, ax) =>
ballarin@28795
   674
      Element.prove_witness defs_ctxt t
wenzelm@41228
   675
       (rewrite_goals_tac defs THEN
ballarin@28795
   676
        Tactic.compose_tac (false, ax, 0) 1));
ballarin@28795
   677
  in ((statement, intro, axioms), defs_thy) end;
ballarin@28795
   678
ballarin@28795
   679
in
ballarin@28795
   680
wenzelm@30344
   681
(* main predicate definition function *)
ballarin@28795
   682
haftmann@33360
   683
fun define_preds binding parms (((exts, exts'), (ints, ints')), defs) thy =
ballarin@28795
   684
  let
wenzelm@30762
   685
    val defs' = map (cterm_of thy #> Assumption.assume #> Drule.abs_def) defs;
ballarin@29031
   686
ballarin@28795
   687
    val (a_pred, a_intro, a_axioms, thy'') =
ballarin@28795
   688
      if null exts then (NONE, NONE, [], thy)
ballarin@28795
   689
      else
ballarin@28795
   690
        let
haftmann@33360
   691
          val abinding = if null ints then binding else Binding.suffix_name ("_" ^ axiomsN) binding;
ballarin@28795
   692
          val ((statement, intro, axioms), thy') =
ballarin@28795
   693
            thy
haftmann@33360
   694
            |> def_pred abinding parms defs' exts exts';
ballarin@28795
   695
          val (_, thy'') =
ballarin@28795
   696
            thy'
wenzelm@35204
   697
            |> Sign.qualified_path true abinding
wenzelm@39557
   698
            |> Global_Theory.note_thmss ""
wenzelm@33278
   699
              [((Binding.conceal (Binding.name introN), []), [([intro], [Locale.unfold_add])])]
ballarin@28795
   700
            ||> Sign.restore_naming thy';
ballarin@28795
   701
          in (SOME statement, SOME intro, axioms, thy'') end;
ballarin@28795
   702
    val (b_pred, b_intro, b_axioms, thy'''') =
ballarin@28795
   703
      if null ints then (NONE, NONE, [], thy'')
ballarin@28795
   704
      else
ballarin@28795
   705
        let
ballarin@28795
   706
          val ((statement, intro, axioms), thy''') =
ballarin@28795
   707
            thy''
haftmann@33360
   708
            |> def_pred binding parms defs' (ints @ the_list a_pred) (ints' @ the_list a_pred);
ballarin@28795
   709
          val (_, thy'''') =
ballarin@28795
   710
            thy'''
wenzelm@35204
   711
            |> Sign.qualified_path true binding
wenzelm@39557
   712
            |> Global_Theory.note_thmss ""
wenzelm@33278
   713
                 [((Binding.conceal (Binding.name introN), []), [([intro], [Locale.intro_add])]),
wenzelm@33278
   714
                  ((Binding.conceal (Binding.name axiomsN), []),
wenzelm@35021
   715
                    [(map (Drule.export_without_context o Element.conclude_witness) axioms, [])])]
ballarin@28795
   716
            ||> Sign.restore_naming thy''';
ballarin@28795
   717
        in (SOME statement, SOME intro, axioms, thy'''') end;
ballarin@28795
   718
  in ((a_pred, a_intro, a_axioms), (b_pred, b_intro, b_axioms), thy'''') end;
ballarin@28795
   719
ballarin@28795
   720
end;
ballarin@28795
   721
ballarin@28795
   722
ballarin@28795
   723
local
ballarin@28795
   724
ballarin@28795
   725
fun assumes_to_notes (Assumes asms) axms =
ballarin@28795
   726
      fold_map (fn (a, spec) => fn axs =>
ballarin@28795
   727
          let val (ps, qs) = chop (length spec) axs
ballarin@28795
   728
          in ((a, [(ps, [])]), qs) end) asms axms
wenzelm@33644
   729
      |> apfst (curry Notes "")
ballarin@28795
   730
  | assumes_to_notes e axms = (e, axms);
ballarin@28795
   731
ballarin@29031
   732
fun defines_to_notes thy (Defines defs) =
wenzelm@42440
   733
      Notes ("", map (fn (a, (def, _)) =>
ballarin@29245
   734
        (a, [([Assumption.assume (cterm_of thy def)],
wenzelm@30725
   735
          [(Attrib.internal o K) Locale.witness_add])])) defs)
ballarin@29031
   736
  | defines_to_notes _ e = e;
ballarin@28795
   737
ballarin@28898
   738
fun gen_add_locale prep_decl
wenzelm@41585
   739
    before_exit binding raw_predicate_binding raw_import raw_body thy =
ballarin@28795
   740
  let
haftmann@33360
   741
    val name = Sign.full_name thy binding;
haftmann@29391
   742
    val _ = Locale.defined thy name andalso
ballarin@28795
   743
      error ("Duplicate definition of locale " ^ quote name);
ballarin@28795
   744
wenzelm@47311
   745
    val ((fixed, deps, body_elems, _), (parms, ctxt')) =
wenzelm@42360
   746
      prep_decl raw_import I raw_body (Proof_Context.init_global thy);
ballarin@29221
   747
    val text as (((_, exts'), _), defs) = eval ctxt' deps body_elems;
ballarin@29221
   748
wenzelm@37313
   749
    val extraTs =
wenzelm@37313
   750
      subtract (op =) (fold Term.add_tfreesT (map snd parms) []) (fold Term.add_tfrees exts' []);
wenzelm@37313
   751
    val _ =
wenzelm@37313
   752
      if null extraTs then ()
wenzelm@37313
   753
      else warning ("Additional type variable(s) in locale specification " ^
wenzelm@42381
   754
          Binding.print binding ^ ": " ^
wenzelm@37313
   755
          commas (map (Syntax.string_of_typ ctxt' o TFree) (sort_wrt #1 extraTs)));
wenzelm@37313
   756
haftmann@33360
   757
    val predicate_binding =
haftmann@33360
   758
      if Binding.is_empty raw_predicate_binding then binding
haftmann@33360
   759
      else raw_predicate_binding;
ballarin@28872
   760
    val ((a_statement, a_intro, a_axioms), (b_statement, b_intro, b_axioms), thy') =
haftmann@33360
   761
      define_preds predicate_binding parms text thy;
ballarin@28795
   762
ballarin@29035
   763
    val a_satisfy = Element.satisfy_morphism a_axioms;
ballarin@29035
   764
    val b_satisfy = Element.satisfy_morphism b_axioms;
ballarin@28903
   765
ballarin@28895
   766
    val params = fixed @
wenzelm@30755
   767
      maps (fn Fixes fixes =>
wenzelm@30755
   768
        map (fn (b, SOME T, mx) => ((Binding.name_of b, T), mx)) fixes | _ => []) body_elems;
ballarin@28903
   769
    val asm = if is_some b_statement then b_statement else a_statement;
ballarin@29028
   770
ballarin@29028
   771
    val notes =
wenzelm@33278
   772
      if is_some asm then
wenzelm@33643
   773
        [("", [((Binding.conceal (Binding.suffix_name ("_" ^ axiomsN) binding), []),
wenzelm@33278
   774
          [([Assumption.assume (cterm_of thy' (the asm))],
wenzelm@33278
   775
            [(Attrib.internal o K) Locale.witness_add])])])]
wenzelm@30725
   776
      else [];
ballarin@28795
   777
ballarin@29035
   778
    val notes' = body_elems |>
ballarin@29035
   779
      map (defines_to_notes thy') |>
wenzelm@45290
   780
      map (Element.transform_ctxt a_satisfy) |>
ballarin@29035
   781
      (fn elems => fold_map assumes_to_notes elems (map Element.conclude_witness a_axioms)) |>
ballarin@29035
   782
      fst |>
wenzelm@45290
   783
      map (Element.transform_ctxt b_satisfy) |>
ballarin@29035
   784
      map_filter (fn Notes notes => SOME notes | _ => NONE);
ballarin@29035
   785
ballarin@29035
   786
    val deps' = map (fn (l, morph) => (l, morph $> b_satisfy)) deps;
haftmann@29441
   787
    val axioms = map Element.conclude_witness b_axioms;
ballarin@28872
   788
haftmann@29358
   789
    val loc_ctxt = thy'
haftmann@33360
   790
      |> Locale.register_locale binding (extraTs, params)
wenzelm@35798
   791
          (asm, rev defs) (a_intro, b_intro) axioms [] (rev notes) (rev deps')
wenzelm@41585
   792
      |> Named_Target.init before_exit name
wenzelm@33671
   793
      |> fold (fn (kind, facts) => Local_Theory.notes_kind kind facts #> snd) notes';
ballarin@29028
   794
haftmann@29358
   795
  in (name, loc_ctxt) end;
ballarin@28795
   796
ballarin@28795
   797
in
ballarin@28795
   798
haftmann@29501
   799
val add_locale = gen_add_locale cert_declaration;
ballarin@28902
   800
val add_locale_cmd = gen_add_locale read_declaration;
ballarin@28795
   801
ballarin@28795
   802
end;
ballarin@28795
   803
ballarin@28895
   804
ballarin@28895
   805
(*** Interpretation ***)
ballarin@28895
   806
haftmann@51731
   807
local
haftmann@51731
   808
ballarin@43543
   809
fun read_with_extended_syntax parse_prop deps ctxt props =
ballarin@43543
   810
  let
ballarin@43543
   811
    val deps_ctxt = fold Locale.activate_declarations deps ctxt;
ballarin@43543
   812
  in
ballarin@43543
   813
    map (parse_prop deps_ctxt o snd) props |> Syntax.check_terms deps_ctxt
ballarin@43543
   814
      |> Variable.export_terms deps_ctxt ctxt
ballarin@43543
   815
  end;
ballarin@43543
   816
haftmann@51731
   817
fun read_interpretation prep_expr parse_prop prep_attr expression equations initial_ctxt =
haftmann@51731
   818
  let
haftmann@51731
   819
    val ((propss, deps, export), expr_ctxt) = prep_expr expression initial_ctxt;
haftmann@51731
   820
    val eqns = read_with_extended_syntax parse_prop deps expr_ctxt equations;
haftmann@51731
   821
    val attrss = map (apsnd (map (prep_attr (Proof_Context.theory_of initial_ctxt))) o fst) equations;
haftmann@51731
   822
    val goal_ctxt = fold Variable.auto_fixes eqns expr_ctxt;
haftmann@51731
   823
    val export' = Variable.export_morphism goal_ctxt expr_ctxt;
haftmann@51731
   824
  in (((propss, deps, export, export'), (eqns, attrss)), goal_ctxt) end;
haftmann@51731
   825
wenzelm@45588
   826
fun meta_rewrite ctxt = map (Local_Defs.meta_rewrite_rule ctxt #> Drule.abs_def);
wenzelm@45588
   827
haftmann@51731
   828
fun note_eqns_register note add_registration deps witss eqns attrss export export' ctxt =
haftmann@51727
   829
  let
haftmann@51727
   830
    val facts = 
haftmann@51727
   831
      (attrss ~~ map (fn eqn => [([Morphism.thm (export' $> export) eqn], [])]) eqns);
haftmann@51730
   832
    val (eqns', ctxt') = ctxt
haftmann@51730
   833
      |> note Thm.lemmaK facts
haftmann@51730
   834
      |-> (fn facts' => `(fn ctxt'' => meta_rewrite ctxt'' (maps snd facts')));
haftmann@51727
   835
  in
haftmann@51730
   836
    ctxt'
haftmann@51730
   837
    |> fold2 (fn (dep, morph) => fn wits => fn ctxt'' =>
haftmann@51730
   838
      add_registration
wenzelm@46858
   839
        (dep, morph $> Element.satisfy_morphism (map (Element.transform_witness export') wits))
haftmann@51730
   840
        (Element.eq_morphism (Proof_Context.theory_of ctxt'') eqns' |> Option.map (rpair true))
haftmann@51730
   841
        export ctxt'') deps witss
haftmann@51727
   842
  end;
ballarin@38108
   843
haftmann@51731
   844
fun generic_interpretation prep_expr parse_prop prep_attr setup_proof note add_registration
haftmann@51731
   845
    expression equations initial_ctxt = 
ballarin@28993
   846
  let
haftmann@51731
   847
    val (((propss, deps, export, export'), (eqns, attrss)), goal_ctxt) = 
haftmann@51731
   848
      read_interpretation prep_expr parse_prop prep_attr expression equations initial_ctxt;
haftmann@51731
   849
    fun after_qed witss eqns =
haftmann@51731
   850
      note_eqns_register note add_registration deps witss eqns attrss export export';
haftmann@51731
   851
  in setup_proof after_qed propss eqns goal_ctxt end;
haftmann@29441
   852
haftmann@51731
   853
fun gen_interpretation prep_expr parse_prop prep_attr expression equations thy =
haftmann@51731
   854
  thy
haftmann@51731
   855
  |> Named_Target.theory_init
haftmann@51731
   856
  |> generic_interpretation prep_expr parse_prop prep_attr
haftmann@51731
   857
      Element.witness_proof_eqs
haftmann@51731
   858
      Local_Theory.notes_kind
haftmann@51731
   859
      (Proof_Context.background_theory o Context.theory_map ooo Locale.add_registration)
haftmann@51731
   860
      expression equations;
ballarin@29210
   861
haftmann@51731
   862
fun gen_interpret prep_expr parse_prop prep_attr expression equations int state =
ballarin@38108
   863
  let
ballarin@38108
   864
    val _ = Proof.assert_forward_or_chain state;
ballarin@38108
   865
    val ctxt = Proof.context_of state;
haftmann@51731
   866
    fun lift_after_qed after_qed witss eqns = Proof.map_context (after_qed witss eqns) #> Proof.reset_facts;
haftmann@51731
   867
    fun setup_proof after_qed propss eqns goal_ctxt = 
haftmann@51731
   868
      Element.witness_local_proof_eqs (lift_after_qed after_qed) "interpret" propss eqns goal_ctxt int state;
ballarin@38108
   869
  in
haftmann@51731
   870
    generic_interpretation prep_expr parse_prop prep_attr
haftmann@51731
   871
      setup_proof
haftmann@51731
   872
      Attrib.local_notes
haftmann@51731
   873
      (Context.proof_map ooo Locale.add_registration)
haftmann@51731
   874
      expression equations ctxt
haftmann@51731
   875
  end;
haftmann@51731
   876
 
haftmann@51731
   877
fun gen_sublocale prep_expr prep_loc parse_prop prep_attr before_exit raw_locale expression equations thy =
haftmann@51731
   878
  let
haftmann@51731
   879
    val locale = prep_loc thy raw_locale;
haftmann@51731
   880
  in
haftmann@51731
   881
    thy
haftmann@51731
   882
    |> Named_Target.init before_exit locale
haftmann@51731
   883
    |> generic_interpretation prep_expr parse_prop prep_attr
haftmann@51731
   884
        Element.witness_proof_eqs
haftmann@51731
   885
        Local_Theory.notes_kind
haftmann@51731
   886
        (Proof_Context.background_theory ooo Locale.add_dependency locale)
haftmann@51731
   887
        expression equations
ballarin@38108
   888
  end;
ballarin@38108
   889
ballarin@28993
   890
in
ballarin@28993
   891
haftmann@29501
   892
fun interpretation x = gen_interpretation cert_goal_expression (K I) (K I) x;
ballarin@29210
   893
fun interpretation_cmd x = gen_interpretation read_goal_expression
ballarin@29211
   894
  Syntax.parse_prop Attrib.intern_src x;
ballarin@28895
   895
ballarin@38108
   896
fun interpret x = gen_interpret cert_goal_expression (K I) (K I) x;
ballarin@38108
   897
fun interpret_cmd x = gen_interpret read_goal_expression
ballarin@38108
   898
  Syntax.parse_prop Attrib.intern_src x;
ballarin@38108
   899
ballarin@41270
   900
fun sublocale x = gen_sublocale cert_goal_expression (K I) (K I) (K I) x;
wenzelm@41585
   901
fun sublocale_cmd x =
wenzelm@46922
   902
  gen_sublocale read_goal_expression Locale.check Syntax.parse_prop Attrib.intern_src x;
haftmann@32074
   903
haftmann@32074
   904
end;
haftmann@32074
   905
ballarin@41435
   906
ballarin@41435
   907
(** Print the instances that would be activated by an interpretation
ballarin@41435
   908
  of the expression in the current context (clean = false) or in an
ballarin@41435
   909
  empty context (clean = true). **)
ballarin@41435
   910
ballarin@41435
   911
fun print_dependencies ctxt clean expression =
ballarin@41435
   912
  let
ballarin@41435
   913
    val ((_, deps, export), expr_ctxt) = read_goal_expression expression ctxt;
ballarin@51565
   914
    val export' = if clean then Morphism.identity else export;
ballarin@41435
   915
  in
ballarin@51565
   916
    Locale.print_dependencies expr_ctxt clean export' deps
ballarin@41435
   917
  end;
ballarin@41435
   918
ballarin@28993
   919
end;