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