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