1 (* Title: HOL/SPARK/Tools/spark_vcs.ML
2 Author: Stefan Berghofer
3 Copyright: secunet Security Networks AG
5 Store for verification conditions generated by SPARK/Ada.
10 val set_vcs: Fdl_Parser.decls -> Fdl_Parser.rules ->
11 (string * string) * Fdl_Parser.vcs -> Path.T -> string -> theory -> theory
12 val add_proof_fun: (typ option -> 'a -> term) ->
13 string * ((string list * string) option * 'a) ->
15 val add_type: string * typ -> theory -> theory
16 val lookup_vc: theory -> string -> (Element.context_i list *
17 (string * thm list option * Element.context_i * Element.statement_i)) option
18 val get_vcs: theory ->
19 Element.context_i list * (binding * thm) list * (string *
20 (string * thm list option * Element.context_i * Element.statement_i)) list
21 val mark_proved: string -> thm list -> theory -> theory
22 val close: theory -> theory
23 val is_closed: theory -> bool
26 structure SPARK_VCs: SPARK_VCS =
34 fun err_unfinished () = error "An unfinished SPARK environment is still open."
36 val strip_number = pairself implode o take_suffix Fdl_Lexer.is_digit o raw_explode;
38 val name_ord = prod_ord string_ord (option_ord int_ord) o
39 pairself (strip_number ##> Int.fromString);
41 structure VCtab = Table(type key = string val ord = name_ord);
43 structure VCs = Theory_Data
46 {pfuns: ((string list * string) option * term) Symtab.table,
47 type_map: typ Symtab.table,
49 {ctxt: Element.context_i list,
50 defs: (binding * thm) list,
52 funs: (string list * string) tab,
53 ids: (term * string) Symtab.table * Name.context,
55 vcs: (string * thm list option *
56 (string * expr) list * (string * expr) list) VCtab.table,
58 prefix: string} option}
59 val empty : T = {pfuns = Symtab.empty, type_map = Symtab.empty, env = NONE}
61 fun merge ({pfuns = pfuns1, type_map = type_map1, env = NONE},
62 {pfuns = pfuns2, type_map = type_map2, env = NONE}) =
63 {pfuns = Symtab.merge (eq_pair (op =) (op aconv)) (pfuns1, pfuns2),
64 type_map = Symtab.merge (op =) (type_map1, type_map2),
66 | merge _ = err_unfinished ()
72 val to_lower = raw_explode #> map Symbol.to_ascii_lower #> implode;
74 val lcase_eq = (op =) o pairself (to_lower o Long_Name.base_name);
76 fun lookup_prfx "" tab s = Symtab.lookup tab s
77 | lookup_prfx prfx tab s = (case Symtab.lookup tab s of
78 NONE => Symtab.lookup tab (prfx ^ "__" ^ s)
83 fun strip ys [] = ("", implode ys)
84 | strip ys ("_" :: "_" :: xs) = (implode (rev xs), implode ys)
85 | strip ys (x :: xs) = strip (x :: ys) xs
86 in strip [] (rev (raw_explode s)) end;
89 let val T = fastype_of t
90 in Const (s, T --> T) $ t end;
94 val setT = fastype_of t;
95 val T = HOLogic.dest_setT setT;
96 val U = HOLogic.dest_setT (fastype_of u)
98 Const (@{const_name Sigma}, setT --> (T --> HOLogic.mk_setT U) -->
99 HOLogic.mk_setT (HOLogic.mk_prodT (T, U))) $ t $ Abs ("", T, u)
102 fun get_type thy prfx ty =
103 let val {type_map, ...} = VCs.get thy
104 in lookup_prfx prfx type_map ty end;
106 fun mk_type _ _ "integer" = HOLogic.intT
107 | mk_type _ _ "boolean" = HOLogic.boolT
108 | mk_type thy prfx ty =
109 (case get_type thy prfx ty of
111 Syntax.check_typ (Proof_Context.init_global thy)
112 (Type (Sign.full_name thy (Binding.name ty), []))
115 val booleanN = "boolean";
116 val integerN = "integer";
118 fun define_overloaded (def_name, eq) lthy =
120 val ((c, _), rhs) = eq |> Syntax.check_term lthy |>
121 Logic.dest_equals |>> dest_Free;
122 val ((_, (_, thm)), lthy') = Local_Theory.define
123 ((Binding.name c, NoSyn), ((Binding.name def_name, []), rhs)) lthy
124 val ctxt_thy = Proof_Context.init_global (Proof_Context.theory_of lthy');
125 val thm' = singleton (Proof_Context.export lthy' ctxt_thy) thm
126 in (thm', lthy') end;
128 fun strip_underscores s =
129 strip_underscores (unsuffix "_" s) handle Fail _ => s;
132 unsuffix "~" s ^ "_init" handle Fail _ => s;
134 val mangle_name = strip_underscores #> strip_tilde;
136 fun mk_variables thy prfx xs ty (tab, ctxt) =
138 val T = mk_type thy prfx ty;
139 val (ys, ctxt') = Name.variants (map mangle_name xs) ctxt;
140 val zs = map (Free o rpair T) ys;
141 in (zs, (fold (Symtab.update o apsnd (rpair ty)) (xs ~~ zs) tab, ctxt')) end;
143 fun get_record_info thy T = (case Record.dest_recTs T of
144 [(tyname, [@{typ unit}])] =>
145 Record.get_info thy (Long_Name.qualifier tyname)
148 fun find_field fname = find_first (curry lcase_eq fname o fst);
150 fun find_field' fname = get_first (fn (flds, fldty) =>
151 if member (op =) flds fname then SOME fldty else NONE);
153 fun assoc_ty_err thy T s msg =
154 error ("Type " ^ Syntax.string_of_typ_global thy T ^
155 " associated with SPARK type " ^ s ^ "\n" ^ msg);
158 (** generate properties of enumeration types **)
160 fun add_enum_type tyname tyname' thy =
162 val {case_name, ...} = the (Datatype_Data.get_info thy tyname');
163 val cs = map Const (the (Datatype_Data.get_constrs thy tyname'));
165 val T = Type (tyname', []);
166 val p = Const (@{const_name pos}, T --> HOLogic.intT);
167 val v = Const (@{const_name val}, HOLogic.intT --> T);
168 val card = Const (@{const_name card},
169 HOLogic.mk_setT T --> HOLogic.natT) $ HOLogic.mk_UNIV T;
171 fun mk_binrel_def s f = Logic.mk_equals
172 (Const (s, T --> T --> HOLogic.boolT),
173 Abs ("x", T, Abs ("y", T,
174 Const (s, HOLogic.intT --> HOLogic.intT --> HOLogic.boolT) $
175 (f $ Bound 1) $ (f $ Bound 0))));
177 val (((def1, def2), def3), lthy) = thy |>
179 Class.instantiation ([tyname'], [], @{sort spark_enum}) |>
181 define_overloaded ("pos_" ^ tyname ^ "_def", Logic.mk_equals
183 list_comb (Const (case_name, replicate k HOLogic.intT @
184 [T] ---> HOLogic.intT),
185 map (HOLogic.mk_number HOLogic.intT) (0 upto k - 1)))) ||>>
187 define_overloaded ("less_eq_" ^ tyname ^ "_def",
188 mk_binrel_def @{const_name less_eq} p) ||>>
189 define_overloaded ("less_" ^ tyname ^ "_def",
190 mk_binrel_def @{const_name less} p);
192 val UNIV_eq = Goal.prove lthy [] []
193 (HOLogic.mk_Trueprop (HOLogic.mk_eq
194 (HOLogic.mk_UNIV T, HOLogic.mk_set T cs)))
196 rtac @{thm subset_antisym} 1 THEN
197 rtac @{thm subsetI} 1 THEN
198 Datatype_Aux.exh_tac (K (#exhaust (Datatype_Data.the_info
199 (Proof_Context.theory_of lthy) tyname'))) 1 THEN
200 ALLGOALS (asm_full_simp_tac (simpset_of lthy)));
202 val finite_UNIV = Goal.prove lthy [] []
203 (HOLogic.mk_Trueprop (Const (@{const_name finite},
204 HOLogic.mk_setT T --> HOLogic.boolT) $ HOLogic.mk_UNIV T))
205 (fn _ => simp_tac (simpset_of lthy addsimps [UNIV_eq]) 1);
207 val card_UNIV = Goal.prove lthy [] []
208 (HOLogic.mk_Trueprop (HOLogic.mk_eq
209 (card, HOLogic.mk_number HOLogic.natT k)))
210 (fn _ => simp_tac (simpset_of lthy addsimps [UNIV_eq]) 1);
212 val range_pos = Goal.prove lthy [] []
213 (HOLogic.mk_Trueprop (HOLogic.mk_eq
214 (Const (@{const_name image}, (T --> HOLogic.intT) -->
215 HOLogic.mk_setT T --> HOLogic.mk_setT HOLogic.intT) $
216 p $ HOLogic.mk_UNIV T,
217 Const (@{const_name atLeastLessThan}, HOLogic.intT -->
218 HOLogic.intT --> HOLogic.mk_setT HOLogic.intT) $
219 HOLogic.mk_number HOLogic.intT 0 $
220 (@{term int} $ card))))
222 simp_tac (simpset_of lthy addsimps [card_UNIV]) 1 THEN
223 simp_tac (simpset_of lthy addsimps [UNIV_eq, def1]) 1 THEN
224 rtac @{thm subset_antisym} 1 THEN
225 simp_tac (simpset_of lthy) 1 THEN
226 rtac @{thm subsetI} 1 THEN
227 asm_full_simp_tac (simpset_of lthy addsimps @{thms interval_expand}
228 delsimps @{thms atLeastLessThan_iff}) 1);
231 Class.prove_instantiation_instance (fn _ =>
232 Class.intro_classes_tac [] THEN
233 rtac finite_UNIV 1 THEN
234 rtac range_pos 1 THEN
235 simp_tac (HOL_basic_ss addsimps [def3]) 1 THEN
236 simp_tac (HOL_basic_ss addsimps [def2]) 1) lthy;
238 val (pos_eqs, val_eqs) = split_list (map_index (fn (i, c) =>
240 val n = HOLogic.mk_number HOLogic.intT i;
241 val th = Goal.prove lthy' [] []
242 (HOLogic.mk_Trueprop (HOLogic.mk_eq (p $ c, n)))
243 (fn _ => simp_tac (simpset_of lthy' addsimps [def1]) 1);
244 val th' = Goal.prove lthy' [] []
245 (HOLogic.mk_Trueprop (HOLogic.mk_eq (v $ n, c)))
247 rtac (@{thm inj_pos} RS @{thm injD}) 1 THEN
248 simp_tac (simpset_of lthy' addsimps
249 [@{thm pos_val}, range_pos, card_UNIV, th]) 1)
250 in (th, th') end) cs);
252 val first_el = Goal.prove lthy' [] []
253 (HOLogic.mk_Trueprop (HOLogic.mk_eq
254 (Const (@{const_name first_el}, T), hd cs)))
255 (fn _ => simp_tac (simpset_of lthy' addsimps
256 [@{thm first_el_def}, hd val_eqs]) 1);
258 val last_el = Goal.prove lthy' [] []
259 (HOLogic.mk_Trueprop (HOLogic.mk_eq
260 (Const (@{const_name last_el}, T), List.last cs)))
261 (fn _ => simp_tac (simpset_of lthy' addsimps
262 [@{thm last_el_def}, List.last val_eqs, card_UNIV]) 1);
264 val simp_att = [Attrib.internal (K Simplifier.simp_add)]
269 ((Binding.name (tyname ^ "_card"), simp_att), [card_UNIV]) ||>>
271 ((Binding.name (tyname ^ "_pos"), simp_att), pos_eqs) ||>>
273 ((Binding.name (tyname ^ "_val"), simp_att), val_eqs) ||>>
275 ((Binding.name (tyname ^ "_first_el"), simp_att), [first_el]) ||>>
277 ((Binding.name (tyname ^ "_last_el"), simp_att), [last_el]) |> snd |>
278 Local_Theory.exit_global
282 fun check_no_assoc thy prfx s = case get_type thy prfx s of
284 | SOME _ => error ("Cannot associate a type with " ^ s ^
285 "\nsince it is no record or enumeration type");
287 fun check_enum [] [] = NONE
288 | check_enum els [] = SOME ("has no element(s) " ^ commas els)
289 | check_enum [] cs = SOME ("has extra element(s) " ^
290 commas (map (Long_Name.base_name o fst) cs))
291 | check_enum (el :: els) ((cname, _) :: cs) =
292 if lcase_eq (el, cname) then check_enum els cs
293 else SOME ("either has no element " ^ el ^
294 " or it is at the wrong position");
296 fun add_type_def prfx (s, Basic_Type ty) (ids, thy) =
297 (check_no_assoc thy prfx s;
299 Typedecl.abbrev_global (Binding.name s, [], NoSyn)
300 (mk_type thy prfx ty) thy |> snd))
302 | add_type_def prfx (s, Enum_Type els) ((tab, ctxt), thy) =
304 val (thy', tyname) = (case get_type thy prfx s of
307 val tyb = Binding.name s;
308 val tyname = Sign.full_name thy tyb
311 Datatype.add_datatype {strict = true, quiet = true} [s]
313 map (fn s => (Binding.name s, [], NoSyn)) els)] |> snd |>
314 add_enum_type s tyname,
317 | SOME (T as Type (tyname, [])) =>
318 (case Datatype_Data.get_constrs thy tyname of
319 NONE => assoc_ty_err thy T s "is not a datatype"
322 val (prfx', _) = strip_prfx s;
324 if prfx' = "" then els
325 else map (unprefix (prfx' ^ "__")) els
326 handle Fail _ => error ("Bad enumeration type " ^ s)
328 case check_enum els' cs of
329 NONE => (thy, tyname)
330 | SOME msg => assoc_ty_err thy T s msg
332 val cs = map Const (the (Datatype_Data.get_constrs thy' tyname))
334 ((fold (Symtab.update_new o apsnd (rpair s)) (els ~~ cs) tab,
335 fold Name.declare els ctxt),
339 | add_type_def prfx (s, Array_Type (argtys, resty)) (ids, thy) =
340 (check_no_assoc thy prfx s;
342 Typedecl.abbrev_global (Binding.name s, [], NoSyn)
343 (foldr1 HOLogic.mk_prodT (map (mk_type thy prfx) argtys) -->
344 mk_type thy prfx resty) thy |> snd))
346 | add_type_def prfx (s, Record_Type fldtys) (ids, thy) =
348 let val fldTs = maps (fn (flds, ty) =>
349 map (rpair (mk_type thy prfx ty)) flds) fldtys
350 in case get_type thy prfx s of
352 Record.add_record true ([], Binding.name s) NONE
353 (map (fn (fld, T) => (Binding.name fld, T, NoSyn)) fldTs) thy
355 (case get_record_info thy rT of
356 NONE => assoc_ty_err thy rT s "is not a record type"
357 | SOME {fields, ...} =>
358 (case subtract (lcase_eq o pairself fst) fldTs fields of
360 | flds => assoc_ty_err thy rT s ("has extra field(s) " ^
361 commas (map (Long_Name.base_name o fst) flds));
363 case AList.lookup lcase_eq fields fld of
364 NONE => assoc_ty_err thy rT s ("has no field " ^ fld)
365 | SOME U => T = U orelse assoc_ty_err thy rT s
367 fld ^ " whose type\n" ^
368 Syntax.string_of_typ_global thy U ^
369 "\ndoes not match declared type\n" ^
370 Syntax.string_of_typ_global thy T)) fldTs;
374 | add_type_def prfx (s, Pending_Type) (ids, thy) =
375 (check_no_assoc thy prfx s;
376 (ids, Typedecl.typedecl_global (Binding.name s, [], NoSyn) thy |> snd));
379 fun term_of_expr thy prfx types pfuns =
381 fun tm_of vs (Funct ("->", [e, e'])) =
382 (HOLogic.mk_imp (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
384 | tm_of vs (Funct ("<->", [e, e'])) =
385 (HOLogic.mk_eq (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
387 | tm_of vs (Funct ("or", [e, e'])) =
388 (HOLogic.mk_disj (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
390 | tm_of vs (Funct ("and", [e, e'])) =
391 (HOLogic.mk_conj (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
393 | tm_of vs (Funct ("not", [e])) =
394 (HOLogic.mk_not (fst (tm_of vs e)), booleanN)
396 | tm_of vs (Funct ("=", [e, e'])) =
397 (HOLogic.mk_eq (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
399 | tm_of vs (Funct ("<>", [e, e'])) = (HOLogic.mk_not
400 (HOLogic.mk_eq (fst (tm_of vs e), fst (tm_of vs e'))), booleanN)
402 | tm_of vs (Funct ("<", [e, e'])) = (HOLogic.mk_binrel @{const_name less}
403 (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
405 | tm_of vs (Funct (">", [e, e'])) = (HOLogic.mk_binrel @{const_name less}
406 (fst (tm_of vs e'), fst (tm_of vs e)), booleanN)
408 | tm_of vs (Funct ("<=", [e, e'])) = (HOLogic.mk_binrel @{const_name less_eq}
409 (fst (tm_of vs e), fst (tm_of vs e')), booleanN)
411 | tm_of vs (Funct (">=", [e, e'])) = (HOLogic.mk_binrel @{const_name less_eq}
412 (fst (tm_of vs e'), fst (tm_of vs e)), booleanN)
414 | tm_of vs (Funct ("+", [e, e'])) = (HOLogic.mk_binop @{const_name plus}
415 (fst (tm_of vs e), fst (tm_of vs e')), integerN)
417 | tm_of vs (Funct ("-", [e, e'])) = (HOLogic.mk_binop @{const_name minus}
418 (fst (tm_of vs e), fst (tm_of vs e')), integerN)
420 | tm_of vs (Funct ("*", [e, e'])) = (HOLogic.mk_binop @{const_name times}
421 (fst (tm_of vs e), fst (tm_of vs e')), integerN)
423 | tm_of vs (Funct ("/", [e, e'])) = (HOLogic.mk_binop @{const_name divide}
424 (fst (tm_of vs e), fst (tm_of vs e')), integerN)
426 | tm_of vs (Funct ("div", [e, e'])) = (HOLogic.mk_binop @{const_name sdiv}
427 (fst (tm_of vs e), fst (tm_of vs e')), integerN)
429 | tm_of vs (Funct ("mod", [e, e'])) = (HOLogic.mk_binop @{const_name mod}
430 (fst (tm_of vs e), fst (tm_of vs e')), integerN)
432 | tm_of vs (Funct ("-", [e])) =
433 (mk_unop @{const_name uminus} (fst (tm_of vs e)), integerN)
435 | tm_of vs (Funct ("**", [e, e'])) =
436 (Const (@{const_name power}, HOLogic.intT --> HOLogic.natT -->
437 HOLogic.intT) $ fst (tm_of vs e) $
438 (@{const nat} $ fst (tm_of vs e')), integerN)
440 | tm_of (tab, _) (Ident s) =
441 (case Symtab.lookup tab s of
443 | NONE => error ("Undeclared identifier " ^ s))
445 | tm_of _ (Number i) = (HOLogic.mk_number HOLogic.intT i, integerN)
447 | tm_of vs (Quantifier (s, xs, ty, e)) =
449 val (ys, vs') = mk_variables thy prfx xs ty vs;
451 "for_all" => HOLogic.mk_all
452 | "for_some" => HOLogic.mk_exists)
454 (fold_rev (fn Free (x, T) => fn t => q (x, T, t))
455 ys (fst (tm_of vs' e)),
459 | tm_of vs (Funct (s, es)) =
461 (* record field selection *)
462 (case try (unprefix "fld_") s of
463 SOME fname => (case es of
466 val (t, rcdty) = tm_of vs e;
467 val rT = mk_type thy prfx rcdty
468 in case (get_record_info thy rT, lookup types rcdty) of
469 (SOME {fields, ...}, SOME (Record_Type fldtys)) =>
470 (case (find_field fname fields,
471 find_field' fname fldtys) of
472 (SOME (fname', fT), SOME fldty) =>
473 (Const (fname', rT --> fT) $ t, fldty)
474 | _ => error ("Record " ^ rcdty ^
475 " has no field named " ^ fname))
476 | _ => error (rcdty ^ " is not a record type")
478 | _ => error ("Function " ^ s ^ " expects one argument"))
481 (* record field update *)
482 (case try (unprefix "upf_") s of
483 SOME fname => (case es of
486 val (t, rcdty) = tm_of vs e;
487 val rT = mk_type thy prfx rcdty;
488 val (u, fldty) = tm_of vs e';
489 val fT = mk_type thy prfx fldty
490 in case get_record_info thy rT of
491 SOME {fields, ...} =>
492 (case find_field fname fields of
495 (Const (fname' ^ "_update",
496 (fT --> fT) --> rT --> rT) $
497 Abs ("x", fT, u) $ t,
499 else error ("Type\n" ^
500 Syntax.string_of_typ_global thy fT ^
501 "\ndoes not match type\n" ^
502 Syntax.string_of_typ_global thy fU ^
503 "\nof field " ^ fname)
504 | NONE => error ("Record " ^ rcdty ^
505 " has no field named " ^ fname))
506 | _ => error (rcdty ^ " is not a record type")
508 | _ => error ("Function " ^ s ^ " expects two arguments"))
511 (* enumeration type to integer *)
512 (case try (unsuffix "__pos") s of
513 SOME tyname => (case es of
514 [e] => (Const (@{const_name pos},
515 mk_type thy prfx tyname --> HOLogic.intT) $ fst (tm_of vs e),
517 | _ => error ("Function " ^ s ^ " expects one argument"))
520 (* integer to enumeration type *)
521 (case try (unsuffix "__val") s of
522 SOME tyname => (case es of
523 [e] => (Const (@{const_name val},
524 HOLogic.intT --> mk_type thy prfx tyname) $ fst (tm_of vs e),
526 | _ => error ("Function " ^ s ^ " expects one argument"))
529 (* successor / predecessor of enumeration type element *)
530 if s = "succ" orelse s = "pred" then (case es of
533 val (t, tyname) = tm_of vs e;
534 val T = mk_type thy prfx tyname
536 (if s = "succ" then @{const_name succ}
537 else @{const_name pred}, T --> T) $ t, tyname)
539 | _ => error ("Function " ^ s ^ " expects one argument"))
541 (* user-defined proof function *)
543 (case lookup_prfx prfx pfuns s of
544 SOME (SOME (_, resty), t) =>
545 (list_comb (t, map (fst o tm_of vs) es), resty)
546 | _ => error ("Undeclared proof function " ^ s))))))
548 | tm_of vs (Element (e, es)) =
549 let val (t, ty) = tm_of vs e
550 in case lookup types ty of
551 SOME (Array_Type (_, elty)) =>
552 (t $ foldr1 HOLogic.mk_prod (map (fst o tm_of vs) es), elty)
553 | _ => error (ty ^ " is not an array type")
556 | tm_of vs (Update (e, es, e')) =
557 let val (t, ty) = tm_of vs e
558 in case lookup types ty of
559 SOME (Array_Type (idxtys, elty)) =>
561 val T = foldr1 HOLogic.mk_prodT
562 (map (mk_type thy prfx) idxtys);
563 val U = mk_type thy prfx elty;
566 (Const (@{const_name fun_upd}, fT --> T --> U --> fT) $
567 t $ foldr1 HOLogic.mk_prod (map (fst o tm_of vs) es) $
571 | _ => error (ty ^ " is not an array type")
574 | tm_of vs (Record (s, flds)) =
576 val T = mk_type thy prfx s;
577 val {extension = (ext_name, _), fields, ...} =
578 (case get_record_info thy T of
579 NONE => error (s ^ " is not a record type")
580 | SOME info => info);
581 val flds' = map (apsnd (tm_of vs)) flds;
582 val fnames = map (Long_Name.base_name o fst) fields;
583 val fnames' = map fst flds;
584 val (fvals, ftys) = split_list (map (fn s' =>
585 case AList.lookup lcase_eq flds' s' of
586 SOME fval_ty => fval_ty
587 | NONE => error ("Field " ^ s' ^ " missing in record " ^ s))
589 val _ = (case subtract lcase_eq fnames fnames' of
591 | xs => error ("Extra field(s) " ^ commas xs ^
593 val _ = (case duplicates (op =) fnames' of
595 | xs => error ("Duplicate field(s) " ^ commas xs ^
600 map (mk_type thy prfx) ftys @ [HOLogic.unitT] ---> T),
601 fvals @ [HOLogic.unit]),
605 | tm_of vs (Array (s, default, assocs)) =
606 (case lookup types s of
607 SOME (Array_Type (idxtys, elty)) =>
609 val Ts = map (mk_type thy prfx) idxtys;
610 val T = foldr1 HOLogic.mk_prodT Ts;
611 val U = mk_type thy prfx elty;
612 fun mk_idx' T (e, NONE) = HOLogic.mk_set T [fst (tm_of vs e)]
613 | mk_idx' T (e, SOME e') = Const (@{const_name atLeastAtMost},
614 T --> T --> HOLogic.mk_setT T) $
615 fst (tm_of vs e) $ fst (tm_of vs e');
617 if length Ts <> length idx then
618 error ("Arity mismatch in construction of array " ^ s)
619 else foldr1 mk_times (map2 mk_idx' Ts idx);
620 fun mk_upd (idxs, e) t =
621 if length idxs = 1 andalso forall (is_none o snd) (hd idxs)
623 Const (@{const_name fun_upd}, (T --> U) -->
624 T --> U --> T --> U) $ t $
625 foldl1 HOLogic.mk_prod
626 (map (fst o tm_of vs o fst) (hd idxs)) $
629 Const (@{const_name fun_upds}, (T --> U) -->
630 HOLogic.mk_setT T --> U --> T --> U) $ t $
631 foldl1 (HOLogic.mk_binop @{const_name sup})
637 SOME e => Abs ("x", T, fst (tm_of vs e))
638 | NONE => Const (@{const_name undefined}, T --> U)),
641 | _ => error (s ^ " is not an array type"))
646 fun term_of_rule thy prfx types pfuns ids rule =
647 let val tm_of = fst o term_of_expr thy prfx types pfuns ids
649 Inference_Rule (es, e) => Logic.list_implies
650 (map (HOLogic.mk_Trueprop o tm_of) es, HOLogic.mk_Trueprop (tm_of e))
651 | Substitution_Rule (es, e, e') => Logic.list_implies
652 (map (HOLogic.mk_Trueprop o tm_of) es,
653 HOLogic.mk_Trueprop (HOLogic.mk_eq (tm_of e, tm_of e')))
657 val builtin = Symtab.make (map (rpair ())
658 ["->", "<->", "or", "and", "not", "=", "<>", "<", ">", "<=", ">=",
659 "+", "-", "*", "/", "div", "mod", "**"]);
661 fun complex_expr (Number _) = false
662 | complex_expr (Ident _) = false
663 | complex_expr (Funct (s, es)) =
664 not (Symtab.defined builtin s) orelse exists complex_expr es
665 | complex_expr (Quantifier (_, _, _, e)) = complex_expr e
666 | complex_expr _ = true;
668 fun complex_rule (Inference_Rule (es, e)) =
669 complex_expr e orelse exists complex_expr es
670 | complex_rule (Substitution_Rule (es, e, e')) =
671 complex_expr e orelse complex_expr e' orelse
672 exists complex_expr es;
675 Symtab.defined builtin orf
676 can (unprefix "fld_") orf can (unprefix "upf_") orf
677 can (unsuffix "__pos") orf can (unsuffix "__val") orf
678 equal "succ" orf equal "pred";
680 fun fold_opt f = the_default I o Option.map f;
681 fun fold_pair f g (x, y) = f x #> g y;
683 fun fold_expr f g (Funct (s, es)) = f s #> fold (fold_expr f g) es
684 | fold_expr f g (Ident s) = g s
685 | fold_expr f g (Number _) = I
686 | fold_expr f g (Quantifier (_, _, _, e)) = fold_expr f g e
687 | fold_expr f g (Element (e, es)) =
688 fold_expr f g e #> fold (fold_expr f g) es
689 | fold_expr f g (Update (e, es, e')) =
690 fold_expr f g e #> fold (fold_expr f g) es #> fold_expr f g e'
691 | fold_expr f g (Record (_, flds)) = fold (fold_expr f g o snd) flds
692 | fold_expr f g (Array (_, default, assocs)) =
693 fold_opt (fold_expr f g) default #>
695 (fold (fold (fold_pair
696 (fold_expr f g) (fold_opt (fold_expr f g)))))
697 (fold_expr f g)) assocs;
699 val add_expr_pfuns = fold_expr
700 (fn s => if is_pfun s then I else insert (op =) s) (K I);
702 val add_expr_idents = fold_expr (K I) (insert (op =));
704 fun pfun_type thy prfx (argtys, resty) =
705 map (mk_type thy prfx) argtys ---> mk_type thy prfx resty;
707 fun check_pfun_type thy prfx s t optty1 optty2 =
709 val T = fastype_of t;
711 let val U = pfun_type thy prfx ty
715 Syntax.string_of_typ_global thy T ^
717 Syntax.string_of_term_global thy t ^
718 " associated with proof function " ^ s ^
719 "\ndoes not match declared type\n" ^
720 Syntax.string_of_typ_global thy U)
722 in (Option.map check optty1; Option.map check optty2; ()) end;
724 fun upd_option x y = if is_some x then x else y;
726 fun check_pfuns_types thy prfx funs =
727 Symtab.map (fn s => fn (optty, t) =>
728 let val optty' = lookup funs
730 else unprefix (prfx ^ "__") s handle Fail _ => s)
732 (check_pfun_type thy prfx s t optty optty';
733 (NONE |> upd_option optty |> upd_option optty', t))
739 fun err_vcs names = error (Pretty.string_of
740 (Pretty.big_list "The following verification conditions have not been proved:"
741 (map Pretty.str names)))
743 fun set_env (env as {funs, prefix, ...}) thy = VCs.map (fn
744 {pfuns, type_map, env = NONE} =>
745 {pfuns = check_pfuns_types thy prefix funs pfuns,
748 | _ => err_unfinished ()) thy;
750 fun mk_pat s = (case Int.fromString s of
751 SOME i => [HOLogic.mk_Trueprop (Var (("C", i), HOLogic.boolT))]
752 | NONE => error ("Bad conclusion identifier: C" ^ s));
754 fun mk_vc thy prfx types pfuns ids (tr, proved, ps, cs) =
756 HOLogic.mk_Trueprop o fst o term_of_expr thy prfx types pfuns ids
759 Element.Assumes (map (fn (s', e) =>
760 ((Binding.name ("H" ^ s'), []), [(prop_of e, [])])) ps),
761 Element.Shows (map (fn (s', e) =>
762 (Attrib.empty_binding, [(prop_of e, mk_pat s')])) cs))
766 VCtab.fold (fn (_, (_, _, ps, cs)) => fold f ps #> fold f cs) vcs;
768 fun pfuns_of_vcs prfx pfuns vcs =
769 fold_vcs (add_expr_pfuns o snd) vcs [] |>
770 filter (is_none o lookup_prfx prfx pfuns);
772 fun declare_missing_pfuns thy prfx funs pfuns vcs (tab, ctxt) =
774 val (fs, (tys, Ts)) =
775 pfuns_of_vcs prfx pfuns vcs |>
776 map_filter (fn s => lookup funs s |>
777 Option.map (fn ty => (s, (SOME ty, pfun_type thy prfx ty)))) |>
778 split_list ||> split_list;
779 val (fs', ctxt') = Name.variants fs ctxt
781 (fold Symtab.update_new (fs ~~ (tys ~~ map Free (fs' ~~ Ts))) pfuns,
782 Element.Fixes (map2 (fn s => fn T =>
783 (Binding.name s, SOME T, NoSyn)) fs' Ts),
787 fun add_proof_fun prep (s, (optty, raw_t)) thy =
789 {env = SOME {proving = true, ...}, ...} => err_unfinished ()
790 | {pfuns, type_map, env} =>
792 val (optty', prfx) = (case env of
793 SOME {funs, prefix, ...} => (lookup funs s, prefix)
794 | NONE => (NONE, ""));
795 val optty'' = NONE |> upd_option optty |> upd_option optty';
796 val t = prep (Option.map (pfun_type thy prfx) optty'') raw_t;
797 val _ = (case fold_aterms (fn u =>
798 if is_Var u orelse is_Free u then insert (op =) u else I) t [] of
800 | ts => error ("Term\n" ^ Syntax.string_of_term_global thy t ^
801 "\nto be associated with proof function " ^ s ^
802 " contains free variable(s) " ^
803 commas (map (Syntax.string_of_term_global thy) ts)));
805 (check_pfun_type thy prfx s t optty optty';
806 if is_some optty'' orelse is_none env then
807 {pfuns = Symtab.update_new (s, (optty'', t)) pfuns,
810 handle Symtab.DUP _ => error ("Proof function " ^ s ^
811 " already associated with function")
812 else error ("Undeclared proof function " ^ s))
815 fun add_type (s, T as Type (tyname, Ts)) thy =
818 {env = SOME _, ...} => err_unfinished ()
819 | {pfuns, type_map, env} =>
821 type_map = Symtab.update_new (s, T) type_map,
823 handle Symtab.DUP _ => error ("SPARK type " ^ s ^
824 " already associated with type")) |>
826 case Datatype_Data.get_constrs thy' tyname of
831 (fn (_, Type (_, [])) => ()
832 | (cname, _) => assoc_ty_err thy T s
833 ("has illegal constructor " ^
834 Long_Name.base_name cname)) cs;
835 add_enum_type s tyname thy')
836 else assoc_ty_err thy T s "is illegal")
837 | add_type (s, T) thy = assoc_ty_err thy T s "is illegal";
839 val is_closed = is_none o #env o VCs.get;
841 fun lookup_vc thy name =
843 {env = SOME {vcs, types, funs, ids, ctxt, prefix, ...}, pfuns, ...} =>
844 (case VCtab.lookup vcs name of
846 let val (pfuns', ctxt', ids') =
847 declare_missing_pfuns thy prefix funs pfuns vcs ids
848 in SOME (ctxt @ [ctxt'], mk_vc thy prefix types pfuns' ids' vc) end
852 fun get_vcs thy = (case VCs.get thy of
853 {env = SOME {vcs, types, funs, ids, ctxt, defs, prefix, ...}, pfuns, ...} =>
854 let val (pfuns', ctxt', ids') =
855 declare_missing_pfuns thy prefix funs pfuns vcs ids
857 (ctxt @ [ctxt'], defs,
859 map (apsnd (mk_vc thy prefix types pfuns' ids')))
861 | _ => ([], [], []));
863 fun mark_proved name thms = VCs.map (fn
865 env = SOME {ctxt, defs, types, funs, ids, vcs, path, prefix, ...}} =>
868 env = SOME {ctxt = ctxt, defs = defs,
869 types = types, funs = funs, ids = ids,
871 vcs = VCtab.map_entry name (fn (trace, _, ps, cs) =>
872 (trace, SOME thms, ps, cs)) vcs,
880 {pfuns, type_map, env = SOME {vcs, path, ...}} =>
881 (case VCtab.fold_rev (fn vc as (_, (_, p, _, _)) =>
882 (if is_some p then apfst else apsnd) (cons vc)) vcs ([], []) of
884 (Thm.join_proofs (maps (the o #2 o snd) proved);
885 File.write (Path.ext "prv" path)
886 (concat (map (fn (s, _) => snd (strip_number s) ^
887 " -- proved by " ^ Distribution.version ^ "\n") proved));
888 {pfuns = pfuns, type_map = type_map, env = NONE})
889 | (_, unproved) => err_vcs (map fst unproved))
890 | _ => error "No SPARK environment is currently open") |>
894 (** set up verification conditions **)
896 fun partition_opt f =
898 fun part ys zs [] = (rev ys, rev zs)
899 | part ys zs (x :: xs) = (case f x of
900 SOME y => part (y :: ys) zs xs
901 | NONE => part ys (x :: zs) xs)
904 fun dest_def (id, (Substitution_Rule ([], Ident s, rhs))) = SOME (id, (s, rhs))
907 fun mk_rulename (s, i) = Binding.name (s ^ string_of_int i);
909 fun add_const prfx (s, ty) ((tab, ctxt), thy) =
911 val T = mk_type thy prfx ty;
912 val b = Binding.name s;
913 val c = Const (Sign.full_name thy b, T)
916 ((Symtab.update (s, (c, ty)) tab, Name.declare s ctxt),
917 Sign.add_consts_i [(b, T, NoSyn)] thy))
920 fun add_def prfx types pfuns consts (id, (s, e)) (ids as (tab, ctxt), thy) =
921 (case lookup consts s of
924 val (t, ty') = term_of_expr thy prfx types pfuns ids e;
925 val T = mk_type thy prfx ty;
926 val T' = mk_type thy prfx ty';
927 val _ = T = T' orelse
928 error ("Declared type " ^ ty ^ " of " ^ s ^
929 "\ndoes not match type " ^ ty' ^ " in definition");
930 val id' = mk_rulename id;
931 val lthy = Named_Target.theory_init thy;
932 val ((t', (_, th)), lthy') = Specification.definition
933 (NONE, ((id', []), HOLogic.mk_Trueprop (HOLogic.mk_eq
934 (Free (s, T), t)))) lthy;
935 val phi = Proof_Context.export_morphism lthy' lthy
937 ((id', Morphism.thm phi th),
938 ((Symtab.update (s, (Morphism.term phi t', ty)) tab,
939 Name.declare s ctxt),
940 Local_Theory.exit_global lthy'))
942 | NONE => error ("Undeclared constant " ^ s));
944 fun add_var prfx (s, ty) (ids, thy) =
945 let val ([Free p], ids') = mk_variables thy prfx [s] ty ids
946 in (p, (ids', thy)) end;
948 fun add_init_vars prfx vcs (ids_thy as ((tab, _), _)) =
949 fold_map (add_var prfx)
951 (fn s => case try (unsuffix "~") s of
952 SOME s' => (case Symtab.lookup tab s' of
953 SOME (_, ty) => SOME (s, ty)
954 | NONE => error ("Undeclared identifier " ^ s'))
956 (fold_vcs (add_expr_idents o snd) vcs []))
959 fun is_trivial_vc ([], [(_, Ident "true")]) = true
960 | is_trivial_vc _ = false;
962 fun rulenames rules = commas
963 (map (fn ((s, i), _) => s ^ "(" ^ string_of_int i ^ ")") rules);
965 (* sort definitions according to their dependency *)
966 fun sort_defs _ _ _ [] sdefs = rev sdefs
967 | sort_defs prfx pfuns consts defs sdefs =
968 (case find_first (fn (_, (_, e)) =>
969 forall (is_some o lookup_prfx prfx pfuns) (add_expr_pfuns e []) andalso
971 member (fn (s, (_, (s', _))) => s = s') sdefs id orelse
973 (add_expr_idents e [])) defs of
974 SOME d => sort_defs prfx pfuns consts
975 (remove (op =) d defs) (d :: sdefs)
976 | NONE => error ("Bad definitions: " ^ rulenames defs));
978 fun set_vcs ({types, vars, consts, funs} : decls)
979 (rules, _) ((_, ident), vcs) path prfx thy =
981 val {pfuns, ...} = VCs.get thy;
982 val (defs, rules') = partition_opt dest_def rules;
984 subtract (fn ((_, (s, _)), (s', _)) => s = s') defs (items consts);
985 (* ignore all complex rules in rls files *)
986 val (rules'', other_rules) =
987 List.partition (complex_rule o snd) rules';
988 val _ = if null rules'' then ()
989 else warning ("Ignoring rules: " ^ rulenames rules'');
991 val vcs' = VCtab.make (maps (fn (tr, vcs) =>
992 map (fn (s, (ps, cs)) => (s, (tr, NONE, ps, cs)))
993 (filter_out (is_trivial_vc o snd) vcs)) vcs);
995 val _ = (case filter_out (is_some o lookup funs)
996 (pfuns_of_vcs prfx pfuns vcs') of
998 | fs => error ("Undeclared proof function(s) " ^ commas fs));
1000 val (((defs', vars''), ivars), (ids, thy')) =
1002 Symtab.update ("false", (HOLogic.false_const, booleanN)) |>
1003 Symtab.update ("true", (HOLogic.true_const, booleanN)),
1005 thy |> Sign.add_path (Long_Name.base_name ident)) |>
1006 fold (add_type_def prfx) (items types) |>
1007 fold (snd oo add_const prfx) consts' |> (fn ids_thy as ((tab, _), _) =>
1009 fold_map (add_def prfx types pfuns consts)
1010 (sort_defs prfx pfuns (Symtab.defined tab) defs []) ||>>
1011 fold_map (add_var prfx) (items vars) ||>>
1012 add_init_vars prfx vcs');
1015 [Element.Fixes (map (fn (s, T) =>
1016 (Binding.name s, SOME T, NoSyn)) (vars'' @ ivars)),
1017 Element.Assumes (map (fn (id, rl) =>
1018 ((mk_rulename id, []),
1019 [(term_of_rule thy' prfx types pfuns ids rl, [])]))
1021 Element.Notes (Thm.definitionK,
1022 [((Binding.name "defns", []), map (rpair [] o single o snd) defs')])]
1025 set_env {ctxt = ctxt, defs = defs', types = types, funs = funs,
1026 ids = ids, proving = false, vcs = vcs', path = path, prefix = prfx} thy'