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