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