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