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