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