src/Pure/Isar/expression.ML
author ballarin
Mon Nov 24 18:03:48 2008 +0100 (2008-11-24)
changeset 28879 db2816a37a34
parent 28872 686963dbf6cd
child 28885 6f6bf52e75bb
permissions -rw-r--r--
Read/cert_statement for theorem statements.
ballarin@28697
     1
(*  Title:      Pure/Isar/expression.ML
ballarin@28697
     2
    ID:         $Id$
ballarin@28697
     3
    Author:     Clemens Ballarin, TU Muenchen
ballarin@28697
     4
ballarin@28795
     5
New locale development --- experimental.
ballarin@28697
     6
*)
ballarin@28697
     7
ballarin@28697
     8
signature EXPRESSION =
ballarin@28697
     9
sig
ballarin@28872
    10
  type 'term map
ballarin@28795
    11
  type 'morph expr
ballarin@28697
    12
ballarin@28795
    13
  val empty_expr: 'morph expr
ballarin@28795
    14
ballarin@28872
    15
  type expression = (string * string map) expr * (Name.binding * string option * mixfix) list
ballarin@28872
    16
(*  type expression_i = Morphism.morphism expr * (Name.binding * typ option * mixfix) list *)
ballarin@28697
    17
ballarin@28879
    18
  (* Processing of locale statements *)
ballarin@28879
    19
  val read_statement: Element.context list -> (string * string list) list list ->
ballarin@28879
    20
    Proof.context ->  (term * term list) list list * Proof.context;
ballarin@28879
    21
  val cert_statement: Element.context_i list -> (term * term list) list list ->
ballarin@28879
    22
    Proof.context -> (term * term list) list list * Proof.context;
ballarin@28879
    23
ballarin@28795
    24
  (* Declaring locales *)
ballarin@28795
    25
  val add_locale: string -> bstring -> expression -> Element.context list -> theory ->
ballarin@28795
    26
    string * Proof.context
ballarin@28795
    27
(*
ballarin@28795
    28
  val add_locale_i: string -> bstring -> expression_i -> Element.context_i list -> theory ->
ballarin@28795
    29
    string * Proof.context
ballarin@28795
    30
*)
ballarin@28795
    31
  (* Debugging and development *)
ballarin@28795
    32
  val parse_expression: OuterParse.token list -> expression * OuterParse.token list
ballarin@28697
    33
end;
ballarin@28697
    34
ballarin@28697
    35
ballarin@28879
    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@28697
    48
datatype 'morph expr = Expr of (string * 'morph) list;
ballarin@28697
    49
ballarin@28872
    50
type expression = (string * string map) expr * (Name.binding * string option * mixfix) list;
ballarin@28697
    51
ballarin@28795
    52
val empty_expr = Expr [];
ballarin@28795
    53
ballarin@28697
    54
ballarin@28697
    55
(** Parsing and printing **)
ballarin@28697
    56
ballarin@28697
    57
local
ballarin@28697
    58
ballarin@28697
    59
structure P = OuterParse;
ballarin@28697
    60
ballarin@28697
    61
val loc_keyword = P.$$$ "fixes" || P.$$$ "constrains" || P.$$$ "assumes" ||
ballarin@28795
    62
   P.$$$ "defines" || P.$$$ "notes";
ballarin@28697
    63
fun plus1_unless test scan =
ballarin@28697
    64
  scan ::: Scan.repeat (P.$$$ "+" |-- Scan.unless test (P.!!! scan));
ballarin@28697
    65
ballarin@28697
    66
val prefix = P.name --| P.$$$ ":";
ballarin@28697
    67
val named = P.name -- (P.$$$ "=" |-- P.term);
ballarin@28697
    68
val position = P.maybe P.term;
ballarin@28697
    69
val instance = P.$$$ "where" |-- P.and_list1 named >> Named ||
ballarin@28697
    70
  Scan.repeat1 position >> Positional;
ballarin@28697
    71
ballarin@28697
    72
in
ballarin@28697
    73
ballarin@28795
    74
val parse_expression =
ballarin@28697
    75
  let
ballarin@28697
    76
    fun expr2 x = P.xname x;
ballarin@28697
    77
    fun expr1 x = (Scan.optional prefix "" -- expr2 --
ballarin@28697
    78
      Scan.optional instance (Named []) >> (fn ((p, l), i) => (l, (p, i)))) x;
ballarin@28697
    79
    fun expr0 x = (plus1_unless loc_keyword expr1 >> Expr) x;
ballarin@28697
    80
  in expr0 -- P.for_fixes end;
ballarin@28697
    81
ballarin@28697
    82
end;
ballarin@28697
    83
ballarin@28795
    84
fun pretty_expr thy (Expr expr) =
ballarin@28795
    85
  let
ballarin@28795
    86
    fun pretty_pos NONE = Pretty.str "_"
ballarin@28795
    87
      | pretty_pos (SOME x) = Pretty.str x;
ballarin@28795
    88
    fun pretty_named (x, y) = [Pretty.str x, Pretty.brk 1, Pretty.str "=",
ballarin@28795
    89
          Pretty.brk 1, Pretty.str y] |> Pretty.block;
ballarin@28795
    90
    fun pretty_ren (Positional ps) = take_suffix is_none ps |> snd |>
ballarin@28795
    91
          map pretty_pos |> Pretty.breaks
ballarin@28795
    92
      | pretty_ren (Named []) = []
ballarin@28795
    93
      | pretty_ren (Named ps) = Pretty.str "where" :: Pretty.brk 1 ::
ballarin@28795
    94
          (ps |> map pretty_named |> Pretty.separate "and");
ballarin@28795
    95
    fun pretty_rename (loc, ("", ren)) =
ballarin@28795
    96
          Pretty.block (Pretty.str (NewLocale.extern thy loc) :: Pretty.brk 1 :: pretty_ren ren) 
ballarin@28795
    97
      | pretty_rename (loc, (prfx, ren)) =
ballarin@28795
    98
          Pretty.block (Pretty.str prfx :: Pretty.brk 1 :: Pretty.str (NewLocale.extern thy loc) ::
ballarin@28795
    99
            Pretty.brk 1 :: pretty_ren ren);
ballarin@28795
   100
  in Pretty.separate "+" (map pretty_rename expr) |> Pretty.block end;
ballarin@28795
   101
ballarin@28795
   102
fun err_in_expr thy msg (Expr expr) =
ballarin@28795
   103
  let
ballarin@28795
   104
    val err_msg =
ballarin@28795
   105
      if null expr then msg
ballarin@28795
   106
      else msg ^ "\n" ^ Pretty.string_of (Pretty.block
ballarin@28795
   107
        [Pretty.str "The above error(s) occurred in expression:", Pretty.brk 1,
ballarin@28795
   108
          pretty_expr thy (Expr expr)])
ballarin@28795
   109
  in error err_msg end;
ballarin@28697
   110
ballarin@28697
   111
ballarin@28859
   112
(** Internalise locale names in expr **)
ballarin@28697
   113
ballarin@28859
   114
fun intern thy (Expr instances) = Expr (map (apfst (NewLocale.intern thy)) instances);
ballarin@28697
   115
ballarin@28697
   116
ballarin@28859
   117
(** Parameters of expression.
ballarin@28697
   118
   Sanity check of instantiations.
ballarin@28795
   119
   Positional instantiations are extended to match full length of parameter list. **)
ballarin@28697
   120
ballarin@28859
   121
fun parameters_of thy (expr, fixed) =
ballarin@28697
   122
  let
ballarin@28697
   123
    fun reject_dups message xs =
ballarin@28697
   124
      let val dups = duplicates (op =) xs
ballarin@28697
   125
      in
ballarin@28697
   126
        if null dups then () else error (message ^ commas dups)
ballarin@28697
   127
      end;
ballarin@28697
   128
ballarin@28795
   129
    fun match_bind (n, b) = (n = Name.name_of b);
ballarin@28795
   130
    fun bind_eq (b1, b2) = (Name.name_of b1 = Name.name_of b2);
ballarin@28795
   131
      (* FIXME: cannot compare bindings for equality. *)
ballarin@28795
   132
ballarin@28795
   133
    fun params_loc loc =
ballarin@28859
   134
          (NewLocale.params_of thy loc |> map (fn (p, _, mx) => (p, mx)), loc);
ballarin@28795
   135
    fun params_inst (expr as (loc, (prfx, Positional insts))) =
ballarin@28697
   136
          let
ballarin@28795
   137
            val (ps, loc') = params_loc loc;
ballarin@28697
   138
	    val d = length ps - length insts;
ballarin@28697
   139
	    val insts' =
ballarin@28879
   140
	      if d < 0 then error ("More arguments than parameters in instantiation of locale " ^
ballarin@28879
   141
                quote (NewLocale.extern thy loc))
ballarin@28697
   142
	      else insts @ replicate d NONE;
ballarin@28697
   143
            val ps' = (ps ~~ insts') |>
ballarin@28697
   144
              map_filter (fn (p, NONE) => SOME p | (_, SOME _) => NONE);
ballarin@28697
   145
          in
ballarin@28697
   146
            (ps', (loc', (prfx, Positional insts')))
ballarin@28697
   147
          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@28697
   157
          in
ballarin@28697
   158
            (ps', (loc', (prfx, Named insts)))
ballarin@28697
   159
          end;
ballarin@28795
   160
    fun params_expr (Expr is) =
ballarin@28697
   161
          let
ballarin@28697
   162
            val (is', ps') = fold_map (fn i => fn ps =>
ballarin@28697
   163
              let
ballarin@28795
   164
                val (ps', i') = params_inst i;
ballarin@28795
   165
                val ps'' = AList.join bind_eq (fn p => fn (mx1, mx2) =>
ballarin@28795
   166
                  (* FIXME: should check for bindings being the same.
ballarin@28795
   167
                     Instead we check for equal name and syntax. *)
ballarin@28697
   168
                  if mx1 = mx2 then mx1
haftmann@28862
   169
                  else error ("Conflicting syntax for parameter" ^ quote (Name.display p) ^
ballarin@28859
   170
                    " in expression.")) (ps, ps')
ballarin@28697
   171
              in (i', ps'') end) is []
ballarin@28697
   172
          in
ballarin@28697
   173
            (ps', Expr is')
ballarin@28697
   174
          end;
ballarin@28697
   175
ballarin@28795
   176
    val (parms, expr') = params_expr expr;
ballarin@28697
   177
ballarin@28859
   178
    val parms' = map (#1 #> Name.name_of) parms;
ballarin@28697
   179
    val fixed' = map (#1 #> Name.name_of) fixed;
ballarin@28697
   180
    val _ = reject_dups "Duplicate fixed parameter(s): " fixed';
ballarin@28697
   181
    val _ = reject_dups "Parameter(s) declared simultaneously in expression and for clause: " (parms' @ fixed');
ballarin@28697
   182
ballarin@28859
   183
  in (expr', (map (fn (b, mx) => (b, NONE, mx)) parms @ fixed)) end;
ballarin@28697
   184
ballarin@28795
   185
ballarin@28795
   186
(** Read instantiation **)
ballarin@28795
   187
ballarin@28872
   188
(* Parse positional or named instantiation *)
ballarin@28872
   189
ballarin@28859
   190
local
ballarin@28859
   191
ballarin@28872
   192
fun prep_inst parse_term parms (Positional insts) ctxt =
ballarin@28872
   193
      (insts ~~ parms) |> map (fn
ballarin@28872
   194
        (NONE, p) => Syntax.parse_term ctxt p |
ballarin@28872
   195
        (SOME t, _) => parse_term ctxt t)
ballarin@28872
   196
  | prep_inst parse_term parms (Named insts) ctxt =
ballarin@28872
   197
      parms |> map (fn p => case AList.lookup (op =) insts p of
ballarin@28872
   198
        SOME t => parse_term ctxt t |
ballarin@28872
   199
        NONE => Syntax.parse_term ctxt p);
ballarin@28872
   200
ballarin@28872
   201
in
ballarin@28872
   202
ballarin@28872
   203
fun parse_inst x = prep_inst Syntax.parse_term x;
ballarin@28872
   204
fun make_inst x = prep_inst (K I) x;
ballarin@28872
   205
ballarin@28872
   206
end;
ballarin@28872
   207
ballarin@28872
   208
(* Prepare type inference problem for Syntax.check_terms *)
ballarin@28872
   209
ballarin@28872
   210
fun varify_indexT i ty = ty |> Term.map_atyps
ballarin@28872
   211
  (fn TFree (a, S) => TVar ((a, i), S)
ballarin@28872
   212
    | TVar (ai, _) => raise TYPE ("Illegal schematic variable: " ^
ballarin@28872
   213
        quote (Term.string_of_vname ai), [ty], []));
ballarin@28872
   214
ballarin@28872
   215
(* Instantiation morphism *)
ballarin@28872
   216
ballarin@28872
   217
fun inst_morph (parm_names, parm_types) (prfx, insts') ctxt =
ballarin@28795
   218
  let
ballarin@28795
   219
    (* parameters *)
ballarin@28795
   220
    val type_parm_names = fold Term.add_tfreesT parm_types [] |> map fst;
ballarin@28795
   221
ballarin@28795
   222
    (* type inference and contexts *)
ballarin@28795
   223
    val parm_types' = map (TypeInfer.paramify_vars o Logic.varifyT) parm_types;
ballarin@28795
   224
    val type_parms = fold Term.add_tvarsT parm_types' [] |> map (Logic.mk_type o TVar);
ballarin@28795
   225
    val arg = type_parms @ map2 TypeInfer.constrain parm_types' insts';
ballarin@28795
   226
    val res = Syntax.check_terms ctxt arg;
ballarin@28795
   227
    val ctxt' = ctxt |> fold Variable.auto_fixes res;
ballarin@28872
   228
    
ballarin@28795
   229
    (* instantiation *)
ballarin@28795
   230
    val (type_parms'', res') = chop (length type_parms) res;
ballarin@28795
   231
    val insts'' = (parm_names ~~ res') |> map_filter
ballarin@28795
   232
      (fn (inst as (x, Free (y, _))) => if x = y then NONE else SOME inst |
ballarin@28795
   233
        inst => SOME inst);
ballarin@28795
   234
    val instT = Symtab.make (type_parm_names ~~ map Logic.dest_type type_parms'');
ballarin@28795
   235
    val inst = Symtab.make insts'';
ballarin@28795
   236
  in
ballarin@28795
   237
    (Element.inst_morphism (ProofContext.theory_of ctxt) (instT, inst) $>
ballarin@28795
   238
      Morphism.name_morphism (Name.qualified prfx), ctxt')
ballarin@28795
   239
  end;
ballarin@28859
   240
ballarin@28795
   241
ballarin@28795
   242
(*** Locale processing ***)
ballarin@28795
   243
ballarin@28852
   244
(** Parsing **)
ballarin@28852
   245
ballarin@28852
   246
fun parse_elem prep_typ prep_term ctxt elem =
ballarin@28852
   247
  Element.map_ctxt {name = I, var = I, typ = prep_typ ctxt,
ballarin@28852
   248
    term = prep_term ctxt, fact = I, attrib = I} elem;
ballarin@28852
   249
ballarin@28852
   250
fun parse_concl prep_term ctxt concl =
ballarin@28852
   251
  (map o map) (fn (t, ps) =>
ballarin@28852
   252
    (prep_term ctxt, map (prep_term ctxt) ps)) concl;
ballarin@28852
   253
ballarin@28852
   254
ballarin@28852
   255
(** Type checking **)
ballarin@28852
   256
ballarin@28852
   257
fun extract_elem (Fixes fixes) = map (#2 #> the_list #> map (Logic.mk_type #> rpair [])) fixes
ballarin@28852
   258
  | extract_elem (Constrains csts) = map (#2 #> single #> map (Logic.mk_type #> rpair [])) csts
ballarin@28852
   259
  | extract_elem (Assumes asms) = map #2 asms
ballarin@28852
   260
  | extract_elem (Defines defs) = map (fn (_, (t, ps)) => [(t, ps)]) defs
ballarin@28852
   261
  | extract_elem (Notes _) = [];
ballarin@28795
   262
ballarin@28852
   263
fun restore_elem (Fixes fixes, propps) =
ballarin@28852
   264
      (fixes ~~ propps) |> map (fn ((x, _, mx), propp) =>
ballarin@28852
   265
        (x, propp |> map (fst #> Logic.dest_type) |> try hd, mx)) |> Fixes
ballarin@28852
   266
  | restore_elem (Constrains csts, propps) =
ballarin@28852
   267
      (csts ~~ propps) |> map (fn ((x, _), propp) =>
ballarin@28852
   268
        (x, propp |> map (fst #> Logic.dest_type) |> hd)) |> Constrains
ballarin@28852
   269
  | restore_elem (Assumes asms, propps) =
ballarin@28852
   270
      (asms ~~ propps) |> map (fn ((b, _), propp) => (b, propp)) |> Assumes
ballarin@28852
   271
  | restore_elem (Defines defs, propps) =
ballarin@28852
   272
      (defs ~~ propps) |> map (fn ((b, _), [propp]) => (b, propp)) |> Defines
ballarin@28852
   273
  | restore_elem (Notes notes, _) = Notes notes;
ballarin@28852
   274
ballarin@28872
   275
fun check_autofix insts elems concl ctxt =
ballarin@28852
   276
  let
ballarin@28872
   277
    val instss = map (snd o snd) insts |> (map o map) (fn t => (t, []));
ballarin@28872
   278
    val elemss = elems |> map extract_elem;
ballarin@28872
   279
    val all_terms' = (burrow o burrow_fst) (Syntax.check_terms ctxt) (concl @ instss @ flat elemss); 
ballarin@28852
   280
(*    val (ctxt', all_props') = ProofContext.check_propp_schematic (ctxt, concl @ flat propss); *)
ballarin@28872
   281
    val ctxt'' = (fold o fold) (fn (t, _) => Variable.auto_fixes t) all_terms' ctxt;
ballarin@28872
   282
    val (concl', mores') = chop (length concl) all_terms';
ballarin@28872
   283
    val (insts', elems') = chop (length instss) mores';
ballarin@28872
   284
  in (insts' |> (map o map) fst |> curry (op ~~) insts |> map (fn ((l, (p, _)), is) => (l, (p, is))),
ballarin@28872
   285
    elems' |> unflat elemss |> curry (op ~~) elems |> map restore_elem, concl', ctxt'') end;
ballarin@28852
   286
ballarin@28852
   287
ballarin@28852
   288
(** Prepare locale elements **)
ballarin@28795
   289
ballarin@28795
   290
fun declare_elem prep_vars (Fixes fixes) ctxt =
ballarin@28795
   291
      let val (vars, _) = prep_vars fixes ctxt
ballarin@28852
   292
      in ctxt |> ProofContext.add_fixes_i vars |> snd end
ballarin@28795
   293
  | declare_elem prep_vars (Constrains csts) ctxt =
ballarin@28852
   294
      ctxt |> prep_vars (map (fn (x, T) => (Name.binding x, SOME T, NoSyn)) csts) |> snd
ballarin@28872
   295
  | declare_elem _ (Assumes _) ctxt = ctxt
ballarin@28872
   296
  | declare_elem _ (Defines _) ctxt = ctxt
ballarin@28852
   297
  | declare_elem _ (Notes _) ctxt = ctxt;
ballarin@28795
   298
ballarin@28852
   299
(** Finish locale elements, extract specification text **)
ballarin@28795
   300
ballarin@28795
   301
val norm_term = Envir.beta_norm oo Term.subst_atomic;
ballarin@28795
   302
ballarin@28795
   303
fun abstract_thm thy eq =
ballarin@28795
   304
  Thm.assume (Thm.cterm_of thy eq) |> Drule.gen_all |> Drule.abs_def;
ballarin@28795
   305
ballarin@28795
   306
fun bind_def ctxt eq (xs, env, ths) =
ballarin@28795
   307
  let
ballarin@28795
   308
    val ((y, T), b) = LocalDefs.abs_def eq;
ballarin@28795
   309
    val b' = norm_term env b;
ballarin@28795
   310
    val th = abstract_thm (ProofContext.theory_of ctxt) eq;
ballarin@28795
   311
    fun err msg = error (msg ^ ": " ^ quote y);
ballarin@28795
   312
  in
ballarin@28795
   313
    exists (fn (x, _) => x = y) xs andalso
ballarin@28795
   314
      err "Attempt to define previously specified variable";
ballarin@28795
   315
    exists (fn (Free (y', _), _) => y = y' | _ => false) env andalso
ballarin@28795
   316
      err "Attempt to redefine variable";
ballarin@28795
   317
    (Term.add_frees b' xs, (Free (y, T), b') :: env, th :: ths)
ballarin@28795
   318
  end;
ballarin@28795
   319
ballarin@28872
   320
fun eval_text _ _ (Fixes _) text = text
ballarin@28872
   321
  | eval_text _ _ (Constrains _) text = text
ballarin@28872
   322
  | eval_text _ is_ext (Assumes asms)
ballarin@28795
   323
        (((exts, exts'), (ints, ints')), (xs, env, defs)) =
ballarin@28795
   324
      let
ballarin@28795
   325
        val ts = maps (map #1 o #2) asms;
ballarin@28795
   326
        val ts' = map (norm_term env) ts;
ballarin@28872
   327
        val spec' =
ballarin@28872
   328
          if is_ext then ((exts @ ts, exts' @ ts'), (ints, ints'))
ballarin@28872
   329
          else ((exts, exts'), (ints @ ts, ints' @ ts'));
ballarin@28795
   330
      in (spec', (fold Term.add_frees ts' xs, env, defs)) end
ballarin@28872
   331
  | eval_text ctxt _ (Defines defs) (spec, binds) =
ballarin@28795
   332
      (spec, fold (bind_def ctxt o #1 o #2) defs binds)
ballarin@28872
   333
  | eval_text _ _ (Notes _) text = text;
ballarin@28795
   334
ballarin@28852
   335
fun closeup _ _ false elem = elem
ballarin@28852
   336
  | closeup ctxt parms true elem =
ballarin@28795
   337
      let
ballarin@28795
   338
        fun close_frees t =
ballarin@28795
   339
          let
ballarin@28795
   340
            val rev_frees =
ballarin@28795
   341
              Term.fold_aterms (fn Free (x, T) =>
ballarin@28852
   342
                if AList.defined (op =) parms x then I else insert (op =) (x, T) | _ => I) t [];
ballarin@28795
   343
          in Term.list_all_free (rev rev_frees, t) end;
ballarin@28795
   344
ballarin@28795
   345
        fun no_binds [] = []
ballarin@28852
   346
          | no_binds _ = error "Illegal term bindings in context element";
ballarin@28795
   347
      in
ballarin@28795
   348
        (case elem of
ballarin@28795
   349
          Assumes asms => Assumes (asms |> map (fn (a, propps) =>
ballarin@28795
   350
            (a, map (fn (t, ps) => (close_frees t, no_binds ps)) propps)))
ballarin@28795
   351
        | Defines defs => Defines (defs |> map (fn (a, (t, ps)) =>
ballarin@28795
   352
            (a, (close_frees (#2 (LocalDefs.cert_def ctxt t)), no_binds ps))))
ballarin@28795
   353
        | e => e)
ballarin@28795
   354
      end;
ballarin@28795
   355
ballarin@28872
   356
fun finish_primitive parms _ (Fixes fixes) = Fixes (map (fn (binding, _, mx) =>
ballarin@28795
   357
      let val x = Name.name_of binding
ballarin@28795
   358
      in (binding, AList.lookup (op =) parms x, mx) end) fixes)
ballarin@28872
   359
  | finish_primitive _ _ (Constrains _) = Constrains []
ballarin@28872
   360
  | finish_primitive _ close (Assumes asms) = close (Assumes asms)
ballarin@28872
   361
  | finish_primitive _ close (Defines defs) = close (Defines defs)
ballarin@28872
   362
  | finish_primitive _ _ (Notes facts) = Notes facts;
ballarin@28872
   363
ballarin@28872
   364
fun finish_inst ctxt parms do_close (loc, (prfx, inst)) text =
ballarin@28872
   365
  let
ballarin@28872
   366
    val thy = ProofContext.theory_of ctxt;
ballarin@28872
   367
    val (parm_names, parm_types) = NewLocale.params_of thy loc |>
ballarin@28872
   368
      map (fn (b, SOME T, _) => (Name.name_of b, T)) |> split_list;
ballarin@28872
   369
    val (asm, defs) = NewLocale.specification_of thy loc;
ballarin@28872
   370
    val (morph, _) = inst_morph (parm_names, parm_types) (prfx, inst) ctxt;
ballarin@28872
   371
    val asm' = Option.map (Morphism.term morph) asm;
ballarin@28872
   372
    val defs' = map (Morphism.term morph) defs;
ballarin@28872
   373
    val text' = text |>
ballarin@28872
   374
      (if is_some asm
ballarin@28872
   375
        then eval_text ctxt false (Assumes [(Attrib.no_binding, [(the asm', [])])])
ballarin@28872
   376
        else I) |>
ballarin@28872
   377
      (if not (null defs)
ballarin@28872
   378
        then eval_text ctxt false (Defines (map (fn def => (Attrib.no_binding, (def, []))) defs'))
ballarin@28872
   379
        else I)
ballarin@28872
   380
(* FIXME clone from new_locale.ML *)
ballarin@28872
   381
  in ((loc, morph), text') end;
ballarin@28795
   382
ballarin@28852
   383
fun finish_elem ctxt parms do_close elem text =
ballarin@28795
   384
  let
ballarin@28872
   385
    val elem' = finish_primitive parms (closeup ctxt parms do_close) elem;
ballarin@28872
   386
    val text' = eval_text ctxt true elem' text;
ballarin@28795
   387
  in (elem', text') end
ballarin@28795
   388
  
ballarin@28872
   389
fun finish ctxt parms do_close insts elems text =
ballarin@28872
   390
  let
ballarin@28872
   391
    val (deps, text') = fold_map (finish_inst ctxt parms do_close) insts text;
ballarin@28872
   392
    val (elems', text'') = fold_map (finish_elem ctxt parms do_close) elems text';
ballarin@28872
   393
  in (deps, elems', text'') end;
ballarin@28795
   394
ballarin@28795
   395
ballarin@28795
   396
local
ballarin@28795
   397
ballarin@28852
   398
(* nice, but for now not needed
ballarin@28852
   399
fun fold_suffixes f [] y = f [] y
ballarin@28852
   400
  | fold_suffixes f (x :: xs) y = f (x :: xs) (f xs y);
ballarin@28795
   401
ballarin@28852
   402
fun fold_prefixes f xs y = fold_suffixes (f o rev) (rev xs) y;
ballarin@28852
   403
*)
ballarin@28795
   404
ballarin@28872
   405
fun prep_elems parse_typ parse_prop parse_inst prep_vars
ballarin@28872
   406
    do_close context fixed raw_insts raw_elems raw_concl =
ballarin@28795
   407
  let
ballarin@28872
   408
    val thy = ProofContext.theory_of context;
ballarin@28872
   409
ballarin@28879
   410
    fun prep_inst (loc, (prfx, inst)) (i, marked, insts, ctxt) =
ballarin@28872
   411
      let
ballarin@28872
   412
        val (parm_names, parm_types) = NewLocale.params_of thy loc |>
ballarin@28872
   413
          map (fn (b, SOME T, _) => (Name.name_of b, T)) |> split_list;
ballarin@28872
   414
        val inst' = parse_inst parm_names inst ctxt;
ballarin@28872
   415
        val parm_types' = map (TypeInfer.paramify_vars o varify_indexT i) parm_types;
ballarin@28872
   416
        val inst'' = map2 TypeInfer.constrain parm_types' inst';
ballarin@28872
   417
        val insts' = insts @ [(loc, (prfx, inst''))];
ballarin@28872
   418
        val (insts'', _, _, ctxt') = check_autofix insts' [] [] ctxt;
ballarin@28872
   419
        val inst''' = insts'' |> List.last |> snd |> snd;
ballarin@28872
   420
        val (morph, _) = inst_morph (parm_names, parm_types) (prfx, inst''') ctxt;
ballarin@28879
   421
        val (marked', ctxt'') = NewLocale.activate_declarations thy (loc, morph) (marked, ctxt);
ballarin@28879
   422
      in (i+1, marked', insts', ctxt'') end;
ballarin@28872
   423
  
ballarin@28872
   424
    fun prep_elem raw_elem (insts, elems, ctxt) =
ballarin@28852
   425
      let
ballarin@28852
   426
        val ctxt' = declare_elem prep_vars raw_elem ctxt;
ballarin@28852
   427
        val elems' = elems @ [parse_elem parse_typ parse_prop ctxt' raw_elem];
ballarin@28852
   428
        (* FIXME term bindings *)
ballarin@28872
   429
        val (_, _, _, ctxt'') = check_autofix insts elems' [] ctxt';
ballarin@28872
   430
      in (insts, elems', ctxt') end;
ballarin@28795
   431
ballarin@28872
   432
    fun prep_concl raw_concl (insts, elems, ctxt) =
ballarin@28795
   433
      let
ballarin@28852
   434
        val concl = (map o map) (fn (t, ps) =>
ballarin@28852
   435
          (parse_prop ctxt t, map (parse_prop ctxt) ps)) raw_concl;
ballarin@28872
   436
      in check_autofix insts elems concl ctxt end;
ballarin@28795
   437
ballarin@28872
   438
    val fors = prep_vars fixed context |> fst;
ballarin@28872
   439
    val ctxt = context |> ProofContext.add_fixes_i fors |> snd;
ballarin@28872
   440
    val (_, _, insts', ctxt') = fold prep_inst raw_insts (0, NewLocale.empty, [], ctxt);
ballarin@28872
   441
    val (_, elems'', ctxt'') = fold prep_elem raw_elems (insts', [], ctxt');
ballarin@28872
   442
    val (insts, elems, concl, ctxt) = prep_concl raw_concl (insts', elems'', ctxt'');
ballarin@28795
   443
ballarin@28872
   444
    (* Retrieve parameter types *)
ballarin@28795
   445
    val xs = fold (fn Fixes fixes => (fn ps => ps @ map (Name.name_of o #1) fixes) |
ballarin@28872
   446
      _ => fn ps => ps) (Fixes fors :: elems) [];
ballarin@28859
   447
    val (Ts, ctxt') = fold_map ProofContext.inferred_param xs ctxt; 
ballarin@28852
   448
    val parms = xs ~~ Ts;
ballarin@28795
   449
ballarin@28872
   450
    val Fixes fors' = finish_primitive parms I (Fixes fors);
ballarin@28872
   451
    val (deps, elems', text) = finish ctxt' parms do_close insts elems ((([], []), ([], [])), ([], [], []));
ballarin@28852
   452
    (* text has the following structure:
ballarin@28795
   453
           (((exts, exts'), (ints, ints')), (xs, env, defs))
ballarin@28795
   454
       where
ballarin@28872
   455
         exts: external assumptions (terms in assumes elements)
ballarin@28795
   456
         exts': dito, normalised wrt. env
ballarin@28872
   457
         ints: internal assumptions (terms in assumptions from insts)
ballarin@28795
   458
         ints': dito, normalised wrt. env
ballarin@28795
   459
         xs: the free variables in exts' and ints' and rhss of definitions,
ballarin@28795
   460
           this includes parameters except defined parameters
ballarin@28795
   461
         env: list of term pairs encoding substitutions, where the first term
ballarin@28795
   462
           is a free variable; substitutions represent defines elements and
ballarin@28795
   463
           the rhs is normalised wrt. the previous env
ballarin@28795
   464
         defs: theorems representing the substitutions from defines elements
ballarin@28795
   465
           (thms are normalised wrt. env).
ballarin@28795
   466
       elems is an updated version of raw_elems:
ballarin@28795
   467
         - type info added to Fixes and modified in Constrains
ballarin@28795
   468
         - axiom and definition statement replaced by corresponding one
ballarin@28795
   469
           from proppss in Assumes and Defines
ballarin@28795
   470
         - Facts unchanged
ballarin@28795
   471
       *)
ballarin@28852
   472
ballarin@28872
   473
  in ((parms, fors', deps, elems', concl), text) end
ballarin@28795
   474
ballarin@28795
   475
in
ballarin@28795
   476
ballarin@28872
   477
fun read_elems x = prep_elems Syntax.parse_typ Syntax.parse_prop parse_inst
ballarin@28872
   478
  ProofContext.read_vars x;
ballarin@28879
   479
fun cert_elems x = prep_elems (K I) (K I)  make_inst
ballarin@28872
   480
  ProofContext.cert_vars x;
ballarin@28795
   481
ballarin@28795
   482
end;
ballarin@28795
   483
ballarin@28795
   484
ballarin@28795
   485
(* full context statements: import + elements + conclusion *)
ballarin@28795
   486
ballarin@28795
   487
local
ballarin@28795
   488
ballarin@28879
   489
fun prep_context_statement prep_expr prep_elems activate_elems
ballarin@28795
   490
    do_close imprt elements raw_concl context =
ballarin@28795
   491
  let
ballarin@28795
   492
    val thy = ProofContext.theory_of context;
ballarin@28795
   493
ballarin@28872
   494
    val (Expr expr, fixed) = parameters_of thy (apfst (prep_expr thy) imprt);
ballarin@28872
   495
    val ((parms, fors, deps, elems, concl), (spec, (_, _, defs))) =
ballarin@28872
   496
      prep_elems do_close context fixed expr elements raw_concl;
ballarin@28879
   497
ballarin@28879
   498
    val (_, ctxt0) = ProofContext.add_fixes_i fors context;
ballarin@28879
   499
    val (_, ctxt) = fold (NewLocale.activate_facts thy) deps (NewLocale.empty, ctxt0);  
ballarin@28879
   500
    val ((elems', _), ctxt') = activate_elems elems (ProofContext.set_stmt true ctxt);
ballarin@28795
   501
  in
ballarin@28872
   502
    (((fors, deps), (ctxt', elems'), (parms, spec, defs)), concl)
ballarin@28879
   503
  end;
ballarin@28879
   504
ballarin@28879
   505
fun prep_statement prep_ctxt elems concl ctxt =
ballarin@28879
   506
  let
ballarin@28879
   507
    val (((_, (ctxt', _), _)), concl) = prep_ctxt false (Expr [], []) elems concl ctxt
ballarin@28879
   508
  in (concl, ctxt') end;
ballarin@28795
   509
ballarin@28795
   510
in
ballarin@28795
   511
ballarin@28879
   512
fun read_statement body concl ctxt =
ballarin@28879
   513
  prep_statement (prep_context_statement intern read_elems Element.activate) body concl ctxt;
ballarin@28879
   514
fun cert_statement body concl ctxt =
ballarin@28879
   515
  prep_statement (prep_context_statement (K I) cert_elems Element.activate_i) body concl ctxt;
ballarin@28879
   516
ballarin@28795
   517
fun read_context imprt body ctxt =
ballarin@28879
   518
  #1 (prep_context_statement intern read_elems Element.activate true imprt body [] ctxt);
ballarin@28795
   519
fun cert_context imprt body ctxt =
ballarin@28879
   520
  #1 (prep_context_statement (K I) cert_elems Element.activate_i true imprt body [] ctxt);
ballarin@28879
   521
ballarin@28795
   522
end;
ballarin@28795
   523
ballarin@28795
   524
ballarin@28795
   525
(** Dependencies **)
ballarin@28795
   526
ballarin@28795
   527
ballarin@28795
   528
ballarin@28795
   529
(*** Locale declarations ***)
ballarin@28795
   530
ballarin@28795
   531
local
ballarin@28795
   532
ballarin@28795
   533
(* introN: name of theorems for introduction rules of locale and
ballarin@28795
   534
     delta predicates;
ballarin@28795
   535
   axiomsN: name of theorem set with destruct rules for locale predicates,
ballarin@28795
   536
     also name suffix of delta predicates. *)
ballarin@28795
   537
ballarin@28795
   538
val introN = "intro";
ballarin@28795
   539
val axiomsN = "axioms";
ballarin@28795
   540
ballarin@28795
   541
fun atomize_spec thy ts =
ballarin@28795
   542
  let
ballarin@28795
   543
    val t = Logic.mk_conjunction_balanced ts;
ballarin@28795
   544
    val body = ObjectLogic.atomize_term thy t;
ballarin@28795
   545
    val bodyT = Term.fastype_of body;
ballarin@28795
   546
  in
ballarin@28795
   547
    if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of thy t))
ballarin@28795
   548
    else (body, bodyT, ObjectLogic.atomize (Thm.cterm_of thy t))
ballarin@28795
   549
  end;
ballarin@28795
   550
ballarin@28795
   551
(* achieve plain syntax for locale predicates (without "PROP") *)
ballarin@28795
   552
ballarin@28795
   553
fun aprop_tr' n c = (Syntax.constN ^ c, fn ctxt => fn args =>
ballarin@28795
   554
  if length args = n then
ballarin@28795
   555
    Syntax.const "_aprop" $
ballarin@28795
   556
      Term.list_comb (Syntax.free (Consts.extern (ProofContext.consts_of ctxt) c), args)
ballarin@28795
   557
  else raise Match);
ballarin@28795
   558
ballarin@28795
   559
(* CB: define one predicate including its intro rule and axioms
ballarin@28795
   560
   - bname: predicate name
ballarin@28795
   561
   - parms: locale parameters
ballarin@28795
   562
   - defs: thms representing substitutions from defines elements
ballarin@28795
   563
   - ts: terms representing locale assumptions (not normalised wrt. defs)
ballarin@28795
   564
   - norm_ts: terms representing locale assumptions (normalised wrt. defs)
ballarin@28795
   565
   - thy: the theory
ballarin@28795
   566
*)
ballarin@28795
   567
ballarin@28795
   568
fun def_pred bname parms defs ts norm_ts thy =
ballarin@28795
   569
  let
ballarin@28795
   570
    val name = Sign.full_name thy bname;
ballarin@28795
   571
ballarin@28795
   572
    val (body, bodyT, body_eq) = atomize_spec thy norm_ts;
ballarin@28795
   573
    val env = Term.add_term_free_names (body, []);
ballarin@28795
   574
    val xs = filter (member (op =) env o #1) parms;
ballarin@28795
   575
    val Ts = map #2 xs;
ballarin@28795
   576
    val extraTs = (Term.term_tfrees body \\ fold Term.add_tfreesT Ts [])
ballarin@28795
   577
      |> Library.sort_wrt #1 |> map TFree;
ballarin@28795
   578
    val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
ballarin@28795
   579
ballarin@28795
   580
    val args = map Logic.mk_type extraTs @ map Free xs;
ballarin@28795
   581
    val head = Term.list_comb (Const (name, predT), args);
ballarin@28795
   582
    val statement = ObjectLogic.ensure_propT thy head;
ballarin@28795
   583
ballarin@28795
   584
    val ([pred_def], defs_thy) =
ballarin@28795
   585
      thy
ballarin@28795
   586
      |> bodyT = propT ? Sign.add_advanced_trfuns ([], [], [aprop_tr' (length args) name], [])
ballarin@28795
   587
      |> Sign.declare_const [] ((Name.binding bname, predT), NoSyn) |> snd
ballarin@28795
   588
      |> PureThy.add_defs false
ballarin@28795
   589
        [((Thm.def_name bname, Logic.mk_equals (head, body)), [Thm.kind_internal])];
ballarin@28795
   590
    val defs_ctxt = ProofContext.init defs_thy |> Variable.declare_term head;
ballarin@28795
   591
ballarin@28795
   592
    val cert = Thm.cterm_of defs_thy;
ballarin@28795
   593
ballarin@28795
   594
    val intro = Goal.prove_global defs_thy [] norm_ts statement (fn _ =>
ballarin@28795
   595
      MetaSimplifier.rewrite_goals_tac [pred_def] THEN
ballarin@28795
   596
      Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
ballarin@28795
   597
      Tactic.compose_tac (false,
ballarin@28795
   598
        Conjunction.intr_balanced (map (Thm.assume o cert) norm_ts), 0) 1);
ballarin@28795
   599
ballarin@28795
   600
    val conjuncts =
ballarin@28795
   601
      (Drule.equal_elim_rule2 OF [body_eq,
ballarin@28795
   602
        MetaSimplifier.rewrite_rule [pred_def] (Thm.assume (cert statement))])
ballarin@28795
   603
      |> Conjunction.elim_balanced (length ts);
ballarin@28795
   604
    val axioms = ts ~~ conjuncts |> map (fn (t, ax) =>
ballarin@28795
   605
      Element.prove_witness defs_ctxt t
ballarin@28795
   606
       (MetaSimplifier.rewrite_goals_tac defs THEN
ballarin@28795
   607
        Tactic.compose_tac (false, ax, 0) 1));
ballarin@28795
   608
  in ((statement, intro, axioms), defs_thy) end;
ballarin@28795
   609
ballarin@28795
   610
in
ballarin@28795
   611
ballarin@28795
   612
(* CB: main predicate definition function *)
ballarin@28795
   613
ballarin@28795
   614
fun define_preds pname (parms, ((exts, exts'), (ints, ints')), defs) thy =
ballarin@28795
   615
  let
ballarin@28795
   616
    val (a_pred, a_intro, a_axioms, thy'') =
ballarin@28795
   617
      if null exts then (NONE, NONE, [], thy)
ballarin@28795
   618
      else
ballarin@28795
   619
        let
ballarin@28795
   620
          val aname = if null ints then pname else pname ^ "_" ^ axiomsN;
ballarin@28795
   621
          val ((statement, intro, axioms), thy') =
ballarin@28795
   622
            thy
ballarin@28795
   623
            |> def_pred aname parms defs exts exts';
ballarin@28795
   624
          val (_, thy'') =
ballarin@28795
   625
            thy'
ballarin@28795
   626
            |> Sign.add_path aname
ballarin@28795
   627
            |> Sign.no_base_names
ballarin@28795
   628
            |> PureThy.note_thmss Thm.internalK [((Name.binding introN, []), [([intro], [])])]
ballarin@28795
   629
            ||> Sign.restore_naming thy';
ballarin@28795
   630
          in (SOME statement, SOME intro, axioms, thy'') end;
ballarin@28795
   631
    val (b_pred, b_intro, b_axioms, thy'''') =
ballarin@28795
   632
      if null ints then (NONE, NONE, [], thy'')
ballarin@28795
   633
      else
ballarin@28795
   634
        let
ballarin@28795
   635
          val ((statement, intro, axioms), thy''') =
ballarin@28795
   636
            thy''
ballarin@28795
   637
            |> def_pred pname parms defs (ints @ the_list a_pred) (ints' @ the_list a_pred);
ballarin@28795
   638
          val (_, thy'''') =
ballarin@28795
   639
            thy'''
ballarin@28795
   640
            |> Sign.add_path pname
ballarin@28795
   641
            |> Sign.no_base_names
ballarin@28795
   642
            |> PureThy.note_thmss Thm.internalK
ballarin@28795
   643
                 [((Name.binding introN, []), [([intro], [])]),
ballarin@28795
   644
                  ((Name.binding axiomsN, []),
ballarin@28795
   645
                    [(map (Drule.standard o Element.conclude_witness) axioms, [])])]
ballarin@28795
   646
            ||> Sign.restore_naming thy''';
ballarin@28795
   647
        in (SOME statement, SOME intro, axioms, thy'''') end;
ballarin@28795
   648
  in ((a_pred, a_intro, a_axioms), (b_pred, b_intro, b_axioms), thy'''') end;
ballarin@28795
   649
ballarin@28795
   650
end;
ballarin@28795
   651
ballarin@28795
   652
ballarin@28795
   653
local
ballarin@28795
   654
ballarin@28795
   655
fun assumes_to_notes (Assumes asms) axms =
ballarin@28795
   656
      fold_map (fn (a, spec) => fn axs =>
ballarin@28795
   657
          let val (ps, qs) = chop (length spec) axs
ballarin@28795
   658
          in ((a, [(ps, [])]), qs) end) asms axms
ballarin@28795
   659
      |> apfst (curry Notes Thm.assumptionK)
ballarin@28795
   660
  | assumes_to_notes e axms = (e, axms);
ballarin@28795
   661
ballarin@28795
   662
fun defines_to_notes thy (Defines defs) defns =
ballarin@28795
   663
    let
ballarin@28795
   664
      val defs' = map (fn (_, (def, _)) => def) defs
ballarin@28795
   665
      val notes = map (fn (a, (def, _)) =>
ballarin@28795
   666
        (a, [([assume (cterm_of thy def)], [])])) defs
ballarin@28795
   667
    in
ballarin@28795
   668
      (Notes (Thm.definitionK, notes), defns @ defs')
ballarin@28795
   669
    end
ballarin@28795
   670
  | defines_to_notes _ e defns = (e, defns);
ballarin@28795
   671
ballarin@28872
   672
fun gen_add_locale prep_context
ballarin@28795
   673
    bname predicate_name raw_imprt raw_body thy =
ballarin@28795
   674
  let
ballarin@28795
   675
    val thy_ctxt = ProofContext.init thy;
ballarin@28795
   676
    val name = Sign.full_name thy bname;
ballarin@28795
   677
    val _ = NewLocale.test_locale thy name andalso
ballarin@28795
   678
      error ("Duplicate definition of locale " ^ quote name);
ballarin@28795
   679
ballarin@28872
   680
    val ((fors, deps), (_, body_elems), text as (parms, ((_, exts'), _), defs)) =
ballarin@28872
   681
      prep_context raw_imprt raw_body thy_ctxt;
ballarin@28872
   682
    val ((a_statement, a_intro, a_axioms), (b_statement, b_intro, b_axioms), thy') =
ballarin@28795
   683
      define_preds predicate_name text thy;
ballarin@28795
   684
ballarin@28795
   685
    val extraTs = fold Term.add_tfrees exts' [] \\ fold Term.add_tfreesT (map snd parms) [];
ballarin@28795
   686
    val _ = if null extraTs then ()
ballarin@28795
   687
      else warning ("Additional type variable(s) in locale specification " ^ quote bname);
ballarin@28795
   688
ballarin@28872
   689
    val satisfy = Element.satisfy_morphism b_axioms;
ballarin@28872
   690
    val params = fors @
ballarin@28872
   691
      (body_elems |> map_filter (fn Fixes fixes => SOME fixes | _ => NONE) |> flat);
ballarin@28795
   692
    val (body_elems', defns) = fold_map (defines_to_notes thy) body_elems [];
ballarin@28795
   693
ballarin@28795
   694
    val notes = body_elems' |>
ballarin@28872
   695
      (fn elems => fold_map assumes_to_notes elems (map Element.conclude_witness a_axioms)) |>
ballarin@28872
   696
      fst |> map (Element.morph_ctxt satisfy) |>
ballarin@28795
   697
      map_filter (fn Notes notes => SOME notes | _ => NONE);
ballarin@28795
   698
ballarin@28872
   699
    val deps' = map (fn (l, morph) => (l, morph $> satisfy)) deps;
ballarin@28872
   700
ballarin@28795
   701
    val loc_ctxt = thy' |>
ballarin@28872
   702
      NewLocale.register_locale name (extraTs, params)
ballarin@28872
   703
        (if is_some b_statement then b_statement else a_statement, map prop_of defs) ([], [])
ballarin@28872
   704
        (map (fn n => (n, stamp ())) notes |> rev) (map (fn d => (d, stamp ())) deps' |> rev) |>
ballarin@28795
   705
      NewLocale.init name
ballarin@28795
   706
  in (name, loc_ctxt) end;
ballarin@28795
   707
ballarin@28795
   708
in
ballarin@28795
   709
ballarin@28795
   710
val add_locale = gen_add_locale read_context;
ballarin@28795
   711
(* val add_locale_i = gen_add_locale cert_context; *)
ballarin@28795
   712
ballarin@28795
   713
end;
ballarin@28795
   714
ballarin@28795
   715
end;