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