src/Pure/Isar/expression.ML
author ballarin
Thu, 06 Jan 2011 21:06:18 +0100
changeset 41683 12585dfb86fe
parent 41518 dea60d052923
child 41833 45d7da4e4ccf
permissions -rw-r--r--
Diagnostic command to show locale dependencies.
ballarin@28697
     1
(*  Title:      Pure/Isar/expression.ML
ballarin@28697
     2
    Author:     Clemens Ballarin, TU Muenchen
ballarin@28697
     3
ballarin@32784
     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@29439
    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@30762
    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@30762
    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@30762
    30
    Proof.context -> (((string * typ) * mixfix) list * (string * morphism) list
haftmann@29501
    31
      * Element.context_i list) * ((string * typ) list * Proof.context)
wenzelm@30350
    32
  val add_locale: binding -> binding -> expression_i -> Element.context_i list ->
haftmann@29501
    33
    theory -> string * local_theory
wenzelm@30350
    34
  val add_locale_cmd: binding -> binding -> expression -> Element.context list ->
haftmann@29501
    35
    theory -> string * local_theory
ballarin@28885
    36
ballarin@28895
    37
  (* Interpretation *)
haftmann@29439
    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
ballarin@41518
    42
  val sublocale: string -> expression_i -> (Attrib.binding * term) list ->
ballarin@41518
    43
    theory -> Proof.state
ballarin@41518
    44
  val sublocale_cmd: string -> expression -> (Attrib.binding * string) list ->
ballarin@41518
    45
    theory -> Proof.state
ballarin@41518
    46
  val interpretation: expression_i -> (Attrib.binding * term) list ->
ballarin@41518
    47
    theory -> Proof.state
ballarin@41518
    48
  val interpretation_cmd: expression -> (Attrib.binding * string) list ->
ballarin@41518
    49
    theory -> Proof.state
ballarin@41518
    50
  val interpret: expression_i -> (Attrib.binding * term) list ->
ballarin@41518
    51
    bool -> Proof.state -> Proof.state
ballarin@41518
    52
  val interpret_cmd: expression -> (Attrib.binding * string) list ->
ballarin@41518
    53
    bool -> Proof.state -> Proof.state
ballarin@41683
    54
ballarin@41683
    55
  (* Diagnostic *)
ballarin@41683
    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@28795
    81
wenzelm@30783
    82
(** Parameters of expression **)
ballarin@28697
    83
wenzelm@30783
    84
(*Sanity check of instantiations and extraction of implicit parameters.
wenzelm@30783
    85
  The latter only occurs iff strict = false.
wenzelm@30783
    86
  Positional instantiations are extended to match full length of parameter list
wenzelm@30783
    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@30762
    92
      (case duplicates (op =) xs of
wenzelm@30762
    93
        [] => ()
wenzelm@30762
    94
      | dups => error (message ^ commas dups));
ballarin@28697
    95
wenzelm@30762
    96
    fun parm_eq ((p1: string, mx1: mixfix), (p2, mx2)) = p1 = p2 andalso
wenzelm@30762
    97
      (mx1 = mx2 orelse error ("Conflicting syntax for parameter " ^ quote p1 ^ " in expression"));
wenzelm@30350
    98
wenzelm@30762
    99
    fun params_loc loc = Locale.params_of thy loc |> map (apfst #1);
wenzelm@30783
   100
    fun params_inst (loc, (prfx, Positional insts)) =
ballarin@28697
   101
          let
wenzelm@30762
   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@30762
   110
          in (ps', (loc, (prfx, Positional insts'))) end
wenzelm@30783
   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@30783
   115
            val ps' = (insts, params_loc loc) |-> fold (fn (p, _) => fn ps =>
wenzelm@30762
   116
              if AList.defined (op =) ps p then AList.delete (op =) p ps
wenzelm@30783
   117
              else error (quote p ^ " not a parameter of instantiated expression"));
wenzelm@30762
   118
          in (ps', (loc, (prfx, Named insts))) end;
ballarin@28885
   119
    fun params_expr is =
wenzelm@30783
   120
      let
wenzelm@30783
   121
        val (is', ps') = fold_map (fn i => fn ps =>
ballarin@28697
   122
          let
wenzelm@30783
   123
            val (ps', i') = params_inst i;
wenzelm@30783
   124
            val ps'' = distinct parm_eq (ps @ ps');
wenzelm@30783
   125
          in (i', ps'') end) is []
wenzelm@30783
   126
      in (ps', is') end;
ballarin@28697
   127
ballarin@28895
   128
    val (implicit, expr') = params_expr expr;
ballarin@28697
   129
wenzelm@30762
   130
    val implicit' = map #1 implicit;
wenzelm@30588
   131
    val fixed' = map (#1 #> Name.of_binding) fixed;
ballarin@28697
   132
    val _ = reject_dups "Duplicate fixed parameter(s): " fixed';
wenzelm@30350
   133
    val implicit'' =
wenzelm@30350
   134
      if strict then []
wenzelm@30350
   135
      else
wenzelm@30350
   136
        let val _ = reject_dups
ballarin@28895
   137
          "Parameter(s) declared simultaneously in expression and for clause: " (implicit' @ fixed')
wenzelm@30762
   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@29734
   149
fun prep_inst prep_term ctxt parms (Positional insts) =
ballarin@28872
   150
      (insts ~~ parms) |> map (fn
haftmann@29734
   151
        (NONE, p) => Free (p, dummyT) |
haftmann@29734
   152
        (SOME t, _) => prep_term ctxt t)
haftmann@29734
   153
  | prep_inst prep_term ctxt parms (Named insts) =
ballarin@28872
   154
      parms |> map (fn p => case AList.lookup (op =) insts p of
haftmann@29734
   155
        SOME t => prep_term ctxt t |
haftmann@29734
   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@30779
   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@37153
   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@39541
   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@30350
   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@30781
   183
      (fn inst as (x, Free (y, _)) => if x = y then NONE else SOME inst
wenzelm@30781
   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@30779
   189
      Morphism.binding_morphism (Binding.prefix mandatory prfx), ctxt')
ballarin@28795
   190
  end;
ballarin@28859
   191
ballarin@28697
   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@30728
   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@28852
   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@39541
   218
fun mk_propp (p, pats) = (Type.constraint propT p, pats);
ballarin@28885
   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@28852
   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@30781
   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@28934
   268
    val (elem_css', [concl_cs']) = chop (length elem_css) css';
ballarin@28885
   269
  in
wenzelm@30781
   270
    (map restore_inst (insts ~~ inst_cs'),
wenzelm@30781
   271
      map restore_elem (elems ~~ elem_css'),
ballarin@28934
   272
      concl_cs', ctxt')
ballarin@28885
   273
  end;
ballarin@28885
   274
ballarin@28885
   275
end;
ballarin@28852
   276
ballarin@28852
   277
ballarin@28795
   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@30770
   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@30781
   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@30728
   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@30728
   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@30448
   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@30227
   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@32792
   323
fun finish_inst ctxt (loc, (prfx, inst)) =
ballarin@28872
   324
  let
ballarin@28872
   325
    val thy = ProofContext.theory_of ctxt;
wenzelm@30762
   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@30728
   331
  finish_primitive parms (closeup ctxt parms do_close) elem;
wenzelm@30350
   332
ballarin@29221
   333
fun finish ctxt parms do_close insts elems =
ballarin@28872
   334
  let
wenzelm@32792
   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@29734
   346
fun prep_full_context_statement parse_typ parse_prop prep_vars_elem prep_inst prep_vars_inst prep_expr
wenzelm@30793
   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@30783
   353
    fun prep_insts_cumulative (loc, (prfx, inst)) (i, insts, ctxt) =
ballarin@28872
   354
      let
wenzelm@30762
   355
        val (parm_names, parm_types) = Locale.params_of thy loc |> map #1 |> split_list;
haftmann@29734
   356
        val inst' = prep_inst ctxt parm_names inst;
wenzelm@37153
   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@39541
   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@30771
   364
        val ctxt'' = Locale.activate_declarations (loc, morph) ctxt;
wenzelm@30728
   365
      in (i + 1, insts', ctxt'') end;
wenzelm@30350
   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@30783
   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@28852
   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@30770
   380
    val ctxt2 = ctxt1 |> ProofContext.add_fixes fors |> snd;
wenzelm@30783
   381
    val (_, insts', ctxt3) = fold prep_insts_cumulative raw_insts (0, [], ctxt2);
wenzelm@30793
   382
wenzelm@30793
   383
    val add_free = fold_aterms
wenzelm@30793
   384
      (fn Free (x, T) => not (Variable.is_fixed ctxt3 x) ? insert (op =) (x, T) | _ => I);
wenzelm@30793
   385
    val _ =
wenzelm@30793
   386
      if fixed_frees then ()
wenzelm@30793
   387
      else
wenzelm@30793
   388
        (case fold (fold add_free o snd o snd) insts' [] of
wenzelm@30793
   389
          [] => ()
wenzelm@30793
   390
        | frees => error ("Illegal free variables in expression: " ^
wenzelm@30793
   391
            commas_quote (map (Syntax.string_of_term ctxt3 o Free) (rev frees))));
wenzelm@30793
   392
haftmann@29702
   393
    val ctxt4 = init_body ctxt3;
haftmann@29702
   394
    val (elems, ctxt5) = fold (prep_elem insts') raw_elems ([], ctxt4);
wenzelm@30783
   395
    val (insts, elems', concl, ctxt6) = prep_concl raw_concl (insts', elems, ctxt5);
ballarin@28795
   396
ballarin@28872
   397
    (* Retrieve parameter types *)
wenzelm@30588
   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@30350
   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@30762
   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@30762
   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@30781
   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@30781
   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@30793
   433
       prep {strict = true, do_close = false, fixed_frees = true}
wenzelm@30793
   434
        ([], []) I raw_elems raw_concl context;
haftmann@29501
   435
     val (_, context') = context |>
haftmann@29501
   436
       ProofContext.set_stmt true |>
wenzelm@30782
   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@30762
   450
fun fix_params params =
wenzelm@30770
   451
  ProofContext.add_fixes (map (fn ((x, T), mx) => (Binding.name x, SOME T, mx)) params) #> snd;
wenzelm@30762
   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@30793
   458
      prep {strict = false, do_close = true, fixed_frees = false}
wenzelm@30793
   459
        raw_import init_body raw_elems [] context;
ballarin@28898
   460
    (* Declare parameters and imported facts *)
ballarin@28898
   461
    val context' = context |>
wenzelm@30762
   462
      fix_params fixed |>
ballarin@38540
   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@30782
   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@28879
   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@28898
   492
haftmann@29358
   493
    val ((fixed, deps, _, _), _) =
wenzelm@30793
   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@30762
   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@31979
   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@30350
   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@30728
   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@35148
   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@39814
   652
      |> Global_Theory.add_defs false
wenzelm@35238
   653
        [((Binding.conceal (Thm.def_binding binding), Logic.mk_equals (head, body)), [])];
wenzelm@36633
   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@41494
   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@41494
   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@41494
   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@30350
   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@30769
   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@35215
   692
            |> Sign.qualified_path true abinding
wenzelm@39814
   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@35215
   706
            |> Sign.qualified_path true binding
wenzelm@39814
   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@30728
   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
haftmann@33360
   734
    binding raw_predicate_binding raw_import raw_body thy =
ballarin@28795
   735
  let
haftmann@33360
   736
    val name = Sign.full_name thy binding;
haftmann@29389
   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@36633
   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@37331
   744
    val extraTs =
wenzelm@37331
   745
      subtract (op =) (fold Term.add_tfreesT (map snd parms) []) (fold Term.add_tfrees exts' []);
wenzelm@37331
   746
    val _ =
wenzelm@37331
   747
      if null extraTs then ()
wenzelm@37331
   748
      else warning ("Additional type variable(s) in locale specification " ^
wenzelm@37331
   749
        quote (Binding.str_of binding) ^ ": " ^
wenzelm@37331
   750
          commas (map (Syntax.string_of_typ ctxt' o TFree) (sort_wrt #1 extraTs)));
wenzelm@37331
   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@30762
   762
      maps (fn Fixes fixes =>
wenzelm@30762
   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@30728
   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@29439
   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@35800
   786
          (asm, rev defs) (a_intro, b_intro) axioms [] (rev notes) (rev deps')
haftmann@38615
   787
      |> Named_Target.init name
wenzelm@33673
   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@38354
   802
(** Interpretation in theories and proof contexts **)
ballarin@28993
   803
ballarin@28993
   804
local
ballarin@28993
   805
ballarin@38354
   806
fun note_eqns_register deps witss attrss eqns export export' context =
ballarin@38354
   807
  let
ballarin@38354
   808
    fun meta_rewrite context =
ballarin@38354
   809
      map (Local_Defs.meta_rewrite_rule (Context.proof_of context) #> Drule.abs_def) o
ballarin@38354
   810
        maps snd;
ballarin@38354
   811
  in
ballarin@38354
   812
    context
ballarin@38354
   813
    |> Element.generic_note_thmss Thm.lemmaK
ballarin@41518
   814
      (attrss ~~ map (fn eqn => [([Morphism.thm (export' $> export) eqn], [])]) eqns)
ballarin@38354
   815
    |-> (fn facts => `(fn context => meta_rewrite context facts))
ballarin@38354
   816
    |-> (fn eqns => fold (fn ((dep, morph), wits) =>
ballarin@38354
   817
      fn context =>
ballarin@38354
   818
        Locale.add_registration (dep, morph $> Element.satisfy_morphism
ballarin@38354
   819
            (map (Element.morph_witness export') wits))
ballarin@38354
   820
          (Element.eq_morphism (Context.theory_of context) eqns |>
ballarin@38354
   821
            Option.map (rpair true))
ballarin@38354
   822
          export context) (deps ~~ witss))
ballarin@38354
   823
  end;
ballarin@38354
   824
ballarin@29211
   825
fun gen_interpretation prep_expr parse_prop prep_attr
haftmann@29496
   826
    expression equations theory =
ballarin@28993
   827
  let
wenzelm@36633
   828
    val ((propss, deps, export), expr_ctxt) = ProofContext.init_global theory
haftmann@29496
   829
      |> prep_expr expression;
haftmann@29439
   830
ballarin@29211
   831
    val eqns = map (parse_prop expr_ctxt o snd) equations |> Syntax.check_terms expr_ctxt;
haftmann@32066
   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@39032
   836
    fun after_qed witss eqns =
wenzelm@39032
   837
      (ProofContext.background_theory o Context.theory_map)
wenzelm@39032
   838
        (note_eqns_register deps witss attrss eqns export export');
haftmann@29439
   839
haftmann@29578
   840
  in Element.witness_proof_eqs after_qed propss eqns goal_ctxt end;
ballarin@28993
   841
ballarin@38354
   842
fun gen_interpret prep_expr parse_prop prep_attr
ballarin@38354
   843
    expression equations int state =
ballarin@38354
   844
  let
ballarin@38354
   845
    val _ = Proof.assert_forward_or_chain state;
ballarin@38354
   846
    val ctxt = Proof.context_of state;
ballarin@38354
   847
    val theory = ProofContext.theory_of ctxt;
ballarin@38354
   848
ballarin@38354
   849
    val ((propss, deps, export), expr_ctxt) = prep_expr expression ctxt;
ballarin@38354
   850
ballarin@38354
   851
    val eqns = map (parse_prop expr_ctxt o snd) equations |> Syntax.check_terms expr_ctxt;
ballarin@38354
   852
    val attrss = map ((apsnd o map) (prep_attr theory) o fst) equations;
ballarin@38354
   853
    val goal_ctxt = fold Variable.auto_fixes eqns expr_ctxt;
ballarin@38354
   854
    val export' = Variable.export_morphism goal_ctxt expr_ctxt;
ballarin@38354
   855
ballarin@38354
   856
    fun after_qed witss eqns = (Proof.map_context o Context.proof_map)
ballarin@38354
   857
      (note_eqns_register deps witss attrss eqns export export');
ballarin@38354
   858
  in
ballarin@38354
   859
    state
ballarin@38354
   860
    |> Element.witness_local_proof_eqs after_qed "interpret" propss eqns goal_ctxt int
ballarin@38354
   861
  end;
ballarin@38354
   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@38354
   869
fun interpret x = gen_interpret cert_goal_expression (K I) (K I) x;
ballarin@38354
   870
fun interpret_cmd x = gen_interpret read_goal_expression
ballarin@38354
   871
  Syntax.parse_prop Attrib.intern_src x;
ballarin@38354
   872
ballarin@28895
   873
end;
ballarin@28903
   874
ballarin@29018
   875
haftmann@32066
   876
(** Interpretation between locales: declaring sublocale relationships **)
haftmann@32066
   877
haftmann@32066
   878
local
haftmann@32066
   879
ballarin@41518
   880
fun note_eqns_dependency target deps witss attrss eqns export export' ctxt =
ballarin@41518
   881
  let
ballarin@41518
   882
    fun meta_rewrite ctxt =
ballarin@41518
   883
      map (Local_Defs.meta_rewrite_rule ctxt #> Drule.abs_def) o maps snd;
ballarin@41518
   884
    val facts =
ballarin@41518
   885
      (attrss ~~ map (fn eqn => [([Morphism.thm (export' $> export) eqn], [])]) eqns);
ballarin@41518
   886
    val eqns' = ctxt |> Context.Proof
ballarin@41518
   887
      |> Element.generic_note_thmss Thm.lemmaK facts
ballarin@41518
   888
      |> apsnd Context.the_proof  (* FIXME Context.proof_map_result *)
ballarin@41518
   889
      |-> (fn facts => `(fn ctxt => meta_rewrite ctxt facts))
ballarin@41518
   890
      |> fst;  (* FIXME duplication to add_thmss *)
ballarin@41518
   891
  in
ballarin@41518
   892
    ctxt
ballarin@41518
   893
    |> Locale.add_thmss target Thm.lemmaK facts
ballarin@41518
   894
    |> ProofContext.background_theory (fold (fn ((dep, morph), wits) =>
ballarin@41518
   895
      fn theory =>
ballarin@41518
   896
        Locale.add_dependency target
ballarin@41518
   897
          (dep, morph $> Element.satisfy_morphism
ballarin@41518
   898
            (map (Element.morph_witness export') wits))
ballarin@41518
   899
          (Element.eq_morphism theory eqns' |> Option.map (rpair true))
ballarin@41518
   900
          export theory) (deps ~~ witss))
ballarin@41518
   901
  end;
ballarin@41518
   902
ballarin@41518
   903
fun gen_sublocale prep_expr intern parse_prop prep_attr raw_target
ballarin@41518
   904
    expression equations thy =
haftmann@32066
   905
  let
haftmann@32066
   906
    val target = intern thy raw_target;
haftmann@38615
   907
    val target_ctxt = Named_Target.init target thy;
ballarin@41518
   908
    val ((propss, deps, export), expr_ctxt) = prep_expr expression target_ctxt;
ballarin@41518
   909
ballarin@41518
   910
    val eqns = map (parse_prop expr_ctxt o snd) equations |> Syntax.check_terms expr_ctxt;
ballarin@41518
   911
    val attrss = map ((apsnd o map) (prep_attr thy) o fst) equations;
ballarin@41518
   912
    val goal_ctxt = fold Variable.auto_fixes eqns expr_ctxt;
ballarin@41518
   913
    val export' = Variable.export_morphism goal_ctxt expr_ctxt;
ballarin@41518
   914
ballarin@41518
   915
    fun after_qed witss eqns =
ballarin@41518
   916
      note_eqns_dependency target deps witss attrss eqns export export';
ballarin@41518
   917
ballarin@41518
   918
  in Element.witness_proof_eqs after_qed propss eqns goal_ctxt end;
haftmann@32066
   919
in
haftmann@32066
   920
ballarin@41518
   921
fun sublocale x = gen_sublocale cert_goal_expression (K I) (K I) (K I) x;
ballarin@41518
   922
fun sublocale_cmd x = gen_sublocale read_goal_expression Locale.intern
ballarin@41518
   923
  Syntax.parse_prop Attrib.intern_src x;
haftmann@32066
   924
haftmann@32066
   925
end;
haftmann@32066
   926
ballarin@41683
   927
ballarin@41683
   928
(** Print the instances that would be activated by an interpretation
ballarin@41683
   929
  of the expression in the current context (clean = false) or in an
ballarin@41683
   930
  empty context (clean = true). **)
ballarin@41683
   931
ballarin@41683
   932
fun print_dependencies ctxt clean expression =
ballarin@41683
   933
  let
ballarin@41683
   934
    val ((_, deps, export), expr_ctxt) = read_goal_expression expression ctxt;
ballarin@41683
   935
  in
ballarin@41683
   936
    Locale.print_dependencies expr_ctxt clean export deps
ballarin@41683
   937
  end;
ballarin@41683
   938
ballarin@28993
   939
end;
ballarin@28993
   940