src/Pure/Isar/expression.ML
author ballarin
Tue Nov 18 09:40:06 2008 +0100 (2008-11-18)
changeset 28832 cf7237498e7a
parent 28795 6891e273c33b
child 28852 5ddea758679b
permissions -rw-r--r--
Activate elements moved to element.ML.
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@28795
    10
  type map
ballarin@28795
    11
  type 'morph expr
ballarin@28697
    12
ballarin@28795
    13
  val empty_expr: 'morph expr
ballarin@28795
    14
ballarin@28795
    15
  type expression = (string * map) expr * (Name.binding * string option * mixfix) list
ballarin@28795
    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@28697
    25
ballarin@28795
    26
  (* Debugging and development *)
ballarin@28795
    27
  val parse_expression: OuterParse.token list -> expression * OuterParse.token list
ballarin@28795
    28
  val debug_parameters: expression -> Proof.context -> Proof.context
ballarin@28795
    29
  val debug_context: expression -> Proof.context -> Proof.context
ballarin@28697
    30
ballarin@28697
    31
end;
ballarin@28697
    32
ballarin@28697
    33
ballarin@28697
    34
structure Expression: EXPRESSION =
ballarin@28697
    35
struct
ballarin@28697
    36
ballarin@28795
    37
datatype ctxt = datatype Element.ctxt;
ballarin@28795
    38
ballarin@28795
    39
ballarin@28795
    40
(*** Expressions ***)
ballarin@28697
    41
ballarin@28697
    42
datatype map =
ballarin@28697
    43
  Positional of string option list |
ballarin@28697
    44
  Named of (string * string) list;
ballarin@28697
    45
ballarin@28697
    46
datatype 'morph expr = Expr of (string * 'morph) list;
ballarin@28697
    47
ballarin@28697
    48
type expression = (string * map) expr * (Name.binding * string option * mixfix) list;
ballarin@28697
    49
type expression_i = Morphism.morphism expr * (Name.binding * typ option * mixfix) list;
ballarin@28697
    50
ballarin@28795
    51
val empty_expr = Expr [];
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@28697
    78
    fun expr0 x = (plus1_unless loc_keyword expr1 >> Expr) x;
ballarin@28697
    79
  in expr0 -- P.for_fixes end;
ballarin@28697
    80
ballarin@28697
    81
end;
ballarin@28697
    82
ballarin@28795
    83
fun pretty_expr thy (Expr 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@28795
   100
ballarin@28795
   101
fun err_in_expr thy msg (Expr 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@28795
   107
          pretty_expr thy (Expr expr)])
ballarin@28795
   108
  in error err_msg end;
ballarin@28697
   109
ballarin@28697
   110
ballarin@28795
   111
(** Internalise locale names **)
ballarin@28697
   112
ballarin@28795
   113
fun intern_expr thy (Expr instances) = Expr (map (apfst (NewLocale.intern thy)) instances);
ballarin@28697
   114
ballarin@28697
   115
ballarin@28795
   116
(** Parameters of expression (not expression_i).
ballarin@28697
   117
   Sanity check of instantiations.
ballarin@28795
   118
   Positional instantiations are extended to match full length of parameter list. **)
ballarin@28697
   119
haftmann@28701
   120
fun parameters thy (expr, fixed : (Name.binding * string option * mixfix) list) =
ballarin@28697
   121
  let
ballarin@28697
   122
    fun reject_dups message xs =
ballarin@28697
   123
      let val dups = duplicates (op =) xs
ballarin@28697
   124
      in
ballarin@28697
   125
        if null dups then () else error (message ^ commas dups)
ballarin@28697
   126
      end;
ballarin@28697
   127
ballarin@28795
   128
    fun match_bind (n, b) = (n = Name.name_of b);
ballarin@28795
   129
    fun bind_eq (b1, b2) = (Name.name_of b1 = Name.name_of b2);
ballarin@28795
   130
      (* FIXME: cannot compare bindings for equality. *)
ballarin@28795
   131
ballarin@28795
   132
    fun params_loc loc =
ballarin@28795
   133
          (NewLocale.params_of thy loc |> map (fn (p, _, mx) => (p, mx)), loc)
ballarin@28795
   134
            handle ERROR msg => err_in_expr thy msg (Expr [(loc, ("", Named []))]);
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@28795
   140
	      if d < 0 then err_in_expr thy "More arguments than parameters in instantiation."
ballarin@28795
   141
                (Expr [expr])
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@28795
   151
              (map fst insts)
ballarin@28795
   152
              handle ERROR msg => err_in_expr thy msg (Expr [expr]);
ballarin@28697
   153
ballarin@28795
   154
            val (ps, loc') = params_loc loc;
ballarin@28697
   155
            val ps' = fold (fn (p, _) => fn ps =>
ballarin@28795
   156
              if AList.defined match_bind ps p then AList.delete match_bind p ps
ballarin@28795
   157
              else err_in_expr thy (quote p ^" not a parameter of instantiated expression.")
ballarin@28795
   158
                (Expr [expr])) insts ps;
ballarin@28697
   159
          in
ballarin@28697
   160
            (ps', (loc', (prfx, Named insts)))
ballarin@28697
   161
          end;
ballarin@28795
   162
    fun params_expr (Expr is) =
ballarin@28697
   163
          let
ballarin@28697
   164
            val (is', ps') = fold_map (fn i => fn ps =>
ballarin@28697
   165
              let
ballarin@28795
   166
                val (ps', i') = params_inst i;
ballarin@28795
   167
                val ps'' = AList.join bind_eq (fn p => fn (mx1, mx2) =>
ballarin@28795
   168
                  (* FIXME: should check for bindings being the same.
ballarin@28795
   169
                     Instead we check for equal name and syntax. *)
ballarin@28697
   170
                  if mx1 = mx2 then mx1
ballarin@28795
   171
                  else err_in_expr thy ("Conflicting syntax for parameter" ^ quote (Name.name_of p) ^ " in expression.")
ballarin@28795
   172
                    (Expr is)) (ps, ps')
ballarin@28697
   173
              in (i', ps'') end) is []
ballarin@28697
   174
          in
ballarin@28697
   175
            (ps', Expr is')
ballarin@28697
   176
          end;
ballarin@28697
   177
ballarin@28795
   178
    val (parms, expr') = params_expr expr;
ballarin@28697
   179
ballarin@28795
   180
    val parms' = map (fst #> Name.name_of) parms;
ballarin@28697
   181
    val fixed' = map (#1 #> Name.name_of) fixed;
ballarin@28697
   182
    val _ = reject_dups "Duplicate fixed parameter(s): " fixed';
ballarin@28697
   183
    val _ = reject_dups "Parameter(s) declared simultaneously in expression and for clause: " (parms' @ fixed');
ballarin@28697
   184
ballarin@28697
   185
  in (expr', (parms, fixed)) end;
ballarin@28697
   186
ballarin@28795
   187
ballarin@28795
   188
(** Read instantiation **)
ballarin@28795
   189
ballarin@28795
   190
fun read_inst parse_term parms (prfx, insts) ctxt =
ballarin@28795
   191
  let
ballarin@28795
   192
    (* parameters *)
ballarin@28795
   193
    val (parm_names, parm_types) = split_list parms;
ballarin@28795
   194
    val type_parm_names = fold Term.add_tfreesT parm_types [] |> map fst;
ballarin@28795
   195
ballarin@28795
   196
    (* parameter instantiations *)
ballarin@28795
   197
    val insts' = case insts of
ballarin@28795
   198
      Positional insts => (insts ~~ parm_names) |> map (fn
ballarin@28795
   199
        (NONE, p) => parse_term ctxt p |
ballarin@28795
   200
        (SOME t, _) => parse_term ctxt t) |
ballarin@28795
   201
      Named insts => parm_names |> map (fn
ballarin@28795
   202
        p => case AList.lookup (op =) insts p of
ballarin@28795
   203
          SOME t => parse_term ctxt t |
ballarin@28795
   204
          NONE => parse_term ctxt p);
ballarin@28795
   205
ballarin@28795
   206
    (* type inference and contexts *)
ballarin@28795
   207
    val parm_types' = map (TypeInfer.paramify_vars o Logic.varifyT) parm_types;
ballarin@28795
   208
    val type_parms = fold Term.add_tvarsT parm_types' [] |> map (Logic.mk_type o TVar);
ballarin@28795
   209
    val arg = type_parms @ map2 TypeInfer.constrain parm_types' insts';
ballarin@28795
   210
    val res = Syntax.check_terms ctxt arg;
ballarin@28795
   211
    val ctxt' = ctxt |> fold Variable.auto_fixes res;
ballarin@28795
   212
ballarin@28795
   213
    (* instantiation *)
ballarin@28795
   214
    val (type_parms'', res') = chop (length type_parms) res;
ballarin@28795
   215
    val insts'' = (parm_names ~~ res') |> map_filter
ballarin@28795
   216
      (fn (inst as (x, Free (y, _))) => if x = y then NONE else SOME inst |
ballarin@28795
   217
        inst => SOME inst);
ballarin@28795
   218
    val instT = Symtab.make (type_parm_names ~~ map Logic.dest_type type_parms'');
ballarin@28795
   219
    val inst = Symtab.make insts'';
ballarin@28795
   220
  in
ballarin@28795
   221
    (Element.inst_morphism (ProofContext.theory_of ctxt) (instT, inst) $>
ballarin@28795
   222
      Morphism.name_morphism (Name.qualified prfx), ctxt')
ballarin@28795
   223
  end;
ballarin@28795
   224
        
ballarin@28795
   225
        
ballarin@28795
   226
(** Debugging **)
ballarin@28795
   227
  
ballarin@28697
   228
fun debug_parameters raw_expr ctxt =
ballarin@28697
   229
  let
ballarin@28697
   230
    val thy = ProofContext.theory_of ctxt;
ballarin@28795
   231
    val expr = apfst (intern_expr thy) raw_expr;
ballarin@28697
   232
    val (expr', (parms, fixed)) = parameters thy expr;
ballarin@28697
   233
  in ctxt end;
ballarin@28697
   234
ballarin@28697
   235
ballarin@28697
   236
fun debug_context (raw_expr, fixed) ctxt =
ballarin@28697
   237
  let
ballarin@28697
   238
    val thy = ProofContext.theory_of ctxt;
ballarin@28795
   239
    val expr = intern_expr thy raw_expr;
ballarin@28697
   240
    val (expr', (parms, fixed)) = parameters thy (expr, fixed);
ballarin@28697
   241
ballarin@28697
   242
    fun declare_parameters (parms, fixed) ctxt =
ballarin@28697
   243
      let
ballarin@28697
   244
      val (parms', ctxt') =
ballarin@28795
   245
        ProofContext.add_fixes (map (fn (p, mx) => (p, NONE, mx)) parms) ctxt;
ballarin@28697
   246
      val (fixed', ctxt'') =
ballarin@28697
   247
        ProofContext.add_fixes fixed ctxt';
ballarin@28697
   248
      in
ballarin@28697
   249
        (parms' @ fixed', ctxt'')
ballarin@28697
   250
      end;
ballarin@28697
   251
ballarin@28697
   252
    fun rough_inst loc prfx insts ctxt =
ballarin@28697
   253
      let
ballarin@28697
   254
        (* locale data *)
ballarin@28795
   255
        val (parm_names, parm_types) = loc |> NewLocale.params_of thy |>
ballarin@28795
   256
          map (fn (b, SOME T, _) => (Name.name_of b, T)) |> split_list;
ballarin@28697
   257
ballarin@28697
   258
        (* type parameters *)
ballarin@28697
   259
        val type_parm_names = fold Term.add_tfreesT parm_types [] |> map fst;
ballarin@28697
   260
ballarin@28697
   261
        (* parameter instantiations *)
ballarin@28697
   262
        val insts' = case insts of
ballarin@28697
   263
          Positional insts => (insts ~~ parm_names) |> map (fn
ballarin@28697
   264
            (NONE, p) => Syntax.parse_term ctxt p |
ballarin@28697
   265
            (SOME t, _) => Syntax.parse_term ctxt t) |
ballarin@28697
   266
          Named insts => parm_names |> map (fn
ballarin@28697
   267
            p => case AList.lookup (op =) insts p of
ballarin@28697
   268
              SOME t => Syntax.parse_term ctxt t |
ballarin@28697
   269
              NONE => Syntax.parse_term ctxt p);
ballarin@28697
   270
ballarin@28697
   271
	(* type inference and contexts *)
ballarin@28697
   272
        val parm_types' = map (TypeInfer.paramify_vars o Logic.varifyT) parm_types;
ballarin@28697
   273
        val type_parms = fold Term.add_tvarsT parm_types' [] |> map (Logic.mk_type o TVar);
ballarin@28697
   274
	val arg = type_parms @ map2 TypeInfer.constrain parm_types' insts';
ballarin@28697
   275
	val res = Syntax.check_terms ctxt arg;
ballarin@28697
   276
	val ctxt' = ctxt |> fold Variable.auto_fixes res;
ballarin@28697
   277
ballarin@28697
   278
	(* instantiation *)
ballarin@28697
   279
	val (type_parms'', res') = chop (length type_parms) res;
ballarin@28697
   280
        val insts'' = (parm_names ~~ res') |> map_filter
ballarin@28697
   281
          (fn (inst as (x, Free (y, _))) => if x = y then NONE else SOME inst |
ballarin@28697
   282
            inst => SOME inst);
ballarin@28697
   283
	val instT = Symtab.make (type_parm_names ~~ map Logic.dest_type type_parms'');
ballarin@28697
   284
	val inst = Symtab.make insts'';
ballarin@28697
   285
      in
ballarin@28697
   286
        (Element.inst_morphism thy (instT, inst) $>
ballarin@28697
   287
          Morphism.name_morphism (Name.qualified prfx), ctxt')
ballarin@28697
   288
      end;
ballarin@28697
   289
ballarin@28697
   290
    fun add_declarations loc morph ctxt =
ballarin@28697
   291
      let
ballarin@28697
   292
        (* locale data *)
ballarin@28795
   293
        val parms = loc |> NewLocale.params_of thy |>
ballarin@28795
   294
          map (fn (b, SOME T, mx) => ((Name.name_of b, T), mx));
ballarin@28795
   295
        val (typ_decls, term_decls) = NewLocale.declarations_of thy loc;
ballarin@28697
   296
ballarin@28697
   297
        (* declarations from locale *)
ballarin@28697
   298
	val ctxt'' = ctxt |>
ballarin@28697
   299
	  fold_rev (fn decl => Context.proof_map (decl morph)) typ_decls |>
ballarin@28697
   300
	  fold_rev (fn decl => Context.proof_map (decl morph)) term_decls;
ballarin@28697
   301
      in
ballarin@28697
   302
        ctxt''
ballarin@28697
   303
      end;
ballarin@28697
   304
ballarin@28697
   305
    val Expr [(loc1, (prfx1, insts1))] = expr';
ballarin@28697
   306
    val ctxt0 = ProofContext.init thy;
ballarin@28697
   307
    val (parms, ctxt') = declare_parameters (parms, fixed) ctxt0;
ballarin@28697
   308
    val (morph1, ctxt'') = rough_inst loc1 prfx1 insts1 ctxt';
ballarin@28697
   309
    val ctxt'' = add_declarations loc1 morph1 ctxt';
ballarin@28795
   310
  in ctxt0 end;
ballarin@28795
   311
ballarin@28795
   312
ballarin@28795
   313
(*** Locale processing ***)
ballarin@28795
   314
ballarin@28795
   315
(** Prepare locale elements **)
ballarin@28795
   316
ballarin@28795
   317
local
ballarin@28795
   318
ballarin@28795
   319
fun declare_elem prep_vars (Fixes fixes) ctxt =
ballarin@28795
   320
      let val (vars, _) = prep_vars fixes ctxt
ballarin@28795
   321
      in ([], ctxt |> ProofContext.add_fixes_i vars |> snd) end
ballarin@28795
   322
  | declare_elem prep_vars (Constrains csts) ctxt =
ballarin@28795
   323
      let val (_, ctxt') = prep_vars (map (fn (x, T) => (Name.binding x, SOME T, NoSyn)) csts) ctxt
ballarin@28795
   324
      in ([], ctxt') end
ballarin@28795
   325
  | declare_elem _ (Assumes asms) ctxt = (map #2 asms, ctxt)
ballarin@28795
   326
  | declare_elem _ (Defines defs) ctxt = (map (fn (_, (t, ps)) => [(t, ps)]) defs, ctxt)
ballarin@28795
   327
  | declare_elem _ (Notes _) ctxt = ([], ctxt);
ballarin@28795
   328
ballarin@28795
   329
in
ballarin@28795
   330
ballarin@28795
   331
fun declare_elems prep_vars raw_elems ctxt =
ballarin@28795
   332
  fold_map (declare_elem prep_vars) raw_elems ctxt;
ballarin@28795
   333
ballarin@28795
   334
end;
ballarin@28795
   335
ballarin@28795
   336
local
ballarin@28795
   337
ballarin@28795
   338
val norm_term = Envir.beta_norm oo Term.subst_atomic;
ballarin@28795
   339
ballarin@28795
   340
fun abstract_thm thy eq =
ballarin@28795
   341
  Thm.assume (Thm.cterm_of thy eq) |> Drule.gen_all |> Drule.abs_def;
ballarin@28795
   342
ballarin@28795
   343
fun bind_def ctxt eq (xs, env, ths) =
ballarin@28795
   344
  let
ballarin@28795
   345
    val ((y, T), b) = LocalDefs.abs_def eq;
ballarin@28795
   346
    val b' = norm_term env b;
ballarin@28795
   347
    val th = abstract_thm (ProofContext.theory_of ctxt) eq;
ballarin@28795
   348
    fun err msg = error (msg ^ ": " ^ quote y);
ballarin@28795
   349
  in
ballarin@28795
   350
    exists (fn (x, _) => x = y) xs andalso
ballarin@28795
   351
      err "Attempt to define previously specified variable";
ballarin@28795
   352
    exists (fn (Free (y', _), _) => y = y' | _ => false) env andalso
ballarin@28795
   353
      err "Attempt to redefine variable";
ballarin@28795
   354
    (Term.add_frees b' xs, (Free (y, T), b') :: env, th :: ths)
ballarin@28795
   355
  end;
ballarin@28795
   356
ballarin@28795
   357
fun eval_text _ (Fixes _) text = text
ballarin@28795
   358
  | eval_text _ (Constrains _) text = text
ballarin@28795
   359
  | eval_text _ (Assumes asms)
ballarin@28795
   360
        (((exts, exts'), (ints, ints')), (xs, env, defs)) =
ballarin@28795
   361
      let
ballarin@28795
   362
        val ts = maps (map #1 o #2) asms;
ballarin@28795
   363
        val ts' = map (norm_term env) ts;
ballarin@28795
   364
        val spec' = ((exts @ ts, exts' @ ts'), (ints, ints'));
ballarin@28795
   365
      in (spec', (fold Term.add_frees ts' xs, env, defs)) end
ballarin@28795
   366
  | eval_text ctxt (Defines defs) (spec, binds) =
ballarin@28795
   367
      (spec, fold (bind_def ctxt o #1 o #2) defs binds)
ballarin@28795
   368
  | eval_text _ (Notes _) text = text;
ballarin@28795
   369
ballarin@28795
   370
fun closeup _ false elem = elem
ballarin@28795
   371
  | closeup ctxt true elem =
ballarin@28795
   372
      let
ballarin@28795
   373
        fun close_frees t =
ballarin@28795
   374
          let
ballarin@28795
   375
            val rev_frees =
ballarin@28795
   376
              Term.fold_aterms (fn Free (x, T) =>
ballarin@28795
   377
                if Variable.is_fixed ctxt x then I else insert (op =) (x, T) | _ => I) t [];
ballarin@28795
   378
          in Term.list_all_free (rev rev_frees, t) end;
ballarin@28795
   379
ballarin@28795
   380
        fun no_binds [] = []
ballarin@28795
   381
          | no_binds _ = error "Illegal term bindings in locale element";
ballarin@28795
   382
      in
ballarin@28795
   383
        (case elem of
ballarin@28795
   384
          Assumes asms => Assumes (asms |> map (fn (a, propps) =>
ballarin@28795
   385
            (a, map (fn (t, ps) => (close_frees t, no_binds ps)) propps)))
ballarin@28795
   386
        | Defines defs => Defines (defs |> map (fn (a, (t, ps)) =>
ballarin@28795
   387
            (a, (close_frees (#2 (LocalDefs.cert_def ctxt t)), no_binds ps))))
ballarin@28795
   388
        | e => e)
ballarin@28795
   389
      end;
ballarin@28795
   390
ballarin@28795
   391
fun finish_ext_elem parms _ (Fixes fixes, _) = Fixes (map (fn (binding, _, mx) =>
ballarin@28795
   392
      let val x = Name.name_of binding
ballarin@28795
   393
      in (binding, AList.lookup (op =) parms x, mx) end) fixes)
ballarin@28795
   394
  | finish_ext_elem _ _ (Constrains _, _) = Constrains []
ballarin@28795
   395
  | finish_ext_elem _ close (Assumes asms, propp) =
ballarin@28795
   396
      close (Assumes (map #1 asms ~~ propp))
ballarin@28795
   397
  | finish_ext_elem _ close (Defines defs, propp) =
ballarin@28795
   398
      close (Defines (map #1 defs ~~ map (fn [(t, ps)] => (t, ps)) propp))
ballarin@28795
   399
  | finish_ext_elem _ _ (Notes facts, _) = Notes facts;
ballarin@28795
   400
ballarin@28795
   401
fun finish_elem ctxt parms do_close (elem, propp) text =
ballarin@28795
   402
  let
ballarin@28795
   403
    val elem' = finish_ext_elem parms (closeup ctxt do_close) (elem, propp);
ballarin@28795
   404
    val text' = eval_text ctxt elem' text;
ballarin@28795
   405
  in (elem', text') end
ballarin@28795
   406
  
ballarin@28795
   407
in
ballarin@28795
   408
ballarin@28795
   409
fun finish_elems ctxt parms do_close elems text =
ballarin@28795
   410
  fold_map (finish_elem ctxt parms do_close) elems text;
ballarin@28795
   411
ballarin@28795
   412
end;
ballarin@28795
   413
ballarin@28795
   414
ballarin@28795
   415
local
ballarin@28795
   416
ballarin@28795
   417
fun param_types ps = map_filter (fn (_, NONE) => NONE | (x, SOME T) => SOME (x, T)) ps;
ballarin@28795
   418
ballarin@28795
   419
fun frozen_tvars ctxt Ts =
ballarin@28795
   420
  #1 (Variable.importT_inst (map Logic.mk_type Ts) ctxt)
ballarin@28795
   421
  |> map (fn ((xi, S), T) => (xi, (S, T)));
ballarin@28795
   422
ballarin@28795
   423
fun unify_frozen ctxt maxidx Ts Us =
ballarin@28795
   424
  let
ballarin@28795
   425
    fun paramify NONE i = (NONE, i)
ballarin@28795
   426
      | paramify (SOME T) i = apfst SOME (TypeInfer.paramify_dummies T i);
ballarin@28795
   427
ballarin@28795
   428
    val (Ts', maxidx') = fold_map paramify Ts maxidx;
ballarin@28795
   429
    val (Us', maxidx'') = fold_map paramify Us maxidx';
ballarin@28795
   430
    val thy = ProofContext.theory_of ctxt;
ballarin@28795
   431
ballarin@28795
   432
    fun unify (SOME T, SOME U) env = (Sign.typ_unify thy (U, T) env
ballarin@28795
   433
          handle Type.TUNIFY => raise TYPE ("unify_frozen: failed to unify types", [U, T], []))
ballarin@28795
   434
      | unify _ env = env;
ballarin@28795
   435
    val (unifier, _) = fold unify (Ts' ~~ Us') (Vartab.empty, maxidx'');
ballarin@28795
   436
    val Vs = map (Option.map (Envir.norm_type unifier)) Us';
ballarin@28795
   437
    val unifier' = Vartab.extend (unifier, frozen_tvars ctxt (map_filter I Vs));
ballarin@28795
   438
  in map (Option.map (Envir.norm_type unifier')) Vs end;
ballarin@28795
   439
ballarin@28795
   440
fun prep_elems prep_vars prepp do_close context raw_elems raw_concl =
ballarin@28795
   441
  let
ballarin@28795
   442
    val (raw_propps, raw_ctxt) = declare_elems prep_vars raw_elems context;
ballarin@28795
   443
      (* raw_ctxt is context enriched by syntax from raw_elems *)
ballarin@28795
   444
ballarin@28795
   445
    fun prep_prop raw_propp (raw_ctxt, raw_concl) =
ballarin@28795
   446
      let
ballarin@28795
   447
        (* process patterns (conclusion and external elements) *)
ballarin@28795
   448
        val (ctxt, all_propp) = prepp (raw_ctxt, raw_concl @ raw_propp);
ballarin@28795
   449
        (* add type information from conclusion and external elements to context *)
ballarin@28795
   450
        val ctxt = fold Variable.declare_term (maps (map fst) all_propp) ctxt;
ballarin@28795
   451
        (* resolve schematic variables (patterns) in conclusion and external elements. *)
ballarin@28795
   452
        val all_propp' = map2 (curry (op ~~))
ballarin@28795
   453
          (#1 (#2 (ProofContext.bind_propp_schematic_i (ctxt, all_propp)))) (map (map snd) all_propp);
ballarin@28795
   454
        val (concl, propp) = chop (length raw_concl) all_propp';
ballarin@28795
   455
      in (propp, (ctxt, concl)) end
ballarin@28795
   456
ballarin@28795
   457
    val (propps, (ctxt, concl)) = fold_burrow prep_prop raw_propps (raw_ctxt, raw_concl);
ballarin@28795
   458
ballarin@28795
   459
    (* Infer parameter types *) 
ballarin@28795
   460
    val xs = fold (fn Fixes fixes => (fn ps => ps @ map (Name.name_of o #1) fixes) |
ballarin@28795
   461
      _ => fn ps => ps) raw_elems [];
ballarin@28795
   462
    val typing = unify_frozen ctxt 0
ballarin@28795
   463
      (map (Variable.default_type raw_ctxt) xs)
ballarin@28795
   464
      (map (Variable.default_type ctxt) xs);
ballarin@28795
   465
    val parms = param_types (xs ~~ typing);
ballarin@28795
   466
ballarin@28795
   467
    (* CB: extract information from assumes and defines elements
ballarin@28795
   468
       (fixes, constrains and notes in raw_elemss don't have an effect on
ballarin@28795
   469
       text and elemss), compute final form of context elements. *)
ballarin@28795
   470
   val (elems, text) = finish_elems ctxt parms do_close
ballarin@28795
   471
      (raw_elems ~~ propps) ((([], []), ([], [])), ([], [], []));
ballarin@28795
   472
    (* CB: text has the following structure:
ballarin@28795
   473
           (((exts, exts'), (ints, ints')), (xs, env, defs))
ballarin@28795
   474
       where
ballarin@28795
   475
         exts: external assumptions (terms in external assumes elements)
ballarin@28795
   476
         exts': dito, normalised wrt. env
ballarin@28795
   477
         ints: internal assumptions (terms in internal assumes elements)
ballarin@28795
   478
         ints': dito, normalised wrt. env
ballarin@28795
   479
         xs: the free variables in exts' and ints' and rhss of definitions,
ballarin@28795
   480
           this includes parameters except defined parameters
ballarin@28795
   481
         env: list of term pairs encoding substitutions, where the first term
ballarin@28795
   482
           is a free variable; substitutions represent defines elements and
ballarin@28795
   483
           the rhs is normalised wrt. the previous env
ballarin@28795
   484
         defs: theorems representing the substitutions from defines elements
ballarin@28795
   485
           (thms are normalised wrt. env).
ballarin@28795
   486
       elems is an updated version of raw_elems:
ballarin@28795
   487
         - type info added to Fixes and modified in Constrains
ballarin@28795
   488
         - axiom and definition statement replaced by corresponding one
ballarin@28795
   489
           from proppss in Assumes and Defines
ballarin@28795
   490
         - Facts unchanged
ballarin@28795
   491
       *)
ballarin@28795
   492
   in ((parms, elems, concl), text) end
ballarin@28795
   493
ballarin@28795
   494
in
ballarin@28795
   495
ballarin@28795
   496
fun read_elems x = prep_elems ProofContext.read_vars ProofContext.read_propp_schematic x;
ballarin@28795
   497
fun cert_elems x = prep_elems ProofContext.cert_vars ProofContext.cert_propp_schematic x;
ballarin@28795
   498
ballarin@28795
   499
end;
ballarin@28795
   500
ballarin@28795
   501
ballarin@28795
   502
(* full context statements: import + elements + conclusion *)
ballarin@28795
   503
ballarin@28795
   504
local
ballarin@28795
   505
ballarin@28832
   506
fun prep_context_statement prep_expr prep_elems
ballarin@28795
   507
    do_close imprt elements raw_concl context =
ballarin@28795
   508
  let
ballarin@28795
   509
    val thy = ProofContext.theory_of context;
ballarin@28795
   510
ballarin@28795
   511
    val (expr, (params, fors)) = parameters thy (apfst (prep_expr thy) imprt);
ballarin@28795
   512
    val ctxt = context |>
ballarin@28795
   513
      ProofContext.add_fixes (map (fn (b, mx) => (b, NONE, mx)) params) |> snd |>
ballarin@28795
   514
      ProofContext.add_fixes fors |> snd;
ballarin@28795
   515
  in
ballarin@28795
   516
    case expr of
ballarin@28795
   517
        Expr [] => let
ballarin@28795
   518
          val ((parms, elems, concl), (spec, (_, _, defs))) = prep_elems do_close
ballarin@28795
   519
            context elements raw_concl;
ballarin@28795
   520
          val ((elems', _), ctxt') =
ballarin@28832
   521
            Element.activate elems (ProofContext.set_stmt true ctxt);
ballarin@28795
   522
        in
ballarin@28795
   523
          (((ctxt', elems'), (parms, spec, defs)), concl)
ballarin@28795
   524
        end
ballarin@28795
   525
(*
ballarin@28795
   526
        | Expr [(name, insts)] => let
ballarin@28795
   527
          val parms = parameters_of thy name |> map (fn (b, SOME T, _) => (Name.name_of b, T));
ballarin@28795
   528
          val (morph, ctxt') = read_inst parms insts context;
ballarin@28795
   529
        in
ballarin@28795
   530
          
ballarin@28795
   531
        end
ballarin@28795
   532
*)
ballarin@28795
   533
end
ballarin@28795
   534
ballarin@28795
   535
in
ballarin@28795
   536
ballarin@28795
   537
fun read_context imprt body ctxt =
ballarin@28832
   538
  #1 (prep_context_statement intern_expr read_elems true imprt body [] ctxt);
ballarin@28795
   539
(*
ballarin@28795
   540
fun cert_context imprt body ctxt =
ballarin@28832
   541
  #1 (prep_context_statement (K I) cert_elems true imprt body [] ctxt);
ballarin@28795
   542
*)
ballarin@28795
   543
end;
ballarin@28795
   544
ballarin@28795
   545
ballarin@28795
   546
(** Dependencies **)
ballarin@28795
   547
ballarin@28795
   548
ballarin@28795
   549
ballarin@28795
   550
(*** Locale declarations ***)
ballarin@28795
   551
ballarin@28795
   552
local
ballarin@28795
   553
ballarin@28795
   554
(* introN: name of theorems for introduction rules of locale and
ballarin@28795
   555
     delta predicates;
ballarin@28795
   556
   axiomsN: name of theorem set with destruct rules for locale predicates,
ballarin@28795
   557
     also name suffix of delta predicates. *)
ballarin@28795
   558
ballarin@28795
   559
val introN = "intro";
ballarin@28795
   560
val axiomsN = "axioms";
ballarin@28795
   561
ballarin@28795
   562
fun atomize_spec thy ts =
ballarin@28795
   563
  let
ballarin@28795
   564
    val t = Logic.mk_conjunction_balanced ts;
ballarin@28795
   565
    val body = ObjectLogic.atomize_term thy t;
ballarin@28795
   566
    val bodyT = Term.fastype_of body;
ballarin@28795
   567
  in
ballarin@28795
   568
    if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of thy t))
ballarin@28795
   569
    else (body, bodyT, ObjectLogic.atomize (Thm.cterm_of thy t))
ballarin@28795
   570
  end;
ballarin@28795
   571
ballarin@28795
   572
(* achieve plain syntax for locale predicates (without "PROP") *)
ballarin@28795
   573
ballarin@28795
   574
fun aprop_tr' n c = (Syntax.constN ^ c, fn ctxt => fn args =>
ballarin@28795
   575
  if length args = n then
ballarin@28795
   576
    Syntax.const "_aprop" $
ballarin@28795
   577
      Term.list_comb (Syntax.free (Consts.extern (ProofContext.consts_of ctxt) c), args)
ballarin@28795
   578
  else raise Match);
ballarin@28795
   579
ballarin@28795
   580
(* CB: define one predicate including its intro rule and axioms
ballarin@28795
   581
   - bname: predicate name
ballarin@28795
   582
   - parms: locale parameters
ballarin@28795
   583
   - defs: thms representing substitutions from defines elements
ballarin@28795
   584
   - ts: terms representing locale assumptions (not normalised wrt. defs)
ballarin@28795
   585
   - norm_ts: terms representing locale assumptions (normalised wrt. defs)
ballarin@28795
   586
   - thy: the theory
ballarin@28795
   587
*)
ballarin@28795
   588
ballarin@28795
   589
fun def_pred bname parms defs ts norm_ts thy =
ballarin@28795
   590
  let
ballarin@28795
   591
    val name = Sign.full_name thy bname;
ballarin@28795
   592
ballarin@28795
   593
    val (body, bodyT, body_eq) = atomize_spec thy norm_ts;
ballarin@28795
   594
    val env = Term.add_term_free_names (body, []);
ballarin@28795
   595
    val xs = filter (member (op =) env o #1) parms;
ballarin@28795
   596
    val Ts = map #2 xs;
ballarin@28795
   597
    val extraTs = (Term.term_tfrees body \\ fold Term.add_tfreesT Ts [])
ballarin@28795
   598
      |> Library.sort_wrt #1 |> map TFree;
ballarin@28795
   599
    val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
ballarin@28795
   600
ballarin@28795
   601
    val args = map Logic.mk_type extraTs @ map Free xs;
ballarin@28795
   602
    val head = Term.list_comb (Const (name, predT), args);
ballarin@28795
   603
    val statement = ObjectLogic.ensure_propT thy head;
ballarin@28795
   604
ballarin@28795
   605
    val ([pred_def], defs_thy) =
ballarin@28795
   606
      thy
ballarin@28795
   607
      |> bodyT = propT ? Sign.add_advanced_trfuns ([], [], [aprop_tr' (length args) name], [])
ballarin@28795
   608
      |> Sign.declare_const [] ((Name.binding bname, predT), NoSyn) |> snd
ballarin@28795
   609
      |> PureThy.add_defs false
ballarin@28795
   610
        [((Thm.def_name bname, Logic.mk_equals (head, body)), [Thm.kind_internal])];
ballarin@28795
   611
    val defs_ctxt = ProofContext.init defs_thy |> Variable.declare_term head;
ballarin@28795
   612
ballarin@28795
   613
    val cert = Thm.cterm_of defs_thy;
ballarin@28795
   614
ballarin@28795
   615
    val intro = Goal.prove_global defs_thy [] norm_ts statement (fn _ =>
ballarin@28795
   616
      MetaSimplifier.rewrite_goals_tac [pred_def] THEN
ballarin@28795
   617
      Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
ballarin@28795
   618
      Tactic.compose_tac (false,
ballarin@28795
   619
        Conjunction.intr_balanced (map (Thm.assume o cert) norm_ts), 0) 1);
ballarin@28795
   620
ballarin@28795
   621
    val conjuncts =
ballarin@28795
   622
      (Drule.equal_elim_rule2 OF [body_eq,
ballarin@28795
   623
        MetaSimplifier.rewrite_rule [pred_def] (Thm.assume (cert statement))])
ballarin@28795
   624
      |> Conjunction.elim_balanced (length ts);
ballarin@28795
   625
    val axioms = ts ~~ conjuncts |> map (fn (t, ax) =>
ballarin@28795
   626
      Element.prove_witness defs_ctxt t
ballarin@28795
   627
       (MetaSimplifier.rewrite_goals_tac defs THEN
ballarin@28795
   628
        Tactic.compose_tac (false, ax, 0) 1));
ballarin@28795
   629
  in ((statement, intro, axioms), defs_thy) end;
ballarin@28795
   630
ballarin@28795
   631
in
ballarin@28795
   632
ballarin@28795
   633
(* CB: main predicate definition function *)
ballarin@28795
   634
ballarin@28795
   635
fun define_preds pname (parms, ((exts, exts'), (ints, ints')), defs) thy =
ballarin@28795
   636
  let
ballarin@28795
   637
    val (a_pred, a_intro, a_axioms, thy'') =
ballarin@28795
   638
      if null exts then (NONE, NONE, [], thy)
ballarin@28795
   639
      else
ballarin@28795
   640
        let
ballarin@28795
   641
          val aname = if null ints then pname else pname ^ "_" ^ axiomsN;
ballarin@28795
   642
          val ((statement, intro, axioms), thy') =
ballarin@28795
   643
            thy
ballarin@28795
   644
            |> def_pred aname parms defs exts exts';
ballarin@28795
   645
          val (_, thy'') =
ballarin@28795
   646
            thy'
ballarin@28795
   647
            |> Sign.add_path aname
ballarin@28795
   648
            |> Sign.no_base_names
ballarin@28795
   649
            |> PureThy.note_thmss Thm.internalK [((Name.binding introN, []), [([intro], [])])]
ballarin@28795
   650
            ||> Sign.restore_naming thy';
ballarin@28795
   651
          in (SOME statement, SOME intro, axioms, thy'') end;
ballarin@28795
   652
    val (b_pred, b_intro, b_axioms, thy'''') =
ballarin@28795
   653
      if null ints then (NONE, NONE, [], thy'')
ballarin@28795
   654
      else
ballarin@28795
   655
        let
ballarin@28795
   656
          val ((statement, intro, axioms), thy''') =
ballarin@28795
   657
            thy''
ballarin@28795
   658
            |> def_pred pname parms defs (ints @ the_list a_pred) (ints' @ the_list a_pred);
ballarin@28795
   659
          val (_, thy'''') =
ballarin@28795
   660
            thy'''
ballarin@28795
   661
            |> Sign.add_path pname
ballarin@28795
   662
            |> Sign.no_base_names
ballarin@28795
   663
            |> PureThy.note_thmss Thm.internalK
ballarin@28795
   664
                 [((Name.binding introN, []), [([intro], [])]),
ballarin@28795
   665
                  ((Name.binding axiomsN, []),
ballarin@28795
   666
                    [(map (Drule.standard o Element.conclude_witness) axioms, [])])]
ballarin@28795
   667
            ||> Sign.restore_naming thy''';
ballarin@28795
   668
        in (SOME statement, SOME intro, axioms, thy'''') end;
ballarin@28795
   669
  in ((a_pred, a_intro, a_axioms), (b_pred, b_intro, b_axioms), thy'''') end;
ballarin@28795
   670
ballarin@28795
   671
end;
ballarin@28795
   672
ballarin@28795
   673
ballarin@28795
   674
local
ballarin@28795
   675
ballarin@28795
   676
fun assumes_to_notes (Assumes asms) axms =
ballarin@28795
   677
      fold_map (fn (a, spec) => fn axs =>
ballarin@28795
   678
          let val (ps, qs) = chop (length spec) axs
ballarin@28795
   679
          in ((a, [(ps, [])]), qs) end) asms axms
ballarin@28795
   680
      |> apfst (curry Notes Thm.assumptionK)
ballarin@28795
   681
  | assumes_to_notes e axms = (e, axms);
ballarin@28795
   682
ballarin@28795
   683
fun defines_to_notes thy (Defines defs) defns =
ballarin@28795
   684
    let
ballarin@28795
   685
      val defs' = map (fn (_, (def, _)) => def) defs
ballarin@28795
   686
      val notes = map (fn (a, (def, _)) =>
ballarin@28795
   687
        (a, [([assume (cterm_of thy def)], [])])) defs
ballarin@28795
   688
    in
ballarin@28795
   689
      (Notes (Thm.definitionK, notes), defns @ defs')
ballarin@28795
   690
    end
ballarin@28795
   691
  | defines_to_notes _ e defns = (e, defns);
ballarin@28795
   692
ballarin@28795
   693
fun gen_add_locale prep_ctxt
ballarin@28795
   694
    bname predicate_name raw_imprt raw_body thy =
ballarin@28795
   695
  let
ballarin@28795
   696
    val thy_ctxt = ProofContext.init thy;
ballarin@28795
   697
    val name = Sign.full_name thy bname;
ballarin@28795
   698
    val _ = NewLocale.test_locale thy name andalso
ballarin@28795
   699
      error ("Duplicate definition of locale " ^ quote name);
ballarin@28795
   700
ballarin@28795
   701
    val ((body_ctxt, body_elems), text as (parms, ((_, exts'), _), defs)) =
ballarin@28795
   702
      prep_ctxt raw_imprt raw_body thy_ctxt;
ballarin@28795
   703
    val ((statement, intro, axioms), _, thy') =
ballarin@28795
   704
      define_preds predicate_name text thy;
ballarin@28795
   705
ballarin@28795
   706
    val extraTs = fold Term.add_tfrees exts' [] \\ fold Term.add_tfreesT (map snd parms) [];
ballarin@28795
   707
    val _ = if null extraTs then ()
ballarin@28795
   708
      else warning ("Additional type variable(s) in locale specification " ^ quote bname);
ballarin@28795
   709
ballarin@28795
   710
    val params = body_elems |>
ballarin@28795
   711
      map_filter (fn Fixes fixes => SOME fixes | _ => NONE) |> flat;
ballarin@28795
   712
ballarin@28795
   713
    val (body_elems', defns) = fold_map (defines_to_notes thy) body_elems [];
ballarin@28795
   714
ballarin@28795
   715
    val notes = body_elems' |>
ballarin@28795
   716
      (fn elems => fold_map assumes_to_notes elems (map Element.conclude_witness axioms)) |>
ballarin@28795
   717
      fst |>
ballarin@28795
   718
      map_filter (fn Notes notes => SOME notes | _ => NONE);
ballarin@28795
   719
ballarin@28795
   720
    val loc_ctxt = thy' |>
ballarin@28795
   721
      NewLocale.register_locale name (extraTs, params) (statement, defns) ([], [])
ballarin@28795
   722
        (map (fn n => (n, stamp ())) notes |> rev) [] |>
ballarin@28795
   723
      NewLocale.init name
ballarin@28795
   724
  in (name, loc_ctxt) end;
ballarin@28795
   725
ballarin@28795
   726
in
ballarin@28795
   727
ballarin@28795
   728
val add_locale = gen_add_locale read_context;
ballarin@28795
   729
(* val add_locale_i = gen_add_locale cert_context; *)
ballarin@28795
   730
ballarin@28795
   731
end;
ballarin@28795
   732
ballarin@28795
   733
end;