src/Pure/Isar/expression.ML
author wenzelm
Sun Jan 16 14:57:14 2011 +0100 (2011-01-16)
changeset 41585 45d7da4e4ccf
parent 41435 12585dfb86fe
child 42290 b1f544c84040
permissions -rw-r--r--
added before_exit continuation for named targets (locale, class etc.), e.g. for final check/cleanup as in VC management;
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
haftmann@29501
    11
  type 'term expr = (string * ((string * bool) * 'term map)) list
haftmann@29578
    12
  type expression_i = term expr * (binding * typ option * mixfix) list
haftmann@29578
    13
  type expression = string expr * (binding * string option * mixfix) list
ballarin@28697
    14
ballarin@28898
    15
  (* Processing of context statements *)
haftmann@29441
    16
  val cert_statement: Element.context_i list -> (term * term list) list list ->
haftmann@29501
    17
    Proof.context -> (term * term list) list list * Proof.context
ballarin@28879
    18
  val read_statement: Element.context list -> (string * string list) list list ->
haftmann@29501
    19
    Proof.context -> (term * term list) list list * Proof.context
ballarin@28879
    20
ballarin@28795
    21
  (* Declaring locales *)
haftmann@29702
    22
  val cert_declaration: expression_i -> (Proof.context -> Proof.context) -> Element.context_i list ->
wenzelm@30755
    23
    Proof.context -> (((string * typ) * mixfix) list * (string * morphism) list
haftmann@29501
    24
      * Element.context_i list) * ((string * typ) list * Proof.context)
haftmann@29702
    25
  val cert_read_declaration: expression_i -> (Proof.context -> Proof.context) -> Element.context list ->
wenzelm@30755
    26
    Proof.context -> (((string * typ) * mixfix) list * (string * morphism) list
haftmann@29501
    27
      * Element.context_i list) * ((string * typ) list * Proof.context)
haftmann@29501
    28
      (*FIXME*)
haftmann@29702
    29
  val read_declaration: expression -> (Proof.context -> Proof.context) -> Element.context list ->
wenzelm@30755
    30
    Proof.context -> (((string * typ) * mixfix) list * (string * morphism) list
haftmann@29501
    31
      * Element.context_i list) * ((string * typ) list * Proof.context)
wenzelm@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@41585
    44
  val sublocale_cmd: (local_theory -> local_theory) -> string -> 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
ballarin@29214
    71
type 'term expr = (string * ((string * bool) * 'term map)) list;
ballarin@28697
    72
haftmann@29578
    73
type expression = string expr * (binding * string option * mixfix) list;
haftmann@29578
    74
type expression_i = term expr * (binding * typ option * mixfix) list;
ballarin@28795
    75
ballarin@28697
    76
ballarin@28859
    77
(** Internalise locale names in expr **)
ballarin@28697
    78
haftmann@29360
    79
fun intern thy instances =  map (apfst (Locale.intern 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@30585
   131
    val fixed' = map (#1 #> Name.of_binding) 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
ballarin@28795
   188
    (Element.inst_morphism (ProofContext.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@29604
   201
    term = prep_term (ProofContext.set_mode ProofContext.mode_schematic ctxt),
wenzelm@29604
   202
    pattern = prep_term (ProofContext.set_mode ProofContext.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@30725
   208
    (prep_term (ProofContext.set_mode ProofContext.mode_schematic ctxt) t,
ballarin@29215
   209
      map (prep_term (ProofContext.set_mode ProofContext.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
ballarin@28885
   250
        ((t, Syntax.check_props (ProofContext.set_mode ProofContext.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
ballarin@28885
   255
        (ProofContext.set_mode ProofContext.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@30763
   282
      in ctxt |> ProofContext.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
ballarin@28872
   325
    val thy = ProofContext.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
haftmann@29797
   346
fun prep_full_context_statement parse_typ parse_prop prep_vars_elem prep_inst prep_vars_inst prep_expr
wenzelm@30786
   347
    {strict, do_close, fixed_frees} raw_import init_body raw_elems raw_concl ctxt1 =
ballarin@28795
   348
  let
haftmann@29358
   349
    val thy = ProofContext.theory_of ctxt1;
ballarin@28872
   350
ballarin@28895
   351
    val (raw_insts, fixed) = parameters_of thy strict (apfst (prep_expr thy) raw_import);
ballarin@28895
   352
wenzelm@30778
   353
    fun prep_insts_cumulative (loc, (prfx, inst)) (i, insts, ctxt) =
ballarin@28872
   354
      let
wenzelm@30755
   355
        val (parm_names, parm_types) = Locale.params_of thy loc |> map #1 |> split_list;
haftmann@29797
   356
        val inst' = prep_inst ctxt parm_names inst;
wenzelm@37145
   357
        val parm_types' = map (Type_Infer.paramify_vars o
wenzelm@35845
   358
          Term.map_type_tvar (fn ((x, _), S) => TVar ((x, i), S)) o Logic.varifyT_global) parm_types;
wenzelm@39288
   359
        val inst'' = map2 Type.constraint parm_types' inst';
ballarin@28872
   360
        val insts' = insts @ [(loc, (prfx, inst''))];
ballarin@28951
   361
        val (insts'', _, _, ctxt' (* FIXME not used *) ) = 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@29501
   367
    fun prep_elem insts raw_elem (elems, ctxt) =
ballarin@28852
   368
      let
haftmann@29501
   369
        val ctxt' = declare_elem prep_vars_elem raw_elem ctxt;
ballarin@28852
   370
        val elems' = elems @ [parse_elem parse_typ parse_prop ctxt' raw_elem];
wenzelm@30778
   371
        val (_, _, _, ctxt'' (* FIXME not used *) ) = check_autofix insts elems' [] ctxt';
haftmann@29501
   372
      in (elems', ctxt') end;
ballarin@28795
   373
ballarin@28872
   374
    fun prep_concl raw_concl (insts, elems, ctxt) =
ballarin@28795
   375
      let
ballarin@29215
   376
        val concl = parse_concl parse_prop ctxt raw_concl;
ballarin@28872
   377
      in check_autofix insts elems concl ctxt end;
ballarin@28795
   378
haftmann@29501
   379
    val fors = prep_vars_inst fixed ctxt1 |> fst;
wenzelm@30763
   380
    val ctxt2 = ctxt1 |> ProofContext.add_fixes fors |> snd;
wenzelm@30778
   381
    val (_, insts', ctxt3) = fold prep_insts_cumulative raw_insts (0, [], ctxt2);
wenzelm@30786
   382
wenzelm@30786
   383
    val add_free = fold_aterms
wenzelm@30786
   384
      (fn Free (x, T) => not (Variable.is_fixed ctxt3 x) ? insert (op =) (x, T) | _ => I);
wenzelm@30786
   385
    val _ =
wenzelm@30786
   386
      if fixed_frees then ()
wenzelm@30786
   387
      else
wenzelm@30786
   388
        (case fold (fold add_free 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@30585
   398
    val xs = fold (fn Fixes fixes => (fn ps => ps @ map (Name.of_binding o #1) fixes)
haftmann@29501
   399
      | _ => fn ps => ps) (Fixes fors :: elems') [];
wenzelm@30344
   400
    val (Ts, ctxt7) = fold_map ProofContext.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 =
haftmann@29501
   412
  prep_full_context_statement (K I) (K I) ProofContext.cert_vars
haftmann@29501
   413
  make_inst ProofContext.cert_vars (K I) x;
wenzelm@30776
   414
haftmann@29501
   415
fun cert_read_full_context_statement x =
haftmann@29501
   416
  prep_full_context_statement Syntax.parse_typ Syntax.parse_prop ProofContext.read_vars
haftmann@29501
   417
  make_inst ProofContext.cert_vars (K I) x;
wenzelm@30776
   418
ballarin@28895
   419
fun read_full_context_statement x =
haftmann@29501
   420
  prep_full_context_statement Syntax.parse_typ Syntax.parse_prop ProofContext.read_vars
haftmann@29501
   421
  parse_inst ProofContext.read_vars intern 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 |>
haftmann@29501
   436
       ProofContext.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@30763
   451
  ProofContext.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' |>
haftmann@29501
   465
      ProofContext.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
ballarin@28898
   491
    val thy = ProofContext.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@29604
   506
    val export' = Morphism.morphism {binding = I, typ = exp_typ, term = exp_term, fact = exp_fact};
ballarin@28898
   507
  in ((propss, deps, export'), goal_ctxt) end;
wenzelm@30344
   508
ballarin@28898
   509
in
ballarin@28898
   510
haftmann@29501
   511
fun cert_goal_expression x = prep_goal_expression cert_full_context_statement x;
ballarin@28898
   512
fun read_goal_expression x = prep_goal_expression read_full_context_statement x;
ballarin@28879
   513
ballarin@28795
   514
end;
ballarin@28795
   515
ballarin@28795
   516
ballarin@28795
   517
(*** Locale declarations ***)
ballarin@28795
   518
ballarin@29221
   519
(* extract specification text *)
ballarin@29221
   520
ballarin@29221
   521
val norm_term = Envir.beta_norm oo Term.subst_atomic;
ballarin@29221
   522
ballarin@29221
   523
fun bind_def ctxt eq (xs, env, eqs) =
ballarin@29221
   524
  let
wenzelm@35624
   525
    val _ = Local_Defs.cert_def ctxt eq;
wenzelm@35624
   526
    val ((y, T), b) = Local_Defs.abs_def eq;
ballarin@29221
   527
    val b' = norm_term env b;
ballarin@29221
   528
    fun err msg = error (msg ^ ": " ^ quote y);
ballarin@29221
   529
  in
ballarin@29250
   530
    case filter (fn (Free (y', _), _) => y = y' | _ => false) env of
ballarin@29250
   531
      [] => (Term.add_frees b' xs, (Free (y, T), b') :: env, eq :: eqs) |
ballarin@29250
   532
      dups => if forall (fn (_, b'') => b' aconv b'') dups
ballarin@29250
   533
        then (xs, env, eqs)
ballarin@29250
   534
        else err "Attempt to redefine variable"
ballarin@29221
   535
  end;
ballarin@29221
   536
ballarin@29221
   537
(* text has the following structure:
ballarin@29221
   538
       (((exts, exts'), (ints, ints')), (xs, env, defs))
ballarin@29221
   539
   where
ballarin@29221
   540
     exts: external assumptions (terms in assumes elements)
ballarin@29221
   541
     exts': dito, normalised wrt. env
ballarin@29221
   542
     ints: internal assumptions (terms in assumptions from insts)
ballarin@29221
   543
     ints': dito, normalised wrt. env
ballarin@29221
   544
     xs: the free variables in exts' and ints' and rhss of definitions,
ballarin@29221
   545
       this includes parameters except defined parameters
ballarin@29221
   546
     env: list of term pairs encoding substitutions, where the first term
ballarin@29221
   547
       is a free variable; substitutions represent defines elements and
ballarin@29221
   548
       the rhs is normalised wrt. the previous env
ballarin@29221
   549
     defs: the equations from the defines elements
ballarin@29221
   550
   *)
ballarin@29221
   551
ballarin@29221
   552
fun eval_text _ _ (Fixes _) text = text
ballarin@29221
   553
  | eval_text _ _ (Constrains _) text = text
ballarin@29221
   554
  | eval_text _ is_ext (Assumes asms)
ballarin@29221
   555
        (((exts, exts'), (ints, ints')), (xs, env, defs)) =
ballarin@29221
   556
      let
ballarin@29221
   557
        val ts = maps (map #1 o #2) asms;
ballarin@29221
   558
        val ts' = map (norm_term env) ts;
ballarin@29221
   559
        val spec' =
ballarin@29221
   560
          if is_ext then ((exts @ ts, exts' @ ts'), (ints, ints'))
ballarin@29221
   561
          else ((exts, exts'), (ints @ ts, ints' @ ts'));
ballarin@29221
   562
      in (spec', (fold Term.add_frees ts' xs, env, defs)) end
ballarin@29221
   563
  | eval_text ctxt _ (Defines defs) (spec, binds) =
ballarin@29221
   564
      (spec, fold (bind_def ctxt o #1 o #2) defs binds)
ballarin@29221
   565
  | eval_text _ _ (Notes _) text = text;
ballarin@29221
   566
ballarin@29221
   567
fun eval_inst ctxt (loc, morph) text =
ballarin@29221
   568
  let
ballarin@29221
   569
    val thy = ProofContext.theory_of ctxt;
haftmann@29360
   570
    val (asm, defs) = Locale.specification_of thy loc;
ballarin@29221
   571
    val asm' = Option.map (Morphism.term morph) asm;
ballarin@29221
   572
    val defs' = map (Morphism.term morph) defs;
ballarin@29221
   573
    val text' = text |>
ballarin@29221
   574
      (if is_some asm
ballarin@29221
   575
        then eval_text ctxt false (Assumes [(Attrib.empty_binding, [(the asm', [])])])
ballarin@29221
   576
        else I) |>
ballarin@29221
   577
      (if not (null defs)
ballarin@29221
   578
        then eval_text ctxt false (Defines (map (fn def => (Attrib.empty_binding, (def, []))) defs'))
ballarin@29221
   579
        else I)
haftmann@29360
   580
(* FIXME clone from locale.ML *)
ballarin@29221
   581
  in text' end;
ballarin@29221
   582
ballarin@29221
   583
fun eval_elem ctxt elem text =
wenzelm@30725
   584
  eval_text ctxt true elem text;
ballarin@29221
   585
ballarin@29221
   586
fun eval ctxt deps elems =
ballarin@29221
   587
  let
ballarin@29221
   588
    val text' = fold (eval_inst ctxt) deps ((([], []), ([], [])), ([], [], []));
ballarin@29221
   589
    val ((spec, (_, _, defs))) = fold (eval_elem ctxt) elems text';
ballarin@29221
   590
  in (spec, defs) end;
ballarin@29221
   591
ballarin@28903
   592
(* axiomsN: name of theorem set with destruct rules for locale predicates,
ballarin@28903
   593
     also name suffix of delta predicates and assumptions. *)
ballarin@28903
   594
ballarin@28903
   595
val axiomsN = "axioms";
ballarin@28903
   596
ballarin@28795
   597
local
ballarin@28795
   598
ballarin@28795
   599
(* introN: name of theorems for introduction rules of locale and
ballarin@28903
   600
     delta predicates *)
ballarin@28795
   601
ballarin@28795
   602
val introN = "intro";
ballarin@28795
   603
ballarin@28795
   604
fun atomize_spec thy ts =
ballarin@28795
   605
  let
ballarin@28795
   606
    val t = Logic.mk_conjunction_balanced ts;
wenzelm@35625
   607
    val body = Object_Logic.atomize_term thy t;
ballarin@28795
   608
    val bodyT = Term.fastype_of body;
ballarin@28795
   609
  in
ballarin@28795
   610
    if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of thy t))
wenzelm@35625
   611
    else (body, bodyT, Object_Logic.atomize (Thm.cterm_of thy t))
ballarin@28795
   612
  end;
ballarin@28795
   613
ballarin@28795
   614
(* achieve plain syntax for locale predicates (without "PROP") *)
ballarin@28795
   615
wenzelm@35262
   616
fun aprop_tr' n c = (Syntax.mark_const c, fn ctxt => fn args =>
ballarin@28795
   617
  if length args = n then
wenzelm@35143
   618
    Syntax.const "_aprop" $   (* FIXME avoid old-style early externing (!??) *)
ballarin@28795
   619
      Term.list_comb (Syntax.free (Consts.extern (ProofContext.consts_of ctxt) c), args)
ballarin@28795
   620
  else raise Match);
ballarin@28795
   621
ballarin@28898
   622
(* define one predicate including its intro rule and axioms
haftmann@33360
   623
   - binding: predicate name
ballarin@28795
   624
   - parms: locale parameters
ballarin@28795
   625
   - defs: thms representing substitutions from defines elements
ballarin@28795
   626
   - ts: terms representing locale assumptions (not normalised wrt. defs)
ballarin@28795
   627
   - norm_ts: terms representing locale assumptions (normalised wrt. defs)
ballarin@28795
   628
   - thy: the theory
ballarin@28795
   629
*)
ballarin@28795
   630
haftmann@33360
   631
fun def_pred binding parms defs ts norm_ts thy =
ballarin@28795
   632
  let
haftmann@33360
   633
    val name = Sign.full_name thy binding;
ballarin@28795
   634
ballarin@28795
   635
    val (body, bodyT, body_eq) = atomize_spec thy norm_ts;
wenzelm@29272
   636
    val env = Term.add_free_names body [];
ballarin@28795
   637
    val xs = filter (member (op =) env o #1) parms;
ballarin@28795
   638
    val Ts = map #2 xs;
wenzelm@29272
   639
    val extraTs =
haftmann@33040
   640
      (subtract (op =) (fold Term.add_tfreesT Ts []) (Term.add_tfrees body []))
ballarin@28795
   641
      |> Library.sort_wrt #1 |> map TFree;
ballarin@28795
   642
    val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
ballarin@28795
   643
ballarin@28795
   644
    val args = map Logic.mk_type extraTs @ map Free xs;
ballarin@28795
   645
    val head = Term.list_comb (Const (name, predT), args);
wenzelm@35625
   646
    val statement = Object_Logic.ensure_propT thy head;
ballarin@28795
   647
ballarin@28795
   648
    val ([pred_def], defs_thy) =
ballarin@28795
   649
      thy
ballarin@28795
   650
      |> bodyT = propT ? Sign.add_advanced_trfuns ([], [], [aprop_tr' (length args) name], [])
haftmann@33360
   651
      |> Sign.declare_const ((Binding.conceal binding, predT), NoSyn) |> snd
wenzelm@39557
   652
      |> Global_Theory.add_defs false
wenzelm@35238
   653
        [((Binding.conceal (Thm.def_binding binding), Logic.mk_equals (head, body)), [])];
wenzelm@36610
   654
    val defs_ctxt = ProofContext.init_global defs_thy |> Variable.declare_term head;
ballarin@28795
   655
ballarin@28795
   656
    val cert = Thm.cterm_of defs_thy;
ballarin@28795
   657
ballarin@28795
   658
    val intro = Goal.prove_global defs_thy [] norm_ts statement (fn _ =>
wenzelm@41228
   659
      rewrite_goals_tac [pred_def] THEN
ballarin@28795
   660
      Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
ballarin@28795
   661
      Tactic.compose_tac (false,
ballarin@28795
   662
        Conjunction.intr_balanced (map (Thm.assume o cert) norm_ts), 0) 1);
ballarin@28795
   663
ballarin@28795
   664
    val conjuncts =
ballarin@28795
   665
      (Drule.equal_elim_rule2 OF [body_eq,
wenzelm@41228
   666
        Raw_Simplifier.rewrite_rule [pred_def] (Thm.assume (cert statement))])
ballarin@28795
   667
      |> Conjunction.elim_balanced (length ts);
ballarin@28795
   668
    val axioms = ts ~~ conjuncts |> map (fn (t, ax) =>
ballarin@28795
   669
      Element.prove_witness defs_ctxt t
wenzelm@41228
   670
       (rewrite_goals_tac defs THEN
ballarin@28795
   671
        Tactic.compose_tac (false, ax, 0) 1));
ballarin@28795
   672
  in ((statement, intro, axioms), defs_thy) end;
ballarin@28795
   673
ballarin@28795
   674
in
ballarin@28795
   675
wenzelm@30344
   676
(* main predicate definition function *)
ballarin@28795
   677
haftmann@33360
   678
fun define_preds binding parms (((exts, exts'), (ints, ints')), defs) thy =
ballarin@28795
   679
  let
wenzelm@30762
   680
    val defs' = map (cterm_of thy #> Assumption.assume #> Drule.abs_def) defs;
ballarin@29031
   681
ballarin@28795
   682
    val (a_pred, a_intro, a_axioms, thy'') =
ballarin@28795
   683
      if null exts then (NONE, NONE, [], thy)
ballarin@28795
   684
      else
ballarin@28795
   685
        let
haftmann@33360
   686
          val abinding = if null ints then binding else Binding.suffix_name ("_" ^ axiomsN) binding;
ballarin@28795
   687
          val ((statement, intro, axioms), thy') =
ballarin@28795
   688
            thy
haftmann@33360
   689
            |> def_pred abinding parms defs' exts exts';
ballarin@28795
   690
          val (_, thy'') =
ballarin@28795
   691
            thy'
wenzelm@35204
   692
            |> Sign.qualified_path true abinding
wenzelm@39557
   693
            |> Global_Theory.note_thmss ""
wenzelm@33278
   694
              [((Binding.conceal (Binding.name introN), []), [([intro], [Locale.unfold_add])])]
ballarin@28795
   695
            ||> Sign.restore_naming thy';
ballarin@28795
   696
          in (SOME statement, SOME intro, axioms, thy'') end;
ballarin@28795
   697
    val (b_pred, b_intro, b_axioms, thy'''') =
ballarin@28795
   698
      if null ints then (NONE, NONE, [], thy'')
ballarin@28795
   699
      else
ballarin@28795
   700
        let
ballarin@28795
   701
          val ((statement, intro, axioms), thy''') =
ballarin@28795
   702
            thy''
haftmann@33360
   703
            |> def_pred binding parms defs' (ints @ the_list a_pred) (ints' @ the_list a_pred);
ballarin@28795
   704
          val (_, thy'''') =
ballarin@28795
   705
            thy'''
wenzelm@35204
   706
            |> Sign.qualified_path true binding
wenzelm@39557
   707
            |> Global_Theory.note_thmss ""
wenzelm@33278
   708
                 [((Binding.conceal (Binding.name introN), []), [([intro], [Locale.intro_add])]),
wenzelm@33278
   709
                  ((Binding.conceal (Binding.name axiomsN), []),
wenzelm@35021
   710
                    [(map (Drule.export_without_context o Element.conclude_witness) axioms, [])])]
ballarin@28795
   711
            ||> Sign.restore_naming thy''';
ballarin@28795
   712
        in (SOME statement, SOME intro, axioms, thy'''') end;
ballarin@28795
   713
  in ((a_pred, a_intro, a_axioms), (b_pred, b_intro, b_axioms), thy'''') end;
ballarin@28795
   714
ballarin@28795
   715
end;
ballarin@28795
   716
ballarin@28795
   717
ballarin@28795
   718
local
ballarin@28795
   719
ballarin@28795
   720
fun assumes_to_notes (Assumes asms) axms =
ballarin@28795
   721
      fold_map (fn (a, spec) => fn axs =>
ballarin@28795
   722
          let val (ps, qs) = chop (length spec) axs
ballarin@28795
   723
          in ((a, [(ps, [])]), qs) end) asms axms
wenzelm@33644
   724
      |> apfst (curry Notes "")
ballarin@28795
   725
  | assumes_to_notes e axms = (e, axms);
ballarin@28795
   726
ballarin@29031
   727
fun defines_to_notes thy (Defines defs) =
ballarin@29031
   728
      Notes (Thm.definitionK, map (fn (a, (def, _)) =>
ballarin@29245
   729
        (a, [([Assumption.assume (cterm_of thy def)],
wenzelm@30725
   730
          [(Attrib.internal o K) Locale.witness_add])])) defs)
ballarin@29031
   731
  | defines_to_notes _ e = e;
ballarin@28795
   732
ballarin@28898
   733
fun gen_add_locale prep_decl
wenzelm@41585
   734
    before_exit binding raw_predicate_binding raw_import raw_body thy =
ballarin@28795
   735
  let
haftmann@33360
   736
    val name = Sign.full_name thy binding;
haftmann@29391
   737
    val _ = Locale.defined thy name andalso
ballarin@28795
   738
      error ("Duplicate definition of locale " ^ quote name);
ballarin@28795
   739
ballarin@29221
   740
    val ((fixed, deps, body_elems), (parms, ctxt')) =
wenzelm@36610
   741
      prep_decl raw_import I raw_body (ProofContext.init_global thy);
ballarin@29221
   742
    val text as (((_, exts'), _), defs) = eval ctxt' deps body_elems;
ballarin@29221
   743
wenzelm@37313
   744
    val extraTs =
wenzelm@37313
   745
      subtract (op =) (fold Term.add_tfreesT (map snd parms) []) (fold Term.add_tfrees exts' []);
wenzelm@37313
   746
    val _ =
wenzelm@37313
   747
      if null extraTs then ()
wenzelm@37313
   748
      else warning ("Additional type variable(s) in locale specification " ^
wenzelm@37313
   749
        quote (Binding.str_of binding) ^ ": " ^
wenzelm@37313
   750
          commas (map (Syntax.string_of_typ ctxt' o TFree) (sort_wrt #1 extraTs)));
wenzelm@37313
   751
haftmann@33360
   752
    val predicate_binding =
haftmann@33360
   753
      if Binding.is_empty raw_predicate_binding then binding
haftmann@33360
   754
      else raw_predicate_binding;
ballarin@28872
   755
    val ((a_statement, a_intro, a_axioms), (b_statement, b_intro, b_axioms), thy') =
haftmann@33360
   756
      define_preds predicate_binding parms text thy;
ballarin@28795
   757
ballarin@29035
   758
    val a_satisfy = Element.satisfy_morphism a_axioms;
ballarin@29035
   759
    val b_satisfy = Element.satisfy_morphism b_axioms;
ballarin@28903
   760
ballarin@28895
   761
    val params = fixed @
wenzelm@30755
   762
      maps (fn Fixes fixes =>
wenzelm@30755
   763
        map (fn (b, SOME T, mx) => ((Binding.name_of b, T), mx)) fixes | _ => []) body_elems;
ballarin@28903
   764
    val asm = if is_some b_statement then b_statement else a_statement;
ballarin@29028
   765
ballarin@29028
   766
    val notes =
wenzelm@33278
   767
      if is_some asm then
wenzelm@33643
   768
        [("", [((Binding.conceal (Binding.suffix_name ("_" ^ axiomsN) binding), []),
wenzelm@33278
   769
          [([Assumption.assume (cterm_of thy' (the asm))],
wenzelm@33278
   770
            [(Attrib.internal o K) Locale.witness_add])])])]
wenzelm@30725
   771
      else [];
ballarin@28795
   772
ballarin@29035
   773
    val notes' = body_elems |>
ballarin@29035
   774
      map (defines_to_notes thy') |>
ballarin@29035
   775
      map (Element.morph_ctxt a_satisfy) |>
ballarin@29035
   776
      (fn elems => fold_map assumes_to_notes elems (map Element.conclude_witness a_axioms)) |>
ballarin@29035
   777
      fst |>
ballarin@29035
   778
      map (Element.morph_ctxt b_satisfy) |>
ballarin@29035
   779
      map_filter (fn Notes notes => SOME notes | _ => NONE);
ballarin@29035
   780
ballarin@29035
   781
    val deps' = map (fn (l, morph) => (l, morph $> b_satisfy)) deps;
haftmann@29441
   782
    val axioms = map Element.conclude_witness b_axioms;
ballarin@28872
   783
haftmann@29358
   784
    val loc_ctxt = thy'
haftmann@33360
   785
      |> Locale.register_locale binding (extraTs, params)
wenzelm@35798
   786
          (asm, rev defs) (a_intro, b_intro) axioms [] (rev notes) (rev deps')
wenzelm@41585
   787
      |> Named_Target.init before_exit name
wenzelm@33671
   788
      |> fold (fn (kind, facts) => Local_Theory.notes_kind kind facts #> snd) notes';
ballarin@29028
   789
haftmann@29358
   790
  in (name, loc_ctxt) end;
ballarin@28795
   791
ballarin@28795
   792
in
ballarin@28795
   793
haftmann@29501
   794
val add_locale = gen_add_locale cert_declaration;
ballarin@28902
   795
val add_locale_cmd = gen_add_locale read_declaration;
ballarin@28795
   796
ballarin@28795
   797
end;
ballarin@28795
   798
ballarin@28895
   799
ballarin@28895
   800
(*** Interpretation ***)
ballarin@28895
   801
ballarin@38108
   802
(** Interpretation in theories and proof contexts **)
ballarin@28993
   803
ballarin@28993
   804
local
ballarin@28993
   805
ballarin@38108
   806
fun note_eqns_register deps witss attrss eqns export export' context =
ballarin@38108
   807
  let
ballarin@38108
   808
    fun meta_rewrite context =
ballarin@38108
   809
      map (Local_Defs.meta_rewrite_rule (Context.proof_of context) #> Drule.abs_def) o
ballarin@38108
   810
        maps snd;
ballarin@38108
   811
  in
ballarin@38108
   812
    context
ballarin@38108
   813
    |> Element.generic_note_thmss Thm.lemmaK
ballarin@41270
   814
      (attrss ~~ map (fn eqn => [([Morphism.thm (export' $> export) eqn], [])]) eqns)
ballarin@38108
   815
    |-> (fn facts => `(fn context => meta_rewrite context facts))
ballarin@38108
   816
    |-> (fn eqns => fold (fn ((dep, morph), wits) =>
ballarin@38108
   817
      fn context =>
ballarin@38108
   818
        Locale.add_registration (dep, morph $> Element.satisfy_morphism
ballarin@38108
   819
            (map (Element.morph_witness export') wits))
ballarin@38108
   820
          (Element.eq_morphism (Context.theory_of context) eqns |>
ballarin@38108
   821
            Option.map (rpair true))
ballarin@38108
   822
          export context) (deps ~~ witss))
ballarin@38108
   823
  end;
ballarin@38108
   824
ballarin@29211
   825
fun gen_interpretation prep_expr parse_prop prep_attr
haftmann@29496
   826
    expression equations theory =
ballarin@28993
   827
  let
wenzelm@36610
   828
    val ((propss, deps, export), expr_ctxt) = ProofContext.init_global theory
haftmann@29496
   829
      |> prep_expr expression;
haftmann@29441
   830
ballarin@29211
   831
    val eqns = map (parse_prop expr_ctxt o snd) equations |> Syntax.check_terms expr_ctxt;
haftmann@32074
   832
    val attrss = map ((apsnd o map) (prep_attr theory) o fst) equations;
ballarin@29211
   833
    val goal_ctxt = fold Variable.auto_fixes eqns expr_ctxt;
ballarin@29211
   834
    val export' = Variable.export_morphism goal_ctxt expr_ctxt;
ballarin@29210
   835
wenzelm@38757
   836
    fun after_qed witss eqns =
wenzelm@38757
   837
      (ProofContext.background_theory o Context.theory_map)
wenzelm@38757
   838
        (note_eqns_register deps witss attrss eqns export export');
haftmann@29441
   839
haftmann@29578
   840
  in Element.witness_proof_eqs after_qed propss eqns goal_ctxt end;
ballarin@28993
   841
ballarin@38108
   842
fun gen_interpret prep_expr parse_prop prep_attr
ballarin@38108
   843
    expression equations int state =
ballarin@38108
   844
  let
ballarin@38108
   845
    val _ = Proof.assert_forward_or_chain state;
ballarin@38108
   846
    val ctxt = Proof.context_of state;
ballarin@38108
   847
    val theory = ProofContext.theory_of ctxt;
ballarin@38108
   848
ballarin@38108
   849
    val ((propss, deps, export), expr_ctxt) = prep_expr expression ctxt;
ballarin@38108
   850
ballarin@38108
   851
    val eqns = map (parse_prop expr_ctxt o snd) equations |> Syntax.check_terms expr_ctxt;
ballarin@38108
   852
    val attrss = map ((apsnd o map) (prep_attr theory) o fst) equations;
ballarin@38108
   853
    val goal_ctxt = fold Variable.auto_fixes eqns expr_ctxt;
ballarin@38108
   854
    val export' = Variable.export_morphism goal_ctxt expr_ctxt;
ballarin@38108
   855
ballarin@38108
   856
    fun after_qed witss eqns = (Proof.map_context o Context.proof_map)
ballarin@38108
   857
      (note_eqns_register deps witss attrss eqns export export');
ballarin@38108
   858
  in
ballarin@38108
   859
    state
ballarin@38108
   860
    |> Element.witness_local_proof_eqs after_qed "interpret" propss eqns goal_ctxt int
ballarin@38108
   861
  end;
ballarin@38108
   862
ballarin@28993
   863
in
ballarin@28993
   864
haftmann@29501
   865
fun interpretation x = gen_interpretation cert_goal_expression (K I) (K I) x;
ballarin@29210
   866
fun interpretation_cmd x = gen_interpretation read_goal_expression
ballarin@29211
   867
  Syntax.parse_prop Attrib.intern_src x;
ballarin@28895
   868
ballarin@38108
   869
fun interpret x = gen_interpret cert_goal_expression (K I) (K I) x;
ballarin@38108
   870
fun interpret_cmd x = gen_interpret read_goal_expression
ballarin@38108
   871
  Syntax.parse_prop Attrib.intern_src x;
ballarin@38108
   872
ballarin@28895
   873
end;
ballarin@28903
   874
ballarin@29018
   875
haftmann@32074
   876
(** Interpretation between locales: declaring sublocale relationships **)
haftmann@32074
   877
haftmann@32074
   878
local
haftmann@32074
   879
ballarin@41270
   880
fun note_eqns_dependency target deps witss attrss eqns export export' ctxt =
ballarin@41270
   881
  let
ballarin@41270
   882
    fun meta_rewrite ctxt =
ballarin@41270
   883
      map (Local_Defs.meta_rewrite_rule ctxt #> Drule.abs_def) o maps snd;
ballarin@41270
   884
    val facts =
ballarin@41270
   885
      (attrss ~~ map (fn eqn => [([Morphism.thm (export' $> export) eqn], [])]) eqns);
ballarin@41270
   886
    val eqns' = ctxt |> Context.Proof
ballarin@41270
   887
      |> Element.generic_note_thmss Thm.lemmaK facts
ballarin@41270
   888
      |> apsnd Context.the_proof  (* FIXME Context.proof_map_result *)
ballarin@41270
   889
      |-> (fn facts => `(fn ctxt => meta_rewrite ctxt facts))
ballarin@41270
   890
      |> fst;  (* FIXME duplication to add_thmss *)
ballarin@41270
   891
  in
ballarin@41270
   892
    ctxt
ballarin@41270
   893
    |> Locale.add_thmss target Thm.lemmaK facts
ballarin@41270
   894
    |> ProofContext.background_theory (fold (fn ((dep, morph), wits) =>
ballarin@41270
   895
      fn theory =>
ballarin@41270
   896
        Locale.add_dependency target
ballarin@41270
   897
          (dep, morph $> Element.satisfy_morphism
ballarin@41270
   898
            (map (Element.morph_witness export') wits))
ballarin@41270
   899
          (Element.eq_morphism theory eqns' |> Option.map (rpair true))
ballarin@41270
   900
          export theory) (deps ~~ witss))
ballarin@41270
   901
  end;
ballarin@41270
   902
wenzelm@41585
   903
fun gen_sublocale prep_expr intern parse_prop prep_attr
wenzelm@41585
   904
    before_exit raw_target expression equations thy =
haftmann@32074
   905
  let
haftmann@32074
   906
    val target = intern thy raw_target;
wenzelm@41585
   907
    val target_ctxt = Named_Target.init before_exit target thy;
ballarin@41270
   908
    val ((propss, deps, export), expr_ctxt) = prep_expr expression target_ctxt;
ballarin@41270
   909
ballarin@41270
   910
    val eqns = map (parse_prop expr_ctxt o snd) equations |> Syntax.check_terms expr_ctxt;
ballarin@41270
   911
    val attrss = map ((apsnd o map) (prep_attr thy) o fst) equations;
ballarin@41270
   912
    val goal_ctxt = fold Variable.auto_fixes eqns expr_ctxt;
ballarin@41270
   913
    val export' = Variable.export_morphism goal_ctxt expr_ctxt;
ballarin@41270
   914
ballarin@41270
   915
    fun after_qed witss eqns =
ballarin@41270
   916
      note_eqns_dependency target deps witss attrss eqns export export';
ballarin@41270
   917
ballarin@41270
   918
  in Element.witness_proof_eqs after_qed propss eqns goal_ctxt end;
haftmann@32074
   919
in
haftmann@32074
   920
ballarin@41270
   921
fun sublocale x = gen_sublocale cert_goal_expression (K I) (K I) (K I) x;
wenzelm@41585
   922
fun sublocale_cmd x =
wenzelm@41585
   923
  gen_sublocale read_goal_expression Locale.intern Syntax.parse_prop Attrib.intern_src x;
haftmann@32074
   924
haftmann@32074
   925
end;
haftmann@32074
   926
ballarin@41435
   927
ballarin@41435
   928
(** Print the instances that would be activated by an interpretation
ballarin@41435
   929
  of the expression in the current context (clean = false) or in an
ballarin@41435
   930
  empty context (clean = true). **)
ballarin@41435
   931
ballarin@41435
   932
fun print_dependencies ctxt clean expression =
ballarin@41435
   933
  let
ballarin@41435
   934
    val ((_, deps, export), expr_ctxt) = read_goal_expression expression ctxt;
ballarin@41435
   935
  in
ballarin@41435
   936
    Locale.print_dependencies expr_ctxt clean export deps
ballarin@41435
   937
  end;
ballarin@41435
   938
ballarin@28993
   939
end;
ballarin@28993
   940