src/Pure/Isar/expression.ML
author ballarin
Wed Nov 19 17:04:29 2008 +0100 (2008-11-19)
changeset 28852 5ddea758679b
parent 28832 cf7237498e7a
child 28859 d50b523c55db
permissions -rw-r--r--
Type inference for elements through syntax module.
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@28852
   315
(** Parsing **)
ballarin@28852
   316
ballarin@28852
   317
fun parse_elem prep_typ prep_term ctxt elem =
ballarin@28852
   318
  Element.map_ctxt {name = I, var = I, typ = prep_typ ctxt,
ballarin@28852
   319
    term = prep_term ctxt, fact = I, attrib = I} elem;
ballarin@28852
   320
ballarin@28852
   321
fun parse_concl prep_term ctxt concl =
ballarin@28852
   322
  (map o map) (fn (t, ps) =>
ballarin@28852
   323
    (prep_term ctxt, map (prep_term ctxt) ps)) concl;
ballarin@28852
   324
ballarin@28852
   325
ballarin@28852
   326
(** Type checking **)
ballarin@28852
   327
ballarin@28852
   328
fun extract_elem (Fixes fixes) = map (#2 #> the_list #> map (Logic.mk_type #> rpair [])) fixes
ballarin@28852
   329
  | extract_elem (Constrains csts) = map (#2 #> single #> map (Logic.mk_type #> rpair [])) csts
ballarin@28852
   330
  | extract_elem (Assumes asms) = map #2 asms
ballarin@28852
   331
  | extract_elem (Defines defs) = map (fn (_, (t, ps)) => [(t, ps)]) defs
ballarin@28852
   332
  | extract_elem (Notes _) = [];
ballarin@28795
   333
ballarin@28852
   334
fun restore_elem (Fixes fixes, propps) =
ballarin@28852
   335
      (fixes ~~ propps) |> map (fn ((x, _, mx), propp) =>
ballarin@28852
   336
        (x, propp |> map (fst #> Logic.dest_type) |> try hd, mx)) |> Fixes
ballarin@28852
   337
  | restore_elem (Constrains csts, propps) =
ballarin@28852
   338
      (csts ~~ propps) |> map (fn ((x, _), propp) =>
ballarin@28852
   339
        (x, propp |> map (fst #> Logic.dest_type) |> hd)) |> Constrains
ballarin@28852
   340
  | restore_elem (Assumes asms, propps) =
ballarin@28852
   341
      (asms ~~ propps) |> map (fn ((b, _), propp) => (b, propp)) |> Assumes
ballarin@28852
   342
  | restore_elem (Defines defs, propps) =
ballarin@28852
   343
      (defs ~~ propps) |> map (fn ((b, _), [propp]) => (b, propp)) |> Defines
ballarin@28852
   344
  | restore_elem (Notes notes, _) = Notes notes;
ballarin@28852
   345
ballarin@28852
   346
fun check_autofix_elems elems concl ctxt =
ballarin@28852
   347
  let
ballarin@28852
   348
    val termss = elems |> map extract_elem;
ballarin@28852
   349
    val all_terms' = (burrow o burrow_fst) (Syntax.check_terms ctxt) (concl @ flat termss); 
ballarin@28852
   350
(*    val (ctxt', all_props') = ProofContext.check_propp_schematic (ctxt, concl @ flat propss); *)
ballarin@28852
   351
val _ = "check" |> warning;
ballarin@28852
   352
val _ = PolyML.makestring all_terms' |> warning;
ballarin@28852
   353
    val (concl', terms') = chop (length concl) all_terms';
ballarin@28852
   354
    val ctxt'' = (fold o fold) (fn (t, _) => Variable.auto_fixes t) terms' ctxt;
ballarin@28852
   355
  in (terms' |> unflat termss |> curry (op ~~) elems |> map restore_elem, concl', ctxt'') end;
ballarin@28852
   356
ballarin@28852
   357
ballarin@28852
   358
(** Prepare locale elements **)
ballarin@28795
   359
ballarin@28795
   360
fun declare_elem prep_vars (Fixes fixes) ctxt =
ballarin@28795
   361
      let val (vars, _) = prep_vars fixes ctxt
ballarin@28852
   362
      in ctxt |> ProofContext.add_fixes_i vars |> snd end
ballarin@28795
   363
  | declare_elem prep_vars (Constrains csts) ctxt =
ballarin@28852
   364
      ctxt |> prep_vars (map (fn (x, T) => (Name.binding x, SOME T, NoSyn)) csts) |> snd
ballarin@28852
   365
  | declare_elem _ (Assumes asms) ctxt = ctxt
ballarin@28852
   366
  | declare_elem _ (Defines defs) ctxt = ctxt
ballarin@28852
   367
  | declare_elem _ (Notes _) ctxt = ctxt;
ballarin@28795
   368
ballarin@28852
   369
(** Finish locale elements, extract specification text **)
ballarin@28795
   370
ballarin@28795
   371
local
ballarin@28795
   372
ballarin@28795
   373
val norm_term = Envir.beta_norm oo Term.subst_atomic;
ballarin@28795
   374
ballarin@28795
   375
fun abstract_thm thy eq =
ballarin@28795
   376
  Thm.assume (Thm.cterm_of thy eq) |> Drule.gen_all |> Drule.abs_def;
ballarin@28795
   377
ballarin@28795
   378
fun bind_def ctxt eq (xs, env, ths) =
ballarin@28795
   379
  let
ballarin@28795
   380
    val ((y, T), b) = LocalDefs.abs_def eq;
ballarin@28795
   381
    val b' = norm_term env b;
ballarin@28795
   382
    val th = abstract_thm (ProofContext.theory_of ctxt) eq;
ballarin@28795
   383
    fun err msg = error (msg ^ ": " ^ quote y);
ballarin@28795
   384
  in
ballarin@28795
   385
    exists (fn (x, _) => x = y) xs andalso
ballarin@28795
   386
      err "Attempt to define previously specified variable";
ballarin@28795
   387
    exists (fn (Free (y', _), _) => y = y' | _ => false) env andalso
ballarin@28795
   388
      err "Attempt to redefine variable";
ballarin@28795
   389
    (Term.add_frees b' xs, (Free (y, T), b') :: env, th :: ths)
ballarin@28795
   390
  end;
ballarin@28795
   391
ballarin@28795
   392
fun eval_text _ (Fixes _) text = text
ballarin@28795
   393
  | eval_text _ (Constrains _) text = text
ballarin@28795
   394
  | eval_text _ (Assumes asms)
ballarin@28795
   395
        (((exts, exts'), (ints, ints')), (xs, env, defs)) =
ballarin@28795
   396
      let
ballarin@28795
   397
        val ts = maps (map #1 o #2) asms;
ballarin@28795
   398
        val ts' = map (norm_term env) ts;
ballarin@28795
   399
        val spec' = ((exts @ ts, exts' @ ts'), (ints, ints'));
ballarin@28795
   400
      in (spec', (fold Term.add_frees ts' xs, env, defs)) end
ballarin@28795
   401
  | eval_text ctxt (Defines defs) (spec, binds) =
ballarin@28795
   402
      (spec, fold (bind_def ctxt o #1 o #2) defs binds)
ballarin@28795
   403
  | eval_text _ (Notes _) text = text;
ballarin@28795
   404
ballarin@28852
   405
fun closeup _ _ false elem = elem
ballarin@28852
   406
  | closeup ctxt parms true elem =
ballarin@28795
   407
      let
ballarin@28795
   408
        fun close_frees t =
ballarin@28795
   409
          let
ballarin@28795
   410
            val rev_frees =
ballarin@28795
   411
              Term.fold_aterms (fn Free (x, T) =>
ballarin@28852
   412
                if AList.defined (op =) parms x then I else insert (op =) (x, T) | _ => I) t [];
ballarin@28795
   413
          in Term.list_all_free (rev rev_frees, t) end;
ballarin@28795
   414
ballarin@28795
   415
        fun no_binds [] = []
ballarin@28852
   416
          | no_binds _ = error "Illegal term bindings in context element";
ballarin@28795
   417
      in
ballarin@28795
   418
        (case elem of
ballarin@28795
   419
          Assumes asms => Assumes (asms |> map (fn (a, propps) =>
ballarin@28795
   420
            (a, map (fn (t, ps) => (close_frees t, no_binds ps)) propps)))
ballarin@28795
   421
        | Defines defs => Defines (defs |> map (fn (a, (t, ps)) =>
ballarin@28795
   422
            (a, (close_frees (#2 (LocalDefs.cert_def ctxt t)), no_binds ps))))
ballarin@28795
   423
        | e => e)
ballarin@28795
   424
      end;
ballarin@28795
   425
ballarin@28852
   426
fun finish_ext_elem parms _ (Fixes fixes) = Fixes (map (fn (binding, _, mx) =>
ballarin@28795
   427
      let val x = Name.name_of binding
ballarin@28795
   428
      in (binding, AList.lookup (op =) parms x, mx) end) fixes)
ballarin@28852
   429
  | finish_ext_elem _ _ (Constrains _) = Constrains []
ballarin@28852
   430
  | finish_ext_elem _ close (Assumes asms) = close (Assumes asms)
ballarin@28852
   431
  | finish_ext_elem _ close (Defines defs) = close (Defines defs)
ballarin@28852
   432
  | finish_ext_elem _ _ (Notes facts) = Notes facts;
ballarin@28795
   433
ballarin@28852
   434
fun finish_elem ctxt parms do_close elem text =
ballarin@28795
   435
  let
ballarin@28852
   436
    val elem' = finish_ext_elem parms (closeup ctxt parms do_close) elem;
ballarin@28795
   437
    val text' = eval_text ctxt elem' text;
ballarin@28795
   438
  in (elem', text') end
ballarin@28795
   439
  
ballarin@28795
   440
in
ballarin@28795
   441
ballarin@28795
   442
fun finish_elems ctxt parms do_close elems text =
ballarin@28795
   443
  fold_map (finish_elem ctxt parms do_close) elems text;
ballarin@28795
   444
ballarin@28795
   445
end;
ballarin@28795
   446
ballarin@28795
   447
ballarin@28795
   448
local
ballarin@28795
   449
ballarin@28852
   450
(* nice, but for now not needed
ballarin@28852
   451
fun fold_suffixes f [] y = f [] y
ballarin@28852
   452
  | fold_suffixes f (x :: xs) y = f (x :: xs) (f xs y);
ballarin@28795
   453
ballarin@28852
   454
fun fold_prefixes f xs y = fold_suffixes (f o rev) (rev xs) y;
ballarin@28852
   455
*)
ballarin@28795
   456
ballarin@28852
   457
fun prep_elems parse_typ parse_prop prep_vars do_close context raw_elems raw_concl =
ballarin@28795
   458
  let
ballarin@28852
   459
    fun prep_elem raw_elem (elems, ctxt) =
ballarin@28852
   460
      let
ballarin@28852
   461
        val ctxt' = declare_elem prep_vars raw_elem ctxt;
ballarin@28852
   462
        val elems' = elems @ [parse_elem parse_typ parse_prop ctxt' raw_elem];
ballarin@28852
   463
        (* FIXME term bindings *)
ballarin@28852
   464
        val (_, _, ctxt'') = check_autofix_elems elems' [] ctxt';
ballarin@28852
   465
      in (elems', ctxt'') end;
ballarin@28795
   466
ballarin@28852
   467
    fun prep_concl raw_concl (elems, ctxt) =
ballarin@28795
   468
      let
ballarin@28852
   469
        val concl = (map o map) (fn (t, ps) =>
ballarin@28852
   470
          (parse_prop ctxt t, map (parse_prop ctxt) ps)) raw_concl;
ballarin@28852
   471
      in check_autofix_elems elems concl ctxt end;
ballarin@28795
   472
ballarin@28852
   473
    val (elems, concl, ctxt) = fold prep_elem raw_elems ([], context) |>
ballarin@28852
   474
      prep_concl raw_concl;
ballarin@28795
   475
ballarin@28852
   476
    (* Retrieve parameter types *) 
ballarin@28795
   477
    val xs = fold (fn Fixes fixes => (fn ps => ps @ map (Name.name_of o #1) fixes) |
ballarin@28852
   478
      _ => fn ps => ps) elems [];
ballarin@28852
   479
    val (Ts, _) = fold_map ProofContext.inferred_param xs ctxt; 
ballarin@28852
   480
    val parms = xs ~~ Ts;
ballarin@28795
   481
ballarin@28852
   482
    val (elems', text) = finish_elems ctxt parms do_close elems ((([], []), ([], [])), ([], [], []));
ballarin@28852
   483
    (* text has the following structure:
ballarin@28795
   484
           (((exts, exts'), (ints, ints')), (xs, env, defs))
ballarin@28795
   485
       where
ballarin@28795
   486
         exts: external assumptions (terms in external assumes elements)
ballarin@28795
   487
         exts': dito, normalised wrt. env
ballarin@28795
   488
         ints: internal assumptions (terms in internal assumes elements)
ballarin@28795
   489
         ints': dito, normalised wrt. env
ballarin@28795
   490
         xs: the free variables in exts' and ints' and rhss of definitions,
ballarin@28795
   491
           this includes parameters except defined parameters
ballarin@28795
   492
         env: list of term pairs encoding substitutions, where the first term
ballarin@28795
   493
           is a free variable; substitutions represent defines elements and
ballarin@28795
   494
           the rhs is normalised wrt. the previous env
ballarin@28795
   495
         defs: theorems representing the substitutions from defines elements
ballarin@28795
   496
           (thms are normalised wrt. env).
ballarin@28795
   497
       elems is an updated version of raw_elems:
ballarin@28795
   498
         - type info added to Fixes and modified in Constrains
ballarin@28795
   499
         - axiom and definition statement replaced by corresponding one
ballarin@28795
   500
           from proppss in Assumes and Defines
ballarin@28795
   501
         - Facts unchanged
ballarin@28795
   502
       *)
ballarin@28852
   503
ballarin@28852
   504
  in ((parms, elems', concl), text) end
ballarin@28795
   505
ballarin@28795
   506
in
ballarin@28795
   507
ballarin@28852
   508
fun read_elems x = prep_elems Syntax.parse_typ Syntax.parse_prop ProofContext.read_vars x;
ballarin@28852
   509
fun cert_elems x = prep_elems (K I) (K I) ProofContext.cert_vars x;
ballarin@28795
   510
ballarin@28795
   511
end;
ballarin@28795
   512
ballarin@28795
   513
ballarin@28795
   514
(* full context statements: import + elements + conclusion *)
ballarin@28795
   515
ballarin@28795
   516
local
ballarin@28795
   517
ballarin@28832
   518
fun prep_context_statement prep_expr prep_elems
ballarin@28795
   519
    do_close imprt elements raw_concl context =
ballarin@28795
   520
  let
ballarin@28795
   521
    val thy = ProofContext.theory_of context;
ballarin@28795
   522
ballarin@28795
   523
    val (expr, (params, fors)) = parameters thy (apfst (prep_expr thy) imprt);
ballarin@28795
   524
    val ctxt = context |>
ballarin@28795
   525
      ProofContext.add_fixes (map (fn (b, mx) => (b, NONE, mx)) params) |> snd |>
ballarin@28795
   526
      ProofContext.add_fixes fors |> snd;
ballarin@28795
   527
  in
ballarin@28795
   528
    case expr of
ballarin@28795
   529
        Expr [] => let
ballarin@28795
   530
          val ((parms, elems, concl), (spec, (_, _, defs))) = prep_elems do_close
ballarin@28795
   531
            context elements raw_concl;
ballarin@28795
   532
          val ((elems', _), ctxt') =
ballarin@28832
   533
            Element.activate elems (ProofContext.set_stmt true ctxt);
ballarin@28795
   534
        in
ballarin@28795
   535
          (((ctxt', elems'), (parms, spec, defs)), concl)
ballarin@28795
   536
        end
ballarin@28795
   537
(*
ballarin@28795
   538
        | Expr [(name, insts)] => let
ballarin@28795
   539
          val parms = parameters_of thy name |> map (fn (b, SOME T, _) => (Name.name_of b, T));
ballarin@28795
   540
          val (morph, ctxt') = read_inst parms insts context;
ballarin@28795
   541
        in
ballarin@28795
   542
          
ballarin@28795
   543
        end
ballarin@28795
   544
*)
ballarin@28795
   545
end
ballarin@28795
   546
ballarin@28795
   547
in
ballarin@28795
   548
ballarin@28795
   549
fun read_context imprt body ctxt =
ballarin@28832
   550
  #1 (prep_context_statement intern_expr read_elems true imprt body [] ctxt);
ballarin@28795
   551
fun cert_context imprt body ctxt =
ballarin@28832
   552
  #1 (prep_context_statement (K I) cert_elems true imprt body [] ctxt);
ballarin@28852
   553
ballarin@28795
   554
end;
ballarin@28795
   555
ballarin@28795
   556
ballarin@28795
   557
(** Dependencies **)
ballarin@28795
   558
ballarin@28795
   559
ballarin@28795
   560
ballarin@28795
   561
(*** Locale declarations ***)
ballarin@28795
   562
ballarin@28795
   563
local
ballarin@28795
   564
ballarin@28795
   565
(* introN: name of theorems for introduction rules of locale and
ballarin@28795
   566
     delta predicates;
ballarin@28795
   567
   axiomsN: name of theorem set with destruct rules for locale predicates,
ballarin@28795
   568
     also name suffix of delta predicates. *)
ballarin@28795
   569
ballarin@28795
   570
val introN = "intro";
ballarin@28795
   571
val axiomsN = "axioms";
ballarin@28795
   572
ballarin@28795
   573
fun atomize_spec thy ts =
ballarin@28795
   574
  let
ballarin@28795
   575
    val t = Logic.mk_conjunction_balanced ts;
ballarin@28795
   576
    val body = ObjectLogic.atomize_term thy t;
ballarin@28795
   577
    val bodyT = Term.fastype_of body;
ballarin@28795
   578
  in
ballarin@28795
   579
    if bodyT = propT then (t, propT, Thm.reflexive (Thm.cterm_of thy t))
ballarin@28795
   580
    else (body, bodyT, ObjectLogic.atomize (Thm.cterm_of thy t))
ballarin@28795
   581
  end;
ballarin@28795
   582
ballarin@28795
   583
(* achieve plain syntax for locale predicates (without "PROP") *)
ballarin@28795
   584
ballarin@28795
   585
fun aprop_tr' n c = (Syntax.constN ^ c, fn ctxt => fn args =>
ballarin@28795
   586
  if length args = n then
ballarin@28795
   587
    Syntax.const "_aprop" $
ballarin@28795
   588
      Term.list_comb (Syntax.free (Consts.extern (ProofContext.consts_of ctxt) c), args)
ballarin@28795
   589
  else raise Match);
ballarin@28795
   590
ballarin@28795
   591
(* CB: define one predicate including its intro rule and axioms
ballarin@28795
   592
   - bname: predicate name
ballarin@28795
   593
   - parms: locale parameters
ballarin@28795
   594
   - defs: thms representing substitutions from defines elements
ballarin@28795
   595
   - ts: terms representing locale assumptions (not normalised wrt. defs)
ballarin@28795
   596
   - norm_ts: terms representing locale assumptions (normalised wrt. defs)
ballarin@28795
   597
   - thy: the theory
ballarin@28795
   598
*)
ballarin@28795
   599
ballarin@28795
   600
fun def_pred bname parms defs ts norm_ts thy =
ballarin@28795
   601
  let
ballarin@28795
   602
    val name = Sign.full_name thy bname;
ballarin@28795
   603
ballarin@28795
   604
    val (body, bodyT, body_eq) = atomize_spec thy norm_ts;
ballarin@28795
   605
    val env = Term.add_term_free_names (body, []);
ballarin@28795
   606
    val xs = filter (member (op =) env o #1) parms;
ballarin@28795
   607
    val Ts = map #2 xs;
ballarin@28795
   608
    val extraTs = (Term.term_tfrees body \\ fold Term.add_tfreesT Ts [])
ballarin@28795
   609
      |> Library.sort_wrt #1 |> map TFree;
ballarin@28795
   610
    val predT = map Term.itselfT extraTs ---> Ts ---> bodyT;
ballarin@28795
   611
ballarin@28795
   612
    val args = map Logic.mk_type extraTs @ map Free xs;
ballarin@28795
   613
    val head = Term.list_comb (Const (name, predT), args);
ballarin@28795
   614
    val statement = ObjectLogic.ensure_propT thy head;
ballarin@28795
   615
ballarin@28795
   616
    val ([pred_def], defs_thy) =
ballarin@28795
   617
      thy
ballarin@28795
   618
      |> bodyT = propT ? Sign.add_advanced_trfuns ([], [], [aprop_tr' (length args) name], [])
ballarin@28795
   619
      |> Sign.declare_const [] ((Name.binding bname, predT), NoSyn) |> snd
ballarin@28795
   620
      |> PureThy.add_defs false
ballarin@28795
   621
        [((Thm.def_name bname, Logic.mk_equals (head, body)), [Thm.kind_internal])];
ballarin@28795
   622
    val defs_ctxt = ProofContext.init defs_thy |> Variable.declare_term head;
ballarin@28795
   623
ballarin@28795
   624
    val cert = Thm.cterm_of defs_thy;
ballarin@28795
   625
ballarin@28795
   626
    val intro = Goal.prove_global defs_thy [] norm_ts statement (fn _ =>
ballarin@28795
   627
      MetaSimplifier.rewrite_goals_tac [pred_def] THEN
ballarin@28795
   628
      Tactic.compose_tac (false, body_eq RS Drule.equal_elim_rule1, 1) 1 THEN
ballarin@28795
   629
      Tactic.compose_tac (false,
ballarin@28795
   630
        Conjunction.intr_balanced (map (Thm.assume o cert) norm_ts), 0) 1);
ballarin@28795
   631
ballarin@28795
   632
    val conjuncts =
ballarin@28795
   633
      (Drule.equal_elim_rule2 OF [body_eq,
ballarin@28795
   634
        MetaSimplifier.rewrite_rule [pred_def] (Thm.assume (cert statement))])
ballarin@28795
   635
      |> Conjunction.elim_balanced (length ts);
ballarin@28795
   636
    val axioms = ts ~~ conjuncts |> map (fn (t, ax) =>
ballarin@28795
   637
      Element.prove_witness defs_ctxt t
ballarin@28795
   638
       (MetaSimplifier.rewrite_goals_tac defs THEN
ballarin@28795
   639
        Tactic.compose_tac (false, ax, 0) 1));
ballarin@28795
   640
  in ((statement, intro, axioms), defs_thy) end;
ballarin@28795
   641
ballarin@28795
   642
in
ballarin@28795
   643
ballarin@28795
   644
(* CB: main predicate definition function *)
ballarin@28795
   645
ballarin@28795
   646
fun define_preds pname (parms, ((exts, exts'), (ints, ints')), defs) thy =
ballarin@28795
   647
  let
ballarin@28795
   648
    val (a_pred, a_intro, a_axioms, thy'') =
ballarin@28795
   649
      if null exts then (NONE, NONE, [], thy)
ballarin@28795
   650
      else
ballarin@28795
   651
        let
ballarin@28795
   652
          val aname = if null ints then pname else pname ^ "_" ^ axiomsN;
ballarin@28795
   653
          val ((statement, intro, axioms), thy') =
ballarin@28795
   654
            thy
ballarin@28795
   655
            |> def_pred aname parms defs exts exts';
ballarin@28795
   656
          val (_, thy'') =
ballarin@28795
   657
            thy'
ballarin@28795
   658
            |> Sign.add_path aname
ballarin@28795
   659
            |> Sign.no_base_names
ballarin@28795
   660
            |> PureThy.note_thmss Thm.internalK [((Name.binding introN, []), [([intro], [])])]
ballarin@28795
   661
            ||> Sign.restore_naming thy';
ballarin@28795
   662
          in (SOME statement, SOME intro, axioms, thy'') end;
ballarin@28795
   663
    val (b_pred, b_intro, b_axioms, thy'''') =
ballarin@28795
   664
      if null ints then (NONE, NONE, [], thy'')
ballarin@28795
   665
      else
ballarin@28795
   666
        let
ballarin@28795
   667
          val ((statement, intro, axioms), thy''') =
ballarin@28795
   668
            thy''
ballarin@28795
   669
            |> def_pred pname parms defs (ints @ the_list a_pred) (ints' @ the_list a_pred);
ballarin@28795
   670
          val (_, thy'''') =
ballarin@28795
   671
            thy'''
ballarin@28795
   672
            |> Sign.add_path pname
ballarin@28795
   673
            |> Sign.no_base_names
ballarin@28795
   674
            |> PureThy.note_thmss Thm.internalK
ballarin@28795
   675
                 [((Name.binding introN, []), [([intro], [])]),
ballarin@28795
   676
                  ((Name.binding axiomsN, []),
ballarin@28795
   677
                    [(map (Drule.standard o Element.conclude_witness) axioms, [])])]
ballarin@28795
   678
            ||> Sign.restore_naming thy''';
ballarin@28795
   679
        in (SOME statement, SOME intro, axioms, thy'''') end;
ballarin@28795
   680
  in ((a_pred, a_intro, a_axioms), (b_pred, b_intro, b_axioms), thy'''') end;
ballarin@28795
   681
ballarin@28795
   682
end;
ballarin@28795
   683
ballarin@28795
   684
ballarin@28795
   685
local
ballarin@28795
   686
ballarin@28795
   687
fun assumes_to_notes (Assumes asms) axms =
ballarin@28795
   688
      fold_map (fn (a, spec) => fn axs =>
ballarin@28795
   689
          let val (ps, qs) = chop (length spec) axs
ballarin@28795
   690
          in ((a, [(ps, [])]), qs) end) asms axms
ballarin@28795
   691
      |> apfst (curry Notes Thm.assumptionK)
ballarin@28795
   692
  | assumes_to_notes e axms = (e, axms);
ballarin@28795
   693
ballarin@28795
   694
fun defines_to_notes thy (Defines defs) defns =
ballarin@28795
   695
    let
ballarin@28795
   696
      val defs' = map (fn (_, (def, _)) => def) defs
ballarin@28795
   697
      val notes = map (fn (a, (def, _)) =>
ballarin@28795
   698
        (a, [([assume (cterm_of thy def)], [])])) defs
ballarin@28795
   699
    in
ballarin@28795
   700
      (Notes (Thm.definitionK, notes), defns @ defs')
ballarin@28795
   701
    end
ballarin@28795
   702
  | defines_to_notes _ e defns = (e, defns);
ballarin@28795
   703
ballarin@28795
   704
fun gen_add_locale prep_ctxt
ballarin@28795
   705
    bname predicate_name raw_imprt raw_body thy =
ballarin@28795
   706
  let
ballarin@28795
   707
    val thy_ctxt = ProofContext.init thy;
ballarin@28795
   708
    val name = Sign.full_name thy bname;
ballarin@28795
   709
    val _ = NewLocale.test_locale thy name andalso
ballarin@28795
   710
      error ("Duplicate definition of locale " ^ quote name);
ballarin@28795
   711
ballarin@28795
   712
    val ((body_ctxt, body_elems), text as (parms, ((_, exts'), _), defs)) =
ballarin@28795
   713
      prep_ctxt raw_imprt raw_body thy_ctxt;
ballarin@28795
   714
    val ((statement, intro, axioms), _, thy') =
ballarin@28795
   715
      define_preds predicate_name text thy;
ballarin@28795
   716
ballarin@28795
   717
    val extraTs = fold Term.add_tfrees exts' [] \\ fold Term.add_tfreesT (map snd parms) [];
ballarin@28795
   718
    val _ = if null extraTs then ()
ballarin@28795
   719
      else warning ("Additional type variable(s) in locale specification " ^ quote bname);
ballarin@28795
   720
ballarin@28795
   721
    val params = body_elems |>
ballarin@28795
   722
      map_filter (fn Fixes fixes => SOME fixes | _ => NONE) |> flat;
ballarin@28795
   723
ballarin@28795
   724
    val (body_elems', defns) = fold_map (defines_to_notes thy) body_elems [];
ballarin@28795
   725
ballarin@28795
   726
    val notes = body_elems' |>
ballarin@28795
   727
      (fn elems => fold_map assumes_to_notes elems (map Element.conclude_witness axioms)) |>
ballarin@28795
   728
      fst |>
ballarin@28795
   729
      map_filter (fn Notes notes => SOME notes | _ => NONE);
ballarin@28795
   730
ballarin@28795
   731
    val loc_ctxt = thy' |>
ballarin@28795
   732
      NewLocale.register_locale name (extraTs, params) (statement, defns) ([], [])
ballarin@28795
   733
        (map (fn n => (n, stamp ())) notes |> rev) [] |>
ballarin@28795
   734
      NewLocale.init name
ballarin@28795
   735
  in (name, loc_ctxt) end;
ballarin@28795
   736
ballarin@28795
   737
in
ballarin@28795
   738
ballarin@28795
   739
val add_locale = gen_add_locale read_context;
ballarin@28795
   740
(* val add_locale_i = gen_add_locale cert_context; *)
ballarin@28795
   741
ballarin@28795
   742
end;
ballarin@28795
   743
ballarin@28795
   744
end;