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