src/HOL/SPARK/Tools/spark_vcs.ML
author wenzelm
Wed, 30 Nov 2011 23:30:08 +0100
changeset 46572 615da8b8d758
parent 46463 8baa0b7f3f66
child 46611 132a3e1c0fe5
permissions -rw-r--r--
discontinued obsolete datatype "alt_names";
berghofe@41809
     1
(*  Title:      HOL/SPARK/Tools/spark_vcs.ML
berghofe@41809
     2
    Author:     Stefan Berghofer
berghofe@41809
     3
    Copyright:  secunet Security Networks AG
berghofe@41809
     4
berghofe@41809
     5
Store for verification conditions generated by SPARK/Ada.
berghofe@41809
     6
*)
berghofe@41809
     7
berghofe@41809
     8
signature SPARK_VCS =
berghofe@41809
     9
sig
berghofe@43227
    10
  val set_vcs: Fdl_Parser.decls -> Fdl_Parser.rules ->
berghofe@43267
    11
    (string * string) * Fdl_Parser.vcs -> Path.T -> string -> theory -> theory
berghofe@41809
    12
  val add_proof_fun: (typ option -> 'a -> term) ->
berghofe@41809
    13
    string * ((string list * string) option * 'a) ->
berghofe@41809
    14
    theory -> theory
berghofe@43227
    15
  val add_type: string * typ -> theory -> theory
berghofe@41809
    16
  val lookup_vc: theory -> string -> (Element.context_i list *
berghofe@42767
    17
    (string * thm list option * Element.context_i * Element.statement_i)) option
berghofe@41809
    18
  val get_vcs: theory ->
berghofe@42767
    19
    Element.context_i list * (binding * thm) list * (string *
berghofe@42767
    20
    (string * thm list option * Element.context_i * Element.statement_i)) list
berghofe@42767
    21
  val mark_proved: string -> thm list -> theory -> theory
berghofe@41809
    22
  val close: theory -> theory
berghofe@41809
    23
  val is_closed: theory -> bool
berghofe@41809
    24
end;
berghofe@41809
    25
berghofe@41809
    26
structure SPARK_VCs: SPARK_VCS =
berghofe@41809
    27
struct
berghofe@41809
    28
berghofe@41809
    29
open Fdl_Parser;
berghofe@41809
    30
berghofe@41809
    31
berghofe@43227
    32
(** theory data **)
berghofe@43227
    33
berghofe@43227
    34
fun err_unfinished () = error "An unfinished SPARK environment is still open."
berghofe@43227
    35
berghofe@43227
    36
val strip_number = pairself implode o take_suffix Fdl_Lexer.is_digit o raw_explode;
berghofe@43227
    37
berghofe@43227
    38
val name_ord = prod_ord string_ord (option_ord int_ord) o
berghofe@43227
    39
  pairself (strip_number ##> Int.fromString);
berghofe@43227
    40
berghofe@43227
    41
structure VCtab = Table(type key = string val ord = name_ord);
berghofe@43227
    42
berghofe@43227
    43
structure VCs = Theory_Data
berghofe@43227
    44
(
berghofe@43227
    45
  type T =
berghofe@43227
    46
    {pfuns: ((string list * string) option * term) Symtab.table,
berghofe@43227
    47
     type_map: typ Symtab.table,
berghofe@43227
    48
     env:
berghofe@43227
    49
       {ctxt: Element.context_i list,
berghofe@43227
    50
        defs: (binding * thm) list,
berghofe@43227
    51
        types: fdl_type tab,
berghofe@43227
    52
        funs: (string list * string) tab,
berghofe@43227
    53
        ids: (term * string) Symtab.table * Name.context,
berghofe@43227
    54
        proving: bool,
berghofe@43227
    55
        vcs: (string * thm list option *
berghofe@43227
    56
          (string * expr) list * (string * expr) list) VCtab.table,
berghofe@43267
    57
        path: Path.T,
berghofe@43267
    58
        prefix: string} option}
berghofe@43227
    59
  val empty : T = {pfuns = Symtab.empty, type_map = Symtab.empty, env = NONE}
berghofe@43227
    60
  val extend = I
berghofe@43227
    61
  fun merge ({pfuns = pfuns1, type_map = type_map1, env = NONE},
berghofe@43227
    62
        {pfuns = pfuns2, type_map = type_map2, env = NONE}) =
berghofe@43227
    63
        {pfuns = Symtab.merge (eq_pair (op =) (op aconv)) (pfuns1, pfuns2),
berghofe@43227
    64
         type_map = Symtab.merge (op =) (type_map1, type_map2),
berghofe@43227
    65
         env = NONE}
berghofe@43227
    66
    | merge _ = err_unfinished ()
berghofe@43227
    67
)
berghofe@43227
    68
berghofe@43227
    69
berghofe@41809
    70
(** utilities **)
berghofe@41809
    71
berghofe@43227
    72
val to_lower = raw_explode #> map Symbol.to_ascii_lower #> implode;
berghofe@43227
    73
berghofe@43227
    74
val lcase_eq = (op =) o pairself (to_lower o Long_Name.base_name);
berghofe@43227
    75
berghofe@43267
    76
fun lookup_prfx "" tab s = Symtab.lookup tab s
berghofe@43267
    77
  | lookup_prfx prfx tab s = (case Symtab.lookup tab s of
berghofe@43267
    78
        NONE => Symtab.lookup tab (prfx ^ "__" ^ s)
berghofe@43267
    79
      | x => x);
berghofe@43267
    80
berghofe@43267
    81
fun strip_prfx s =
berghofe@43267
    82
  let
berghofe@43267
    83
    fun strip ys [] = ("", implode ys)
berghofe@43267
    84
      | strip ys ("_" :: "_" :: xs) = (implode (rev xs), implode ys)
berghofe@43267
    85
      | strip ys (x :: xs) = strip (x :: ys) xs
berghofe@43267
    86
  in strip [] (rev (raw_explode s)) end;
berghofe@43267
    87
berghofe@41809
    88
fun mk_unop s t =
berghofe@41809
    89
  let val T = fastype_of t
berghofe@41809
    90
  in Const (s, T --> T) $ t end;
berghofe@41809
    91
berghofe@41809
    92
fun mk_times (t, u) =
berghofe@41809
    93
  let
berghofe@41809
    94
    val setT = fastype_of t;
berghofe@41809
    95
    val T = HOLogic.dest_setT setT;
berghofe@41809
    96
    val U = HOLogic.dest_setT (fastype_of u)
berghofe@41809
    97
  in
berghofe@41809
    98
    Const (@{const_name Sigma}, setT --> (T --> HOLogic.mk_setT U) -->
berghofe@41809
    99
      HOLogic.mk_setT (HOLogic.mk_prodT (T, U))) $ t $ Abs ("", T, u)
berghofe@41809
   100
  end;
berghofe@41809
   101
berghofe@43267
   102
fun get_type thy prfx ty =
berghofe@43227
   103
  let val {type_map, ...} = VCs.get thy
berghofe@43267
   104
  in lookup_prfx prfx type_map ty end;
berghofe@43227
   105
berghofe@43267
   106
fun mk_type _ _ "integer" = HOLogic.intT
berghofe@43267
   107
  | mk_type _ _ "boolean" = HOLogic.boolT
berghofe@43267
   108
  | mk_type thy prfx ty =
berghofe@43267
   109
      (case get_type thy prfx ty of
berghofe@43227
   110
         NONE =>
wenzelm@43232
   111
           Syntax.check_typ (Proof_Context.init_global thy)
berghofe@43227
   112
             (Type (Sign.full_name thy (Binding.name ty), []))
berghofe@43227
   113
       | SOME T => T);
berghofe@41809
   114
berghofe@41809
   115
val booleanN = "boolean";
berghofe@41809
   116
val integerN = "integer";
berghofe@41809
   117
berghofe@41809
   118
fun define_overloaded (def_name, eq) lthy =
berghofe@41809
   119
  let
berghofe@41809
   120
    val ((c, _), rhs) = eq |> Syntax.check_term lthy |>
berghofe@41809
   121
      Logic.dest_equals |>> dest_Free;
berghofe@41809
   122
    val ((_, (_, thm)), lthy') = Local_Theory.define
berghofe@41809
   123
      ((Binding.name c, NoSyn), ((Binding.name def_name, []), rhs)) lthy
wenzelm@43232
   124
    val ctxt_thy = Proof_Context.init_global (Proof_Context.theory_of lthy');
wenzelm@43232
   125
    val thm' = singleton (Proof_Context.export lthy' ctxt_thy) thm
berghofe@41809
   126
  in (thm', lthy') end;
berghofe@41809
   127
berghofe@41809
   128
fun strip_underscores s =
berghofe@41809
   129
  strip_underscores (unsuffix "_" s) handle Fail _ => s;
berghofe@41809
   130
berghofe@41809
   131
fun strip_tilde s =
berghofe@41809
   132
  unsuffix "~" s ^ "_init" handle Fail _ => s;
berghofe@41809
   133
berghofe@41809
   134
val mangle_name = strip_underscores #> strip_tilde;
berghofe@41809
   135
berghofe@43267
   136
fun mk_variables thy prfx xs ty (tab, ctxt) =
berghofe@41809
   137
  let
berghofe@43267
   138
    val T = mk_type thy prfx ty;
wenzelm@44208
   139
    val (ys, ctxt') = fold_map Name.variant (map mangle_name xs) ctxt;
berghofe@41809
   140
    val zs = map (Free o rpair T) ys;
berghofe@41809
   141
  in (zs, (fold (Symtab.update o apsnd (rpair ty)) (xs ~~ zs) tab, ctxt')) end;
berghofe@41809
   142
berghofe@43227
   143
fun get_record_info thy T = (case Record.dest_recTs T of
berghofe@43227
   144
    [(tyname, [@{typ unit}])] =>
berghofe@43227
   145
      Record.get_info thy (Long_Name.qualifier tyname)
berghofe@43227
   146
  | _ => NONE);
berghofe@43227
   147
berghofe@43227
   148
fun find_field fname = find_first (curry lcase_eq fname o fst);
berghofe@43227
   149
berghofe@43227
   150
fun find_field' fname = get_first (fn (flds, fldty) =>
berghofe@43227
   151
  if member (op =) flds fname then SOME fldty else NONE);
berghofe@43227
   152
berghofe@43227
   153
fun assoc_ty_err thy T s msg =
berghofe@43227
   154
  error ("Type " ^ Syntax.string_of_typ_global thy T ^
berghofe@43227
   155
    " associated with SPARK type " ^ s ^ "\n" ^ msg);
berghofe@43227
   156
berghofe@41809
   157
berghofe@41809
   158
(** generate properties of enumeration types **)
berghofe@41809
   159
berghofe@43227
   160
fun add_enum_type tyname tyname' thy =
berghofe@41809
   161
  let
berghofe@43227
   162
    val {case_name, ...} = the (Datatype_Data.get_info thy tyname');
berghofe@43227
   163
    val cs = map Const (the (Datatype_Data.get_constrs thy tyname'));
berghofe@43227
   164
    val k = length cs;
berghofe@41809
   165
    val T = Type (tyname', []);
berghofe@41809
   166
    val p = Const (@{const_name pos}, T --> HOLogic.intT);
berghofe@41809
   167
    val v = Const (@{const_name val}, HOLogic.intT --> T);
berghofe@41809
   168
    val card = Const (@{const_name card},
berghofe@41809
   169
      HOLogic.mk_setT T --> HOLogic.natT) $ HOLogic.mk_UNIV T;
berghofe@41809
   170
berghofe@41809
   171
    fun mk_binrel_def s f = Logic.mk_equals
berghofe@41809
   172
      (Const (s, T --> T --> HOLogic.boolT),
berghofe@41809
   173
       Abs ("x", T, Abs ("y", T,
berghofe@41809
   174
         Const (s, HOLogic.intT --> HOLogic.intT --> HOLogic.boolT) $
berghofe@41809
   175
           (f $ Bound 1) $ (f $ Bound 0))));
berghofe@41809
   176
berghofe@41809
   177
    val (((def1, def2), def3), lthy) = thy |>
berghofe@41809
   178
berghofe@43273
   179
      Class.instantiation ([tyname'], [], @{sort spark_enum}) |>
berghofe@41809
   180
berghofe@41809
   181
      define_overloaded ("pos_" ^ tyname ^ "_def", Logic.mk_equals
berghofe@41809
   182
        (p,
berghofe@41809
   183
         list_comb (Const (case_name, replicate k HOLogic.intT @
berghofe@41809
   184
             [T] ---> HOLogic.intT),
berghofe@41809
   185
           map (HOLogic.mk_number HOLogic.intT) (0 upto k - 1)))) ||>>
berghofe@41809
   186
berghofe@41809
   187
      define_overloaded ("less_eq_" ^ tyname ^ "_def",
berghofe@41809
   188
        mk_binrel_def @{const_name less_eq} p) ||>>
berghofe@41809
   189
      define_overloaded ("less_" ^ tyname ^ "_def",
berghofe@41809
   190
        mk_binrel_def @{const_name less} p);
berghofe@41809
   191
berghofe@41809
   192
    val UNIV_eq = Goal.prove lthy [] []
berghofe@41809
   193
      (HOLogic.mk_Trueprop (HOLogic.mk_eq
berghofe@41809
   194
         (HOLogic.mk_UNIV T, HOLogic.mk_set T cs)))
berghofe@41809
   195
      (fn _ =>
berghofe@41809
   196
         rtac @{thm subset_antisym} 1 THEN
berghofe@41809
   197
         rtac @{thm subsetI} 1 THEN
berghofe@41809
   198
         Datatype_Aux.exh_tac (K (#exhaust (Datatype_Data.the_info
wenzelm@43232
   199
           (Proof_Context.theory_of lthy) tyname'))) 1 THEN
berghofe@41809
   200
         ALLGOALS (asm_full_simp_tac (simpset_of lthy)));
berghofe@41809
   201
berghofe@41809
   202
    val finite_UNIV = Goal.prove lthy [] []
berghofe@41809
   203
      (HOLogic.mk_Trueprop (Const (@{const_name finite},
berghofe@41809
   204
         HOLogic.mk_setT T --> HOLogic.boolT) $ HOLogic.mk_UNIV T))
berghofe@41809
   205
      (fn _ => simp_tac (simpset_of lthy addsimps [UNIV_eq]) 1);
berghofe@41809
   206
berghofe@41809
   207
    val card_UNIV = Goal.prove lthy [] []
berghofe@41809
   208
      (HOLogic.mk_Trueprop (HOLogic.mk_eq
berghofe@41809
   209
         (card, HOLogic.mk_number HOLogic.natT k)))
berghofe@41809
   210
      (fn _ => simp_tac (simpset_of lthy addsimps [UNIV_eq]) 1);
berghofe@41809
   211
berghofe@41809
   212
    val range_pos = Goal.prove lthy [] []
berghofe@41809
   213
      (HOLogic.mk_Trueprop (HOLogic.mk_eq
berghofe@41809
   214
         (Const (@{const_name image}, (T --> HOLogic.intT) -->
berghofe@41809
   215
            HOLogic.mk_setT T --> HOLogic.mk_setT HOLogic.intT) $
berghofe@41809
   216
              p $ HOLogic.mk_UNIV T,
berghofe@41809
   217
          Const (@{const_name atLeastLessThan}, HOLogic.intT -->
berghofe@41809
   218
            HOLogic.intT --> HOLogic.mk_setT HOLogic.intT) $
berghofe@41809
   219
              HOLogic.mk_number HOLogic.intT 0 $
berghofe@41809
   220
              (@{term int} $ card))))
berghofe@41809
   221
      (fn _ =>
berghofe@41809
   222
         simp_tac (simpset_of lthy addsimps [card_UNIV]) 1 THEN
berghofe@41809
   223
         simp_tac (simpset_of lthy addsimps [UNIV_eq, def1]) 1 THEN
berghofe@41809
   224
         rtac @{thm subset_antisym} 1 THEN
berghofe@41809
   225
         simp_tac (simpset_of lthy) 1 THEN
berghofe@41809
   226
         rtac @{thm subsetI} 1 THEN
berghofe@41809
   227
         asm_full_simp_tac (simpset_of lthy addsimps @{thms interval_expand}
berghofe@41809
   228
           delsimps @{thms atLeastLessThan_iff}) 1);
berghofe@41809
   229
berghofe@41809
   230
    val lthy' =
berghofe@41809
   231
      Class.prove_instantiation_instance (fn _ =>
berghofe@41809
   232
        Class.intro_classes_tac [] THEN
berghofe@41809
   233
        rtac finite_UNIV 1 THEN
berghofe@41809
   234
        rtac range_pos 1 THEN
berghofe@41809
   235
        simp_tac (HOL_basic_ss addsimps [def3]) 1 THEN
berghofe@41809
   236
        simp_tac (HOL_basic_ss addsimps [def2]) 1) lthy;
berghofe@41809
   237
berghofe@41809
   238
    val (pos_eqs, val_eqs) = split_list (map_index (fn (i, c) =>
berghofe@41809
   239
      let
berghofe@41809
   240
        val n = HOLogic.mk_number HOLogic.intT i;
berghofe@41809
   241
        val th = Goal.prove lthy' [] []
berghofe@41809
   242
          (HOLogic.mk_Trueprop (HOLogic.mk_eq (p $ c, n)))
berghofe@41809
   243
          (fn _ => simp_tac (simpset_of lthy' addsimps [def1]) 1);
berghofe@41809
   244
        val th' = Goal.prove lthy' [] []
berghofe@41809
   245
          (HOLogic.mk_Trueprop (HOLogic.mk_eq (v $ n, c)))
berghofe@41809
   246
          (fn _ =>
berghofe@41809
   247
             rtac (@{thm inj_pos} RS @{thm injD}) 1 THEN
berghofe@41809
   248
             simp_tac (simpset_of lthy' addsimps
berghofe@41809
   249
               [@{thm pos_val}, range_pos, card_UNIV, th]) 1)
berghofe@41809
   250
      in (th, th') end) cs);
berghofe@41809
   251
berghofe@41809
   252
    val first_el = Goal.prove lthy' [] []
berghofe@41809
   253
      (HOLogic.mk_Trueprop (HOLogic.mk_eq
berghofe@41809
   254
         (Const (@{const_name first_el}, T), hd cs)))
berghofe@41809
   255
      (fn _ => simp_tac (simpset_of lthy' addsimps
berghofe@41809
   256
         [@{thm first_el_def}, hd val_eqs]) 1);
berghofe@41809
   257
berghofe@41809
   258
    val last_el = Goal.prove lthy' [] []
berghofe@41809
   259
      (HOLogic.mk_Trueprop (HOLogic.mk_eq
berghofe@41809
   260
         (Const (@{const_name last_el}, T), List.last cs)))
berghofe@41809
   261
      (fn _ => simp_tac (simpset_of lthy' addsimps
berghofe@41809
   262
         [@{thm last_el_def}, List.last val_eqs, card_UNIV]) 1);
berghofe@41809
   263
  in
berghofe@43227
   264
    lthy' |>
berghofe@43227
   265
    Local_Theory.note
wenzelm@46463
   266
      ((Binding.name (tyname ^ "_card"), @{attributes [simp]}), [card_UNIV]) ||>>
berghofe@43227
   267
    Local_Theory.note
wenzelm@46463
   268
      ((Binding.name (tyname ^ "_pos"), @{attributes [simp]}), pos_eqs) ||>>
berghofe@43227
   269
    Local_Theory.note
wenzelm@46463
   270
      ((Binding.name (tyname ^ "_val"), @{attributes [simp]}), val_eqs) ||>>
berghofe@43227
   271
    Local_Theory.note
wenzelm@46463
   272
      ((Binding.name (tyname ^ "_first_el"), @{attributes [simp]}), [first_el]) ||>>
berghofe@43227
   273
    Local_Theory.note
wenzelm@46463
   274
      ((Binding.name (tyname ^ "_last_el"), @{attributes [simp]}), [last_el]) |> snd |>
berghofe@43227
   275
    Local_Theory.exit_global
berghofe@41809
   276
  end;
berghofe@41809
   277
berghofe@41809
   278
berghofe@43267
   279
fun check_no_assoc thy prfx s = case get_type thy prfx s of
berghofe@43227
   280
    NONE => ()
berghofe@43227
   281
  | SOME _ => error ("Cannot associate a type with " ^ s ^
berghofe@43227
   282
      "\nsince it is no record or enumeration type");
berghofe@43227
   283
berghofe@43227
   284
fun check_enum [] [] = NONE 
berghofe@43227
   285
  | check_enum els [] = SOME ("has no element(s) " ^ commas els)
berghofe@43227
   286
  | check_enum [] cs = SOME ("has extra element(s) " ^
berghofe@43227
   287
      commas (map (Long_Name.base_name o fst) cs))
berghofe@43227
   288
  | check_enum (el :: els) ((cname, _) :: cs) =
berghofe@43227
   289
      if lcase_eq (el, cname) then check_enum els cs
berghofe@43227
   290
      else SOME ("either has no element " ^ el ^
berghofe@43227
   291
        " or it is at the wrong position");
berghofe@43227
   292
berghofe@43267
   293
fun add_type_def prfx (s, Basic_Type ty) (ids, thy) =
berghofe@43267
   294
      (check_no_assoc thy prfx s;
berghofe@43227
   295
       (ids,
berghofe@43227
   296
        Typedecl.abbrev_global (Binding.name s, [], NoSyn)
berghofe@43267
   297
          (mk_type thy prfx ty) thy |> snd))
berghofe@41809
   298
berghofe@43267
   299
  | add_type_def prfx (s, Enum_Type els) ((tab, ctxt), thy) =
berghofe@43227
   300
      let
berghofe@43267
   301
        val (thy', tyname) = (case get_type thy prfx s of
berghofe@43227
   302
            NONE =>
berghofe@43227
   303
              let
berghofe@43227
   304
                val tyb = Binding.name s;
berghofe@43227
   305
                val tyname = Sign.full_name thy tyb
berghofe@43227
   306
              in
berghofe@43227
   307
                (thy |>
wenzelm@46572
   308
                 Datatype.add_datatype {strict = true, quiet = true}
berghofe@43227
   309
                   [([], tyb, NoSyn,
berghofe@43227
   310
                     map (fn s => (Binding.name s, [], NoSyn)) els)] |> snd |>
berghofe@43227
   311
                 add_enum_type s tyname,
berghofe@43227
   312
                 tyname)
berghofe@43227
   313
              end
berghofe@43227
   314
          | SOME (T as Type (tyname, [])) =>
berghofe@43227
   315
              (case Datatype_Data.get_constrs thy tyname of
berghofe@43227
   316
                 NONE => assoc_ty_err thy T s "is not a datatype"
berghofe@43267
   317
               | SOME cs =>
berghofe@43267
   318
                   let
berghofe@43267
   319
                     val (prfx', _) = strip_prfx s;
berghofe@43267
   320
                     val els' =
berghofe@43267
   321
                       if prfx' = "" then els
berghofe@43267
   322
                       else map (unprefix (prfx' ^ "__")) els
berghofe@43267
   323
                         handle Fail _ => error ("Bad enumeration type " ^ s)
berghofe@43267
   324
                   in
berghofe@43267
   325
                     case check_enum els' cs of
berghofe@43267
   326
                       NONE => (thy, tyname)
berghofe@43267
   327
                     | SOME msg => assoc_ty_err thy T s msg
berghofe@43267
   328
                   end));
berghofe@43227
   329
        val cs = map Const (the (Datatype_Data.get_constrs thy' tyname))
berghofe@43227
   330
      in
berghofe@43227
   331
        ((fold (Symtab.update_new o apsnd (rpair s)) (els ~~ cs) tab,
berghofe@43227
   332
          fold Name.declare els ctxt),
berghofe@43227
   333
         thy')
berghofe@43227
   334
      end
berghofe@41809
   335
berghofe@43267
   336
  | add_type_def prfx (s, Array_Type (argtys, resty)) (ids, thy) =
berghofe@43267
   337
      (check_no_assoc thy prfx s;
berghofe@43227
   338
       (ids,
berghofe@43227
   339
        Typedecl.abbrev_global (Binding.name s, [], NoSyn)
berghofe@43267
   340
          (foldr1 HOLogic.mk_prodT (map (mk_type thy prfx) argtys) -->
berghofe@43267
   341
             mk_type thy prfx resty) thy |> snd))
berghofe@41809
   342
berghofe@43267
   343
  | add_type_def prfx (s, Record_Type fldtys) (ids, thy) =
berghofe@41809
   344
      (ids,
berghofe@43227
   345
       let val fldTs = maps (fn (flds, ty) =>
berghofe@43267
   346
         map (rpair (mk_type thy prfx ty)) flds) fldtys
berghofe@43267
   347
       in case get_type thy prfx s of
berghofe@43227
   348
           NONE =>
wenzelm@45524
   349
             Record.add_record ([], Binding.name s) NONE
berghofe@43227
   350
               (map (fn (fld, T) => (Binding.name fld, T, NoSyn)) fldTs) thy
berghofe@43227
   351
         | SOME rT =>
berghofe@43227
   352
             (case get_record_info thy rT of
berghofe@43227
   353
                NONE => assoc_ty_err thy rT s "is not a record type"
berghofe@43227
   354
              | SOME {fields, ...} =>
berghofe@43227
   355
                  (case subtract (lcase_eq o pairself fst) fldTs fields of
berghofe@43227
   356
                     [] => ()
berghofe@43227
   357
                   | flds => assoc_ty_err thy rT s ("has extra field(s) " ^
berghofe@43227
   358
                       commas (map (Long_Name.base_name o fst) flds));
berghofe@43227
   359
                   map (fn (fld, T) =>
berghofe@43227
   360
                     case AList.lookup lcase_eq fields fld of
berghofe@43227
   361
                       NONE => assoc_ty_err thy rT s ("has no field " ^ fld)
berghofe@43227
   362
                     | SOME U => T = U orelse assoc_ty_err thy rT s
berghofe@43227
   363
                         ("has field " ^
berghofe@43227
   364
                          fld ^ " whose type\n" ^
berghofe@43227
   365
                          Syntax.string_of_typ_global thy U ^
berghofe@43227
   366
                          "\ndoes not match declared type\n" ^
berghofe@43227
   367
                          Syntax.string_of_typ_global thy T)) fldTs;
berghofe@43227
   368
                   thy))
berghofe@43227
   369
       end)
berghofe@41809
   370
berghofe@43267
   371
  | add_type_def prfx (s, Pending_Type) (ids, thy) =
berghofe@44901
   372
      (ids,
berghofe@44901
   373
       case get_type thy prfx s of
berghofe@44901
   374
         SOME _ => thy
berghofe@44901
   375
       | NONE => Typedecl.typedecl_global
berghofe@44901
   376
           (Binding.name s, [], NoSyn) thy |> snd);
berghofe@41809
   377
berghofe@41809
   378
berghofe@43267
   379
fun term_of_expr thy prfx types pfuns =
berghofe@41809
   380
  let
berghofe@41809
   381
    fun tm_of vs (Funct ("->", [e, e'])) =
berghofe@41809
   382
          (HOLogic.mk_imp (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
berghofe@41809
   383
berghofe@41809
   384
      | tm_of vs (Funct ("<->", [e, e'])) =
berghofe@41809
   385
          (HOLogic.mk_eq (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
berghofe@41809
   386
berghofe@41809
   387
      | tm_of vs (Funct ("or", [e, e'])) =
berghofe@41809
   388
          (HOLogic.mk_disj (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
berghofe@41809
   389
berghofe@41809
   390
      | tm_of vs (Funct ("and", [e, e'])) =
berghofe@41809
   391
          (HOLogic.mk_conj (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
berghofe@41809
   392
berghofe@41809
   393
      | tm_of vs (Funct ("not", [e])) =
berghofe@41809
   394
          (HOLogic.mk_not (fst (tm_of vs e)), booleanN)
berghofe@41809
   395
berghofe@41809
   396
      | tm_of vs (Funct ("=", [e, e'])) =
berghofe@41809
   397
          (HOLogic.mk_eq (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
berghofe@41809
   398
berghofe@41809
   399
      | tm_of vs (Funct ("<>", [e, e'])) = (HOLogic.mk_not
berghofe@41809
   400
          (HOLogic.mk_eq (fst (tm_of vs e), fst (tm_of vs e'))), booleanN)
berghofe@41809
   401
berghofe@41809
   402
      | tm_of vs (Funct ("<", [e, e'])) = (HOLogic.mk_binrel @{const_name less}
berghofe@41809
   403
          (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
berghofe@41809
   404
berghofe@41809
   405
      | tm_of vs (Funct (">", [e, e'])) = (HOLogic.mk_binrel @{const_name less}
berghofe@41809
   406
          (fst (tm_of vs e'), fst (tm_of vs e)), booleanN)
berghofe@41809
   407
berghofe@41809
   408
      | tm_of vs (Funct ("<=", [e, e'])) = (HOLogic.mk_binrel @{const_name less_eq}
berghofe@41809
   409
          (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
berghofe@41809
   410
berghofe@41809
   411
      | tm_of vs (Funct (">=", [e, e'])) = (HOLogic.mk_binrel @{const_name less_eq}
berghofe@41809
   412
          (fst (tm_of vs e'), fst (tm_of vs e)), booleanN)
berghofe@41809
   413
berghofe@41809
   414
      | tm_of vs (Funct ("+", [e, e'])) = (HOLogic.mk_binop @{const_name plus}
berghofe@41809
   415
          (fst (tm_of vs e), fst (tm_of vs e')), integerN)
berghofe@41809
   416
berghofe@41809
   417
      | tm_of vs (Funct ("-", [e, e'])) = (HOLogic.mk_binop @{const_name minus}
berghofe@41809
   418
          (fst (tm_of vs e), fst (tm_of vs e')), integerN)
berghofe@41809
   419
berghofe@41809
   420
      | tm_of vs (Funct ("*", [e, e'])) = (HOLogic.mk_binop @{const_name times}
berghofe@41809
   421
          (fst (tm_of vs e), fst (tm_of vs e')), integerN)
berghofe@41809
   422
berghofe@41809
   423
      | tm_of vs (Funct ("/", [e, e'])) = (HOLogic.mk_binop @{const_name divide}
berghofe@41809
   424
          (fst (tm_of vs e), fst (tm_of vs e')), integerN)
berghofe@41809
   425
berghofe@41809
   426
      | tm_of vs (Funct ("div", [e, e'])) = (HOLogic.mk_binop @{const_name sdiv}
berghofe@41809
   427
          (fst (tm_of vs e), fst (tm_of vs e')), integerN)
berghofe@41809
   428
berghofe@41883
   429
      | tm_of vs (Funct ("mod", [e, e'])) = (HOLogic.mk_binop @{const_name mod}
berghofe@41809
   430
          (fst (tm_of vs e), fst (tm_of vs e')), integerN)
berghofe@41809
   431
berghofe@41809
   432
      | tm_of vs (Funct ("-", [e])) =
berghofe@41809
   433
          (mk_unop @{const_name uminus} (fst (tm_of vs e)), integerN)
berghofe@41809
   434
berghofe@41809
   435
      | tm_of vs (Funct ("**", [e, e'])) =
berghofe@41809
   436
          (Const (@{const_name power}, HOLogic.intT --> HOLogic.natT -->
berghofe@41809
   437
             HOLogic.intT) $ fst (tm_of vs e) $
berghofe@41809
   438
               (@{const nat} $ fst (tm_of vs e')), integerN)
berghofe@41809
   439
berghofe@41809
   440
      | tm_of (tab, _) (Ident s) =
berghofe@41809
   441
          (case Symtab.lookup tab s of
berghofe@41809
   442
             SOME t_ty => t_ty
berghofe@43370
   443
           | NONE => (case lookup_prfx prfx pfuns s of
berghofe@43370
   444
               SOME (SOME ([], resty), t) => (t, resty)
berghofe@43370
   445
             | _ => error ("Undeclared identifier " ^ s)))
berghofe@41809
   446
berghofe@41809
   447
      | tm_of _ (Number i) = (HOLogic.mk_number HOLogic.intT i, integerN)
berghofe@41809
   448
berghofe@41809
   449
      | tm_of vs (Quantifier (s, xs, ty, e)) =
berghofe@41809
   450
          let
berghofe@43267
   451
            val (ys, vs') = mk_variables thy prfx xs ty vs;
berghofe@41809
   452
            val q = (case s of
berghofe@41809
   453
                "for_all" => HOLogic.mk_all
berghofe@41809
   454
              | "for_some" => HOLogic.mk_exists)
berghofe@41809
   455
          in
berghofe@41809
   456
            (fold_rev (fn Free (x, T) => fn t => q (x, T, t))
berghofe@41809
   457
               ys (fst (tm_of vs' e)),
berghofe@41809
   458
             booleanN)
berghofe@41809
   459
          end
berghofe@41809
   460
berghofe@41809
   461
      | tm_of vs (Funct (s, es)) =
berghofe@41809
   462
berghofe@41809
   463
          (* record field selection *)
berghofe@41809
   464
          (case try (unprefix "fld_") s of
berghofe@41809
   465
             SOME fname => (case es of
berghofe@41809
   466
               [e] =>
berghofe@43227
   467
                 let
berghofe@43227
   468
                   val (t, rcdty) = tm_of vs e;
berghofe@43267
   469
                   val rT = mk_type thy prfx rcdty
berghofe@43227
   470
                 in case (get_record_info thy rT, lookup types rcdty) of
berghofe@43227
   471
                     (SOME {fields, ...}, SOME (Record_Type fldtys)) =>
berghofe@43227
   472
                       (case (find_field fname fields,
berghofe@43227
   473
                            find_field' fname fldtys) of
berghofe@43227
   474
                          (SOME (fname', fT), SOME fldty) =>
berghofe@43227
   475
                            (Const (fname', rT --> fT) $ t, fldty)
berghofe@43227
   476
                        | _ => error ("Record " ^ rcdty ^
berghofe@41809
   477
                            " has no field named " ^ fname))
berghofe@41809
   478
                   | _ => error (rcdty ^ " is not a record type")
berghofe@41809
   479
                 end
berghofe@41809
   480
             | _ => error ("Function " ^ s ^ " expects one argument"))
berghofe@41809
   481
           | NONE =>
berghofe@41809
   482
berghofe@41809
   483
          (* record field update *)
berghofe@41809
   484
          (case try (unprefix "upf_") s of
berghofe@41809
   485
             SOME fname => (case es of
berghofe@41809
   486
               [e, e'] =>
berghofe@41809
   487
                 let
berghofe@41809
   488
                   val (t, rcdty) = tm_of vs e;
berghofe@43267
   489
                   val rT = mk_type thy prfx rcdty;
berghofe@41809
   490
                   val (u, fldty) = tm_of vs e';
berghofe@43267
   491
                   val fT = mk_type thy prfx fldty
berghofe@43227
   492
                 in case get_record_info thy rT of
berghofe@43227
   493
                     SOME {fields, ...} =>
berghofe@43227
   494
                       (case find_field fname fields of
berghofe@43227
   495
                          SOME (fname', fU) =>
berghofe@43227
   496
                            if fT = fU then
berghofe@43227
   497
                              (Const (fname' ^ "_update",
berghofe@41809
   498
                                 (fT --> fT) --> rT --> rT) $
berghofe@41809
   499
                                   Abs ("x", fT, u) $ t,
berghofe@41809
   500
                               rcdty)
berghofe@43227
   501
                            else error ("Type\n" ^
berghofe@43227
   502
                              Syntax.string_of_typ_global thy fT ^
berghofe@43227
   503
                              "\ndoes not match type\n" ^
berghofe@43227
   504
                              Syntax.string_of_typ_global thy fU ^
berghofe@43227
   505
                              "\nof field " ^ fname)
berghofe@41809
   506
                        | NONE => error ("Record " ^ rcdty ^
berghofe@41809
   507
                            " has no field named " ^ fname))
berghofe@41809
   508
                   | _ => error (rcdty ^ " is not a record type")
berghofe@41809
   509
                 end
berghofe@41809
   510
             | _ => error ("Function " ^ s ^ " expects two arguments"))
berghofe@41809
   511
           | NONE =>
berghofe@41809
   512
berghofe@41809
   513
          (* enumeration type to integer *)
berghofe@41809
   514
          (case try (unsuffix "__pos") s of
berghofe@41809
   515
             SOME tyname => (case es of
berghofe@41809
   516
               [e] => (Const (@{const_name pos},
berghofe@43267
   517
                   mk_type thy prfx tyname --> HOLogic.intT) $ fst (tm_of vs e),
berghofe@43267
   518
                 integerN)
berghofe@41809
   519
             | _ => error ("Function " ^ s ^ " expects one argument"))
berghofe@41809
   520
           | NONE =>
berghofe@41809
   521
berghofe@41809
   522
          (* integer to enumeration type *)
berghofe@41809
   523
          (case try (unsuffix "__val") s of
berghofe@41809
   524
             SOME tyname => (case es of
berghofe@41809
   525
               [e] => (Const (@{const_name val},
berghofe@43267
   526
                   HOLogic.intT --> mk_type thy prfx tyname) $ fst (tm_of vs e),
berghofe@43267
   527
                 tyname)
berghofe@41809
   528
             | _ => error ("Function " ^ s ^ " expects one argument"))
berghofe@41809
   529
           | NONE =>
berghofe@41809
   530
berghofe@41809
   531
          (* successor / predecessor of enumeration type element *)
berghofe@41809
   532
          if s = "succ" orelse s = "pred" then (case es of
berghofe@41809
   533
              [e] =>
berghofe@41809
   534
                let
berghofe@41809
   535
                  val (t, tyname) = tm_of vs e;
berghofe@43267
   536
                  val T = mk_type thy prfx tyname
berghofe@41809
   537
                in (Const
berghofe@41809
   538
                  (if s = "succ" then @{const_name succ}
berghofe@41809
   539
                   else @{const_name pred}, T --> T) $ t, tyname)
berghofe@41809
   540
                end
berghofe@41809
   541
            | _ => error ("Function " ^ s ^ " expects one argument"))
berghofe@41809
   542
berghofe@41809
   543
          (* user-defined proof function *)
berghofe@41809
   544
          else
berghofe@43267
   545
            (case lookup_prfx prfx pfuns s of
berghofe@41809
   546
               SOME (SOME (_, resty), t) =>
berghofe@41809
   547
                 (list_comb (t, map (fst o tm_of vs) es), resty)
berghofe@41809
   548
             | _ => error ("Undeclared proof function " ^ s))))))
berghofe@41809
   549
berghofe@41809
   550
      | tm_of vs (Element (e, es)) =
berghofe@41809
   551
          let val (t, ty) = tm_of vs e
berghofe@41809
   552
          in case lookup types ty of
berghofe@41809
   553
              SOME (Array_Type (_, elty)) =>
berghofe@41809
   554
                (t $ foldr1 HOLogic.mk_prod (map (fst o tm_of vs) es), elty)
berghofe@41809
   555
            | _ => error (ty ^ " is not an array type")
berghofe@41809
   556
          end
berghofe@41809
   557
berghofe@41809
   558
      | tm_of vs (Update (e, es, e')) =
berghofe@41809
   559
          let val (t, ty) = tm_of vs e
berghofe@41809
   560
          in case lookup types ty of
berghofe@41809
   561
              SOME (Array_Type (idxtys, elty)) =>
berghofe@41809
   562
                let
berghofe@43267
   563
                  val T = foldr1 HOLogic.mk_prodT
berghofe@43267
   564
                    (map (mk_type thy prfx) idxtys);
berghofe@43267
   565
                  val U = mk_type thy prfx elty;
berghofe@41809
   566
                  val fT = T --> U
berghofe@41809
   567
                in
berghofe@41809
   568
                  (Const (@{const_name fun_upd}, fT --> T --> U --> fT) $
berghofe@41809
   569
                     t $ foldr1 HOLogic.mk_prod (map (fst o tm_of vs) es) $
berghofe@41809
   570
                       fst (tm_of vs e'),
berghofe@41809
   571
                   ty)
berghofe@41809
   572
                end
berghofe@41809
   573
            | _ => error (ty ^ " is not an array type")
berghofe@41809
   574
          end
berghofe@41809
   575
berghofe@41809
   576
      | tm_of vs (Record (s, flds)) =
berghofe@43227
   577
          let
berghofe@43267
   578
            val T = mk_type thy prfx s;
berghofe@43227
   579
            val {extension = (ext_name, _), fields, ...} =
berghofe@43227
   580
              (case get_record_info thy T of
berghofe@43227
   581
                 NONE => error (s ^ " is not a record type")
berghofe@43227
   582
               | SOME info => info);
berghofe@43227
   583
            val flds' = map (apsnd (tm_of vs)) flds;
berghofe@43227
   584
            val fnames = map (Long_Name.base_name o fst) fields;
berghofe@43227
   585
            val fnames' = map fst flds;
berghofe@43227
   586
            val (fvals, ftys) = split_list (map (fn s' =>
berghofe@43227
   587
              case AList.lookup lcase_eq flds' s' of
berghofe@43227
   588
                SOME fval_ty => fval_ty
berghofe@43227
   589
              | NONE => error ("Field " ^ s' ^ " missing in record " ^ s))
berghofe@43227
   590
                  fnames);
berghofe@43227
   591
            val _ = (case subtract lcase_eq fnames fnames' of
berghofe@43227
   592
                [] => ()
berghofe@43227
   593
              | xs => error ("Extra field(s) " ^ commas xs ^
berghofe@43227
   594
                  " in record " ^ s));
berghofe@43227
   595
            val _ = (case duplicates (op =) fnames' of
berghofe@43227
   596
                [] => ()
berghofe@43227
   597
              | xs => error ("Duplicate field(s) " ^ commas xs ^
berghofe@43227
   598
                  " in record " ^ s))
berghofe@43227
   599
          in
berghofe@43227
   600
            (list_comb
berghofe@43227
   601
               (Const (ext_name,
berghofe@43267
   602
                  map (mk_type thy prfx) ftys @ [HOLogic.unitT] ---> T),
berghofe@43227
   603
                fvals @ [HOLogic.unit]),
berghofe@43227
   604
             s)
berghofe@43227
   605
          end
berghofe@41809
   606
berghofe@41809
   607
      | tm_of vs (Array (s, default, assocs)) =
berghofe@41809
   608
          (case lookup types s of
berghofe@41809
   609
             SOME (Array_Type (idxtys, elty)) =>
berghofe@41809
   610
               let
berghofe@43267
   611
                 val Ts = map (mk_type thy prfx) idxtys;
berghofe@41809
   612
                 val T = foldr1 HOLogic.mk_prodT Ts;
berghofe@43267
   613
                 val U = mk_type thy prfx elty;
berghofe@41809
   614
                 fun mk_idx' T (e, NONE) = HOLogic.mk_set T [fst (tm_of vs e)]
berghofe@41809
   615
                   | mk_idx' T (e, SOME e') = Const (@{const_name atLeastAtMost},
berghofe@41809
   616
                       T --> T --> HOLogic.mk_setT T) $
berghofe@41809
   617
                         fst (tm_of vs e) $ fst (tm_of vs e');
berghofe@41809
   618
                 fun mk_idx idx =
berghofe@41809
   619
                   if length Ts <> length idx then
berghofe@41809
   620
                     error ("Arity mismatch in construction of array " ^ s)
berghofe@41809
   621
                   else foldr1 mk_times (map2 mk_idx' Ts idx);
berghofe@41809
   622
                 fun mk_upd (idxs, e) t =
berghofe@41809
   623
                   if length idxs = 1 andalso forall (is_none o snd) (hd idxs)
berghofe@41809
   624
                   then
berghofe@41809
   625
                     Const (@{const_name fun_upd}, (T --> U) -->
berghofe@41809
   626
                         T --> U --> T --> U) $ t $
berghofe@41809
   627
                       foldl1 HOLogic.mk_prod
berghofe@41809
   628
                         (map (fst o tm_of vs o fst) (hd idxs)) $
berghofe@41809
   629
                       fst (tm_of vs e)
berghofe@41809
   630
                   else
berghofe@41809
   631
                     Const (@{const_name fun_upds}, (T --> U) -->
berghofe@41809
   632
                         HOLogic.mk_setT T --> U --> T --> U) $ t $
berghofe@41809
   633
                       foldl1 (HOLogic.mk_binop @{const_name sup})
berghofe@41809
   634
                         (map mk_idx idxs) $
berghofe@41809
   635
                       fst (tm_of vs e)
berghofe@41809
   636
               in
berghofe@41809
   637
                 (fold mk_upd assocs
berghofe@41809
   638
                    (case default of
berghofe@41809
   639
                       SOME e => Abs ("x", T, fst (tm_of vs e))
berghofe@41809
   640
                     | NONE => Const (@{const_name undefined}, T --> U)),
berghofe@41809
   641
                  s)
berghofe@41809
   642
               end
berghofe@41809
   643
           | _ => error (s ^ " is not an array type"))
berghofe@41809
   644
berghofe@41809
   645
  in tm_of end;
berghofe@41809
   646
berghofe@41809
   647
berghofe@43267
   648
fun term_of_rule thy prfx types pfuns ids rule =
berghofe@43267
   649
  let val tm_of = fst o term_of_expr thy prfx types pfuns ids
berghofe@41809
   650
  in case rule of
berghofe@41809
   651
      Inference_Rule (es, e) => Logic.list_implies
berghofe@41809
   652
        (map (HOLogic.mk_Trueprop o tm_of) es, HOLogic.mk_Trueprop (tm_of e))
berghofe@41809
   653
    | Substitution_Rule (es, e, e') => Logic.list_implies
berghofe@41809
   654
        (map (HOLogic.mk_Trueprop o tm_of) es,
berghofe@41809
   655
         HOLogic.mk_Trueprop (HOLogic.mk_eq (tm_of e, tm_of e')))
berghofe@41809
   656
  end;
berghofe@41809
   657
berghofe@41809
   658
berghofe@41809
   659
val builtin = Symtab.make (map (rpair ())
berghofe@41809
   660
  ["->", "<->", "or", "and", "not", "=", "<>", "<", ">", "<=", ">=",
berghofe@41809
   661
   "+", "-", "*", "/", "div", "mod", "**"]);
berghofe@41809
   662
berghofe@41809
   663
fun complex_expr (Number _) = false
berghofe@41809
   664
  | complex_expr (Ident _) = false 
berghofe@41809
   665
  | complex_expr (Funct (s, es)) =
berghofe@41809
   666
      not (Symtab.defined builtin s) orelse exists complex_expr es
berghofe@41809
   667
  | complex_expr (Quantifier (_, _, _, e)) = complex_expr e
berghofe@41809
   668
  | complex_expr _ = true;
berghofe@41809
   669
berghofe@41809
   670
fun complex_rule (Inference_Rule (es, e)) =
berghofe@41809
   671
      complex_expr e orelse exists complex_expr es
berghofe@41809
   672
  | complex_rule (Substitution_Rule (es, e, e')) =
berghofe@41809
   673
      complex_expr e orelse complex_expr e' orelse
berghofe@41809
   674
      exists complex_expr es;
berghofe@41809
   675
berghofe@41809
   676
val is_pfun =
berghofe@41809
   677
  Symtab.defined builtin orf
berghofe@41809
   678
  can (unprefix "fld_") orf can (unprefix "upf_") orf
berghofe@41809
   679
  can (unsuffix "__pos") orf can (unsuffix "__val") orf
berghofe@41809
   680
  equal "succ" orf equal "pred";
berghofe@41809
   681
berghofe@41809
   682
fun fold_opt f = the_default I o Option.map f;
berghofe@41809
   683
fun fold_pair f g (x, y) = f x #> g y;
berghofe@41809
   684
berghofe@41809
   685
fun fold_expr f g (Funct (s, es)) = f s #> fold (fold_expr f g) es
berghofe@41809
   686
  | fold_expr f g (Ident s) = g s
berghofe@41809
   687
  | fold_expr f g (Number _) = I
berghofe@41809
   688
  | fold_expr f g (Quantifier (_, _, _, e)) = fold_expr f g e
berghofe@41809
   689
  | fold_expr f g (Element (e, es)) =
berghofe@41809
   690
      fold_expr f g e #> fold (fold_expr f g) es
berghofe@41809
   691
  | fold_expr f g (Update (e, es, e')) =
berghofe@41809
   692
      fold_expr f g e #> fold (fold_expr f g) es #> fold_expr f g e'
berghofe@41809
   693
  | fold_expr f g (Record (_, flds)) = fold (fold_expr f g o snd) flds
berghofe@41809
   694
  | fold_expr f g (Array (_, default, assocs)) =
berghofe@41809
   695
      fold_opt (fold_expr f g) default #>
berghofe@41809
   696
      fold (fold_pair
berghofe@41809
   697
        (fold (fold (fold_pair
berghofe@41809
   698
          (fold_expr f g) (fold_opt (fold_expr f g)))))
berghofe@41809
   699
        (fold_expr f g)) assocs;
berghofe@41809
   700
berghofe@43370
   701
fun add_expr_pfuns funs = fold_expr
berghofe@43370
   702
  (fn s => if is_pfun s then I else insert (op =) s)
berghofe@43370
   703
  (fn s => if is_none (lookup funs s) then I else insert (op =) s);
berghofe@41809
   704
berghofe@41809
   705
val add_expr_idents = fold_expr (K I) (insert (op =));
berghofe@41809
   706
berghofe@43267
   707
fun pfun_type thy prfx (argtys, resty) =
berghofe@43267
   708
  map (mk_type thy prfx) argtys ---> mk_type thy prfx resty;
berghofe@41809
   709
berghofe@43267
   710
fun check_pfun_type thy prfx s t optty1 optty2 =
berghofe@41809
   711
  let
berghofe@41809
   712
    val T = fastype_of t;
berghofe@41809
   713
    fun check ty =
berghofe@43267
   714
      let val U = pfun_type thy prfx ty
berghofe@41809
   715
      in
berghofe@41809
   716
        T = U orelse
berghofe@41809
   717
        error ("Type\n" ^
berghofe@41809
   718
          Syntax.string_of_typ_global thy T ^
berghofe@41809
   719
          "\nof function " ^
berghofe@41809
   720
          Syntax.string_of_term_global thy t ^
berghofe@41809
   721
          " associated with proof function " ^ s ^
berghofe@41809
   722
          "\ndoes not match declared type\n" ^
berghofe@41809
   723
          Syntax.string_of_typ_global thy U)
berghofe@41809
   724
      end
berghofe@41809
   725
  in (Option.map check optty1; Option.map check optty2; ()) end;
berghofe@41809
   726
berghofe@41809
   727
fun upd_option x y = if is_some x then x else y;
berghofe@41809
   728
berghofe@43267
   729
fun check_pfuns_types thy prfx funs =
berghofe@41809
   730
  Symtab.map (fn s => fn (optty, t) =>
berghofe@43267
   731
   let val optty' = lookup funs
berghofe@43267
   732
     (if prfx = "" then s
berghofe@43267
   733
      else unprefix (prfx ^ "__") s handle Fail _ => s)
berghofe@41809
   734
   in
berghofe@43267
   735
     (check_pfun_type thy prfx s t optty optty';
berghofe@41809
   736
      (NONE |> upd_option optty |> upd_option optty', t))
berghofe@41809
   737
   end);
berghofe@41809
   738
berghofe@41809
   739
berghofe@41809
   740
(** the VC store **)
berghofe@41809
   741
berghofe@41809
   742
fun err_vcs names = error (Pretty.string_of
berghofe@41809
   743
  (Pretty.big_list "The following verification conditions have not been proved:"
berghofe@41809
   744
    (map Pretty.str names)))
berghofe@41809
   745
berghofe@43267
   746
fun set_env (env as {funs, prefix, ...}) thy = VCs.map (fn
berghofe@43227
   747
    {pfuns, type_map, env = NONE} =>
berghofe@43267
   748
      {pfuns = check_pfuns_types thy prefix funs pfuns,
berghofe@43227
   749
       type_map = type_map,
berghofe@43227
   750
       env = SOME env}
berghofe@41809
   751
  | _ => err_unfinished ()) thy;
berghofe@41809
   752
berghofe@41809
   753
fun mk_pat s = (case Int.fromString s of
berghofe@41809
   754
    SOME i => [HOLogic.mk_Trueprop (Var (("C", i), HOLogic.boolT))]
berghofe@41809
   755
  | NONE => error ("Bad conclusion identifier: C" ^ s));
berghofe@41809
   756
berghofe@43267
   757
fun mk_vc thy prfx types pfuns ids (tr, proved, ps, cs) =
berghofe@41809
   758
  let val prop_of =
berghofe@43267
   759
    HOLogic.mk_Trueprop o fst o term_of_expr thy prfx types pfuns ids
berghofe@41809
   760
  in
berghofe@41809
   761
    (tr, proved,
berghofe@41809
   762
     Element.Assumes (map (fn (s', e) =>
berghofe@41809
   763
       ((Binding.name ("H" ^ s'), []), [(prop_of e, [])])) ps),
berghofe@41809
   764
     Element.Shows (map (fn (s', e) =>
berghofe@41809
   765
       (Attrib.empty_binding, [(prop_of e, mk_pat s')])) cs))
berghofe@41809
   766
  end;
berghofe@41809
   767
berghofe@41809
   768
fun fold_vcs f vcs =
berghofe@41809
   769
  VCtab.fold (fn (_, (_, _, ps, cs)) => fold f ps #> fold f cs) vcs;
berghofe@41809
   770
berghofe@43370
   771
fun pfuns_of_vcs prfx funs pfuns vcs =
berghofe@43370
   772
  fold_vcs (add_expr_pfuns funs o snd) vcs [] |>
berghofe@43267
   773
  filter (is_none o lookup_prfx prfx pfuns);
berghofe@41809
   774
berghofe@43267
   775
fun declare_missing_pfuns thy prfx funs pfuns vcs (tab, ctxt) =
berghofe@41809
   776
  let
berghofe@41809
   777
    val (fs, (tys, Ts)) =
berghofe@43370
   778
      pfuns_of_vcs prfx funs pfuns vcs |>
berghofe@41809
   779
      map_filter (fn s => lookup funs s |>
berghofe@43267
   780
        Option.map (fn ty => (s, (SOME ty, pfun_type thy prfx ty)))) |>
berghofe@41809
   781
      split_list ||> split_list;
wenzelm@44208
   782
    val (fs', ctxt') = fold_map Name.variant fs ctxt
berghofe@41809
   783
  in
berghofe@41809
   784
    (fold Symtab.update_new (fs ~~ (tys ~~ map Free (fs' ~~ Ts))) pfuns,
berghofe@41809
   785
     Element.Fixes (map2 (fn s => fn T =>
berghofe@41809
   786
       (Binding.name s, SOME T, NoSyn)) fs' Ts),
berghofe@41809
   787
     (tab, ctxt'))
berghofe@41809
   788
  end;
berghofe@41809
   789
berghofe@41809
   790
fun add_proof_fun prep (s, (optty, raw_t)) thy =
berghofe@41809
   791
  VCs.map (fn
berghofe@41809
   792
      {env = SOME {proving = true, ...}, ...} => err_unfinished ()
berghofe@43227
   793
    | {pfuns, type_map, env} =>
berghofe@41809
   794
        let
berghofe@43267
   795
          val (optty', prfx) = (case env of
berghofe@43267
   796
              SOME {funs, prefix, ...} => (lookup funs s, prefix)
berghofe@43267
   797
            | NONE => (NONE, ""));
berghofe@41809
   798
          val optty'' = NONE |> upd_option optty |> upd_option optty';
berghofe@43267
   799
          val t = prep (Option.map (pfun_type thy prfx) optty'') raw_t;
berghofe@43227
   800
          val _ = (case fold_aterms (fn u =>
berghofe@43227
   801
              if is_Var u orelse is_Free u then insert (op =) u else I) t [] of
berghofe@43227
   802
              [] => ()
berghofe@43227
   803
            | ts => error ("Term\n" ^ Syntax.string_of_term_global thy t ^
berghofe@43227
   804
                "\nto be associated with proof function " ^ s ^
berghofe@43227
   805
                " contains free variable(s) " ^
berghofe@43227
   806
                commas (map (Syntax.string_of_term_global thy) ts)));
berghofe@41809
   807
        in
berghofe@43267
   808
          (check_pfun_type thy prfx s t optty optty';
berghofe@41809
   809
           if is_some optty'' orelse is_none env then
berghofe@41809
   810
             {pfuns = Symtab.update_new (s, (optty'', t)) pfuns,
berghofe@43227
   811
              type_map = type_map,
berghofe@41809
   812
              env = env}
berghofe@41809
   813
               handle Symtab.DUP _ => error ("Proof function " ^ s ^
berghofe@41809
   814
                 " already associated with function")
berghofe@41809
   815
           else error ("Undeclared proof function " ^ s))
berghofe@41809
   816
        end) thy;
berghofe@41809
   817
berghofe@43227
   818
fun add_type (s, T as Type (tyname, Ts)) thy =
berghofe@43227
   819
      thy |>
berghofe@43227
   820
      VCs.map (fn
berghofe@43227
   821
          {env = SOME _, ...} => err_unfinished ()
berghofe@43227
   822
        | {pfuns, type_map, env} =>
berghofe@43227
   823
            {pfuns = pfuns,
berghofe@43227
   824
             type_map = Symtab.update_new (s, T) type_map,
berghofe@43227
   825
             env = env}
berghofe@43227
   826
              handle Symtab.DUP _ => error ("SPARK type " ^ s ^
berghofe@43227
   827
                " already associated with type")) |>
berghofe@43227
   828
      (fn thy' =>
berghofe@43227
   829
         case Datatype_Data.get_constrs thy' tyname of
berghofe@43227
   830
           NONE => thy'
berghofe@43227
   831
         | SOME cs =>
berghofe@43227
   832
             if null Ts then
berghofe@43227
   833
               (map
berghofe@43227
   834
                  (fn (_, Type (_, [])) => ()
berghofe@43227
   835
                    | (cname, _) => assoc_ty_err thy T s
berghofe@43227
   836
                        ("has illegal constructor " ^
berghofe@43227
   837
                         Long_Name.base_name cname)) cs;
berghofe@43227
   838
                add_enum_type s tyname thy')
berghofe@43227
   839
             else assoc_ty_err thy T s "is illegal")
berghofe@43227
   840
  | add_type (s, T) thy = assoc_ty_err thy T s "is illegal";
berghofe@43227
   841
berghofe@41809
   842
val is_closed = is_none o #env o VCs.get;
berghofe@41809
   843
berghofe@41809
   844
fun lookup_vc thy name =
berghofe@41809
   845
  (case VCs.get thy of
berghofe@43267
   846
    {env = SOME {vcs, types, funs, ids, ctxt, prefix, ...}, pfuns, ...} =>
berghofe@41809
   847
      (case VCtab.lookup vcs name of
berghofe@43267
   848
         SOME vc =>
berghofe@41809
   849
           let val (pfuns', ctxt', ids') =
berghofe@43267
   850
             declare_missing_pfuns thy prefix funs pfuns vcs ids
berghofe@43267
   851
           in SOME (ctxt @ [ctxt'], mk_vc thy prefix types pfuns' ids' vc) end
berghofe@41809
   852
       | NONE => NONE)
berghofe@41809
   853
  | _ => NONE);
berghofe@41809
   854
berghofe@41809
   855
fun get_vcs thy = (case VCs.get thy of
berghofe@43267
   856
    {env = SOME {vcs, types, funs, ids, ctxt, defs, prefix, ...}, pfuns, ...} =>
berghofe@41809
   857
      let val (pfuns', ctxt', ids') =
berghofe@43267
   858
        declare_missing_pfuns thy prefix funs pfuns vcs ids
berghofe@41809
   859
      in
berghofe@41809
   860
        (ctxt @ [ctxt'], defs,
berghofe@41809
   861
         VCtab.dest vcs |>
berghofe@43267
   862
         map (apsnd (mk_vc thy prefix types pfuns' ids')))
berghofe@41809
   863
      end
berghofe@41809
   864
  | _ => ([], [], []));
berghofe@41809
   865
berghofe@42767
   866
fun mark_proved name thms = VCs.map (fn
berghofe@43227
   867
    {pfuns, type_map,
berghofe@43267
   868
     env = SOME {ctxt, defs, types, funs, ids, vcs, path, prefix, ...}} =>
berghofe@41809
   869
      {pfuns = pfuns,
berghofe@43227
   870
       type_map = type_map,
berghofe@41809
   871
       env = SOME {ctxt = ctxt, defs = defs,
berghofe@41809
   872
         types = types, funs = funs, ids = ids,
berghofe@41809
   873
         proving = true,
berghofe@41809
   874
         vcs = VCtab.map_entry name (fn (trace, _, ps, cs) =>
berghofe@42767
   875
           (trace, SOME thms, ps, cs)) vcs,
berghofe@43267
   876
         path = path,
berghofe@43267
   877
         prefix = prefix}}
berghofe@41809
   878
  | x => x);
berghofe@41809
   879
berghofe@43227
   880
fun close thy =
berghofe@43227
   881
  thy |>
berghofe@43227
   882
  VCs.map (fn
berghofe@43227
   883
      {pfuns, type_map, env = SOME {vcs, path, ...}} =>
berghofe@43227
   884
        (case VCtab.fold_rev (fn vc as (_, (_, p, _, _)) =>
berghofe@43227
   885
             (if is_some p then apfst else apsnd) (cons vc)) vcs ([], []) of
berghofe@43227
   886
           (proved, []) =>
berghofe@43227
   887
             (Thm.join_proofs (maps (the o #2 o snd) proved);
wenzelm@46457
   888
              File.write (Path.ext "prv" path)
wenzelm@44577
   889
                (implode (map (fn (s, _) => snd (strip_number s) ^
berghofe@43227
   890
                   " -- proved by " ^ Distribution.version ^ "\n") proved));
berghofe@43227
   891
              {pfuns = pfuns, type_map = type_map, env = NONE})
berghofe@43227
   892
         | (_, unproved) => err_vcs (map fst unproved))
berghofe@43227
   893
    | _ => error "No SPARK environment is currently open") |>
berghofe@43227
   894
  Sign.parent_path;
berghofe@41809
   895
berghofe@41809
   896
berghofe@41809
   897
(** set up verification conditions **)
berghofe@41809
   898
berghofe@41809
   899
fun partition_opt f =
berghofe@41809
   900
  let
berghofe@41809
   901
    fun part ys zs [] = (rev ys, rev zs)
berghofe@41809
   902
      | part ys zs (x :: xs) = (case f x of
berghofe@41809
   903
            SOME y => part (y :: ys) zs xs
berghofe@41809
   904
          | NONE => part ys (x :: zs) xs)
berghofe@41809
   905
  in part [] [] end;
berghofe@41809
   906
berghofe@41809
   907
fun dest_def (id, (Substitution_Rule ([], Ident s, rhs))) = SOME (id, (s, rhs))
berghofe@41809
   908
  | dest_def _ = NONE;
berghofe@41809
   909
berghofe@41809
   910
fun mk_rulename (s, i) = Binding.name (s ^ string_of_int i);
berghofe@41809
   911
berghofe@43267
   912
fun add_const prfx (s, ty) ((tab, ctxt), thy) =
berghofe@41809
   913
  let
berghofe@43267
   914
    val T = mk_type thy prfx ty;
berghofe@41809
   915
    val b = Binding.name s;
berghofe@41809
   916
    val c = Const (Sign.full_name thy b, T)
berghofe@41809
   917
  in
berghofe@41809
   918
    (c,
berghofe@41809
   919
     ((Symtab.update (s, (c, ty)) tab, Name.declare s ctxt),
berghofe@41809
   920
      Sign.add_consts_i [(b, T, NoSyn)] thy))
berghofe@41809
   921
  end;
berghofe@41809
   922
berghofe@43267
   923
fun add_def prfx types pfuns consts (id, (s, e)) (ids as (tab, ctxt), thy) =
berghofe@41809
   924
  (case lookup consts s of
berghofe@41809
   925
     SOME ty =>
berghofe@41809
   926
       let
berghofe@43267
   927
         val (t, ty') = term_of_expr thy prfx types pfuns ids e;
berghofe@43267
   928
         val T = mk_type thy prfx ty;
berghofe@43267
   929
         val T' = mk_type thy prfx ty';
berghofe@42749
   930
         val _ = T = T' orelse
berghofe@41809
   931
           error ("Declared type " ^ ty ^ " of " ^ s ^
berghofe@41809
   932
             "\ndoes not match type " ^ ty' ^ " in definition");
berghofe@41809
   933
         val id' = mk_rulename id;
berghofe@41809
   934
         val lthy = Named_Target.theory_init thy;
berghofe@41809
   935
         val ((t', (_, th)), lthy') = Specification.definition
berghofe@41809
   936
           (NONE, ((id', []), HOLogic.mk_Trueprop (HOLogic.mk_eq
berghofe@42749
   937
             (Free (s, T), t)))) lthy;
wenzelm@43232
   938
         val phi = Proof_Context.export_morphism lthy' lthy
berghofe@41809
   939
       in
berghofe@41809
   940
         ((id', Morphism.thm phi th),
berghofe@41809
   941
          ((Symtab.update (s, (Morphism.term phi t', ty)) tab,
berghofe@41809
   942
            Name.declare s ctxt),
berghofe@41809
   943
           Local_Theory.exit_global lthy'))
berghofe@41809
   944
       end
berghofe@41809
   945
   | NONE => error ("Undeclared constant " ^ s));
berghofe@41809
   946
berghofe@43267
   947
fun add_var prfx (s, ty) (ids, thy) =
berghofe@43267
   948
  let val ([Free p], ids') = mk_variables thy prfx [s] ty ids
berghofe@41809
   949
  in (p, (ids', thy)) end;
berghofe@41809
   950
berghofe@43267
   951
fun add_init_vars prfx vcs (ids_thy as ((tab, _), _)) =
berghofe@43267
   952
  fold_map (add_var prfx)
berghofe@41809
   953
    (map_filter
berghofe@41809
   954
       (fn s => case try (unsuffix "~") s of
berghofe@41809
   955
          SOME s' => (case Symtab.lookup tab s' of
berghofe@41809
   956
            SOME (_, ty) => SOME (s, ty)
berghofe@41809
   957
          | NONE => error ("Undeclared identifier " ^ s'))
berghofe@41809
   958
        | NONE => NONE)
berghofe@41809
   959
       (fold_vcs (add_expr_idents o snd) vcs []))
berghofe@41809
   960
    ids_thy;
berghofe@41809
   961
berghofe@41809
   962
fun is_trivial_vc ([], [(_, Ident "true")]) = true
berghofe@41809
   963
  | is_trivial_vc _ = false;
berghofe@41809
   964
berghofe@41809
   965
fun rulenames rules = commas
berghofe@41809
   966
  (map (fn ((s, i), _) => s ^ "(" ^ string_of_int i ^ ")") rules);
berghofe@41809
   967
berghofe@41809
   968
(* sort definitions according to their dependency *)
berghofe@43370
   969
fun sort_defs _ _ _ _ [] sdefs = rev sdefs
berghofe@43370
   970
  | sort_defs prfx funs pfuns consts defs sdefs =
berghofe@41809
   971
      (case find_first (fn (_, (_, e)) =>
berghofe@43370
   972
         forall (is_some o lookup_prfx prfx pfuns)
berghofe@43370
   973
           (add_expr_pfuns funs e []) andalso
berghofe@41809
   974
         forall (fn id =>
berghofe@41809
   975
           member (fn (s, (_, (s', _))) => s = s') sdefs id orelse
berghofe@42749
   976
           consts id)
berghofe@41809
   977
             (add_expr_idents e [])) defs of
berghofe@43370
   978
         SOME d => sort_defs prfx funs pfuns consts
berghofe@41809
   979
           (remove (op =) d defs) (d :: sdefs)
berghofe@41809
   980
       | NONE => error ("Bad definitions: " ^ rulenames defs));
berghofe@41809
   981
berghofe@43227
   982
fun set_vcs ({types, vars, consts, funs} : decls)
berghofe@43267
   983
      (rules, _) ((_, ident), vcs) path prfx thy =
berghofe@41809
   984
  let
berghofe@41809
   985
    val {pfuns, ...} = VCs.get thy;
berghofe@42749
   986
    val (defs, rules') = partition_opt dest_def rules;
berghofe@41809
   987
    val consts' =
berghofe@42749
   988
      subtract (fn ((_, (s, _)), (s', _)) => s = s') defs (items consts);
berghofe@41809
   989
    (* ignore all complex rules in rls files *)
berghofe@41809
   990
    val (rules'', other_rules) =
berghofe@41809
   991
      List.partition (complex_rule o snd) rules';
berghofe@41809
   992
    val _ = if null rules'' then ()
berghofe@41809
   993
      else warning ("Ignoring rules: " ^ rulenames rules'');
berghofe@41809
   994
berghofe@41809
   995
    val vcs' = VCtab.make (maps (fn (tr, vcs) =>
berghofe@42767
   996
      map (fn (s, (ps, cs)) => (s, (tr, NONE, ps, cs)))
berghofe@41809
   997
        (filter_out (is_trivial_vc o snd) vcs)) vcs);
berghofe@41809
   998
berghofe@41809
   999
    val _ = (case filter_out (is_some o lookup funs)
berghofe@43370
  1000
        (pfuns_of_vcs prfx funs pfuns vcs') of
berghofe@41809
  1001
        [] => ()
berghofe@41809
  1002
      | fs => error ("Undeclared proof function(s) " ^ commas fs));
berghofe@41809
  1003
berghofe@41809
  1004
    val (((defs', vars''), ivars), (ids, thy')) =
berghofe@41809
  1005
      ((Symtab.empty |>
berghofe@41809
  1006
        Symtab.update ("false", (HOLogic.false_const, booleanN)) |>
berghofe@41809
  1007
        Symtab.update ("true", (HOLogic.true_const, booleanN)),
berghofe@43227
  1008
        Name.context),
berghofe@43227
  1009
       thy |> Sign.add_path (Long_Name.base_name ident)) |>
berghofe@43267
  1010
      fold (add_type_def prfx) (items types) |>
berghofe@43267
  1011
      fold (snd oo add_const prfx) consts' |> (fn ids_thy as ((tab, _), _) =>
berghofe@42749
  1012
        ids_thy |>
berghofe@43267
  1013
        fold_map (add_def prfx types pfuns consts)
berghofe@43370
  1014
          (sort_defs prfx funs pfuns (Symtab.defined tab) defs []) ||>>
berghofe@43267
  1015
        fold_map (add_var prfx) (items vars) ||>>
berghofe@43267
  1016
        add_init_vars prfx vcs');
berghofe@41809
  1017
berghofe@41809
  1018
    val ctxt =
berghofe@41809
  1019
      [Element.Fixes (map (fn (s, T) =>
berghofe@41809
  1020
         (Binding.name s, SOME T, NoSyn)) (vars'' @ ivars)),
berghofe@41809
  1021
       Element.Assumes (map (fn (id, rl) =>
berghofe@41809
  1022
         ((mk_rulename id, []),
berghofe@43267
  1023
          [(term_of_rule thy' prfx types pfuns ids rl, [])]))
berghofe@41809
  1024
           other_rules),
wenzelm@43311
  1025
       Element.Notes ("", [((Binding.name "defns", []), map (rpair [] o single o snd) defs')])]
berghofe@41809
  1026
          
berghofe@41809
  1027
  in
berghofe@41809
  1028
    set_env {ctxt = ctxt, defs = defs', types = types, funs = funs,
berghofe@43267
  1029
      ids = ids, proving = false, vcs = vcs', path = path, prefix = prfx} thy'
berghofe@41809
  1030
  end;
berghofe@41809
  1031
berghofe@41809
  1032
end;