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