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