diff --git a/src/HOL/Analysis/measurable.ML b/src/HOL/Analysis/measurable.ML --- a/src/HOL/Analysis/measurable.ML +++ b/src/HOL/Analysis/measurable.ML @@ -1,280 +1,280 @@ (* Title: HOL/Analysis/measurable.ML Author: Johannes Hölzl Measurability prover. *) signature MEASURABLE = sig type preprocessor = thm -> Proof.context -> (thm list * Proof.context) datatype level = Concrete | Generic val dest_thm_attr : attribute context_parser val cong_thm_attr : attribute context_parser val measurable_thm_attr : bool * (bool * level) -> attribute val add_del_cong_thm : bool -> thm -> Context.generic -> Context.generic ; val get_all : Context.generic -> thm list val get_dest : Context.generic -> thm list val get_cong : Context.generic -> thm list val measurable_tac : Proof.context -> thm list -> tactic val simproc : Proof.context -> cterm -> thm option val add_preprocessor : string -> preprocessor -> Context.generic -> Context.generic val del_preprocessor : string -> Context.generic -> Context.generic val add_local_cong : thm -> Proof.context -> Proof.context val prepare_facts : Proof.context -> thm list -> (thm list * Proof.context) end ; structure Measurable : MEASURABLE = struct type preprocessor = thm -> Proof.context -> (thm list * Proof.context) datatype level = Concrete | Generic; fun eq_measurable_thms ((th1, d1), (th2, d2)) = d1 = d2 andalso Thm.eq_thm_prop (th1, th2) ; fun merge_dups (xs:(string * preprocessor) list) ys = xs @ (filter (fn (name, _) => is_none (find_first (fn (name', _) => name' = name) xs)) ys) structure Data = Generic_Data ( type T = { measurable_thms : (thm * (bool * level)) Item_Net.T, dest_thms : thm Item_Net.T, cong_thms : thm Item_Net.T, preprocessors : (string * preprocessor) list } val empty: T = { measurable_thms = Item_Net.init eq_measurable_thms (single o Thm.prop_of o fst), dest_thms = Thm.full_rules, cong_thms = Thm.full_rules, preprocessors = [] }; val extend = I; fun merge ({measurable_thms = t1, dest_thms = dt1, cong_thms = ct1, preprocessors = i1 }, {measurable_thms = t2, dest_thms = dt2, cong_thms = ct2, preprocessors = i2 }) : T = { measurable_thms = Item_Net.merge (t1, t2), dest_thms = Item_Net.merge (dt1, dt2), cong_thms = Item_Net.merge (ct1, ct2), preprocessors = merge_dups i1 i2 }; ); val debug = Attrib.setup_config_bool \<^binding>\measurable_debug\ (K false) val split = Attrib.setup_config_bool \<^binding>\measurable_split\ (K true) fun map_data f1 f2 f3 f4 {measurable_thms = t1, dest_thms = t2, cong_thms = t3, preprocessors = t4 } = {measurable_thms = f1 t1, dest_thms = f2 t2, cong_thms = f3 t3, preprocessors = f4 t4} fun map_measurable_thms f = map_data f I I I fun map_dest_thms f = map_data I f I I fun map_cong_thms f = map_data I I f I fun map_preprocessors f = map_data I I I f fun generic_add_del map : attribute context_parser = Scan.lift (Args.add >> K Item_Net.update || Args.del >> K Item_Net.remove || Scan.succeed Item_Net.update) >> (fn f => Thm.declaration_attribute (Data.map o map o f)) val dest_thm_attr = generic_add_del map_dest_thms val cong_thm_attr = generic_add_del map_cong_thms fun del_thm th net = let val thms = net |> Item_Net.content |> filter (fn (th', _) => Thm.eq_thm (th, th')) in fold Item_Net.remove thms net end ; fun measurable_thm_attr (do_add, d) = Thm.declaration_attribute (Data.map o map_measurable_thms o (if do_add then Item_Net.update o rpair d else del_thm)) val get_dest = Item_Net.content o #dest_thms o Data.get; val get_cong = Item_Net.content o #cong_thms o Data.get; val add_cong = Data.map o map_cong_thms o Item_Net.update; val del_cong = Data.map o map_cong_thms o Item_Net.remove; fun add_del_cong_thm true = add_cong | add_del_cong_thm false = del_cong fun add_preprocessor name f = Data.map (map_preprocessors (fn xs => xs @ [(name, f)])) fun del_preprocessor name = Data.map (map_preprocessors (filter (fn (n, _) => n <> name))) val add_local_cong = Context.proof_map o add_cong val get_preprocessors = Context.Proof #> Data.get #> #preprocessors ; fun is_too_generic thm = let val concl = Thm.concl_of thm val concl' = HOLogic.dest_Trueprop concl handle TERM _ => concl in is_Var (head_of concl') end val get_thms = Data.get #> #measurable_thms #> Item_Net.content ; val get_all = get_thms #> map fst ; fun debug_tac ctxt msg f = if Config.get ctxt debug then print_tac ctxt (msg ()) THEN f else f fun nth_hol_goal thm i = HOLogic.dest_Trueprop (Logic.strip_imp_concl (strip_all_body (nth (Thm.prems_of thm) (i - 1)))) fun dest_measurable_fun t = (case t of (Const (\<^const_name>\Set.member\, _) $ f $ (Const (\<^const_name>\measurable\, _) $ _ $ _)) => f | _ => raise (TERM ("not a measurability predicate", [t]))) fun not_measurable_prop n thm = if length (Thm.prems_of thm) < n then false else (case nth_hol_goal thm n of (Const (\<^const_name>\Set.member\, _) $ _ $ (Const (\<^const_name>\sets\, _) $ _)) => false | (Const (\<^const_name>\Set.member\, _) $ _ $ (Const (\<^const_name>\measurable\, _) $ _ $ _)) => false | _ => true) handle TERM _ => true; fun indep (Bound i) t b = i < b orelse t <= i | indep (f $ t) top bot = indep f top bot andalso indep t top bot | indep (Abs (_,_,t)) top bot = indep t (top + 1) (bot + 1) | indep _ _ _ = true; fun cnt_prefixes ctxt (Abs (n, T, t)) = let fun is_countable ty = Sign.of_sort (Proof_Context.theory_of ctxt) (ty, \<^sort>\countable\) fun cnt_walk (Abs (ns, T, t)) Ts = map (fn (t', t'') => (Abs (ns, T, t'), t'')) (cnt_walk t (T::Ts)) | cnt_walk (f $ g) Ts = let val n = length Ts - 1 in map (fn (f', t) => (f' $ g, t)) (cnt_walk f Ts) @ map (fn (g', t) => (f $ g', t)) (cnt_walk g Ts) @ (if is_countable (type_of1 (Ts, g)) andalso loose_bvar1 (g, n) andalso indep g n 0 andalso g <> Bound n then [(f $ Bound (n + 1), incr_boundvars (~ n) g)] else []) end | cnt_walk _ _ = [] in map (fn (t1, t2) => let val T1 = type_of1 ([T], t2) val T2 = type_of1 ([T], t) in ([SOME (Abs (n, T1, Abs (n, T, t1))), NONE, NONE, SOME (Abs (n, T, t2))], [SOME T1, SOME T, SOME T2]) end) (cnt_walk t [T]) end | cnt_prefixes _ _ = [] fun apply_dests thm dests = let fun apply thm th' = let val th'' = thm RS th' in [th''] @ loop th'' end handle (THM _) => [] and loop thm = flat (map (apply thm) dests) in [thm] @ ([thm RS @{thm measurable_compose_rev}] handle (THM _) => []) @ loop thm end fun prepare_facts ctxt facts = let val dests = get_dest (Context.Proof ctxt) fun prep_dest thm = (if is_too_generic thm then [] else apply_dests thm dests) ; val preprocessors = (("std", prep_dest #> pair) :: get_preprocessors ctxt) ; fun preprocess_thm (thm, raw) = if raw then pair [thm] else fold_map (fn (_, proc) => proc thm) preprocessors #>> flat fun sel lv (th, (raw, lv')) = if lv = lv' then SOME (th, raw) else NONE ; fun get lv = ctxt |> Context.Proof |> get_thms |> rev |> map_filter (sel lv) ; val pre_thms = map (Simplifier.norm_hhf ctxt #> rpair false) facts @ get Concrete @ get Generic val (thms, ctxt) = fold_map preprocess_thm pre_thms ctxt |>> flat in (thms, ctxt) end fun measurable_tac ctxt facts = let fun debug_fact msg thm () = msg ^ " " ^ Pretty.unformatted_string_of (Syntax.pretty_term ctxt (Thm.prop_of thm)) fun IF' c t i = COND (c i) (t i) no_tac fun r_tac msg = if Config.get ctxt debug then FIRST' o map (fn thm => resolve_tac ctxt [thm] THEN' K (debug_tac ctxt (debug_fact (msg ^ " resolved using") thm) all_tac)) else resolve_tac ctxt val elem_congI = @{lemma "A = B \ x \ B \ x \ A" by simp} val (thms, ctxt) = prepare_facts ctxt facts fun is_sets_eq (Const (\<^const_name>\HOL.eq\, _) $ (Const (\<^const_name>\sets\, _) $ _) $ (Const (\<^const_name>\sets\, _) $ _)) = true | is_sets_eq (Const (\<^const_name>\HOL.eq\, _) $ (Const (\<^const_name>\measurable\, _) $ _ $ _) $ (Const (\<^const_name>\measurable\, _) $ _ $ _)) = true | is_sets_eq _ = false val cong_thms = get_cong (Context.Proof ctxt) @ filter (fn thm => Thm.concl_of thm |> HOLogic.dest_Trueprop |> is_sets_eq handle TERM _ => false) facts fun sets_cong_tac i = Subgoal.FOCUS (fn {context = ctxt', prems = prems, ...} => ( let val ctxt'' = Simplifier.add_prems prems ctxt' in r_tac "cong intro" [elem_congI] THEN' SOLVED' (fn i => REPEAT_DETERM ( ((r_tac "cong solve" (cong_thms @ [@{thm refl}]) ORELSE' IF' (fn i => fn thm => Thm.nprems_of thm > i) (SOLVED' (asm_full_simp_tac ctxt''))) i))) end) 1) ctxt i THEN flexflex_tac ctxt val simp_solver_tac = IF' not_measurable_prop (debug_tac ctxt (K "simp ") o SOLVED' (asm_full_simp_tac ctxt)) val split_countable_tac = Subgoal.FOCUS (fn {context = ctxt, ...} => SUBGOAL (fn (t, i) => let val f = dest_measurable_fun (HOLogic.dest_Trueprop t) fun inst (ts, Ts) = Thm.instantiate' (map (Option.map (Thm.ctyp_of ctxt)) Ts) (map (Option.map (Thm.cterm_of ctxt)) ts) @{thm measurable_compose_countable} in r_tac "case_prod countable" (cnt_prefixes ctxt f |> map inst) i end handle TERM _ => no_tac) 1) val splitter = if Config.get ctxt split then split_countable_tac ctxt else K no_tac val single_step_tac = simp_solver_tac ORELSE' r_tac "step" thms ORELSE' splitter ORELSE' (CHANGED o sets_cong_tac) ORELSE' (K (debug_tac ctxt (K "backtrack") no_tac)) in debug_tac ctxt (K "start") (REPEAT (single_step_tac 1)) end; fun simproc ctxt redex = let val t = HOLogic.mk_Trueprop (Thm.term_of redex); fun tac {context = ctxt, prems = _ } = SOLVE (measurable_tac ctxt (Simplifier.prems_of ctxt)); - in try (fn () => Goal.prove ctxt [] [] t tac RS @{thm Eq_TrueI}) () end; + in \<^try>\Goal.prove ctxt [] [] t tac RS @{thm Eq_TrueI}\ end; end diff --git a/src/HOL/Tools/Meson/meson.ML b/src/HOL/Tools/Meson/meson.ML --- a/src/HOL/Tools/Meson/meson.ML +++ b/src/HOL/Tools/Meson/meson.ML @@ -1,790 +1,790 @@ (* Title: HOL/Tools/Meson/meson.ML Author: Lawrence C Paulson, Cambridge University Computer Laboratory Author: Jasmin Blanchette, TU Muenchen The MESON resolution proof procedure for HOL. When making clauses, avoids using the rewriter -- instead uses RS recursively. *) signature MESON = sig val trace : bool Config.T val max_clauses : int Config.T val first_order_resolve : Proof.context -> thm -> thm -> thm val size_of_subgoals: thm -> int val has_too_many_clauses: Proof.context -> term -> bool val make_cnf: thm list -> thm -> Proof.context -> thm list * Proof.context val finish_cnf: thm list -> thm list val presimplified_consts : string list val presimplify: Proof.context -> thm -> thm val make_nnf: Proof.context -> thm -> thm val choice_theorems : theory -> thm list val skolemize_with_choice_theorems : Proof.context -> thm list -> thm -> thm val skolemize : Proof.context -> thm -> thm val cong_extensionalize_thm : Proof.context -> thm -> thm val abs_extensionalize_conv : Proof.context -> conv val abs_extensionalize_thm : Proof.context -> thm -> thm val make_clauses_unsorted: Proof.context -> thm list -> thm list val make_clauses: Proof.context -> thm list -> thm list val make_horns: thm list -> thm list val best_prolog_tac: Proof.context -> (thm -> int) -> thm list -> tactic val depth_prolog_tac: Proof.context -> thm list -> tactic val gocls: thm list -> thm list val skolemize_prems_tac : Proof.context -> thm list -> int -> tactic val MESON: tactic -> (thm list -> thm list) -> (thm list -> tactic) -> Proof.context -> int -> tactic val best_meson_tac: (thm -> int) -> Proof.context -> int -> tactic val safe_best_meson_tac: Proof.context -> int -> tactic val depth_meson_tac: Proof.context -> int -> tactic val prolog_step_tac': Proof.context -> thm list -> int -> tactic val iter_deepen_prolog_tac: Proof.context -> thm list -> tactic val iter_deepen_meson_tac: Proof.context -> thm list -> int -> tactic val make_meta_clause: Proof.context -> thm -> thm val make_meta_clauses: Proof.context -> thm list -> thm list val meson_tac: Proof.context -> thm list -> int -> tactic end structure Meson : MESON = struct val trace = Attrib.setup_config_bool \<^binding>\meson_trace\ (K false) fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else () val max_clauses = Attrib.setup_config_int \<^binding>\meson_max_clauses\ (K 60) (*No known example (on 1-5-2007) needs even thirty*) val iter_deepen_limit = 50; val disj_forward = @{thm disj_forward}; val disj_forward2 = @{thm disj_forward2}; val make_pos_rule = @{thm make_pos_rule}; val make_pos_rule' = @{thm make_pos_rule'}; val make_pos_goal = @{thm make_pos_goal}; val make_neg_rule = @{thm make_neg_rule}; val make_neg_rule' = @{thm make_neg_rule'}; val make_neg_goal = @{thm make_neg_goal}; val conj_forward = @{thm conj_forward}; val all_forward = @{thm all_forward}; val ex_forward = @{thm ex_forward}; val not_conjD = @{thm not_conjD}; val not_disjD = @{thm not_disjD}; val not_notD = @{thm not_notD}; val not_allD = @{thm not_allD}; val not_exD = @{thm not_exD}; val imp_to_disjD = @{thm imp_to_disjD}; val not_impD = @{thm not_impD}; val iff_to_disjD = @{thm iff_to_disjD}; val not_iffD = @{thm not_iffD}; val conj_exD1 = @{thm conj_exD1}; val conj_exD2 = @{thm conj_exD2}; val disj_exD = @{thm disj_exD}; val disj_exD1 = @{thm disj_exD1}; val disj_exD2 = @{thm disj_exD2}; val disj_assoc = @{thm disj_assoc}; val disj_comm = @{thm disj_comm}; val disj_FalseD1 = @{thm disj_FalseD1}; val disj_FalseD2 = @{thm disj_FalseD2}; (**** Operators for forward proof ****) (** First-order Resolution **) (*FIXME: currently does not "rename variables apart"*) fun first_order_resolve ctxt thA thB = (case - try (fn () => + \<^try>\ let val thy = Proof_Context.theory_of ctxt val tmA = Thm.concl_of thA val Const(\<^const_name>\Pure.imp\,_) $ tmB $ _ = Thm.prop_of thB val tenv = Pattern.first_order_match thy (tmB, tmA) (Vartab.empty, Vartab.empty) |> snd val insts = Vartab.fold (fn (xi, (_, t)) => cons (xi, Thm.cterm_of ctxt t)) tenv []; - in thA RS (infer_instantiate ctxt insts thB) end) () of + in thA RS (infer_instantiate ctxt insts thB) end\ of SOME th => th | NONE => raise THM ("first_order_resolve", 0, [thA, thB])) (* Hack to make it less likely that we lose our precious bound variable names in "rename_bound_vars_RS" below, because of a clash. *) val protect_prefix = "Meson_xyzzy" fun protect_bound_var_names (t $ u) = protect_bound_var_names t $ protect_bound_var_names u | protect_bound_var_names (Abs (s, T, t')) = Abs (protect_prefix ^ s, T, protect_bound_var_names t') | protect_bound_var_names t = t fun fix_bound_var_names old_t new_t = let fun quant_of \<^const_name>\All\ = SOME true | quant_of \<^const_name>\Ball\ = SOME true | quant_of \<^const_name>\Ex\ = SOME false | quant_of \<^const_name>\Bex\ = SOME false | quant_of _ = NONE val flip_quant = Option.map not fun some_eq (SOME x) (SOME y) = x = y | some_eq _ _ = false fun add_names quant (Const (quant_s, _) $ Abs (s, _, t')) = add_names quant t' #> some_eq quant (quant_of quant_s) ? cons s | add_names quant (\<^const>\Not\ $ t) = add_names (flip_quant quant) t | add_names quant (\<^const>\implies\ $ t1 $ t2) = add_names (flip_quant quant) t1 #> add_names quant t2 | add_names quant (t1 $ t2) = fold (add_names quant) [t1, t2] | add_names _ _ = I fun lost_names quant = subtract (op =) (add_names quant new_t []) (add_names quant old_t []) fun aux ((t1 as Const (quant_s, _)) $ (Abs (s, T, t'))) = t1 $ Abs (s |> String.isPrefix protect_prefix s ? perhaps (try (fn _ => hd (lost_names (quant_of quant_s)))), T, aux t') | aux (t1 $ t2) = aux t1 $ aux t2 | aux t = t in aux new_t end (* Forward proof while preserving bound variables names *) fun rename_bound_vars_RS th rl = let val t = Thm.concl_of th val r = Thm.concl_of rl val th' = th RS Thm.rename_boundvars r (protect_bound_var_names r) rl val t' = Thm.concl_of th' in Thm.rename_boundvars t' (fix_bound_var_names t t') th' end (*raises exception if no rules apply*) fun tryres (th, rls) = let fun tryall [] = raise THM("tryres", 0, th::rls) | tryall (rl::rls) = (rename_bound_vars_RS th rl handle THM _ => tryall rls) in tryall rls end; (* Special version of "resolve_tac" that works around an explosion in the unifier. If the goal has the form "?P c", the danger is that resolving it against a property of the form "... c ... c ... c ..." will lead to a huge unification problem, due to the (spurious) choices between projection and imitation. The workaround is to instantiate "?P := (%c. ... c ... c ... c ...)" manually. *) fun quant_resolve_tac ctxt th i st = case (Thm.concl_of st, Thm.prop_of th) of (\<^const>\Trueprop\ $ (Var _ $ (c as Free _)), \<^const>\Trueprop\ $ _) => let val cc = Thm.cterm_of ctxt c val ct = Thm.dest_arg (Thm.cprop_of th) in resolve_tac ctxt [th] i (Thm.instantiate' [] [SOME (Thm.lambda cc ct)] st) end | _ => resolve_tac ctxt [th] i st (*Permits forward proof from rules that discharge assumptions. The supplied proof state st, e.g. from conj_forward, should have the form "[| P' ==> ?P; Q' ==> ?Q |] ==> ?P & ?Q" and the effect should be to instantiate ?P and ?Q with normalized versions of P' and Q'.*) fun forward_res ctxt nf st = let fun tacf [prem] = quant_resolve_tac ctxt (nf prem) 1 | tacf prems = error (cat_lines ("Bad proof state in forward_res, please inform lcp@cl.cam.ac.uk:" :: Thm.string_of_thm ctxt st :: "Premises:" :: map (Thm.string_of_thm ctxt) prems)) in case Seq.pull (ALLGOALS (Misc_Legacy.METAHYPS ctxt tacf) st) of SOME (th, _) => th | NONE => raise THM ("forward_res", 0, [st]) end; (*Are any of the logical connectives in "bs" present in the term?*) fun has_conns bs = let fun has (Const _) = false | has (Const(\<^const_name>\Trueprop\,_) $ p) = has p | has (Const(\<^const_name>\Not\,_) $ p) = has p | has (Const(\<^const_name>\HOL.disj\,_) $ p $ q) = member (op =) bs \<^const_name>\HOL.disj\ orelse has p orelse has q | has (Const(\<^const_name>\HOL.conj\,_) $ p $ q) = member (op =) bs \<^const_name>\HOL.conj\ orelse has p orelse has q | has (Const(\<^const_name>\All\,_) $ Abs(_,_,p)) = member (op =) bs \<^const_name>\All\ orelse has p | has (Const(\<^const_name>\Ex\,_) $ Abs(_,_,p)) = member (op =) bs \<^const_name>\Ex\ orelse has p | has _ = false in has end; (**** Clause handling ****) fun literals (Const(\<^const_name>\Trueprop\,_) $ P) = literals P | literals (Const(\<^const_name>\HOL.disj\,_) $ P $ Q) = literals P @ literals Q | literals (Const(\<^const_name>\Not\,_) $ P) = [(false,P)] | literals P = [(true,P)]; (*number of literals in a term*) val nliterals = length o literals; (*** Tautology Checking ***) fun signed_lits_aux (Const (\<^const_name>\HOL.disj\, _) $ P $ Q) (poslits, neglits) = signed_lits_aux Q (signed_lits_aux P (poslits, neglits)) | signed_lits_aux (Const(\<^const_name>\Not\,_) $ P) (poslits, neglits) = (poslits, P::neglits) | signed_lits_aux P (poslits, neglits) = (P::poslits, neglits); fun signed_lits th = signed_lits_aux (HOLogic.dest_Trueprop (Thm.concl_of th)) ([],[]); (*Literals like X=X are tautologous*) fun taut_poslit (Const(\<^const_name>\HOL.eq\,_) $ t $ u) = t aconv u | taut_poslit (Const(\<^const_name>\True\,_)) = true | taut_poslit _ = false; fun is_taut th = let val (poslits,neglits) = signed_lits th in exists taut_poslit poslits orelse exists (member (op aconv) neglits) (\<^term>\False\ :: poslits) end handle TERM _ => false; (*probably dest_Trueprop on a weird theorem*) (*** To remove trivial negated equality literals from clauses ***) (*They are typically functional reflexivity axioms and are the converses of injectivity equivalences*) val not_refl_disj_D = @{thm not_refl_disj_D}; (*Is either term a Var that does not properly occur in the other term?*) fun eliminable (t as Var _, u) = t aconv u orelse not (Logic.occs(t,u)) | eliminable (u, t as Var _) = t aconv u orelse not (Logic.occs(t,u)) | eliminable _ = false; fun refl_clause_aux 0 th = th | refl_clause_aux n th = case HOLogic.dest_Trueprop (Thm.concl_of th) of (Const (\<^const_name>\HOL.disj\, _) $ (Const (\<^const_name>\HOL.disj\, _) $ _ $ _) $ _) => refl_clause_aux n (th RS disj_assoc) (*isolate an atom as first disjunct*) | (Const (\<^const_name>\HOL.disj\, _) $ (Const(\<^const_name>\Not\,_) $ (Const(\<^const_name>\HOL.eq\,_) $ t $ u)) $ _) => if eliminable(t,u) then refl_clause_aux (n-1) (th RS not_refl_disj_D) (*Var inequation: delete*) else refl_clause_aux (n-1) (th RS disj_comm) (*not between Vars: ignore*) | (Const (\<^const_name>\HOL.disj\, _) $ _ $ _) => refl_clause_aux n (th RS disj_comm) | _ => (*not a disjunction*) th; fun notequal_lits_count (Const (\<^const_name>\HOL.disj\, _) $ P $ Q) = notequal_lits_count P + notequal_lits_count Q | notequal_lits_count (Const(\<^const_name>\Not\,_) $ (Const(\<^const_name>\HOL.eq\,_) $ _ $ _)) = 1 | notequal_lits_count _ = 0; (*Simplify a clause by applying reflexivity to its negated equality literals*) fun refl_clause th = let val neqs = notequal_lits_count (HOLogic.dest_Trueprop (Thm.concl_of th)) in zero_var_indexes (refl_clause_aux neqs th) end handle TERM _ => th; (*probably dest_Trueprop on a weird theorem*) (*** Removal of duplicate literals ***) (*Forward proof, passing extra assumptions as theorems to the tactic*) fun forward_res2 ctxt nf hyps st = case Seq.pull (REPEAT (Misc_Legacy.METAHYPS ctxt (fn major::minors => resolve_tac ctxt [nf (minors @ hyps) major] 1) 1) st) of SOME(th,_) => th | NONE => raise THM("forward_res2", 0, [st]); (*Remove duplicates in P|Q by assuming ~P in Q rls (initially []) accumulates assumptions of the form P==>False*) fun nodups_aux ctxt rls th = nodups_aux ctxt rls (th RS disj_assoc) handle THM _ => tryres(th,rls) handle THM _ => tryres(forward_res2 ctxt (nodups_aux ctxt) rls (th RS disj_forward2), [disj_FalseD1, disj_FalseD2, asm_rl]) handle THM _ => th; (*Remove duplicate literals, if there are any*) fun nodups ctxt th = if has_duplicates (op =) (literals (Thm.prop_of th)) then nodups_aux ctxt [] th else th; (*** The basic CNF transformation ***) fun estimated_num_clauses bound t = let fun sum x y = if x < bound andalso y < bound then x+y else bound fun prod x y = if x < bound andalso y < bound then x*y else bound (*Estimate the number of clauses in order to detect infeasible theorems*) fun signed_nclauses b (Const(\<^const_name>\Trueprop\,_) $ t) = signed_nclauses b t | signed_nclauses b (Const(\<^const_name>\Not\,_) $ t) = signed_nclauses (not b) t | signed_nclauses b (Const(\<^const_name>\HOL.conj\,_) $ t $ u) = if b then sum (signed_nclauses b t) (signed_nclauses b u) else prod (signed_nclauses b t) (signed_nclauses b u) | signed_nclauses b (Const(\<^const_name>\HOL.disj\,_) $ t $ u) = if b then prod (signed_nclauses b t) (signed_nclauses b u) else sum (signed_nclauses b t) (signed_nclauses b u) | signed_nclauses b (Const(\<^const_name>\HOL.implies\,_) $ t $ u) = if b then prod (signed_nclauses (not b) t) (signed_nclauses b u) else sum (signed_nclauses (not b) t) (signed_nclauses b u) | signed_nclauses b (Const(\<^const_name>\HOL.eq\, Type ("fun", [T, _])) $ t $ u) = if T = HOLogic.boolT then (*Boolean equality is if-and-only-if*) if b then sum (prod (signed_nclauses (not b) t) (signed_nclauses b u)) (prod (signed_nclauses (not b) u) (signed_nclauses b t)) else sum (prod (signed_nclauses b t) (signed_nclauses b u)) (prod (signed_nclauses (not b) t) (signed_nclauses (not b) u)) else 1 | signed_nclauses b (Const(\<^const_name>\Ex\, _) $ Abs (_,_,t)) = signed_nclauses b t | signed_nclauses b (Const(\<^const_name>\All\,_) $ Abs (_,_,t)) = signed_nclauses b t | signed_nclauses _ _ = 1; (* literal *) in signed_nclauses true t end fun has_too_many_clauses ctxt t = let val max_cl = Config.get ctxt max_clauses in estimated_num_clauses (max_cl + 1) t > max_cl end (*Replaces universally quantified variables by FREE variables -- because assumptions may not contain scheme variables. Later, generalize using Variable.export. *) local val spec_var = Thm.dest_arg (Thm.dest_arg (#2 (Thm.dest_implies (Thm.cprop_of spec)))) |> Thm.term_of |> dest_Var; fun name_of (Const (\<^const_name>\All\, _) $ Abs(x, _, _)) = x | name_of _ = Name.uu; in fun freeze_spec th ctxt = let val ([x], ctxt') = Variable.variant_fixes [name_of (HOLogic.dest_Trueprop (Thm.concl_of th))] ctxt; val spec' = spec |> Thm.instantiate ([], [(spec_var, Thm.cterm_of ctxt' (Free (x, snd spec_var)))]); in (th RS spec', ctxt') end end; fun apply_skolem_theorem ctxt (th, rls) = let fun tryall [] = raise THM ("apply_skolem_theorem", 0, th::rls) | tryall (rl :: rls) = first_order_resolve ctxt th rl handle THM _ => tryall rls in tryall rls end (* Conjunctive normal form, adding clauses from th in front of ths (for foldr). Strips universal quantifiers and breaks up conjunctions. Eliminates existential quantifiers using Skolemization theorems. *) fun cnf old_skolem_ths ctxt (th, ths) = let val ctxt_ref = Unsynchronized.ref ctxt (* FIXME ??? *) fun cnf_aux (th,ths) = if not (can HOLogic.dest_Trueprop (Thm.prop_of th)) then ths (*meta-level: ignore*) else if not (has_conns [\<^const_name>\All\, \<^const_name>\Ex\, \<^const_name>\HOL.conj\] (Thm.prop_of th)) then nodups ctxt th :: ths (*no work to do, terminate*) else case head_of (HOLogic.dest_Trueprop (Thm.concl_of th)) of Const (\<^const_name>\HOL.conj\, _) => (*conjunction*) cnf_aux (th RS conjunct1, cnf_aux (th RS conjunct2, ths)) | Const (\<^const_name>\All\, _) => (*universal quantifier*) let val (th', ctxt') = freeze_spec th (! ctxt_ref) in ctxt_ref := ctxt'; cnf_aux (th', ths) end | Const (\<^const_name>\Ex\, _) => (*existential quantifier: Insert Skolem functions*) cnf_aux (apply_skolem_theorem (! ctxt_ref) (th, old_skolem_ths), ths) | Const (\<^const_name>\HOL.disj\, _) => (*Disjunction of P, Q: Create new goal of proving ?P | ?Q and solve it using all combinations of converting P, Q to CNF.*) (*There is one assumption, which gets bound to prem and then normalized via cnf_nil. The normal form is given to resolve_tac, instantiate a Boolean variable created by resolution with disj_forward. Since (cnf_nil prem) returns a LIST of theorems, we can backtrack to get all combinations.*) let val tac = Misc_Legacy.METAHYPS ctxt (fn [prem] => resolve_tac ctxt (cnf_nil prem) 1) 1 in Seq.list_of ((tac THEN tac) (th RS disj_forward)) @ ths end | _ => nodups ctxt th :: ths (*no work to do*) and cnf_nil th = cnf_aux (th, []) val cls = if has_too_many_clauses ctxt (Thm.concl_of th) then (trace_msg ctxt (fn () => "cnf is ignoring: " ^ Thm.string_of_thm ctxt th); ths) else cnf_aux (th, ths) in (cls, !ctxt_ref) end fun make_cnf old_skolem_ths th ctxt = cnf old_skolem_ths ctxt (th, []) (*Generalization, removal of redundant equalities, removal of tautologies.*) fun finish_cnf ths = filter (not o is_taut) (map refl_clause ths); (**** Generation of contrapositives ****) fun is_left (Const (\<^const_name>\Trueprop\, _) $ (Const (\<^const_name>\HOL.disj\, _) $ (Const (\<^const_name>\HOL.disj\, _) $ _ $ _) $ _)) = true | is_left _ = false; (*Associate disjuctions to right -- make leftmost disjunct a LITERAL*) fun assoc_right th = if is_left (Thm.prop_of th) then assoc_right (th RS disj_assoc) else th; (*Must check for negative literal first!*) val clause_rules = [disj_assoc, make_neg_rule, make_pos_rule]; (*For ordinary resolution. *) val resolution_clause_rules = [disj_assoc, make_neg_rule', make_pos_rule']; (*Create a goal or support clause, conclusing False*) fun make_goal th = (*Must check for negative literal first!*) make_goal (tryres(th, clause_rules)) handle THM _ => tryres(th, [make_neg_goal, make_pos_goal]); fun rigid t = not (is_Var (head_of t)); fun ok4horn (Const (\<^const_name>\Trueprop\,_) $ (Const (\<^const_name>\HOL.disj\, _) $ t $ _)) = rigid t | ok4horn (Const (\<^const_name>\Trueprop\,_) $ t) = rigid t | ok4horn _ = false; (*Create a meta-level Horn clause*) fun make_horn crules th = if ok4horn (Thm.concl_of th) then make_horn crules (tryres(th,crules)) handle THM _ => th else th; (*Generate Horn clauses for all contrapositives of a clause. The input, th, is a HOL disjunction.*) fun add_contras crules th hcs = let fun rots (0,_) = hcs | rots (k,th) = zero_var_indexes (make_horn crules th) :: rots(k-1, assoc_right (th RS disj_comm)) in case nliterals(Thm.prop_of th) of 1 => th::hcs | n => rots(n, assoc_right th) end; (*Use "theorem naming" to label the clauses*) fun name_thms label = let fun name1 th (k, ths) = (k-1, Thm.put_name_hint (label ^ string_of_int k) th :: ths) in fn ths => #2 (fold_rev name1 ths (length ths, [])) end; (*Is the given disjunction an all-negative support clause?*) fun is_negative th = forall (not o #1) (literals (Thm.prop_of th)); val neg_clauses = filter is_negative; (***** MESON PROOF PROCEDURE *****) fun rhyps (Const(\<^const_name>\Pure.imp\,_) $ (Const(\<^const_name>\Trueprop\,_) $ A) $ phi, As) = rhyps(phi, A::As) | rhyps (_, As) = As; (** Detecting repeated assumptions in a subgoal **) (*The stringtree detects repeated assumptions.*) fun ins_term t net = Net.insert_term (op aconv) (t, t) net; (*detects repetitions in a list of terms*) fun has_reps [] = false | has_reps [_] = false | has_reps [t,u] = (t aconv u) | has_reps ts = (fold ins_term ts Net.empty; false) handle Net.INSERT => true; (*Like TRYALL eq_assume_tac, but avoids expensive THEN calls*) fun TRYING_eq_assume_tac 0 st = Seq.single st | TRYING_eq_assume_tac i st = TRYING_eq_assume_tac (i-1) (Thm.eq_assumption i st) handle THM _ => TRYING_eq_assume_tac (i-1) st; fun TRYALL_eq_assume_tac st = TRYING_eq_assume_tac (Thm.nprems_of st) st; (*Loop checking: FAIL if trying to prove the same thing twice -- if *ANY* subgoal has repeated literals*) fun check_tac st = if exists (fn prem => has_reps (rhyps(prem,[]))) (Thm.prems_of st) then Seq.empty else Seq.single st; (* resolve_from_net_tac actually made it slower... *) fun prolog_step_tac ctxt horns i = (assume_tac ctxt i APPEND resolve_tac ctxt horns i) THEN check_tac THEN TRYALL_eq_assume_tac; (*Sums the sizes of the subgoals, ignoring hypotheses (ancestors)*) fun addconcl prem sz = size_of_term (Logic.strip_assums_concl prem) + sz; fun size_of_subgoals st = fold_rev addconcl (Thm.prems_of st) 0; (*Negation Normal Form*) val nnf_rls = [imp_to_disjD, iff_to_disjD, not_conjD, not_disjD, not_impD, not_iffD, not_allD, not_exD, not_notD]; fun ok4nnf (Const (\<^const_name>\Trueprop\,_) $ (Const (\<^const_name>\Not\, _) $ t)) = rigid t | ok4nnf (Const (\<^const_name>\Trueprop\,_) $ t) = rigid t | ok4nnf _ = false; fun make_nnf1 ctxt th = if ok4nnf (Thm.concl_of th) then make_nnf1 ctxt (tryres(th, nnf_rls)) handle THM ("tryres", _, _) => forward_res ctxt (make_nnf1 ctxt) (tryres(th, [conj_forward,disj_forward,all_forward,ex_forward])) handle THM ("tryres", _, _) => th else th (*The simplification removes defined quantifiers and occurrences of True and False. nnf_ss also includes the one-point simprocs, which are needed to avoid the various one-point theorems from generating junk clauses.*) val nnf_simps = @{thms simp_implies_def Ex1_def Ball_def Bex_def if_True if_False if_cancel if_eq_cancel cases_simp} val nnf_extra_simps = @{thms split_ifs ex_simps all_simps simp_thms} (* FIXME: "let_simp" is probably redundant now that we also rewrite with "Let_def [abs_def]". *) val nnf_ss = simpset_of (put_simpset HOL_basic_ss \<^context> addsimps nnf_extra_simps addsimprocs [\<^simproc>\defined_All\, \<^simproc>\defined_Ex\, \<^simproc>\neq\, \<^simproc>\let_simp\]) val presimplified_consts = [\<^const_name>\simp_implies\, \<^const_name>\False\, \<^const_name>\True\, \<^const_name>\Ex1\, \<^const_name>\Ball\, \<^const_name>\Bex\, \<^const_name>\If\, \<^const_name>\Let\] fun presimplify ctxt = rewrite_rule ctxt (map safe_mk_meta_eq nnf_simps) #> simplify (put_simpset nnf_ss ctxt) #> rewrite_rule ctxt @{thms Let_def [abs_def]} fun make_nnf ctxt th = (case Thm.prems_of th of [] => th |> presimplify ctxt |> make_nnf1 ctxt | _ => raise THM ("make_nnf: premises in argument", 0, [th])); fun choice_theorems thy = try (Global_Theory.get_thm thy) "Hilbert_Choice.choice" |> the_list (* Pull existential quantifiers to front. This accomplishes Skolemization for clauses that arise from a subgoal. *) fun skolemize_with_choice_theorems ctxt choice_ths = let fun aux th = if not (has_conns [\<^const_name>\Ex\] (Thm.prop_of th)) then th else tryres (th, choice_ths @ [conj_exD1, conj_exD2, disj_exD, disj_exD1, disj_exD2]) |> aux handle THM ("tryres", _, _) => tryres (th, [conj_forward, disj_forward, all_forward]) |> forward_res ctxt aux |> aux handle THM ("tryres", _, _) => rename_bound_vars_RS th ex_forward |> forward_res ctxt aux in aux o make_nnf ctxt end fun skolemize ctxt = let val thy = Proof_Context.theory_of ctxt in skolemize_with_choice_theorems ctxt (choice_theorems thy) end exception NO_F_PATTERN of unit fun get_F_pattern T t u = let fun pat t u = let val ((head1, args1), (head2, args2)) = (t, u) |> apply2 strip_comb in if head1 = head2 then let val pats = map2 pat args1 args2 in case filter (is_some o fst) pats of [(SOME T, _)] => (SOME T, list_comb (head1, map snd pats)) | [] => (NONE, t) | _ => raise NO_F_PATTERN () end else let val T = fastype_of t in if can dest_funT T then (SOME T, Bound 0) else raise NO_F_PATTERN () end end in if T = \<^typ>\bool\ then NONE else case pat t u of (SOME T, p as _ $ _) => SOME (Abs (Name.uu, T, p)) | _ => NONE end handle NO_F_PATTERN () => NONE val ext_cong_neq = @{thm ext_cong_neq} (* Strengthens "f g ~= f h" to "f g ~= f h & (EX x. g x ~= h x)". *) fun cong_extensionalize_thm ctxt th = (case Thm.concl_of th of \<^const>\Trueprop\ $ (\<^const>\Not\ $ (Const (\<^const_name>\HOL.eq\, Type (_, [T, _])) $ (t as _ $ _) $ (u as _ $ _))) => (case get_F_pattern T t u of SOME p => th RS infer_instantiate ctxt [(("F", 0), Thm.cterm_of ctxt p)] ext_cong_neq | NONE => th) | _ => th) (* Removes the lambdas from an equation of the form "t = (%x1 ... xn. u)". It would be desirable to do this symmetrically but there's at least one existing proof in "Tarski" that relies on the current behavior. *) fun abs_extensionalize_conv ctxt ct = (case Thm.term_of ct of Const (\<^const_name>\HOL.eq\, _) $ _ $ Abs _ => ct |> (Conv.rewr_conv @{thm fun_eq_iff [THEN eq_reflection]} then_conv abs_extensionalize_conv ctxt) | _ $ _ => Conv.comb_conv (abs_extensionalize_conv ctxt) ct | Abs _ => Conv.abs_conv (abs_extensionalize_conv o snd) ctxt ct | _ => Conv.all_conv ct) val abs_extensionalize_thm = Conv.fconv_rule o abs_extensionalize_conv fun try_skolemize_etc ctxt th = let val th = th |> cong_extensionalize_thm ctxt in [th] (* Extensionalize lambdas in "th", because that makes sense and that's what Sledgehammer does, but also keep an unextensionalized version of "th" for backward compatibility. *) |> insert Thm.eq_thm_prop (abs_extensionalize_thm ctxt th) |> map_filter (fn th => th |> try (skolemize ctxt) |> tap (fn NONE => trace_msg ctxt (fn () => "Failed to skolemize " ^ Thm.string_of_thm ctxt th) | _ => ())) end fun add_clauses ctxt th cls = let val (cnfs, ctxt') = ctxt |> Variable.declare_thm th |> make_cnf [] th; in Variable.export ctxt' ctxt cnfs @ cls end; (*Sort clauses by number of literals*) fun fewerlits (th1, th2) = nliterals (Thm.prop_of th1) < nliterals (Thm.prop_of th2) (*Make clauses from a list of theorems, previously Skolemized and put into nnf. The resulting clauses are HOL disjunctions.*) fun make_clauses_unsorted ctxt ths = fold_rev (add_clauses ctxt) ths []; val make_clauses = sort (make_ord fewerlits) oo make_clauses_unsorted; (*Convert a list of clauses (disjunctions) to Horn clauses (contrapositives)*) fun make_horns ths = name_thms "Horn#" (distinct Thm.eq_thm_prop (fold_rev (add_contras clause_rules) ths [])); (*Could simply use nprems_of, which would count remaining subgoals -- no discrimination as to their size! With BEST_FIRST, fails for problem 41.*) fun best_prolog_tac ctxt sizef horns = BEST_FIRST (has_fewer_prems 1, sizef) (prolog_step_tac ctxt horns 1); fun depth_prolog_tac ctxt horns = DEPTH_FIRST (has_fewer_prems 1) (prolog_step_tac ctxt horns 1); (*Return all negative clauses, as possible goal clauses*) fun gocls cls = name_thms "Goal#" (map make_goal (neg_clauses cls)); fun skolemize_prems_tac ctxt prems = cut_facts_tac (maps (try_skolemize_etc ctxt) prems) THEN' REPEAT o eresolve_tac ctxt [exE] (*Basis of all meson-tactics. Supplies cltac with clauses: HOL disjunctions. Function mkcl converts theorems to clauses.*) fun MESON preskolem_tac mkcl cltac ctxt i st = SELECT_GOAL (EVERY [Object_Logic.atomize_prems_tac ctxt 1, resolve_tac ctxt @{thms ccontr} 1, preskolem_tac, Subgoal.FOCUS (fn {context = ctxt', prems = negs, ...} => EVERY1 [skolemize_prems_tac ctxt' negs, Subgoal.FOCUS (cltac o mkcl o #prems) ctxt']) ctxt 1]) i st handle THM _ => no_tac st; (*probably from make_meta_clause, not first-order*) (** Best-first search versions **) (*ths is a list of additional clauses (HOL disjunctions) to use.*) fun best_meson_tac sizef ctxt = MESON all_tac (make_clauses ctxt) (fn cls => THEN_BEST_FIRST (resolve_tac ctxt (gocls cls) 1) (has_fewer_prems 1, sizef) (prolog_step_tac ctxt (make_horns cls) 1)) ctxt (*First, breaks the goal into independent units*) fun safe_best_meson_tac ctxt = SELECT_GOAL (TRY (safe_tac ctxt) THEN TRYALL (best_meson_tac size_of_subgoals ctxt)); (** Depth-first search version **) fun depth_meson_tac ctxt = MESON all_tac (make_clauses ctxt) (fn cls => EVERY [resolve_tac ctxt (gocls cls) 1, depth_prolog_tac ctxt (make_horns cls)]) ctxt (** Iterative deepening version **) (*This version does only one inference per call; having only one eq_assume_tac speeds it up!*) fun prolog_step_tac' ctxt horns = let val horn0s = (*0 subgoals vs 1 or more*) take_prefix Thm.no_prems horns val nrtac = resolve_from_net_tac ctxt (Tactic.build_net horns) in fn i => eq_assume_tac i ORELSE match_tac ctxt horn0s i ORELSE (*no backtracking if unit MATCHES*) ((assume_tac ctxt i APPEND nrtac i) THEN check_tac) end; fun iter_deepen_prolog_tac ctxt horns = ITER_DEEPEN iter_deepen_limit (has_fewer_prems 1) (prolog_step_tac' ctxt horns); fun iter_deepen_meson_tac ctxt ths = ctxt |> MESON all_tac (make_clauses ctxt) (fn cls => (case (gocls (cls @ ths)) of [] => no_tac (*no goal clauses*) | goes => let val horns = make_horns (cls @ ths) val _ = trace_msg ctxt (fn () => cat_lines ("meson method called:" :: map (Thm.string_of_thm ctxt) (cls @ ths) @ ["clauses:"] @ map (Thm.string_of_thm ctxt) horns)) in THEN_ITER_DEEPEN iter_deepen_limit (resolve_tac ctxt goes 1) (has_fewer_prems 1) (prolog_step_tac' ctxt horns) end)); fun meson_tac ctxt ths = SELECT_GOAL (TRY (safe_tac ctxt) THEN TRYALL (iter_deepen_meson_tac ctxt ths)); (**** Code to support ordinary resolution, rather than Model Elimination ****) (*Convert a list of clauses (disjunctions) to meta-level clauses (==>), with no contrapositives, for ordinary resolution.*) (*Rules to convert the head literal into a negated assumption. If the head literal is already negated, then using notEfalse instead of notEfalse' prevents a double negation.*) val notEfalse = @{lemma "\ P \ P \ False" by (rule notE)}; val notEfalse' = @{lemma "P \ \ P \ False" by (rule notE)}; fun negated_asm_of_head th = th RS notEfalse handle THM _ => th RS notEfalse'; (*Converting one theorem from a disjunction to a meta-level clause*) fun make_meta_clause ctxt th = let val (fth, thaw) = Misc_Legacy.freeze_thaw_robust ctxt th in (zero_var_indexes o Thm.varifyT_global o thaw 0 o negated_asm_of_head o make_horn resolution_clause_rules) fth end; fun make_meta_clauses ctxt ths = name_thms "MClause#" (distinct Thm.eq_thm_prop (map (make_meta_clause ctxt) ths)); end; diff --git a/src/HOL/Tools/Quotient/quotient_def.ML b/src/HOL/Tools/Quotient/quotient_def.ML --- a/src/HOL/Tools/Quotient/quotient_def.ML +++ b/src/HOL/Tools/Quotient/quotient_def.ML @@ -1,214 +1,214 @@ (* Title: HOL/Tools/Quotient/quotient_def.ML Author: Cezary Kaliszyk and Christian Urban Definitions for constants on quotient types. *) signature QUOTIENT_DEF = sig val add_quotient_def: ((binding * mixfix) * Attrib.binding) * (term * term) -> thm -> local_theory -> Quotient_Info.quotconsts * local_theory val quotient_def: (binding * typ option * mixfix) option * (Attrib.binding * (term * term)) -> local_theory -> Proof.state val quotient_def_cmd: (binding * string option * mixfix) option * (Attrib.binding * (string * string)) -> local_theory -> Proof.state end; structure Quotient_Def: QUOTIENT_DEF = struct (** Interface and Syntax Setup **) (* Generation of the code certificate from the rsp theorem *) open Lifting_Util infix 0 MRSL (* The ML-interface for a quotient definition takes as argument: - an optional binding and mixfix annotation - attributes - the new constant as term - the rhs of the definition as term - respectfulness theorem for the rhs It stores the qconst_info in the quotconsts data slot. Restriction: At the moment the left- and right-hand side of the definition must be a constant. *) fun error_msg bind str = let val name = Binding.name_of bind val pos = Position.here (Binding.pos_of bind) in error ("Head of quotient_definition " ^ quote str ^ " differs from declaration " ^ name ^ pos) end fun add_quotient_def ((var, (name, atts)), (lhs, rhs)) rsp_thm lthy = let val rty = fastype_of rhs val qty = fastype_of lhs val absrep_trm = Quotient_Term.absrep_fun lthy Quotient_Term.AbsF (rty, qty) $ rhs val prop = Syntax.check_term lthy (Logic.mk_equals (lhs, absrep_trm)) val (_, prop') = Local_Defs.cert_def lthy (K []) prop val (_, newrhs) = Local_Defs.abs_def prop' val ((qconst, (_ , def)), lthy') = Local_Theory.define (var, ((Thm.def_binding_optional (#1 var) name, atts), newrhs)) lthy fun qconst_data phi = Quotient_Info.transform_quotconsts phi {qconst = qconst, rconst = rhs, def = def} fun qualify defname suffix = Binding.name suffix |> Binding.qualify true defname val lhs_name = Binding.name_of (#1 var) val rsp_thm_name = qualify lhs_name "rsp" val lthy'' = lthy' |> Local_Theory.declaration {syntax = false, pervasive = true} (fn phi => (case qconst_data phi of qcinfo as {qconst = Const (c, _), ...} => Quotient_Info.update_quotconsts (c, qcinfo) | _ => I)) |> (snd oo Local_Theory.note) ((rsp_thm_name, @{attributes [quot_respect]}), [rsp_thm]) in (qconst_data Morphism.identity, lthy'') end fun mk_readable_rsp_thm_eq tm lthy = let val ctm = Thm.cterm_of lthy tm fun norm_fun_eq ctm = let fun abs_conv2 cv = Conv.abs_conv (K (Conv.abs_conv (K cv) lthy)) lthy fun erase_quants ctm' = case (Thm.term_of ctm') of Const (\<^const_name>\HOL.eq\, _) $ _ $ _ => Conv.all_conv ctm' | _ => (Conv.binder_conv (K erase_quants) lthy then_conv Conv.rewr_conv @{thm fun_eq_iff[symmetric, THEN eq_reflection]}) ctm' in (abs_conv2 erase_quants then_conv Thm.eta_conversion) ctm end fun simp_arrows_conv ctm = let val unfold_conv = Conv.rewrs_conv [@{thm rel_fun_eq_eq_onp[THEN eq_reflection]}, @{thm rel_fun_eq_rel[THEN eq_reflection]}, @{thm rel_fun_def[THEN eq_reflection]}] val left_conv = simp_arrows_conv then_conv Conv.try_conv norm_fun_eq fun binop_conv2 cv1 cv2 = Conv.combination_conv (Conv.arg_conv cv1) cv2 in case (Thm.term_of ctm) of Const (\<^const_name>\rel_fun\, _) $ _ $ _ => (binop_conv2 left_conv simp_arrows_conv then_conv unfold_conv) ctm | _ => Conv.all_conv ctm end val unfold_ret_val_invs = Conv.bottom_conv (K (Conv.try_conv (Conv.rewr_conv @{thm eq_onp_same_args[THEN eq_reflection]}))) lthy val simp_conv = Conv.arg_conv (Conv.fun2_conv simp_arrows_conv) val univq_conv = Conv.rewr_conv @{thm HOL.all_simps(6)[symmetric, THEN eq_reflection]} val univq_prenex_conv = Conv.top_conv (K (Conv.try_conv univq_conv)) lthy val beta_conv = Thm.beta_conversion true val eq_thm = (simp_conv then_conv univq_prenex_conv then_conv beta_conv then_conv unfold_ret_val_invs) ctm in Object_Logic.rulify lthy (eq_thm RS Drule.equal_elim_rule2) end fun gen_quotient_def prep_var parse_term (raw_var, (attr, (raw_lhs, raw_rhs))) lthy = let val (opt_var, ctxt) = (case raw_var of NONE => (NONE, lthy) | SOME var => prep_var var lthy |>> SOME) val lhs_constraints = (case opt_var of SOME (_, SOME T, _) => [T] | _ => []) fun prep_term Ts = parse_term ctxt #> fold Type.constraint Ts #> Syntax.check_term ctxt; val lhs = prep_term lhs_constraints raw_lhs val rhs = prep_term [] raw_rhs val (lhs_str, lhs_ty) = dest_Free lhs handle TERM _ => error "Constant already defined" val _ = if null (strip_abs_vars rhs) then () else error "The definiens cannot be an abstraction" val _ = if is_Const rhs then () else warning "The definiens is not a constant" val var = (case opt_var of NONE => (Binding.name lhs_str, NoSyn) | SOME (binding, _, mx) => if Variable.check_name binding = lhs_str then (binding, mx) else error_msg binding lhs_str); fun try_to_prove_refl thm = let val lhs_eq = thm |> Thm.prop_of |> Logic.dest_implies |> fst |> strip_all_body |> try HOLogic.dest_Trueprop in case lhs_eq of SOME (Const (\<^const_name>\HOL.eq\, _) $ _ $ _) => SOME (@{thm refl} RS thm) | SOME _ => (case body_type (fastype_of lhs) of Type (typ_name, _) => - try (fn () => + \<^try>\ #equiv_thm (the (Quotient_Info.lookup_quotients lthy typ_name)) - RS @{thm Equiv_Relations.equivp_reflp} RS thm) () + RS @{thm Equiv_Relations.equivp_reflp} RS thm\ | _ => NONE ) | _ => NONE end val rsp_rel = Quotient_Term.equiv_relation lthy (fastype_of rhs, lhs_ty) val internal_rsp_tm = HOLogic.mk_Trueprop (Syntax.check_term lthy (rsp_rel $ rhs $ rhs)) val readable_rsp_thm_eq = mk_readable_rsp_thm_eq internal_rsp_tm lthy val maybe_proven_rsp_thm = try_to_prove_refl readable_rsp_thm_eq val (readable_rsp_tm, _) = Logic.dest_implies (Thm.prop_of readable_rsp_thm_eq) fun after_qed thm_list lthy = let val internal_rsp_thm = case thm_list of [] => the maybe_proven_rsp_thm | [[thm]] => Goal.prove ctxt [] [] internal_rsp_tm (fn _ => resolve_tac ctxt [readable_rsp_thm_eq] 1 THEN Proof_Context.fact_tac ctxt [thm] 1) in snd (add_quotient_def ((var, attr), (lhs, rhs)) internal_rsp_thm lthy) end in case maybe_proven_rsp_thm of SOME _ => Proof.theorem NONE after_qed [] lthy | NONE => Proof.theorem NONE after_qed [[(readable_rsp_tm,[])]] lthy end val quotient_def = gen_quotient_def Proof_Context.cert_var (K I) val quotient_def_cmd = gen_quotient_def Proof_Context.read_var Syntax.parse_term (* command syntax *) val _ = Outer_Syntax.local_theory_to_proof \<^command_keyword>\quotient_definition\ "definition for constants over the quotient type" (Scan.option Parse_Spec.constdecl -- Parse.!!! (Parse_Spec.opt_thm_name ":" -- (Parse.term -- (\<^keyword>\is\ |-- Parse.term))) >> quotient_def_cmd); end; diff --git a/src/Pure/General/antiquote.ML b/src/Pure/General/antiquote.ML --- a/src/Pure/General/antiquote.ML +++ b/src/Pure/General/antiquote.ML @@ -1,191 +1,197 @@ (* Title: Pure/General/antiquote.ML Author: Makarius Antiquotations within plain text. *) signature ANTIQUOTE = sig type control = {range: Position.range, name: string * Position.T, body: Symbol_Pos.T list} type antiq = {start: Position.T, stop: Position.T, range: Position.range, body: Symbol_Pos.T list} datatype 'a antiquote = Text of 'a | Control of control | Antiq of antiq - val the_text: 'a antiquote -> 'a + val is_text: 'a antiquote -> bool + val the_text: string -> 'a antiquote -> 'a type text_antiquote = Symbol_Pos.T list antiquote val text_antiquote_range: text_antiquote -> Position.range val text_range: text_antiquote list -> Position.range val split_lines: text_antiquote list -> text_antiquote list list val antiq_reports: 'a antiquote list -> Position.report list val update_reports: bool -> Position.T -> string list -> Position.report_text list val scan_control: control scanner val scan_antiq: antiq scanner val scan_antiquote: text_antiquote scanner val scan_antiquote_comments: text_antiquote scanner val parse_comments: Position.T -> Symbol_Pos.T list -> text_antiquote list val read_comments: Input.source -> text_antiquote list end; structure Antiquote: ANTIQUOTE = struct (* datatype antiquote *) type control = {range: Position.range, name: string * Position.T, body: Symbol_Pos.T list}; type antiq = {start: Position.T, stop: Position.T, range: Position.range, body: Symbol_Pos.T list}; datatype 'a antiquote = Text of 'a | Control of control | Antiq of antiq; -fun bad_text pos = error ("Unexpected antiquotation" ^ Position.here pos); -fun the_text (Text x) = x - | the_text (Control {range, ...}) = bad_text (#1 range) - | the_text (Antiq {range, ...}) = bad_text (#1 range); +val is_text = fn Text _ => true | _ => false; + +fun the_text msg antiq = + let fun err pos = error (msg ^ Position.here pos) in + (case antiq of + Text x => x + | Control {range, ...} => err (#1 range) + | Antiq {range, ...} => err (#1 range)) + end; type text_antiquote = Symbol_Pos.T list antiquote; fun text_antiquote_range (Text ss) = Symbol_Pos.range ss | text_antiquote_range (Control {range, ...}) = range | text_antiquote_range (Antiq {range, ...}) = range; fun text_range ants = if null ants then Position.no_range else Position.range (#1 (text_antiquote_range (hd ants)), #2 (text_antiquote_range (List.last ants))); (* split lines *) fun split_lines input = let fun add a (line, lines) = (a :: line, lines); fun flush (line, lines) = ([], rev line :: lines); fun split (a as Text ss) = (case chop_prefix (fn ("\n", _) => false | _ => true) ss of ([], []) => I | (_, []) => add a | ([], _ :: rest) => flush #> split (Text rest) | (prefix, _ :: rest) => add (Text prefix) #> flush #> split (Text rest)) | split a = add a; in if null input then [] else rev (#2 (flush (fold split input ([], [])))) end; (* reports *) fun antiq_reports ants = ants |> maps (fn Text _ => [] | Control {range = (pos, _), ...} => [(pos, Markup.antiquoted)] | Antiq {start, stop, range = (pos, _), ...} => [(start, Markup.antiquote), (stop, Markup.antiquote), (pos, Markup.antiquoted), (pos, Markup.language_antiquotation)]); (* update *) fun update_reports embedded pos src = let val n = length src; val no_arg = n = 1; val embedded_arg = n = 2 andalso embedded; val control = (case src of name :: _ => if Symbol.is_ascii_identifier name andalso name <> "cartouche" andalso (no_arg orelse embedded_arg) then SOME (Symbol.control_prefix ^ name ^ Symbol.control_suffix) else NONE | [] => NONE); val arg = if embedded_arg then cartouche (nth src 1) else ""; in (case control of SOME sym => [((pos, Markup.update), sym ^ arg)] | NONE => []) end; (* scan *) open Basic_Symbol_Pos; local val err_prefix = "Antiquotation lexical error: "; val scan_nl = Scan.one (fn (s, _) => s = "\n") >> single; val scan_nl_opt = Scan.optional scan_nl []; val scan_plain_txt = Scan.many1 (fn (s, _) => not (Comment.is_symbol s) andalso not (Symbol.is_control s) andalso s <> Symbol.open_ andalso s <> "@" andalso s <> "\n" andalso Symbol.not_eof s) || Scan.one (Comment.is_symbol o Symbol_Pos.symbol) >> single || $$$ "@" --| Scan.ahead (~$$ "{"); val scan_text = scan_nl || Scan.repeats1 scan_plain_txt @@@ scan_nl_opt; val scan_text_comments = scan_nl || Scan.repeats1 (Comment.scan_inner >> #2 || scan_plain_txt) @@@ scan_nl_opt; val scan_antiq_body = Scan.trace (Symbol_Pos.scan_string_qq err_prefix || Symbol_Pos.scan_string_bq err_prefix) >> #2 || Symbol_Pos.scan_cartouche err_prefix || Comment.scan_inner -- Symbol_Pos.!!! (fn () => err_prefix ^ "bad formal comment in antiquote body") Scan.fail >> K [] || Scan.one (fn (s, _) => s <> "}" andalso Symbol.not_eof s) >> single; fun control_name sym = (case Symbol.decode sym of Symbol.Control name => name); in val scan_control = Scan.option (Scan.one (Symbol.is_control o Symbol_Pos.symbol)) -- Symbol_Pos.scan_cartouche err_prefix >> (fn (opt_control, body) => let val (name, range) = (case opt_control of SOME (sym, pos) => ((control_name sym, pos), Symbol_Pos.range ((sym, pos) :: body)) | NONE => (("cartouche", #2 (hd body)), Symbol_Pos.range body)); in {name = name, range = range, body = body} end) || Scan.one (Symbol.is_control o Symbol_Pos.symbol) >> (fn (sym, pos) => {name = (control_name sym, pos), range = Symbol_Pos.range [(sym, pos)], body = []}); val scan_antiq = Symbol_Pos.scan_pos -- ($$ "@" |-- $$ "{" |-- Symbol_Pos.scan_pos -- Symbol_Pos.!!! (fn () => err_prefix ^ "missing closing brace") (Scan.repeats scan_antiq_body -- Symbol_Pos.scan_pos -- ($$ "}" |-- Symbol_Pos.scan_pos))) >> (fn (pos1, (pos2, ((body, pos3), pos4))) => {start = Position.range_position (pos1, pos2), stop = Position.range_position (pos3, pos4), range = Position.range (pos1, pos4), body = body}); val scan_antiquote = scan_text >> Text || scan_control >> Control || scan_antiq >> Antiq; val scan_antiquote_comments = scan_text_comments >> Text || scan_control >> Control || scan_antiq >> Antiq; end; (* parse and read (with formal comments) *) fun parse_comments pos syms = (case Scan.read Symbol_Pos.stopper (Scan.repeat scan_antiquote_comments) syms of SOME ants => ants | NONE => error ("Malformed quotation/antiquotation source" ^ Position.here pos)); fun read_comments source = let val ants = parse_comments (Input.pos_of source) (Input.source_explode source); val _ = Position.reports (antiq_reports ants); in ants end; end; diff --git a/src/Pure/ML/ml_antiquotation.ML b/src/Pure/ML/ml_antiquotation.ML --- a/src/Pure/ML/ml_antiquotation.ML +++ b/src/Pure/ML/ml_antiquotation.ML @@ -1,107 +1,109 @@ (* Title: Pure/ML/ml_antiquotation.ML Author: Makarius ML antiquotations. *) signature ML_ANTIQUOTATION = sig val value_decl: string -> string -> Proof.context -> (Proof.context -> string * string) * Proof.context val declaration: binding -> 'a context_parser -> (Token.src -> 'a -> Proof.context -> (Proof.context -> string * string) * Proof.context) -> theory -> theory val declaration_embedded: binding -> 'a context_parser -> (Token.src -> 'a -> Proof.context -> (Proof.context -> string * string) * Proof.context) -> theory -> theory val inline: binding -> string context_parser -> theory -> theory val inline_embedded: binding -> string context_parser -> theory -> theory val value: binding -> string context_parser -> theory -> theory val value_embedded: binding -> string context_parser -> theory -> theory val special_form: binding -> string -> theory -> theory end; structure ML_Antiquotation: ML_ANTIQUOTATION = struct (* define antiquotations *) fun value_decl a s ctxt = let val (b, ctxt') = ML_Context.variant a ctxt; val env = "val " ^ b ^ " = " ^ s ^ ";\n"; val body = ML_Context.struct_name ctxt ^ "." ^ b; fun decl (_: Proof.context) = (env, body); in (decl, ctxt') end; local fun gen_declaration name embedded scan body = ML_Context.add_antiquotation name embedded (fn range => fn src => fn orig_ctxt => let val (x, _) = Token.syntax scan src orig_ctxt; val (decl, ctxt') = body src x orig_ctxt; in (decl #> apply2 (ML_Lex.tokenize_range range), ctxt') end); fun gen_inline name embedded scan = gen_declaration name embedded scan (fn _ => fn s => fn ctxt => (K ("", s), ctxt)); fun gen_value name embedded scan = gen_declaration name embedded scan (fn _ => value_decl (Binding.name_of name)); in fun declaration name = gen_declaration name false; fun declaration_embedded name = gen_declaration name true; fun inline name = gen_inline name false; fun inline_embedded name = gen_inline name true; fun value name = gen_value name false; fun value_embedded name = gen_value name true; end; (* ML special form *) fun special_form binding operator = ML_Context.add_antiquotation binding true (fn _ => fn src => fn ctxt => let val (s, _) = Token.syntax (Scan.lift Args.embedded_input) src ctxt; val tokenize = ML_Lex.tokenize_range Position.no_range; val tokenize_range = ML_Lex.tokenize_range (Input.range_of s); - fun decl (_: Proof.context) = + + val (decl, ctxt') = ML_Context.expand_antiquotes (ML_Lex.read_source s) ctxt; + fun decl' ctxt'' = let - val expr = ML_Lex.read_source s |> map Antiquote.the_text; - val ml = - tokenize "let val expr = (fn () => " @ expr @ tokenize ");" @ + val (ml_env, ml_body) = decl ctxt''; + val ml_body' = + tokenize "let val expr = (fn () => " @ ml_body @ tokenize ");" @ tokenize " val " @ tokenize_range "result" @ - tokenize (" = " ^ operator ^ " expr; in result end") - in ([], ml) end; - in (decl, ctxt) end); + tokenize (" = " ^ operator ^ " expr; in result end"); + in (ml_env, ml_body') end; + in (decl', ctxt') end); (* basic antiquotations *) val _ = Theory.setup (declaration (Binding.make ("here", \<^here>)) (Scan.succeed ()) (fn src => fn () => value_decl "position" (ML_Syntax.print_position (#2 (Token.name_of_src src)))) #> inline (Binding.make ("make_string", \<^here>)) (Args.context >> K ML_Pretty.make_string_fn) #> value_embedded (Binding.make ("binding", \<^here>)) (Scan.lift (Parse.input Args.embedded) >> (ML_Syntax.make_binding o Input.source_content)) #> value_embedded (Binding.make ("cartouche", \<^here>)) (Scan.lift Args.cartouche_input >> (fn source => "Input.source true " ^ ML_Syntax.print_string (Input.text_of source) ^ " " ^ ML_Syntax.atomic (ML_Syntax.print_range (Input.range_of source)))) #> inline_embedded (Binding.make ("verbatim", \<^here>)) (Scan.lift Args.embedded >> ML_Syntax.print_string)); end; diff --git a/src/Pure/ML/ml_context.ML b/src/Pure/ML/ml_context.ML --- a/src/Pure/ML/ml_context.ML +++ b/src/Pure/ML/ml_context.ML @@ -1,214 +1,225 @@ (* Title: Pure/ML/ml_context.ML Author: Makarius ML context and antiquotations. *) signature ML_CONTEXT = sig val check_antiquotation: Proof.context -> xstring * Position.T -> string val struct_name: Proof.context -> string val variant: string -> Proof.context -> string * Proof.context type decl = Proof.context -> ML_Lex.token list * ML_Lex.token list type antiquotation = Position.range -> Token.src -> Proof.context -> decl * Proof.context val add_antiquotation: binding -> bool -> antiquotation -> theory -> theory val print_antiquotations: bool -> Proof.context -> unit + val expand_antiquotes: ML_Lex.token Antiquote.antiquote list -> + Proof.context -> decl * Proof.context val eval: ML_Compiler.flags -> Position.T -> ML_Lex.token Antiquote.antiquote list -> unit val eval_file: ML_Compiler.flags -> Path.T -> unit val eval_source: ML_Compiler.flags -> Input.source -> unit val eval_in: Proof.context option -> ML_Compiler.flags -> Position.T -> ML_Lex.token Antiquote.antiquote list -> unit val eval_source_in: Proof.context option -> ML_Compiler.flags -> Input.source -> unit val exec: (unit -> unit) -> Context.generic -> Context.generic val expression: Position.T -> ML_Lex.token Antiquote.antiquote list -> Context.generic -> Context.generic end structure ML_Context: ML_CONTEXT = struct (** ML antiquotations **) (* names for generated environment *) structure Names = Proof_Data ( type T = string * Name.context; val init_names = ML_Syntax.reserved |> Name.declare "ML_context"; fun init _ = ("Isabelle0", init_names); ); fun struct_name ctxt = #1 (Names.get ctxt); val struct_begin = (Names.map o apfst) (fn _ => "Isabelle" ^ serial_string ()); fun variant a ctxt = let val names = #2 (Names.get ctxt); val (b, names') = Name.variant (Name.desymbolize (SOME false) a) names; val ctxt' = (Names.map o apsnd) (K names') ctxt; in (b, ctxt') end; (* theory data *) type decl = Proof.context -> ML_Lex.token list * ML_Lex.token list; (*final context -> ML env, ML body*) type antiquotation = Position.range -> Token.src -> Proof.context -> decl * Proof.context; structure Antiquotations = Theory_Data ( type T = (bool * antiquotation) Name_Space.table; val empty : T = Name_Space.empty_table Markup.ML_antiquotationN; val extend = I; fun merge data : T = Name_Space.merge_tables data; ); val get_antiquotations = Antiquotations.get o Proof_Context.theory_of; fun check_antiquotation ctxt = #1 o Name_Space.check (Context.Proof ctxt) (get_antiquotations ctxt); fun add_antiquotation name embedded antiquotation thy = thy |> Antiquotations.map (Name_Space.define (Context.Theory thy) true (name, (embedded, antiquotation)) #> #2); fun print_antiquotations verbose ctxt = Pretty.big_list "ML antiquotations:" (map (Pretty.mark_str o #1) (Name_Space.markup_table verbose ctxt (get_antiquotations ctxt))) |> Pretty.writeln; fun apply_antiquotation range src ctxt = let val (src', (embedded, antiquotation)) = Token.check_src ctxt get_antiquotations src; val _ = if Options.default_bool "update_control_cartouches" then Context_Position.reports_text ctxt (Antiquote.update_reports embedded (#1 range) (map Token.content_of src')) else (); in antiquotation range src' ctxt end; -(* parsing and evaluation *) +(* parsing *) local val antiq = Parse.!!! ((Parse.token Parse.liberal_name ::: Parse.args) --| Scan.ahead Parse.eof); +fun expand_antiquote ant ctxt = + (case ant of + Antiquote.Text tok => (K ([], [tok]), ctxt) + | Antiquote.Control {name, range, body} => + ctxt |> apply_antiquotation range + (Token.make_src name (if null body then [] else [Token.read_cartouche body])) + | Antiquote.Antiq {range, body, ...} => + ctxt |> apply_antiquotation range + (Token.read_antiq (Thy_Header.get_keywords' ctxt) antiq (body, #1 range))); + +in + +fun expand_antiquotes ants ctxt = + let + val (decls, ctxt') = fold_map expand_antiquote ants ctxt; + fun decl ctxt'' = decls |> map (fn d => d ctxt'') |> split_list |> apply2 flat; + in (decl, ctxt') end; + +end; + + +(* evaluation *) + +local + fun make_env name visible = (ML_Lex.tokenize ("structure " ^ name ^ " =\nstruct\n\ \val ML_context = Context_Position.set_visible " ^ Bool.toString visible ^ " (Context.the_local_context ());\n"), ML_Lex.tokenize "end;"); fun reset_env name = ML_Lex.tokenize ("structure " ^ name ^ " = struct end"); -fun eval_antiquotes (ants, pos) opt_context = - let - val visible = - (case opt_context of - SOME (Context.Proof ctxt) => Context_Position.is_visible ctxt - | _ => true); - val opt_ctxt = Option.map Context.proof_of opt_context; - - val ((ml_env, ml_body), opt_ctxt') = - if forall (fn Antiquote.Text _ => true | _ => false) ants - then (([], map (fn Antiquote.Text tok => tok) ants), opt_ctxt) - else - let - fun expand (Antiquote.Text tok) ctxt = (K ([], [tok]), ctxt) - | expand (Antiquote.Control {name, range, body}) ctxt = - apply_antiquotation range - (Token.make_src name (if null body then [] else [Token.read_cartouche body])) ctxt - | expand (Antiquote.Antiq {range, body, ...}) ctxt = - apply_antiquotation range - (Token.read_antiq (Thy_Header.get_keywords' ctxt) antiq (body, #1 range)) ctxt; - - val ctxt = - (case opt_ctxt of - NONE => error ("No context -- cannot expand ML antiquotations" ^ Position.here pos) - | SOME ctxt => struct_begin ctxt); - - val (begin_env, end_env) = make_env (struct_name ctxt) visible; - val (decls, ctxt') = fold_map expand ants ctxt; - val (ml_env, ml_body) = - decls |> map (fn decl => decl ctxt') |> split_list |> apply2 flat; - in ((begin_env @ ml_env @ end_env, ml_body), SOME ctxt') end; - in ((ml_env, ml_body), opt_ctxt') end; +fun eval_antiquotes ants opt_context = + if forall Antiquote.is_text ants orelse is_none opt_context then + (([], map (Antiquote.the_text "No context -- cannot expand ML antiquotations") ants), + Option.map Context.proof_of opt_context) + else + let + val context = the opt_context; + val visible = + (case context of + Context.Proof ctxt => Context_Position.is_visible ctxt + | _ => true); + val ctxt = struct_begin (Context.proof_of context); + val (begin_env, end_env) = make_env (struct_name ctxt) visible; + val (decl, ctxt') = expand_antiquotes ants ctxt; + val (ml_env, ml_body) = decl ctxt'; + in ((begin_env @ ml_env @ end_env, ml_body), SOME ctxt') end; in fun eval flags pos ants = let val non_verbose = ML_Compiler.verbose false flags; (*prepare source text*) - val ((env, body), env_ctxt) = eval_antiquotes (ants, pos) (Context.get_generic_context ()); + val ((env, body), env_ctxt) = eval_antiquotes ants (Context.get_generic_context ()); val _ = (case env_ctxt of SOME ctxt => if Config.get ctxt ML_Options.source_trace andalso Context_Position.is_visible ctxt then tracing (cat_lines [ML_Lex.flatten env, ML_Lex.flatten body]) else () | NONE => ()); (*prepare environment*) val _ = Context.setmp_generic_context (Option.map (Context.Proof o Context_Position.set_visible false) env_ctxt) (fn () => (ML_Compiler.eval non_verbose Position.none env; Context.get_generic_context ())) () |> (fn NONE => () | SOME context' => Context.>> (ML_Env.inherit [context'])); (*eval body*) val _ = ML_Compiler.eval flags pos body; (*clear environment*) val _ = (case (env_ctxt, is_some (Context.get_generic_context ())) of (SOME ctxt, true) => let val name = struct_name ctxt; val _ = ML_Compiler.eval non_verbose Position.none (reset_env name); val _ = Context.>> (ML_Env.forget_structure name); in () end | _ => ()); in () end; end; (* derived versions *) fun eval_file flags path = let val pos = Path.position path in eval flags pos (ML_Lex.read_text (File.read path, pos)) end; fun eval_source flags source = let val opt_context = Context.get_generic_context (); val {read_source, ...} = ML_Env.operations opt_context (#environment flags); in eval flags (Input.pos_of source) (read_source source) end; fun eval_in ctxt flags pos ants = Context.setmp_generic_context (Option.map Context.Proof ctxt) (fn () => eval flags pos ants) (); fun eval_source_in ctxt flags source = Context.setmp_generic_context (Option.map Context.Proof ctxt) (fn () => eval_source flags source) (); fun exec (e: unit -> unit) context = (case Context.setmp_generic_context (SOME context) (fn () => (e (); Context.get_generic_context ())) () of SOME context' => context' | NONE => error "Missing context after execution"); fun expression pos ants = exec (fn () => eval ML_Compiler.flags pos ants); end; val ML = ML_Context.eval_source (ML_Compiler.verbose true ML_Compiler.flags);