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