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