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