{"text": "(*\n Copyright 2022, Proofcraft Pty Ltd\n Copyright 2021, Data61, CSIRO (ABN 41 687 119 230)\n\n SPDX-License-Identifier: CC-BY-SA-4.0\n*)\n\nchapter \\An Isabelle Syntax Style Guide\\\n\ntheory Style\n imports\n Style_pre\n Lib.SplitRule\nbegin\n\ntext \\\n This page describes the Isabelle syntax style conventions that we follow. For more on semantic\n style see Gerwin's style guides [1] and [2].\\\n\nsection \\General Principles\\\n\ntext \\\n Goals:\n * Readability and consistency:\n reduce cognitive overhead.\n\n * Make good use of horizontal space:\n most screens are wide, not high\n\n * Semantic indentation:\n where possible group things according to meaning. But remain syntactically consistent:\n a sub-term should not go more left than its parent term.\n\n * Support tools like diff and grep:\n diff tries to find the \"function\" each chunk belongs to by indentation. If we remain\n compatible, diffs are much easier to read. Pull requests mean we read a lot of diffs.\n grep and other regexp search is not needed as much as it used to, but it's still often\n useful to be able to find constants and lemmas by regexp search outside of Isabelle\n\n * Don't fight existing auto-indent where possible:\n there can be exceptions, but each time we go against defaults, it will be annoying to follow.\n\n * Compatibility with upstream style where it exists:\n there is not much consistent Isabelle distribution style, but where there is, we should follow\n it, so that others can read our code and we can contribute upstream\\\n\ntext \\\n The main rules:\n * Indent your proofs.\n\n * Follow naming conventions.\n\n * Be aware that others have to read what you write.\\\n\ntext \\\n To not drive proof maintainers insane:\n\n * Do not use `auto` except at the end of a proof, see [1].\n\n * Never check in proofs containing `back`.\n\n * Instantiate bound variables in preference to leaving schematics in a subgoal\n (i.e. use erule_tac ... allE in preference to erule allE)\n\n * Explicitly name variables that the proof text refers to (e.g. with rename_tac)\n\n * Don't mix object and meta logic in a lemma statement.\\\n\nsection \\Text and comments\\\n\ntext \\\n Generally, prefer @{command text} comments over (* source comments *), because the former\n will be displayed in LaTeX and HTML output. Be aware of LaTeX pitfalls and use antiquotations\n such as @{text some_id} or @{term \"1+1\"} for identifiers and terms, especially when they\n contain underscores and other sequences that already have meaning in LaTeX.\n\n For comments inside inner-syntax terms use the \\ \\comment symbol\\ and to comment out parts\n of a term the \\<^cancel>\\cancel symbol\\.\n\n For comments in apply proofs use either the \\ \\comment symbol\\ or source (* comments *).\n Source comments are fine here because we don't expect apply proofs to be read in PDF.\\\n\ntext \\This is a comment that fits in one line. It is on the same line as @{command text}.\\\n\ntext \\\n Once you have to break the line, keep @{command text} and the opening bracket on its own line, and\n the closing bracket on the same line as the ending text to not waste too much vertical space.\n Indent text by 2 inside the @{command text} area. This achieves visual separation.\\\n\nsection \\Indentation\\\n\ntext \\\n Isabelle code is much easier to maintain when indented consistently. In apply style proofs we\n indent by 2 spaces, and add an additional space for every additional subgoal.\n\n In the following example, the rules iffI and conjI add a new subgoal, and fast removes a subgoal.\n The idea is that, when something breaks, the indentation tells you whether a tactic used to solve\n a subgoal or produced new ones.\\\n\nlemma disj_conj_distribR:\n \"(A \\ B \\ C) = ((A \\ C) \\ (B \\ C))\"\n apply (rule iffI)\n apply (rule conjI)\n apply fast\n apply fast\n apply auto\n done\n\ntext \\The statement of Hoare triple lemmas are generally indented in the following way.\\\n\nlemma my_hoare_triple_lemma:\n \"\\precondition_one and precondition_two and\n precondition three\\\n my_function param_a param_b\n \\post_condition\\\"\n oops\n\ntext \\ or \\\n\nlemma my_hoare_triple_lemma:\n \"\\precondition_one and precondition_two\n and precondition three\\\n my_function param_a param_b\n \\post_condition\\\"\n oops\n\ntext \\\n Definitions, record and datatypes are generally indented as follows and generally use @{text \\\\\\}\n rather than @{text \\=\\}. Short datatypes can be on a single line.\n\n Note: Upstream Isabelle tends to use @{text \\=\\} rather than @{text \\\\\\}. So we don't enforce a\n strict rule in this case.\\\n\ndefinition word_bits :: nat where\n \"word_bits \\ 32\"\n\ndefinition long_defn_type ::\n \"'this => 'is => 'a => 'long => 'type => 'that => 'does =>\n 'not => 'fit => 'in => 'one => 'line\"\n where\n \"long_defn_type \\ undefined\"\n\nfun foo_fun :: \"nat \\ nat\" where\n \"foo_fun 0 = 0\"\n | \"foo_fun (Suc n) = n\"\n\nrecord cdl_cnode =\n cdl_cnode_caps :: type_foo\n cdl_cnode_size_bits :: type_bar\n\ndatatype cdl_object =\n Endpoint\n | Tcb type_foo\n | CNode cdl_cnode\n | Untyped\n\ndatatype cdl_arch = IA32 | ARM11\n\ntext \\\n There are tools to automatically indent proofs in jEdit. In terms of rules:\n\n * definition and fun should be on the same line as the name.\n * Everything after the first line of a definition or fun statement should be indented.\n * Type definitions (record, type_synonym, datatype) have the defined type on the same line, the\n rest only if it fits.\n * Avoid long hanging indentation in data types, case expressions, etc. That is:\n\n Wrong:\n\n @{term\\\n case xs_blah of [] \\ foo\n | y#ys \\ baz\n \\}\n\n Right:\n\n @{term\\\n case xs_blah of\n [] \\ foo\n | y#ys \\ baz\n \\}\\\n\ntext \\\n If a definition body causes an overflow of the 100 char line limit, use one\n of the following two patterns.\\\n\ndefinition hd_opt :: \"'a list \\ 'a option\" where\n \"hd_opt \\ case_list\n None\n (\\h t. Some h)\"\n\ndefinition hd_opt4 :: \"'a list \\ 'a option\" where\n \"hd_opt4 \\\n case_list None (\\h t. Some h)\"\n\ntext \\\n If an apply line causes an overflow of the 100 char line limit, use one\n of the following two patterns: aligning on \":\" or aligning on left.\\\n\nlemma test_lemma0:\n \"\\hd_opt l \\ None; hd_opt (hd l) = Some x\\ \\\n hd_opt (concat l) = Some x\"\n apply (clarsimp simp: hd_opt_def\n split: list.splits)\n done\n\nlemma test_lemma1:\n \"\\hd_opt l \\ None; hd_opt (hd l) = Some x\\ \\\n hd_opt (concat l) = Some x\"\n apply (clarsimp simp: hd_opt_def\n split: list.splits)\n done\n\nlemma test_lemma3:\n \"case_option None hd_opt (hd_opt l) = Some x \\\n hd_opt (concat l) = Some x\"\n apply ((cases l; simp add: hd_opt_def),\n rename_tac h t,\n case_tac h; simp)\n done\n\nsection \\Other\\\n\ntext \\\n General layout:\n * Wrap at 100, avoid overly long lines, not everyone has a big screen\n * No tabs, use spaces instead, standard indentation is 2\n * Avoid starting lines with quotes (\"), it breaks some automated tools.\n * Avoid unnecessary parentheses, unless it becomes really unclear what is going on. Roughly,\n parentheses are unnecessary if Isabelle doesn't show them in output.\n\n Other:\n * Avoid commands that produce \"legacy\" warnings. Add an issue with tag cleanup if you see them\n after an Isabelle update.\\\n\nsection \\Comments\\\n\ntext \\\n (* .. *) style comments are not printed in latex. Use them if you don't think anyone will want to\n see this printed. Otherwise, prefer text \\ .. \\\n\n In stark difference to the Isabelle distribution, we do comment stuff. If you have defined or done\n anything that is tricky, required you to think deeply, or similar, save everyone else the\n duplicated work and document why things are the way you've written them.\n\n We've been slack on commenting in the past. We should do more of it rather than less.\n There's no need to comment every single thing, though. Use your judgement. Prefer readable\n code/proofs/definitions over commented ones. Comment on why the proof is doing something,\n not what it is doing.\\\n\n\nsection \\Fun, primrec, or case? case!\\\n\ntext \\\n When defining a non-recursive function that uses pattern matching, there are multiple options:\n @{command fun}, @{command primrec}, and @{text case}. @{text case} initially seems like the least\n powerful of these, but combined with the @{attribute split_simps} attribute, it is the option that\n provides the highest degree of proof automation. @{command fun} and @{command primrec} provide\n a simp rule for each of the pattern cases, but when a closed term appears in the proof, there is\n no way to automatically perform a case distinction -- you need to do a manual @{method cases} or\n @{method case_tac} invocation. @{text case} does provide automatic splitting via split rules, and\n @{attribute split_simps} adds the missing simp rules.\n\n So the recommended pattern is to use @{text case} in the definition and supply the simp rules\n directly after it, adding them to the global simp set as @{command fun}/@{command primrec} would\n do. The split rule you need to provide to @{attribute split_simps} is the split rule for the type\n over which the pattern is matched. For nested patterns, multiple split rules can be provided. See\n also the example in @{theory Lib.SplitRule}.\\\n\ndefinition some_f :: \"nat \\ nat\" where\n \"some_f x \\ case x of 0 \\ 1 | Suc n \\ n+2\"\n\nlemmas some_f_simps[simp] = some_f_def[split_simps nat.split]\n\n(* Pattern is simplified automatically: *)\nlemma \"some_f 0 = 1\"\n by simp\n\n(* But automated case split is still available after unfolding: *)\nlemma \"some_f x > 0\"\n unfolding some_f_def by (simp split: nat.split)\n\n\nsection \\More on proofs\\\n\nsubsection \\prefer and defer\\\n\ntext \\\n There are currently no hard rules on the use of `prefer` and `defer n`. Two general principles\n apply:\n\n 1. If they are used too frequently then a proof may become unreadable. Do not use them\n unnecessarily and consider including comments to indicate their purpose.\n 2. If they are used too \"specifically\" then a proof may break very frequently for not-\n interesting reasons. This makes a proof less maintainable and so this should be avoided.\n\n A known use case for `prefer` is where a proof has a tree-like structure, and the prover wants to\n approach it with a breadth-first approach. Since the default isabelle strategy is depth-first,\n prefers (or defers) will be needed, e.g. corres proofs.\\\n\nsubsection \\Using by\\\n\ntext \\\n When all subgoals of a proof can be solved in one apply statement, use `by`.\\\n\nlemma\n \"True\"\n by simp\n\nlemma\n \"X\"\n apply (subgoal_tac \"True\")\n prefer 2\n subgoal by blast\n apply (subgoal_tac \"True\")\n prefer 2\n subgoal\n by blast \\ \\for tactic invocations that would overflow the line\\\n oops\n\ntext \\\n When all subgoals of a proof can be solved in two apply statements, use `by` to indicate the\n intermediate state is not interesting.\\\n\nlemma\n \"True \\ True\"\n by (rule conjI) auto\n\nlemma\n \"True \\ True\"\n by (rule conjI)\n auto \\ \\for tactic invocations that would overflow the line\\\n\ntext \\\n Avoid using `by` at the end of an apply-style proof with multiple steps.\n The exception to this rule are long-running statements (over 2 seconds) that complete the proof.\n There, we favour parallelism (proof forking in interactive mode) over visual consistency.\n\n If you do use `by` starting on a line of its own, it should be indented as if it were an\n apply statement.\n NOTE: the default Isabelle auto-indenter will not indent `by` according to the number of goals,\n which is another reason to avoid mixing it with apply style\\\n\nlemma\n \"True \\ True \\ True \\ True \\ True \\ True \\ True\"\n apply (intro conjI)\n apply blast\n apply blast\n apply auto\n done \\ \\use this style in general: no by\\\n\nlemma long_running_ending:\n \"True \\ True \\ True \\ True \\ True \\ True \\ True\"\n apply (intro conjI)\n apply blast\n apply blast\n by auto \\ \\only if long-running, and note indentation!\\\n\nsubsection \\Unfolding definitions\\\n\ntext \\\n When unfolding definitions at the start of a proof, use `unfolding` instead of the simplifier.\n This is not a hard rule but is strongly preferred, since the unfolding step is then stable and it\n makes it obvious that nothing interesting is supposed to be happening. For example, use\\\n\nlemma my_hoare_triple_lemma:\n \"\\precondition_one and precondition_two and\n precondition three\\\n my_function param_a param_b\n \\post_condition\\\"\n unfolding my_function_def\n oops\n\ntext \\instead of\\\n\nlemma my_hoare_triple_lemma:\n \"\\precondition_one and precondition_two and\n precondition three\\\n my_function param_a param_b\n \\post_condition\\\"\n apply (clarsimp simp: my_function_def)\n oops\n\nsubsection \\ccorres statements\\\n\ntext \\\n We prefer the following formatting for ccorres statements. Recall that a ccorres statement has\n the form\\\n\nlemma ccorres_example:\n \"ccorres rrel xf P Q hs a c\"\n oops\n\ntext \\\n where rrel is the return relation, xf is the extraction function, P is the abstract guard,\n Q is the concrete guard, hs is the handler stack, a is the abstract function, and c is the\n concrete function.\n\n If the statement can fit on a single line within the character limit, then this is best.\n If not, wherever possible\n - rrel and xf should occur on the same line,\n - P, Q, and hs should occur on the same line, and\n - a and c should occur on the same line\n\n Often the guards will require more than one line, and in this case, hs should occur on the same\n line as the concrete guard wherever possible.\n\n If the statement must use more than one line, all lines after the first should be indented by\n 2 spaces from @{term ccorres}.\n\n Here are some examples.\\\n\nlemma short_ccorres_example:\n \"ccorres rrel xf short_abs_guard short_conc_guard hs short_abs_fn short_conc_fn\"\n oops\n\nlemma long_ccorres_example:\n \"ccorres rrel xf\n long_abs_guard long_conc_guard hs\n long_abs_fn long_conc_fn\"\n oops\n\nlemma longer_ccorres_example:\n \"ccorres\n long_rrel\n long_xf\n long_abs_guard\n long_conc_guard hs\n long_abs_fn\n long_conc_fn\"\n oops\n\ntext \\\n The concrete guard will often be simply @{term UNIV}, or an intersection of terms of the form\n @{term \"\\\\pointer = cond\\\"}, which supersedes the set-builder notation wherever applicable.\n Note that the semantically redundant form @{term \"UNIV \\ \\\\pointer = cond\\\"} should no longer\n be necessary, and should be avoided wherever possible.\\\n\nsection \\Referenecs\\\n\ntext \\\n[1] https://proofcraft.org/blog/isabelle-style.html\n[2] https://proofcraft.org/blog/isabelle-style-part2.html \\\n\nend\n", "meta": {"author": "seL4", "repo": "l4v", "sha": "9ba34e269008732d4f89fb7a7e32337ffdd09ff9", "save_path": "github-repos/isabelle/seL4-l4v", "path": "github-repos/isabelle/seL4-l4v/l4v-9ba34e269008732d4f89fb7a7e32337ffdd09ff9/docs/Style.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.2365162364457076, "lm_q1q2_score": 0.09545011339972614}} {"text": "header {* Skeleton for Gabow's SCC Algorithm \\label{sec:skel}*}\ntheory Gabow_Skeleton\nimports \"../CAVA_Automata/Digraph\"\nbegin\ntext {*\n In this theory, we formalize a skeleton of Gabow's SCC algorithm. \n The skeleton serves as a starting point to develop concrete algorithms,\n like enumerating the SCCs or checking emptiness of a generalized Büchi automaton.\n*}\n\nsection {* Statistics Setup *}\ntext {*\n We define some dummy-constants that are included into the generated code,\n and may be mapped to side-effecting ML-code that records statistics and debug information\n about the execution. In the skeleton algorithm, we count the number of visited nodes,\n and include a timing for the whole algorithm.\n*}\n\ndefinition stat_newnode :: \"unit => unit\" -- \"Invoked if new node is visited\"\n where [code]: \"stat_newnode \\ \\_. ()\"\n\ndefinition stat_start :: \"unit => unit\" -- \"Invoked once if algorithm starts\"\n where [code]: \"stat_start \\ \\_. ()\"\n\ndefinition stat_stop :: \"unit => unit\" -- \"Invoked once if algorithm stops\"\n where [code]: \"stat_stop \\ \\_. ()\"\n\nlemma [autoref_rules]: \n \"(stat_newnode,stat_newnode) \\ unit_rel \\ unit_rel\"\n \"(stat_start,stat_start) \\ unit_rel \\ unit_rel\"\n \"(stat_stop,stat_stop) \\ unit_rel \\ unit_rel\"\n by auto\n\nabbreviation \"stat_newnode_nres \\ RETURN (stat_newnode ())\"\nabbreviation \"stat_start_nres \\ RETURN (stat_start ())\"\nabbreviation \"stat_stop_nres \\ RETURN (stat_stop ())\"\n\nlemma discard_stat_refine[refine]:\n \"m1\\m2 \\ stat_newnode_nres \\ m1 \\ m2\"\n \"m1\\m2 \\ stat_start_nres \\ m1 \\ m2\"\n \"m1\\m2 \\ stat_stop_nres \\ m1 \\ m2\"\n by simp_all\n\nsection {* Abstract Algorithm *}\ntext {*\n In this section, we formalize an abstract version of a path-based SCC algorithm.\n Later, this algorithm will be refined to use Gabow's data structure.\n*}\n\nsubsection {* Preliminaries *}\ndefinition path_seg :: \"'a set list \\ nat \\ nat \\ 'a set\"\n -- \"Set of nodes in a segment of the path\"\n where \"path_seg p i j \\ \\{p!k|k. i\\k \\ ki \\ path_seg p i j = {}\"\n \"path_seg p i (Suc i) = p!i\"\n unfolding path_seg_def\n apply auto []\n apply (auto simp: le_less_Suc_eq) []\n done\n\nlemma path_seg_drop:\n \"\\set (drop i p) = path_seg p i (length p)\"\n unfolding path_seg_def\n by (fastforce simp: in_set_drop_conv_nth Bex_def)\n\nlemma path_seg_butlast: \n \"p\\[] \\ path_seg p 0 (length p - Suc 0) = \\set (butlast p)\"\n apply (cases p rule: rev_cases, simp)\n apply (fastforce simp: path_seg_def nth_append in_set_conv_nth)\n done\n\ndefinition idx_of :: \"'a set list \\ 'a \\ nat\"\n -- \"Index of path segment that contains a node\"\n where \"idx_of p v \\ THE i. i v\\p!i\"\n\nlemma idx_of_props:\n assumes \n p_disjoint_sym: \"\\i j v. i j v\\p!i \\ v\\p!j \\ i=j\"\n assumes ON_STACK: \"v\\\\set p\"\n shows \n \"idx_of p v < length p\" and\n \"v \\ p ! idx_of p v\"\nproof -\n from ON_STACK obtain i where \"i p ! i\"\n by (auto simp add: in_set_conv_nth)\n moreover hence \"\\jp ! j \\ i=j\"\n using p_disjoint_sym by auto\n ultimately show \"idx_of p v < length p\" \n and \"v \\ p ! idx_of p v\" unfolding idx_of_def\n by (metis (lifting) theI')+\nqed\n\nlemma idx_of_uniq:\n assumes \n p_disjoint_sym: \"\\i j v. i j v\\p!i \\ v\\p!j \\ i=j\"\n assumes A: \"ip!i\"\n shows \"idx_of p v = i\"\nproof -\n from A p_disjoint_sym have \"\\jp ! j \\ i=j\" by auto\n with A show ?thesis\n unfolding idx_of_def\n by (metis (lifting) the_equality)\nqed\n\n\nsubsection {* Invariants *}\ntext {* The state of the inner loop consists of the path @{text \"p\"} of\n collapsed nodes, the set @{text \"D\"} of finished (done) nodes, and the set\n @{text \"pE\"} of pending edges. *}\ntype_synonym 'v abs_state = \"'v set list \\ 'v set \\ ('v\\'v) set\"\n\ncontext fr_graph\nbegin\n definition touched :: \"'v set list \\ 'v set \\ 'v set\" \n -- \"Touched: Nodes that are done or on path\"\n where \"touched p D \\ D \\ \\set p\"\n\n definition vE :: \"'v set list \\ 'v set \\ ('v \\ 'v) set \\ ('v \\ 'v) set\"\n -- \"Visited edges: No longer pending edges from touched nodes\"\n where \"vE p D pE \\ (E \\ (touched p D \\ UNIV)) - pE\"\n\n lemma vE_ss_E: \"vE p D pE \\ E\" -- \"Visited edges are edges\"\n unfolding vE_def by auto\n\nend\n\nlocale outer_invar_loc -- \"Invariant of the outer loop\"\n = fr_graph G for G :: \"('v,'more) fr_graph_rec_scheme\" +\n fixes it :: \"'v set\" -- {* Remaining nodes to iterate over *}\n fixes D :: \"'v set\" -- {* Finished nodes *}\n\n assumes it_initial: \"it\\V0\" -- \"Only start nodes to iterate over\"\n\n assumes it_done: \"V0 - it \\ D\" -- \"Nodes already iterated over are visited\"\n assumes D_reachable: \"D\\E\\<^sup>*``V0\" -- \"Done nodes are reachable\"\n assumes D_closed: \"E``D \\ D\" -- \"Done is closed under transitions\"\nbegin\n\n lemma locale_this: \"outer_invar_loc G it D\" by unfold_locales\n\n definition (in fr_graph) \"outer_invar \\ \\it D. outer_invar_loc G it D\"\n\n lemma outer_invar_this[simp, intro!]: \"outer_invar it D\"\n unfolding outer_invar_def apply simp by unfold_locales \nend\n\nlocale invar_loc -- \"Invariant of the inner loop\"\n = fr_graph G\n for G :: \"('v, 'more) fr_graph_rec_scheme\" +\n fixes v0 :: \"'v\"\n fixes D0 :: \"'v set\"\n fixes p :: \"'v set list\"\n fixes D :: \"'v set\"\n fixes pE :: \"('v\\'v) set\"\n\n assumes v0_initial[simp, intro!]: \"v0\\V0\"\n assumes D_incr: \"D0 \\ D\"\n\n assumes pE_E_from_p: \"pE \\ E \\ (\\set p) \\ UNIV\" \n -- \"Pending edges are edges from path\"\n assumes E_from_p_touched: \"E \\ (\\set p \\ UNIV) \\ pE \\ UNIV \\ touched p D\" \n -- \"Edges from path are pending or touched\"\n assumes D_reachable: \"D\\E\\<^sup>*``V0\" -- \"Done nodes are reachable\"\n assumes p_connected: \"Suc i p!i \\ p!Suc i \\ (E-pE) \\ {}\"\n -- \"CNodes on path are connected by non-pending edges\"\n\n assumes p_disjoint: \"\\i \\ p!i \\ p!j = {}\" \n -- \"CNodes on path are disjoint\"\n assumes p_sc: \"U\\set p \\ U\\U \\ (vE p D pE \\ U\\U)\\<^sup>*\" \n -- \"Nodes in CNodes are mutually reachable by visited edges\"\n\n assumes root_v0: \"p\\[] \\ v0\\hd p\" -- \"Root CNode contains start node\"\n assumes p_empty_v0: \"p=[] \\ v0\\D\" -- \"Start node is done if path empty\"\n \n assumes D_closed: \"E``D \\ D\" -- \"Done is closed under transitions\"\n (*assumes D_vis: \"E\\D\\D \\ vE\" -- \"All edges from done nodes are visited\"*)\n\n assumes vE_no_back: \"\\i \\ vE p D pE \\ p!j \\ p!i = {}\" \n -- \"Visited edges do not go back on path\"\n assumes p_not_D: \"\\set p \\ D = {}\" -- \"Path does not contain done nodes\"\nbegin\n abbreviation ltouched where \"ltouched \\ touched p D\"\n abbreviation lvE where \"lvE \\ vE p D pE\"\n\n lemma locale_this: \"invar_loc G v0 D0 p D pE\" by unfold_locales\n\n definition (in fr_graph) \n \"invar \\ \\v0 D0 (p,D,pE). invar_loc G v0 D0 p D pE\"\n\n lemma invar_this[simp, intro!]: \"invar v0 D0 (p,D,pE)\"\n unfolding invar_def apply simp by unfold_locales \n\n lemma finite_reachableE_v0[simp, intro!]: \"finite (E\\<^sup>*``{v0})\"\n apply (rule finite_subset[OF _ finite_reachableE_V0])\n using v0_initial by auto\n\n lemma D_vis: \"E\\D\\UNIV \\ lvE\" -- \"All edges from done nodes are visited\"\n unfolding vE_def touched_def using pE_E_from_p p_not_D by blast \n\n lemma vE_touched: \"lvE \\ ltouched \\ ltouched\" \n -- \"Visited edges only between touched nodes\"\n using E_from_p_touched D_closed unfolding vE_def touched_def by blast\n\n lemma lvE_ss_E: \"lvE \\ E\" -- \"Visited edges are edges\"\n unfolding vE_def by auto\n\n\n lemma path_touched: \"\\set p \\ ltouched\" by (auto simp: touched_def)\n lemma D_touched: \"D \\ ltouched\" by (auto simp: touched_def)\n\n lemma pE_by_vE: \"pE = (E \\ \\set p \\ UNIV) - lvE\"\n -- \"Pending edges are edges from path not yet visited\"\n unfolding vE_def touched_def\n using pE_E_from_p\n by auto\n\n lemma pick_pending: \"p\\[] \\ pE \\ last p \\ UNIV = (E-lvE) \\ last p \\ UNIV\"\n -- \"Pending edges from end of path are non-visited edges from end of path\"\n apply (subst pE_by_vE)\n by auto\n\n lemma p_connected': \n assumes A: \"Suc i p!Suc i \\ lvE \\ {}\" \n proof -\n from A p_not_D have \"p!i \\ set p\" \"p!Suc i \\ set p\" by auto\n with p_connected[OF A] show ?thesis unfolding vE_def touched_def\n by blast\n qed\n\nend\n\nsubsubsection {* Termination *}\n\ncontext fr_graph \nbegin\n text {* The termination argument is based on unprocessed edges: \n Reachable edges from untouched nodes and pending edges. *}\n definition \"unproc_edges v0 p D pE \\ (E \\ (E\\<^sup>*``{v0} - (D \\ \\set p)) \\ UNIV) \\ pE\"\n\n text {*\n In each iteration of the loop, either the number of unprocessed edges\n decreases, or the path length decreases. *}\n definition \"abs_wf_rel v0 \\ inv_image (finite_psubset <*lex*> measure length)\n (\\(p,D,pE). (unproc_edges v0 p D pE, p))\"\n\n lemma abs_wf_rel_wf[simp, intro!]: \"wf (abs_wf_rel v0)\"\n unfolding abs_wf_rel_def\n by auto\nend\n\nsubsection {* Abstract Skeleton Algorithm *}\n\ncontext fr_graph\nbegin\n\n definition (in fr_graph) initial :: \"'v \\ 'v set \\ 'v abs_state\"\n where \"initial v0 D \\ ([{v0}], D, (E \\ {v0}\\UNIV))\"\n\n definition (in -) collapse_aux :: \"'a set list \\ nat \\ 'a set list\"\n where \"collapse_aux p i \\ take i p @ [\\set (drop i p)]\"\n\n definition (in -) collapse :: \"'a \\ 'a abs_state \\ 'a abs_state\" \n where \"collapse v PDPE \\ \n let \n (p,D,pE)=PDPE; \n i=idx_of p v;\n p = collapse_aux p i\n in (p,D,pE)\"\n\n definition (in -) \n select_edge :: \"'a abs_state \\ ('a option \\ 'a abs_state) nres\"\n where\n \"select_edge PDPE \\ do {\n let (p,D,pE) = PDPE;\n e \\ select (pE \\ last p \\ UNIV);\n case e of\n None \\ RETURN (None,(p,D,pE))\n | Some (u,v) \\ RETURN (Some v, (p,D,pE - {(u,v)}))\n }\"\n\n definition (in fr_graph) push :: \"'v \\ 'v abs_state \\ 'v abs_state\" \n where \"push v PDPE \\ \n let\n (p,D,pE) = PDPE;\n p = p@[{v}];\n pE = pE \\ (E\\{v}\\UNIV)\n in\n (p,D,pE)\"\n\n definition (in -) pop :: \"'v abs_state \\ 'v abs_state\"\n where \"pop PDPE \\ let\n (p,D,pE) = PDPE;\n (p,V) = (butlast p, last p);\n D = V \\ D\n in\n (p,D,pE)\"\n\n text {* The following lemmas match the definitions presented in the paper: *}\n lemma \"select_edge (p,D,pE) \\ do {\n e \\ select (pE \\ last p \\ UNIV);\n case e of\n None \\ RETURN (None,(p,D,pE))\n | Some (u,v) \\ RETURN (Some v, (p,D,pE - {(u,v)}))\n }\"\n unfolding select_edge_def by simp\n\n lemma \"collapse v (p,D,pE) \n \\ let i=idx_of p v in (take i p @ [\\set (drop i p)],D,pE)\"\n unfolding collapse_def collapse_aux_def by simp\n\n lemma \"push v (p, D, pE) \\ (p @ [{v}], D, pE \\ E \\ {v} \\ UNIV)\"\n unfolding push_def by simp\n\n lemma \"pop (p, D, pE) \\ (butlast p, last p \\ D, pE)\"\n unfolding pop_def by auto\n\n thm pop_def[unfolded Let_def, no_vars]\n\n thm select_edge_def[unfolded Let_def]\n\n\n definition skeleton :: \"'v set nres\" \n -- \"Abstract Skeleton Algorithm\"\n where\n \"skeleton \\ do {\n let D = {};\n r \\ FOREACHi outer_invar V0 (\\v0 D0. do {\n if v0\\D0 then do {\n let s = initial v0 D0;\n\n (p,D,pE) \\ WHILEIT (invar v0 D0)\n (\\(p,D,pE). p \\ []) (\\(p,D,pE). \n do {\n (* Select edge from end of path *)\n (vo,(p,D,pE)) \\ select_edge (p,D,pE);\n\n ASSERT (p\\[]);\n case vo of \n Some v \\ do { (* Found outgoing edge to node v *)\n if v \\ \\set p then do {\n (* Back edge: Collapse path *)\n RETURN (collapse v (p,D,pE))\n } else if v\\D then do {\n (* Edge to new node. Append to path *)\n RETURN (push v (p,D,pE))\n } else do {\n (* Edge to done node. Skip *)\n RETURN (p,D,pE)\n }\n }\n | None \\ do {\n ASSERT (pE \\ last p \\ UNIV = {});\n (* No more outgoing edges from current node on path *)\n RETURN (pop (p,D,pE))\n }\n }) s;\n ASSERT (p=[] \\ pE={});\n RETURN D\n } else\n RETURN D0\n }) D;\n RETURN r\n }\"\n\nend\n\nsubsection {* Invariant Preservation *}\n\ncontext fr_graph begin\n\n lemma set_collapse_aux[simp]: \"\\set (collapse_aux p i) = \\set p\"\n apply (subst (2) append_take_drop_id[of _ p,symmetric])\n apply (simp del: append_take_drop_id)\n unfolding collapse_aux_def by auto\n\n lemma touched_collapse[simp]: \"touched (collapse_aux p i) D = touched p D\"\n unfolding touched_def by simp\n\n lemma vE_collapse_aux[simp]: \"vE (collapse_aux p i) D pE = vE p D pE\"\n unfolding vE_def by simp\n\n lemma touched_push[simp]: \"touched (p @ [V]) D = touched p D \\ V\"\n unfolding touched_def by auto\n\nend\n\nsubsubsection {* Corollaries of the invariant *}\ntext {* In this section, we prove some more corollaries of the invariant,\n which are helpful to show invariant preservation *}\n\ncontext invar_loc\nbegin\n lemma cnode_connectedI: \n \"\\ip!i; v\\p!i\\ \\ (u,v)\\(lvE \\ p!i\\p!i)\\<^sup>*\"\n using p_sc[of \"p!i\"] by (auto simp: in_set_conv_nth)\n\n lemma cnode_connectedI': \"\\ip!i; v\\p!i\\ \\ (u,v)\\(lvE)\\<^sup>*\"\n by (metis inf.cobounded1 rtrancl_mono_mp cnode_connectedI)\n\n lemma p_no_empty: \"{} \\ set p\"\n proof \n assume \"{}\\set p\"\n then obtain i where IDX: \"i p!i\\{}\"\n using p_no_empty by (metis nth_mem)\n \n lemma p_disjoint_sym: \"\\ip!i; v\\p!j\\ \\ i=j\"\n by (metis disjoint_iff_not_equal linorder_neqE_nat p_disjoint)\n\n lemma pi_ss_path_seg_eq[simp]:\n assumes A: \"ilength p\"\n shows \"p!i\\path_seg p l u \\ l\\i \\ ipath_seg p l u\"\n from A obtain x where \"x\\p!i\" by (blast dest: p_no_empty_idx)\n with B obtain i' where C: \"x\\p!i'\" \"l\\i'\" \"i'p!i` `x\\p!i'`] `i'length p`\n have \"i=i'\" by simp\n with C show \"l\\i \\ ilength p\" \"l2length p\"\n shows \"path_seg p l1 u1 \\ path_seg p l2 u2 \\ l2\\l1 \\ u1\\u2\"\n proof\n assume S: \"path_seg p l1 u1 \\ path_seg p l2 u2\"\n have \"p!l1 \\ path_seg p l1 u1\" using A by simp\n also note S finally have 1: \"l2\\l1\" using A by simp\n have \"p!(u1 - 1) \\ path_seg p l1 u1\" using A by simp\n also note S finally have 2: \"u1\\u2\" using A by auto\n from 1 2 show \"l2\\l1 \\ u1\\u2\" ..\n next\n assume \"l2\\l1 \\ u1\\u2\" thus \"path_seg p l1 u1 \\ path_seg p l2 u2\"\n using A\n apply (clarsimp simp: path_seg_def) []\n apply (metis dual_order.strict_trans1 dual_order.trans)\n done\n qed\n\n lemma pathI: \n assumes \"x\\p!i\" \"y\\p!j\"\n assumes \"i\\j\" \"j path_seg p i (Suc j)\"\n shows \"(x,y)\\(lvE \\ seg\\seg)\\<^sup>*\"\n -- \"We can obtain a path between cnodes on path\"\n using assms(3,1,2,4) unfolding seg_def\n proof (induction arbitrary: y rule: dec_induct)\n case base thus ?case by (auto intro!: cnode_connectedI)\n next\n case (step j)\n\n let ?seg = \"path_seg p i (Suc j)\"\n let ?seg' = \"path_seg p i (Suc (Suc j))\"\n\n have SSS: \"?seg \\ ?seg'\" \n apply (subst path_seg_ss_eq)\n using step.hyps step.prems by auto\n\n from p_connected'[OF `Suc j < length p`] obtain u v where \n UV: \"(u,v)\\lvE\" \"u\\p!j\" \"v\\p!Suc j\" by auto\n\n have ISS: \"p!j \\ ?seg'\" \"p!Suc j \\ ?seg'\" \n using step.hyps step.prems by simp_all\n\n from p_no_empty_idx[of j] `Suc j < length p` obtain x' where \"x'\\p!j\" \n by auto\n with step.IH[of x'] `x\\p!i` `Suc j < length p` \n have t: \"(x,x')\\(lvE\\?seg\\?seg)\\<^sup>*\" by auto\n have \"(x,x')\\(lvE\\?seg'\\?seg')\\<^sup>*\" using SSS \n by (auto intro: rtrancl_mono_mp[OF _ t])\n also \n from cnode_connectedI[OF _ `x'\\p!j` `u\\p!j`] `Suc j < length p` have\n t: \"(x', u) \\ (lvE \\ p ! j \\ p ! j)\\<^sup>*\" by auto\n have \"(x', u) \\ (lvE\\?seg'\\?seg')\\<^sup>*\" using ISS\n by (auto intro: rtrancl_mono_mp[OF _ t])\n also have \"(u,v)\\lvE\\?seg'\\?seg'\" using UV ISS by auto\n also from cnode_connectedI[OF `Suc j < length p` `v\\p!Suc j` `y\\p!Suc j`] \n have t: \"(v, y) \\ (lvE \\ p ! Suc j \\ p ! Suc j)\\<^sup>*\" by auto\n have \"(v, y) \\ (lvE\\?seg'\\?seg')\\<^sup>*\" using ISS\n by (auto intro: rtrancl_mono_mp[OF _ t])\n finally show \"(x,y)\\(lvE\\?seg'\\?seg')\\<^sup>*\" .\n qed\n\n lemma p_reachable: \"\\set p \\ E\\<^sup>*``{v0}\" -- \"Nodes on path are reachable\"\n proof \n fix v\n assume A: \"v\\\\set p\"\n then obtain i where \"ip!i\" \n by (metis UnionE in_set_conv_nth)\n moreover from A root_v0 have \"v0\\p!0\" by (cases p) auto\n ultimately have \n t: \"(v0,v)\\(lvE \\ path_seg p 0 (Suc i) \\ path_seg p 0 (Suc i))\\<^sup>*\"\n by (auto intro: pathI)\n from lvE_ss_E have \"(v0,v)\\E\\<^sup>*\" by (auto intro: rtrancl_mono_mp[OF _ t])\n thus \"v\\E\\<^sup>*``{v0}\" by auto\n qed\n\n lemma touched_reachable: \"ltouched \\ E\\<^sup>*``V0\" -- \"Touched nodes are reachable\"\n unfolding touched_def using p_reachable D_reachable by blast\n\n lemma vE_reachable: \"lvE \\ E\\<^sup>*``V0 \\ E\\<^sup>*``V0\"\n apply (rule order_trans[OF vE_touched])\n using touched_reachable by blast\n\n lemma pE_reachable: \"pE \\ E\\<^sup>*``{v0} \\ E\\<^sup>*``{v0}\"\n proof safe\n fix u v\n assume E: \"(u,v)\\pE\"\n with pE_E_from_p p_reachable have \"(v0,u)\\E\\<^sup>*\" \"(u,v)\\E\" by blast+\n thus \"(v0,u)\\E\\<^sup>*\" \"(v0,v)\\E\\<^sup>*\" by auto\n qed\n\n lemma D_closed_vE_rtrancl: \"lvE\\<^sup>*``D \\ D\"\n by (metis D_closed Image_closed_trancl eq_iff reachable_mono lvE_ss_E)\n\n lemma D_closed_path: \"\\path E u q w; u\\D\\ \\ set q \\ D\"\n proof -\n assume a1: \"path E u q w\"\n assume \"u \\ D\"\n hence f1: \"{u} \\ D\"\n using bot.extremum by force\n have \"set q \\ E\\<^sup>* `` {u}\"\n using a1 by (metis insert_subset path_nodes_reachable)\n thus \"set q \\ D\"\n using f1 by (metis D_closed rtrancl_reachable_induct subset_trans)\n qed\n\n lemma D_closed_path_vE: \"\\path lvE u q w; u\\D\\ \\ set q \\ D\"\n by (metis D_closed_path path_mono lvE_ss_E)\n\n lemma path_in_lastnode:\n assumes P: \"path lvE u q v\"\n assumes [simp]: \"p\\[]\"\n assumes ND: \"u\\last p\" \"v\\last p\"\n shows \"set q \\ last p\"\n -- \"A path from the last Cnode to the last Cnode remains in the last Cnode\"\n (* TODO: This can be generalized in two directions: \n either 1) The path end anywhere. Due to vE_touched we can infer \n that it ends in last cnode \n or 2) We may use any cnode, not only the last one\n *)\n using P ND\n proof (induction)\n case (path_prepend u v l w) \n from `(u,v)\\lvE` vE_touched have \"v\\ltouched\" by auto\n hence \"v\\\\set p\"\n unfolding touched_def\n proof\n assume \"v\\D\"\n moreover from `path lvE v l w` have \"(v,w)\\lvE\\<^sup>*\" by (rule path_is_rtrancl)\n ultimately have \"w\\D\" using D_closed_vE_rtrancl by auto\n with `w\\last p` p_not_D have False\n by (metis IntI Misc.last_in_set Sup_inf_eq_bot_iff assms(2) \n bex_empty path_prepend.hyps(2))\n thus ?thesis ..\n qed\n then obtain i where \"ip!i\"\n by (metis UnionE in_set_conv_nth)\n have \"i=length p - 1\"\n proof (rule ccontr)\n assume \"i\\length p - 1\"\n with `i last p \\ p!i = {}\"\n by (simp add: last_conv_nth)\n with `(u,v)\\lvE` `u\\last p` `v\\p!i` show False by auto\n qed\n with `v\\p!i` have \"v\\last p\" by (simp add: last_conv_nth)\n with path_prepend.IH `w\\last p` `u\\last p` show ?case by auto\n qed simp\n\n lemma loop_in_lastnode:\n assumes P: \"path lvE u q u\"\n assumes [simp]: \"p\\[]\"\n assumes ND: \"set q \\ last p \\ {}\"\n shows \"u\\last p\" and \"set q \\ last p\"\n -- \"A loop that touches the last node is completely inside the last node\"\n proof -\n from ND obtain v where \"v\\set q\" \"v\\last p\" by auto\n then obtain q1 q2 where [simp]: \"q=q1@v#q2\" \n by (auto simp: in_set_conv_decomp)\n from P have \"path lvE v (v#q2@q1) v\" \n by (auto simp: path_conc_conv path_cons_conv)\n from path_in_lastnode[OF this `p\\[]` `v\\last p` `v\\last p`] \n show \"set q \\ last p\" by simp\n from P show \"u\\last p\" \n apply (cases q, simp)\n \n apply simp\n using `set q \\ last p`\n apply (auto simp: path_cons_conv)\n done\n qed\n\n\n lemma no_D_p_edges: \"E \\ D \\ \\set p = {}\"\n using D_closed p_not_D by auto\n\n lemma idx_of_props:\n assumes ON_STACK: \"v\\\\set p\"\n shows \n \"idx_of p v < length p\" and\n \"v \\ p ! idx_of p v\"\n using idx_of_props[OF _ assms] p_disjoint_sym by blast+\n\nend\n\nsubsubsection {* Auxiliary Lemmas Regarding the Operations *}\n\nlemma (in fr_graph) vE_initial[simp]: \"vE [{v0}] {} (E \\ {v0} \\ UNIV) = {}\"\n unfolding vE_def touched_def by auto\n\ncontext invar_loc\nbegin\n lemma vE_push: \"\\ (u,v)\\pE; u\\last p; v\\\\set p; v\\D \\ \n \\ vE (p @ [{v}]) D ((pE - {(u,v)}) \\ E\\{v}\\UNIV) = insert (u,v) lvE\"\n unfolding vE_def touched_def using pE_E_from_p\n by auto\n\n lemma vE_remove[simp]: \n \"\\p\\[]; (u,v)\\pE\\ \\ vE p D (pE - {(u,v)}) = insert (u,v) lvE\"\n unfolding vE_def touched_def using pE_E_from_p by blast\n\n lemma vE_pop[simp]: \"p\\[] \\ vE (butlast p) (last p \\ D) pE = lvE\"\n unfolding vE_def touched_def \n by (cases p rule: rev_cases) auto\n\n\n lemma pE_fin: \"p=[] \\ pE={}\"\n using pE_by_vE by auto\n\n lemma (in invar_loc) lastp_un_D_closed:\n assumes NE: \"p \\ []\"\n assumes NO': \"pE \\ (last p \\ UNIV) = {}\"\n shows \"E``(last p \\ D) \\ (last p \\ D)\"\n -- \"On pop, the popped CNode and D are closed under transitions\"\n proof (intro subsetI, elim ImageE)\n from NO' have NO: \"(E - lvE) \\ (last p \\ UNIV) = {}\"\n by (simp add: pick_pending[OF NE])\n\n let ?i = \"length p - 1\"\n from NE have [simp]: \"last p = p!?i\" by (metis last_conv_nth) \n \n fix u v\n assume E: \"(u,v)\\E\"\n assume UI: \"u\\last p \\ D\" hence \"u\\p!?i \\ D\" by simp\n \n {\n assume \"u\\last p\" \"v\\last p\" \n moreover from E NO `u\\last p` have \"(u,v)\\lvE\" by auto\n ultimately have \"v\\D \\ v\\\\set p\" \n using vE_touched unfolding touched_def by auto\n moreover {\n assume \"v\\\\set p\"\n then obtain j where V: \"jp!j\" \n by (metis UnionE in_set_conv_nth)\n with `v\\last p` have \"jlvE` V `u\\last p` have False by auto\n } ultimately have \"v\\D\" by blast\n } with E UI D_closed show \"v\\last p \\ D\" by auto\n qed\n\n\n\nend\n\n\nsubsubsection {* Preservation of Invariant by Operations *}\n\ncontext fr_graph\nbegin\n lemma (in outer_invar_loc) invar_initial_aux: \n assumes \"v0\\it - D\"\n shows \"invar v0 D (initial v0 D)\"\n unfolding invar_def initial_def\n apply simp\n apply unfold_locales\n apply simp_all\n using assms it_initial apply auto []\n using D_reachable it_initial assms apply auto []\n using D_closed apply auto []\n using assms apply auto []\n done\n\n lemma invar_initial: \n \"\\outer_invar it D0; v0\\it; v0\\D0\\ \\ invar v0 D0 (initial v0 D0)\"\n unfolding outer_invar_def\n apply (drule outer_invar_loc.invar_initial_aux) \n by auto\n\n lemma outer_invar_initial[simp, intro!]: \"outer_invar V0 {}\"\n unfolding outer_invar_def\n apply unfold_locales\n by auto\n\n lemma invar_pop:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes NO': \"pE \\ (last p \\ UNIV) = {}\"\n shows \"invar v0 D0 (pop (p,D,pE))\"\n unfolding invar_def pop_def\n apply simp\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp\n\n have [simp]: \"set p = insert (last p) (set (butlast p))\" \n using NE by (cases p rule: rev_cases) auto\n\n from p_disjoint have lp_dj_blp: \"last p \\ \\set (butlast p) = {}\"\n apply (cases p rule: rev_cases)\n apply simp\n apply (fastforce simp: in_set_conv_nth nth_append)\n done\n\n {\n fix i\n assume A: \"Suc i < length (butlast p)\"\n hence A': \"Suc i < length p\" by auto\n\n from nth_butlast[of i p] A have [simp]: \"butlast p ! i = p ! i\" by auto\n from nth_butlast[of \"Suc i\" p] A \n have [simp]: \"butlast p ! Suc i = p ! Suc i\" by auto\n\n from p_connected[OF A'] \n have \"butlast p ! i \\ butlast p ! Suc i \\ (E - pE) \\ {}\"\n by simp\n } note AUX_p_connected = this\n\n (*have [simp]: \"(E \\ (last p \\ D \\ \\set (butlast p)) \\ UNIV - pE) = vE\"\n unfolding vE_def touched_def by auto*)\n\n show \"invar_loc G v0 D0 (butlast p) (last p \\ D) pE\"\n apply unfold_locales\n \n unfolding vE_pop[OF NE]\n\n apply simp\n\n using D_incr apply auto []\n\n using pE_E_from_p NO' apply auto []\n \n using E_from_p_touched apply (auto simp: touched_def) []\n \n using D_reachable p_reachable NE apply auto []\n\n apply (rule AUX_p_connected, assumption+) []\n\n using p_disjoint apply (simp add: nth_butlast)\n\n using p_sc apply simp\n\n using root_v0 apply (cases p rule: rev_cases) apply auto [2]\n\n using root_v0 p_empty_v0 apply (cases p rule: rev_cases) apply auto [2]\n\n apply (rule lastp_un_D_closed, insert NO', auto) []\n\n using vE_no_back apply (auto simp: nth_butlast) []\n\n using p_not_D lp_dj_blp apply auto []\n done\n qed\n\n thm invar_pop[of v_0 D_0, no_vars]\n\n lemma invar_collapse:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes E: \"(u,v)\\pE\" and \"u\\last p\"\n assumes BACK: \"v\\\\set p\"\n defines \"i \\ idx_of p v\"\n defines \"p' \\ collapse_aux p i\"\n shows \"invar v0 D0 (collapse v (p,D,pE - {(u,v)}))\"\n unfolding invar_def collapse_def\n apply simp\n unfolding i_def[symmetric] p'_def[symmetric]\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp\n\n let ?thesis=\"invar_loc G v0 D0 p' D (pE - {(u,v)})\"\n\n have SETP'[simp]: \"\\set p' = \\set p\" unfolding p'_def by simp\n\n have IL: \"i < length p\" and VMEM: \"v\\p!i\" \n using idx_of_props[OF BACK] unfolding i_def by auto\n\n have [simp]: \"length p' = Suc i\" \n unfolding p'_def collapse_aux_def using IL by auto\n\n have P'_IDX_SS: \"\\j p'!j\"\n unfolding p'_def collapse_aux_def using IL \n by (auto simp add: nth_append path_seg_drop)\n\n from `u\\last p` have \"u\\p!(length p - 1)\" by (auto simp: last_conv_nth)\n\n have defs_fold: \n \"vE p' D (pE - {(u,v)}) = insert (u,v) lvE\" \n \"touched p' D = ltouched\"\n by (simp_all add: p'_def E)\n\n {\n fix j\n assume A: \"Suc j < length p'\" \n hence \"Suc j < length p\" using IL by simp\n from p_connected[OF this] have \"p!j \\ p!Suc j \\ (E-pE) \\ {}\" .\n moreover from P'_IDX_SS A have \"p!j\\p'!j\" and \"p!Suc j \\ p'!Suc j\"\n by auto\n ultimately have \"p' ! j \\ p' ! Suc j \\ (E - (pE - {(u, v)})) \\ {}\" \n by blast\n } note AUX_p_connected = this\n\n have P_IDX_EQ[simp]: \"\\j. j < i \\ p'!j = p!j\"\n unfolding p'_def collapse_aux_def using IL \n by (auto simp: nth_append)\n\n have P'_LAST[simp]: \"p'!i = path_seg p i (length p)\" (is \"_ = ?last_cnode\")\n unfolding p'_def collapse_aux_def using IL \n by (auto simp: nth_append path_seg_drop)\n\n {\n fix j k\n assume A: \"j < k\" \"k < length p'\" \n have \"p' ! j \\ p' ! k = {}\"\n proof (safe, simp)\n fix v\n assume \"v\\p'!j\" and \"v\\p'!k\"\n with A have \"v\\p!j\" by simp\n show False proof (cases)\n assume \"k=i\"\n with `v\\p'!k` obtain k' where \"v\\p!k'\" \"i\\k'\" \"k' p ! k' = {}\"\n using A by (auto intro!: p_disjoint)\n with `v\\p!j` `v\\p!k'` show False by auto\n next\n assume \"k\\i\" with A have \"kp'!j` `v\\p'!k` by auto\n qed\n qed\n } note AUX_p_disjoint = this\n\n {\n fix U\n assume A: \"U\\set p'\"\n then obtain j where \"j U \\ (insert (u, v) lvE \\ U \\ U)\\<^sup>*\" \n proof cases\n assume [simp]: \"j=i\"\n show ?thesis proof (clarsimp)\n fix x y\n assume \"x\\path_seg p i (length p)\" \"y\\path_seg p i (length p)\"\n then obtain ix iy where \n IX: \"x\\p!ix\" \"i\\ix\" \"ixp!iy\" \"i\\iy\" \"iy ?last_cnode\"\n by (subst path_seg_ss_eq) auto\n\n from IY have SS2: \"path_seg p i (Suc iy) \\ ?last_cnode\"\n by (subst path_seg_ss_eq) auto\n\n let ?rE = \"\\R. (lvE \\ R\\R)\"\n let ?E = \"(insert (u,v) lvE \\ ?last_cnode \\ ?last_cnode)\"\n\n from pathI[OF `x\\p!ix` `u\\p!(length p - 1)`] have\n \"(x,u)\\(?rE (path_seg p ix (Suc (length p - 1))))\\<^sup>*\" using IX by auto\n hence \"(x,u)\\?E\\<^sup>*\" \n apply (rule rtrancl_mono_mp[rotated]) \n using SS1\n by auto\n\n also have \"(u,v)\\?E\" using `ip!(length p - 1)`])\n apply (simp)\n apply (rule set_rev_mp[OF VMEM])\n apply (simp)\n done\n also \n from pathI[OF `v\\p!i` `y\\p!iy`] have\n \"(v,y)\\(?rE (path_seg p i (Suc iy)))\\<^sup>*\" using IY by auto\n hence \"(v,y)\\?E\\<^sup>*\"\n apply (rule rtrancl_mono_mp[rotated]) \n using SS2\n by auto\n finally show \"(x,y)\\?E\\<^sup>*\" .\n qed\n next\n assume \"j\\i\"\n with `jset p\"\n by (metis Suc_lessD in_set_conv_nth less_trans_Suc) \n\n thus ?thesis using p_sc[of U] `p!j\\set p`\n apply (clarsimp)\n apply (subgoal_tac \"(a,b)\\(lvE \\ p ! j \\ p ! j)\\<^sup>*\")\n apply (erule rtrancl_mono_mp[rotated])\n apply auto\n done\n qed\n } note AUX_p_sc = this\n\n { fix j k\n assume A: \"j p' ! k \\ p' ! j = {}\"\n proof -\n have \"{(u,v)} \\ p' ! k \\ p' ! j = {}\" \n apply auto\n by (metis IL P_IDX_EQ Suc_lessD VMEM `j < i` \n less_irrefl_nat less_trans_Suc p_disjoint_sym)\n moreover have \"lvE \\ p' ! k \\ p' ! j = {}\" \n proof (cases \"klvE\" \"x\\path_seg p i (length p)\" \"y\\p!j\"\n then obtain ix where \"x\\p!ix\" \"i\\ix\" \"ix[]\"\n assumes E: \"(u,v)\\pE\" and UIL: \"u\\last p\"\n assumes VNE: \"v\\\\set p\" \"v\\D\"\n shows \"invar v0 D0 (push v (p,D,pE - {(u,v)}))\"\n unfolding invar_def push_def\n apply simp\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp\n\n let ?thesis \n = \"invar_loc G v0 D0 (p @ [{v}]) D (pE - {(u, v)} \\ E \\ {v} \\ UNIV)\"\n\n note defs_fold = vE_push[OF E UIL VNE] touched_push\n\n {\n fix i\n assume \"Suc i < length (p @ [{v}])\"\n hence \"(p @ [{v}]) ! i \\ (p @ [{v}]) ! Suc i \n \\ (E - (pE - {(u, v)} \\ E \\ {v} \\ UNIV)) \\ {}\"\n apply (cases \"i = length p - 1\")\n using E pE_E_from_p UIL VNE\n apply (simp add: nth_append last_conv_nth) apply fast []\n using p_connected VNE\n apply (simp add: nth_append)\n apply fastforce []\n done\n } note AUX_p_connected = this\n\n {\n fix U\n assume A: \"U \\ set (p @ [{v}])\"\n have \"U \\ U \\ (insert (u, v) lvE \\ U \\ U)\\<^sup>*\"\n proof cases\n assume \"U\\set p\"\n with p_sc have \"U\\U \\ (lvE \\ U\\U)\\<^sup>*\" .\n thus ?thesis\n by (metis (lifting, no_types) Int_insert_left_if0 Int_insert_left_if1 \n in_mono insert_subset rtrancl_mono_mp subsetI)\n next\n assume \"U\\set p\" with A have \"U={v}\" by simp\n thus ?thesis by auto\n qed\n } note AUX_p_sc = this\n\n {\n fix i j\n assume A: \"i < j\" \"j < length (p @ [{v}])\"\n have \"insert (u, v) lvE \\ (p @ [{v}]) ! j \\ (p @ [{v}]) ! i = {}\"\n proof (cases \"j=length p\")\n case False with A have \"j D = {}\" \n by (auto simp: Sup_inf_eq_bot_iff)\n case True thus ?thesis\n using A apply (simp add: nth_append)\n apply (rule conjI)\n using UIL A p_disjoint_sym\n apply (metis Misc.last_in_set NE UnionI VNE(1))\n\n using vE_touched VNE PDDJ apply (auto simp: touched_def) []\n done\n qed\n } note AUX_vE_no_back = this\n \n show ?thesis\n apply unfold_locales\n unfolding defs_fold\n\n apply simp\n\n using D_incr apply auto []\n\n using pE_E_from_p apply auto []\n\n using E_from_p_touched VNE apply (auto simp: touched_def) []\n\n apply (rule D_reachable)\n\n apply (rule AUX_p_connected, assumption+) []\n\n using p_disjoint `v\\\\set p` apply (auto simp: nth_append) []\n\n apply (rule AUX_p_sc, assumption+) []\n\n using root_v0 apply simp\n\n apply simp\n\n apply (rule D_closed)\n\n apply (rule AUX_vE_no_back, assumption+) []\n\n using p_not_D VNE apply auto []\n done\n qed\n\n lemma invar_skip:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes E: \"(u,v)\\pE\" and UIL: \"u\\last p\"\n assumes VNP: \"v\\\\set p\" and VD: \"v\\D\"\n shows \"invar v0 D0 (p,D,pE - {(u, v)})\"\n unfolding invar_def\n apply simp\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp\n let ?thesis = \"invar_loc G v0 D0 p D (pE - {(u, v)})\"\n note defs_fold = vE_remove[OF NE E]\n\n show ?thesis\n apply unfold_locales\n unfolding defs_fold\n \n apply simp\n\n using D_incr apply auto []\n\n using pE_E_from_p apply auto []\n\n using E_from_p_touched VD apply (auto simp: touched_def) []\n\n apply (rule D_reachable)\n\n using p_connected apply auto []\n\n apply (rule p_disjoint, assumption+) []\n\n apply (drule p_sc)\n apply (erule order_trans)\n apply (rule rtrancl_mono)\n apply blast []\n\n apply (rule root_v0, assumption+) []\n\n apply (rule p_empty_v0, assumption+) []\n\n apply (rule D_closed)\n\n using vE_no_back VD p_not_D \n apply clarsimp\n apply (metis Suc_lessD UnionI VNP less_trans_Suc nth_mem)\n\n apply (rule p_not_D)\n done\n qed\n\n\n lemma fin_D_is_reachable: \n -- \"When inner loop terminates, all nodes reachable from start node are\n finished\"\n assumes INV: \"invar v0 D0 ([], D, pE)\"\n shows \"D \\ E\\<^sup>*``{v0}\"\n proof -\n from INV interpret invar_loc G v0 D0 \"[]\" D pE unfolding invar_def by auto\n\n from p_empty_v0 rtrancl_reachable_induct[OF order_refl D_closed] D_reachable\n show ?thesis by auto\n qed\n\n lemma fin_reachable_path: \n -- \"When inner loop terminates, nodes reachable from start node are\n reachable over visited edges\"\n assumes INV: \"invar v0 D0 ([], D, pE)\"\n assumes UR: \"u\\E\\<^sup>*``{v0}\"\n shows \"path (vE [] D pE) u q v \\ path E u q v\"\n proof -\n from INV interpret invar_loc G v0 D0 \"[]\" D pE unfolding invar_def by auto\n \n show ?thesis\n proof\n assume \"path lvE u q v\"\n thus \"path E u q v\" using path_mono[OF lvE_ss_E] by blast\n next\n assume \"path E u q v\"\n thus \"path lvE u q v\" using UR\n proof induction\n case (path_prepend u v p w)\n with fin_D_is_reachable[OF INV] have \"u\\D\" by auto\n with D_closed `(u,v)\\E` have \"v\\D\" by auto\n from path_prepend.prems path_prepend.hyps have \"v\\E\\<^sup>*``{v0}\" by auto\n with path_prepend.IH fin_D_is_reachable[OF INV] have \"path lvE v p w\" \n by simp\n moreover from `u\\D` `v\\D` `(u,v)\\E` D_vis have \"(u,v)\\lvE\" by auto\n ultimately show ?case by (auto simp: path_cons_conv)\n qed simp\n qed\n qed\n\n lemma invar_outer_newnode: \n assumes A: \"v0\\D0\" \"v0\\it\" \n assumes OINV: \"outer_invar it D0\"\n assumes INV: \"invar v0 D0 ([],D',pE)\"\n shows \"outer_invar (it-{v0}) D'\"\n proof -\n from OINV interpret outer_invar_loc G it D0 unfolding outer_invar_def .\n from INV interpret inv!: invar_loc G v0 D0 \"[]\" D' pE \n unfolding invar_def by simp\n \n from fin_D_is_reachable[OF INV] have [simp]: \"v0\\D'\" by auto\n\n show ?thesis\n unfolding outer_invar_def\n apply unfold_locales\n using it_initial apply auto []\n using it_done inv.D_incr apply auto []\n using inv.D_reachable apply assumption\n using inv.D_closed apply assumption\n done\n qed\n\n lemma invar_outer_Dnode:\n assumes A: \"v0\\D0\" \"v0\\it\" \n assumes OINV: \"outer_invar it D0\"\n shows \"outer_invar (it-{v0}) D0\"\n proof -\n from OINV interpret outer_invar_loc G it D0 unfolding outer_invar_def .\n \n show ?thesis\n unfolding outer_invar_def\n apply unfold_locales\n using it_initial apply auto []\n using it_done A apply auto []\n using D_reachable apply assumption\n using D_closed apply assumption\n done\n qed\n\n lemma pE_fin': \"invar x \\ ([], D, pE) \\ pE={}\"\n unfolding invar_def by (simp add: invar_loc.pE_fin)\n\nend\n\nsubsubsection {* Termination *}\n\ncontext invar_loc \nbegin\n lemma unproc_finite[simp, intro!]: \"finite (unproc_edges v0 p D pE)\"\n -- \"The set of unprocessed edges is finite\"\n proof -\n have \"unproc_edges v0 p D pE \\ E\\<^sup>*``{v0} \\ E\\<^sup>*``{v0}\"\n unfolding unproc_edges_def \n using pE_reachable\n by auto\n thus ?thesis\n by (rule finite_subset) simp\n qed\n\n lemma unproc_decreasing: \n -- \"As effect of selecting a pending edge, the set of unprocessed edges\n decreases\"\n assumes [simp]: \"p\\[]\" and A: \"(u,v)\\pE\" \"u\\last p\"\n shows \"unproc_edges v0 p D (pE-{(u,v)}) \\ unproc_edges v0 p D pE\"\n using A unfolding unproc_edges_def\n by fastforce\nend\n\ncontext fr_graph \nbegin\n\n lemma abs_wf_pop:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes NO: \"pE \\ last aba \\ UNIV = {}\"\n shows \"(pop (p,D,pE), (p, D, pE)) \\ abs_wf_rel v0\"\n unfolding pop_def\n apply simp\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp \n let ?thesis = \"((butlast p, last p \\ D, pE), p, D, pE) \\ abs_wf_rel v0\"\n have \"unproc_edges v0 (butlast p) (last p \\ D) pE = unproc_edges v0 p D pE\"\n unfolding unproc_edges_def\n apply (cases p rule: rev_cases, simp)\n apply auto\n done\n thus ?thesis\n by (auto simp: abs_wf_rel_def)\n qed\n\n lemma abs_wf_collapse:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes E: \"(u,v)\\pE\" \"u\\last p\"\n shows \"(collapse v (p,D,pE-{(u,v)}), (p, D, pE))\\ abs_wf_rel v0\"\n unfolding collapse_def\n apply simp\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp \n def i \\ \"idx_of p v\"\n let ?thesis \n = \"((collapse_aux p i, D, pE-{(u,v)}), (p, D, pE)) \\ abs_wf_rel v0\"\n\n have \"unproc_edges v0 (collapse_aux p i) D (pE-{(u,v)}) \n = unproc_edges v0 p D (pE-{(u,v)})\"\n unfolding unproc_edges_def by (auto)\n also note unproc_decreasing[OF NE E]\n finally show ?thesis\n by (auto simp: abs_wf_rel_def)\n qed\n \n lemma abs_wf_push:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes E: \"(u,v)\\pE\" \"u\\last p\" and A: \"v\\D\" \"v\\\\set p\"\n shows \"(push v (p,D,pE-{(u,v)}), (p, D, pE)) \\ abs_wf_rel v0\"\n unfolding push_def\n apply simp\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp \n let ?thesis \n = \"((p@[{v}], D, pE-{(u,v)} \\ E\\{v}\\UNIV), (p, D, pE)) \\ abs_wf_rel v0\"\n\n have \"unproc_edges v0 (p@[{v}]) D (pE-{(u,v)} \\ E\\{v}\\UNIV) \n = unproc_edges v0 p D (pE-{(u,v)})\"\n unfolding unproc_edges_def\n using E A pE_reachable\n by auto\n also note unproc_decreasing[OF NE E]\n finally show ?thesis\n by (auto simp: abs_wf_rel_def)\n qed\n\n lemma abs_wf_skip:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes E: \"(u,v)\\pE\" \"u\\last p\"\n shows \"((p, D, pE-{(u,v)}), (p, D, pE)) \\ abs_wf_rel v0\"\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp \n from unproc_decreasing[OF NE E] show ?thesis\n by (auto simp: abs_wf_rel_def)\n qed\nend\n\nsubsubsection {* Main Correctness Theorem*}\n\ncontext fr_graph \nbegin\n lemmas invar_preserve = \n invar_initial\n invar_pop invar_push invar_skip invar_collapse \n abs_wf_pop abs_wf_collapse abs_wf_push abs_wf_skip \n outer_invar_initial invar_outer_newnode invar_outer_Dnode\n\n text {* The main correctness theorem for the dummy-algorithm just states that\n it satisfies the invariant when finished, and the path is empty.\n *}\n \n\n show ?thesis\n unfolding skeleton_def select_edge_def select_def\n apply (refine_rcg \n WHILEIT_rule[where R=\"abs_wf_rel v0\" for v0] refine_vcg)\n\n apply (vc_solve solve: invar_preserve simp: pE_fin')\n done\n qed\n\n text {* Short proof, as presented in the paper *}\n context \n notes [refine] = refine_vcg \n begin\n theorem \"skeleton \\ SPEC (\\D. outer_invar {} D)\"\n unfolding skeleton_def select_edge_def select_def\n by (refine_rcg WHILEIT_rule[where R=\"abs_wf_rel v0\" for v0])\n (vc_solve solve: invar_preserve simp: pE_fin')\n end\n\nend\n\nsubsection \"Consequences of Invariant when Finished\"\ncontext fr_graph\nbegin\n lemma fin_outer_D_is_reachable:\n -- \"When outer loop terminates, exactly the reachable nodes are finished\"\n assumes INV: \"outer_invar {} D\"\n shows \"D = E\\<^sup>*``V0\"\n proof -\n from INV interpret outer_invar_loc G \"{}\" D unfolding outer_invar_def by auto\n\n from it_done rtrancl_reachable_induct[OF order_refl D_closed] D_reachable\n show ?thesis by auto\n qed\n\nend\n\n\nsection {* Refinement to Gabow's Data Structure *}text_raw{*\\label{sec:algo-ds}*}\n\ntext {*\n The implementation due to Gabow \\cite{Gabow2000} represents a path as\n a stack @{text \"S\"} of single nodes, and a stack @{text \"B\"} that contains the\n boundaries of the collapsed segments. Moreover, a map @{text \"I\"} maps nodes\n to their stack indices.\n\n As we use a tail-recursive formulation, we use another stack \n @{text \"P :: (nat \\ 'v set) list\"} to represent the pending edges. The\n entries in @{text \"P\"} are sorted by ascending first component,\n and @{text \"P\"} only contains entries with non-empty second component. \n An entry @{text \"(i,l)\"} means that the edges from the node at \n @{text \"S[i]\"} to the nodes stored in @{text \"l\"} are pending.\n*}\n\nsubsection {* Preliminaries *}\nprimrec find_max_nat :: \"nat \\ (nat\\bool) \\ nat\" \n -- \"Find the maximum number below an upper bound for which a predicate holds\"\n where\n \"find_max_nat 0 _ = 0\"\n| \"find_max_nat (Suc n) P = (if (P n) then n else find_max_nat n P)\"\n\nlemma find_max_nat_correct: \n \"\\P 0; 0 \\ find_max_nat u P = Max {i. i P i}\"\n apply (induction u)\n apply auto\n\n apply (rule Max_eqI[THEN sym])\n apply auto [3]\n \n apply (case_tac u)\n apply simp\n apply clarsimp\n by (metis less_SucI less_antisym)\n\nlemma find_max_nat_param[param]:\n assumes \"(n,n')\\nat_rel\"\n assumes \"\\j j'. \\(j,j')\\nat_rel; j' \\ (P j,P' j')\\bool_rel\"\n shows \"(find_max_nat n P,find_max_nat n' P') \\ nat_rel\"\n using assms\n by (induction n arbitrary: n') auto\n\ncontext begin interpretation autoref_syn .\n lemma find_max_nat_autoref[autoref_rules]:\n assumes \"(n,n')\\nat_rel\"\n assumes \"\\j j'. \\(j,j')\\nat_rel; j' \\ (P j,P'$j')\\bool_rel\"\n shows \"(find_max_nat n P,\n (OP find_max_nat ::: nat_rel \\ (nat_rel\\bool_rel) \\ nat_rel) $n'$P'\n ) \\ nat_rel\"\n using find_max_nat_param[OF assms]\n by simp\n\nend\n\nsubsection {* Gabow's Datastructure *}\n\nsubsubsection {* Definition and Invariant *}\n\ndatatype node_state = STACK nat | DONE\n\ntype_synonym 'v oGS = \"'v \\ node_state\"\n\ndefinition oGS_\\ :: \"'v oGS \\ 'v set\" where \"oGS_\\ I \\ {v. I v = Some DONE}\"\n\nlocale oGS_invar = \n fixes I :: \"'v oGS\"\n assumes I_no_stack: \"I v \\ Some (STACK j)\"\n\n\ntype_synonym 'a GS \n = \"'a list \\ nat list \\ ('a \\ node_state) \\ (nat \\ 'a set) list\"\nlocale GS = \n fixes SBIP :: \"'a GS\"\nbegin\n definition \"S \\ (\\(S,B,I,P). S) SBIP\"\n definition \"B \\ (\\(S,B,I,P). B) SBIP\"\n definition \"I \\ (\\(S,B,I,P). I) SBIP\"\n definition \"P \\ (\\(S,B,I,P). P) SBIP\"\n\n definition seg_start :: \"nat \\ nat\" -- {* Start index of segment, inclusive *}\n where \"seg_start i \\ B!i\" \n\n definition seg_end :: \"nat \\ nat\" -- {* End index of segment, exclusive *}\n where \"seg_end i \\ if i+1 = length B then length S else B!(i+1)\"\n\n definition seg :: \"nat \\ 'a set\" -- {* Collapsed set at index *}\n where \"seg i \\ {S!j | j. seg_start i \\ j \\ j < seg_end i }\"\n\n definition \"p_\\ \\ map seg [0.. \\ {v. I v = Some DONE}\" -- {* Done nodes *}\n \n definition \"pE_\\ \\ { (u,v) . \\j I. (j,I)\\set P \\ u = S!j \\ v\\I }\" \n -- {* Pending edges *}\n\n definition \"\\ \\ (p_\\,D_\\,pE_\\)\" -- {* Abstract state *}\n\nend\n\nlemma GS_sel_simps[simp]:\n \"GS.S (S,B,I,P) = S\"\n \"GS.B (S,B,I,P) = B\"\n \"GS.I (S,B,I,P) = I\"\n \"GS.P (S,B,I,P) = P\"\n unfolding GS.S_def GS.B_def GS.I_def GS.P_def\n by auto\n\ncontext GS begin\n lemma seg_start_indep[simp]: \"GS.seg_start (S',B,I',P') = seg_start\" \n unfolding GS.seg_start_def[abs_def] by (auto)\n lemma seg_end_indep[simp]: \"GS.seg_end (S,B,I',P') = seg_end\" \n unfolding GS.seg_end_def[abs_def] by auto\n lemma seg_indep[simp]: \"GS.seg (S,B,I',P') = seg\" \n unfolding GS.seg_def[abs_def] by auto\n lemma p_\\_indep[simp]: \"GS.p_\\ (S,B,I',P') = p_\\\"\n unfolding GS.p_\\_def by auto\n\n lemma D_\\_indep[simp]: \"GS.D_\\ (S',B',I,P') = D_\\\"\n unfolding GS.D_\\_def by auto\n\n lemma pE_\\_indep[simp]: \"GS.pE_\\ (S,B',I',P) = pE_\\\" \n unfolding GS.pE_\\_def by auto\n\n definition find_seg -- \"Abs-path index for stack index\"\n where \"find_seg j \\ Max {i. i B!i\\j}\"\n\n definition S_idx_of -- \"Stack index for node\"\n where \"S_idx_of v \\ case I v of Some (STACK i) \\ i\"\n\nend\n\nlocale GS_invar = GS +\n assumes B_in_bound: \"set B \\ {0..[] \\ B\\[] \\ B!0=0\"\n assumes S_distinct: \"distinct S\"\n\n assumes I_consistent: \"(I v = Some (STACK j)) \\ (j v = S!j)\"\n \n assumes P_sorted: \"sorted (map fst P)\"\n assumes P_distinct: \"distinct (map fst P)\"\n assumes P_bound: \"set P \\ {0..Collect (op \\ {})\"\nbegin\n lemma locale_this: \"GS_invar SBIP\" by unfold_locales\n\nend\n\ndefinition \"oGS_rel \\ br oGS_\\ oGS_invar\"\nlemma oGS_rel_sv[intro!,simp,relator_props]: \"single_valued oGS_rel\"\n unfolding oGS_rel_def by auto\n\ndefinition \"GS_rel \\ br GS.\\ GS_invar\"\nlemma GS_rel_sv[intro!,simp,relator_props]: \"single_valued GS_rel\"\n unfolding GS_rel_def by auto\n\ncontext GS_invar\nbegin\n lemma empty_eq: \"S=[] \\ B=[]\"\n using B_in_bound B0 by auto\n\n lemma B_in_bound': \"i B!i < length S\"\n using B_in_bound nth_mem by fastforce\n\n lemma seg_start_bound:\n assumes A: \"i length S\"\n proof (cases \"i+1=length B\")\n case True thus ?thesis by (simp add: seg_end_def)\n next\n case False with A have \"i+1 seg_start i < seg_end i\"\n unfolding seg_start_def seg_end_def\n using B_in_bound' distinct_sorted_mono[OF B_sorted B_distinct]\n by auto\n\n lemma seg_end_less_start: \"\\i \\ seg_end i \\ seg_start j\"\n unfolding seg_start_def seg_end_def\n by (auto simp: distinct_sorted_mono_iff[OF B_distinct B_sorted])\n\n lemma find_seg_bounds:\n assumes A: \"j j\" \n and \"j < seg_end (find_seg j)\" \n and \"find_seg j < length B\"\n proof -\n let ?M = \"{i. i B!i\\j}\"\n from A have [simp]: \"B\\[]\" using empty_eq by (cases S) auto\n have NE: \"?M\\{}\" using A B0 by (cases B) auto\n\n have F: \"finite ?M\" by auto\n \n from Max_in[OF F NE]\n have LEN: \"find_seg j < length B\" and LB: \"B!find_seg j \\ j\"\n unfolding find_seg_def\n by auto\n\n thus \"find_seg j < length B\" by -\n \n from LB show LB': \"seg_start (find_seg j) \\ j\"\n unfolding seg_start_def by simp\n\n moreover show UB': \"j < seg_end (find_seg j)\"\n unfolding seg_end_def \n proof (split split_if, intro impI conjI)\n show \"j length B\" \n with LEN have P1: \"find_seg j + 1 < length B\" by simp\n\n show \"j < B ! (find_seg j + 1)\"\n proof (rule ccontr, simp only: linorder_not_less)\n assume P2: \"B ! (find_seg j + 1) \\ j\"\n with P1 Max_ge[OF F, of \"find_seg j + 1\", folded find_seg_def]\n show False by simp\n qed\n qed\n qed\n \n lemma find_seg_correct:\n assumes A: \"j seg (find_seg j)\" and \"find_seg j < length B\"\n using find_seg_bounds[OF A]\n unfolding seg_def by auto\n\n lemma set_p_\\_is_set_S:\n \"\\set p_\\ = set S\"\n apply rule\n unfolding p_\\_def seg_def[abs_def]\n using seg_end_bound apply fastforce []\n\n apply (auto simp: in_set_conv_nth)\n\n using find_seg_bounds\n apply (fastforce simp: in_set_conv_nth)\n done\n\n lemma S_idx_uniq: \n \"\\i \\ S!i=S!j \\ i=j\"\n using S_distinct\n by (simp add: nth_eq_iff_index_eq)\n\n lemma S_idx_of_correct: \n assumes A: \"v\\\\set p_\\\"\n shows \"S_idx_of v < length S\" and \"S!S_idx_of v = v\"\n proof -\n from A have \"v\\set S\" by (simp add: set_p_\\_is_set_S)\n then obtain j where G1: \"j_disjoint_sym: \n shows \"\\i j v. i \\ j \\ v\\p_\\!i \\ v\\p_\\!j \\ i=j\"\n proof (intro allI impI, elim conjE)\n fix i j v\n assume A: \"i < length p_\\\" \"j < length p_\\\" \"v \\ p_\\ ! i\" \"v \\ p_\\ ! j\"\n from A have LI: \"i_def)\n\n from A have B1: \"seg_start j < seg_end i\" and B2: \"seg_start i < seg_end j\"\n unfolding p_\\_def seg_def[abs_def]\n apply clarsimp_all\n apply (subst (asm) S_idx_uniq)\n apply (metis dual_order.strict_trans1 seg_end_bound)\n apply (metis dual_order.strict_trans1 seg_end_bound)\n apply simp\n apply (subst (asm) S_idx_uniq)\n apply (metis dual_order.strict_trans1 seg_end_bound)\n apply (metis dual_order.strict_trans1 seg_end_bound)\n apply simp\n done\n\n from B1 have B1: \"(B!j < B!Suc i \\ Suc i < length B) \\ i=length B - 1\"\n using LI unfolding seg_start_def seg_end_def by (auto split: split_if_asm)\n\n from B2 have B2: \"(B!i < B!Suc j \\ Suc j < length B) \\ j=length B - 1\"\n using LJ unfolding seg_start_def seg_end_def by (auto split: split_if_asm)\n\n from B1 have B1: \"j i=length B - 1\"\n using LI LJ distinct_sorted_strict_mono_iff[OF B_distinct B_sorted]\n by auto\n\n from B2 have B2: \"i j=length B - 1\"\n using LI LJ distinct_sorted_strict_mono_iff[OF B_distinct B_sorted]\n by auto\n\n from B1 B2 show \"i=j\"\n using LI LJ\n by auto\n qed\n\nend\n\n\nsubsection {* Refinement of the Operations *}\n\ndefinition GS_initial_impl :: \"'a oGS \\ 'a \\ 'a set \\ 'a GS\" where\n \"GS_initial_impl I v0 succs \\ (\n [v0],\n [0],\n I(v0\\(STACK 0)),\n if succs={} then [] else [(0,succs)])\"\n\ncontext GS\nbegin\n definition \"push_impl v succs \\ \n let\n _ = stat_newnode ();\n j = length S;\n S = S@[v];\n B = B@[j];\n I = I(v \\ STACK j);\n P = if succs={} then P else P@[(j,succs)]\n in\n (S,B,I,P)\"\n\n \n definition mark_as_done \n where \"\\l u I. mark_as_done l u I \\ do {\n (_,I)\\WHILET \n (\\(l,I). l(l,I). do { ASSERT (l DONE))}) \n (l,I);\n RETURN I\n }\"\n\n definition mark_as_done_abs where\n \"\\l u I. mark_as_done_abs l u I \n \\ (\\v. if v\\{S!j | j. l\\j \\ jllength S\\ \\ mark_as_done l u I \n \\ SPEC (\\r. r = mark_as_done_abs l u I)\"\n unfolding mark_as_done_def mark_as_done_abs_def\n apply (refine_rcg \n WHILET_rule[where \n I=\"\\(l',I'). \n I' = (\\v. if v\\{S!j | j. l\\j \\ j l\\l' \\ l'\\u\"\n and R=\"measure (\\(l',_). u-l')\" \n ]\n refine_vcg)\n \n apply (auto intro!: ext simp: less_Suc_eq)\n done \n\n definition \"pop_impl \\ \n do {\n let lsi = length B - 1;\n ASSERT (lsi mark_as_done (seg_start lsi) (seg_end lsi) I;\n ASSERT (B\\[]);\n let S = take (last B) S;\n ASSERT (B\\[]);\n let B = butlast B;\n RETURN (S,B,I,P)\n }\"\n\n definition \"sel_rem_last \\ \n if P=[] then \n RETURN (None,(S,B,I,P))\n else do {\n let (j,succs) = last P;\n ASSERT (length B - 1 < length B);\n if j \\ seg_start (length B - 1) then do {\n ASSERT (succs\\{});\n v \\ SPEC (\\x. x\\succs);\n let succs = succs - {v};\n ASSERT (P\\[] \\ length P - 1 < length P);\n let P = (if succs={} then butlast P else P[length P - 1 := (j,succs)]);\n RETURN (Some v,(S,B,I,P))\n } else RETURN (None,(S,B,I,P))\n }\" \n\n\n definition \"find_seg_impl j \\ find_max_nat (length B) (\\i. B!i\\j)\"\n\n lemma (in GS_invar) find_seg_impl:\n \"j find_seg_impl j = find_seg j\"\n unfolding find_seg_impl_def\n thm find_max_nat_correct\n apply (subst find_max_nat_correct)\n apply (simp add: B0)\n apply (simp add: B0)\n apply (simp add: find_seg_def)\n done\n\n\n definition \"idx_of_impl v \\ do {\n ASSERT (\\i. I v = Some (STACK i));\n let j = S_idx_of v;\n ASSERT (j \n do { \n i\\idx_of_impl v;\n ASSERT (i+1 \\ length B);\n let B = take (i+1) B;\n RETURN (S,B,I,P)\n }\"\n\nend\n\nlemma (in -) GS_initial_correct: \n assumes REL: \"(I,D)\\oGS_rel\"\n assumes A: \"v0\\D\"\n shows \"GS.\\ (GS_initial_impl I v0 succs) = ([{v0}],D,{v0}\\succs)\" (is ?G1)\n and \"GS_invar (GS_initial_impl I v0 succs)\" (is ?G2)\nproof -\n from REL have [simp]: \"D = oGS_\\ I\" and I: \"oGS_invar I\"\n by (simp_all add: oGS_rel_def br_def)\n\n from I have [simp]: \"\\j v. I v \\ Some (STACK j)\"\n by (simp add: oGS_invar_def)\n\n show ?G1\n unfolding GS.\\_def GS_initial_impl_def\n apply (simp split del: split_if) apply (intro conjI)\n\n unfolding GS.p_\\_def GS.seg_def[abs_def] GS.seg_start_def GS.seg_end_def\n apply (auto) []\n\n using A unfolding GS.D_\\_def apply (auto simp: oGS_\\_def) []\n\n unfolding GS.pE_\\_def apply auto []\n done\n\n show ?G2\n unfolding GS_initial_impl_def\n apply unfold_locales\n apply auto\n done\nqed\n\ncontext GS_invar\nbegin\n lemma push_correct:\n assumes A: \"v\\\\set p_\\\" and B: \"v\\D_\\\"\n shows \"GS.\\ (push_impl v succs) = (p_\\@[{v}],D_\\,pE_\\ \\ {v}\\succs)\" \n (is ?G1)\n and \"GS_invar (push_impl v succs)\" (is ?G2)\n proof -\n\n note [simp] = Let_def\n\n have A1: \"GS.D_\\ (push_impl v succs) = D_\\\"\n using B\n by (auto simp: push_impl_def GS.D_\\_def)\n\n have iexI: \"\\a b j P. \\a!j = b!j; P j\\ \\ \\j'. a!j = b!j' \\ P j'\"\n by blast\n\n have A2: \"GS.p_\\ (push_impl v succs) = p_\\ @ [{v}]\"\n unfolding push_impl_def GS.p_\\_def GS.seg_def[abs_def] \n GS.seg_start_def GS.seg_end_def\n apply (clarsimp split del: split_if)\n\n apply clarsimp\n apply safe\n apply (((rule iexI)?, \n (auto \n simp: nth_append nat_in_between_eq \n dest: order.strict_trans[OF _ B_in_bound']\n )) []\n ) +\n done\n\n have iexI2: \"\\j I Q. \\(j,I)\\set P; (j,I)\\set P \\ Q j\\ \\ \\j. Q j\"\n by blast\n\n have A3: \"GS.pE_\\ (push_impl v succs) = pE_\\ \\ {v} \\ succs\"\n unfolding push_impl_def GS.pE_\\_def\n using P_bound\n apply (force simp: nth_append elim!: iexI2)\n done\n\n show ?G1\n unfolding GS.\\_def\n by (simp add: A1 A2 A3)\n\n show ?G2\n apply unfold_locales\n unfolding push_impl_def\n apply simp_all\n\n using B_in_bound B_sorted B_distinct apply (auto simp: sorted_append) [3]\n using B_in_bound B0 apply (cases S) apply (auto simp: nth_append) [2]\n\n using S_distinct A apply (simp add: set_p_\\_is_set_S)\n\n using A I_consistent \n apply (auto simp: nth_append set_p_\\_is_set_S split: split_if_asm) []\n \n using P_sorted P_distinct P_bound apply (auto simp: sorted_append) [3]\n done\n qed\n\n lemma no_last_out_P_aux:\n assumes NE: \"p_\\\\[]\" and NS: \"pE_\\ \\ last p_\\ \\ UNIV = {}\"\n shows \"set P \\ {0.. UNIV\"\n proof -\n {\n fix j I\n assume jII: \"(j,I)\\set P\"\n and JL: \"last B\\j\"\n with P_bound have JU: \"j{}\" by auto\n with JL JU have \"S!j \\ last p_\\\"\n using NE\n unfolding p_\\_def \n apply (auto \n simp: last_map seg_def seg_start_def seg_end_def last_conv_nth) \n done\n moreover from jII have \"{S!j} \\ I \\ pE_\\\" unfolding pE_\\_def\n by auto\n moreover note INE NS\n ultimately have False by blast\n } thus ?thesis by fastforce\n qed\n\n lemma pop_correct:\n assumes NE: \"p_\\\\[]\" and NS: \"pE_\\ \\ last p_\\ \\ UNIV = {}\"\n shows \"pop_impl \n \\ \\GS_rel (SPEC (\\r. r=(butlast p_\\, D_\\ \\ last p_\\, pE_\\)))\"\n proof -\n have iexI: \"\\a b j P. \\a!j = b!j; P j\\ \\ \\j'. a!j = b!j' \\ P j'\"\n by blast\n \n have [simp]: \"\\n. n - Suc 0 \\ n \\ n\\0\" by auto\n\n from NE have BNE: \"B\\[]\"\n unfolding p_\\_def by auto\n\n {\n fix i j\n assume B: \"j last B\"\n by (simp add: last_conv_nth)\n finally have \"j < last B\" .\n hence \"take (last B) S ! j = S ! j\" \n and \"take (B!(length B - Suc 0)) S !j = S!j\"\n by (simp_all add: last_conv_nth BNE)\n } note AUX1=this\n\n {\n fix v j\n have \"(mark_as_done_abs \n (seg_start (length B - Suc 0))\n (seg_end (length B - Suc 0)) I v = Some (STACK j)) \n \\ (j < length S \\ j < last B \\ v = take (last B) S ! j)\"\n apply (simp add: mark_as_done_abs_def)\n apply safe []\n using I_consistent\n apply (clarsimp_all\n simp: seg_start_def seg_end_def last_conv_nth BNE\n simp: S_idx_uniq)\n\n apply (force)\n apply (subst nth_take)\n apply force\n apply force\n done\n } note AUX2 = this\n\n def ci \\ \"( \n take (last B) S, \n butlast B,\n mark_as_done_abs \n (seg_start (length B - Suc 0)) (seg_end (length B - Suc 0)) I,\n P)\"\n\n have ABS: \"GS.\\ ci = (butlast p_\\, D_\\ \\ last p_\\, pE_\\)\"\n apply (simp add: GS.\\_def ci_def)\n apply (intro conjI)\n apply (auto \n simp del: map_butlast\n simp add: map_butlast[symmetric] butlast_upt\n simp add: GS.p_\\_def GS.seg_def[abs_def] GS.seg_start_def GS.seg_end_def\n simp: nth_butlast last_conv_nth nth_take AUX1\n cong: if_cong\n intro!: iexI\n dest: order.strict_trans[OF _ B_in_bound']\n ) []\n\n apply (auto \n simp: GS.D_\\_def p_\\_def last_map BNE seg_def mark_as_done_abs_def) []\n\n using AUX1 no_last_out_P_aux[OF NE NS]\n apply (auto simp: GS.pE_\\_def mark_as_done_abs_def elim!: bex2I) []\n done\n\n have INV: \"GS_invar ci\"\n apply unfold_locales\n apply (simp_all add: ci_def)\n\n using B_in_bound B_sorted B_distinct \n apply (cases B rule: rev_cases, simp) \n apply (auto simp: sorted_append order.strict_iff_order) [] \n\n using B_sorted BNE apply (auto simp: sorted_butlast) []\n\n using B_distinct BNE apply (auto simp: distinct_butlast) []\n\n using B0 apply (cases B rule: rev_cases, simp add: BNE) \n apply (auto simp: nth_append split: split_if_asm) []\n \n using S_distinct apply (auto) []\n\n apply (rule AUX2)\n\n using P_sorted P_distinct \n apply (auto) [2]\n\n using P_bound no_last_out_P_aux[OF NE NS]\n apply (auto simp: in_set_conv_decomp)\n done\n \n\n show ?thesis\n unfolding pop_impl_def\n apply (refine_rcg \n SPEC_refine_sv refine_vcg order_trans[OF mark_as_done_aux])\n apply (simp_all add: BNE seg_start_less_end seg_end_bound)\n apply (fold ci_def)\n unfolding GS_rel_def\n apply (rule brI)\n apply (simp_all add: ABS INV)\n done\n qed\n\n\n lemma sel_rem_last_correct:\n assumes NE: \"p_\\\\[]\"\n shows\n \"sel_rem_last \\ \\(Id \\\\<^sub>r GS_rel) (select_edge (p_\\,D_\\,pE_\\))\"\n proof -\n {\n fix l i a b b'\n have \"\\i \\ map fst (l[i:=(a,b')]) = map fst l\"\n by (induct l arbitrary: i) (auto split: nat.split)\n } note map_fst_upd_snd_eq = this\n\n from NE have BNE[simp]: \"B\\[]\" unfolding p_\\_def by simp\n\n have INVAR: \"sel_rem_last \\ SPEC (GS_invar o snd)\"\n unfolding sel_rem_last_def\n apply (refine_rcg refine_vcg)\n using locale_this apply (cases SBIP) apply simp\n\n apply simp\n\n using P_bound apply (cases P rule: rev_cases, auto) []\n\n apply simp\n\n apply simp apply (intro impI conjI)\n\n apply (unfold_locales, simp_all) []\n using B_in_bound B_sorted B_distinct B0 S_distinct I_consistent \n apply auto [6]\n\n using P_sorted P_distinct \n apply (auto simp: map_butlast sorted_butlast distinct_butlast) [2]\n\n using P_bound apply (auto dest: in_set_butlastD) []\n\n apply (unfold_locales, simp_all) []\n using B_in_bound B_sorted B_distinct B0 S_distinct I_consistent \n apply auto [6]\n\n using P_sorted P_distinct \n apply (auto simp: last_conv_nth map_fst_upd_snd_eq) [2]\n\n using P_bound \n apply (cases P rule: rev_cases, simp)\n apply (auto) []\n\n using locale_this apply (cases SBIP) apply simp\n done\n\n\n {\n assume NS: \"pE_\\\\last p_\\\\UNIV = {}\"\n hence \"sel_rem_last \n \\ SPEC (\\r. case r of (None,SBIP') \\ SBIP'=SBIP | _ \\ False)\"\n unfolding sel_rem_last_def\n apply (refine_rcg refine_vcg)\n apply (cases SBIP)\n apply simp\n\n apply simp\n using P_bound apply (cases P rule: rev_cases, auto) []\n apply simp\n\n using no_last_out_P_aux[OF NE NS]\n apply (auto simp: seg_start_def last_conv_nth) []\n\n apply (cases SBIP)\n apply simp\n done\n } note SPEC_E = this\n\n {\n assume NON_EMPTY: \"pE_\\\\last p_\\\\UNIV \\ {}\"\n\n then obtain j succs P' where \n EFMT: \"P = P'@[(j,succs)]\"\n unfolding pE_\\_def\n by (cases P rule: rev_cases) auto\n \n with P_bound have J_UPPER: \"j{}\" \n by auto\n\n have J_LOWER: \"seg_start (length B - Suc 0) \\ j\"\n proof (rule ccontr)\n assume \"\\(seg_start (length B - Suc 0) \\ j)\"\n hence \"j < seg_start (length B - 1)\" by simp\n with P_sorted EFMT \n have P_bound': \"set P \\ {0.. UNIV\"\n by (auto simp: sorted_append)\n hence \"pE_\\ \\ last p_\\\\UNIV = {}\"\n by (auto \n simp: p_\\_def last_conv_nth seg_def pE_\\_def S_idx_uniq seg_end_def)\n thus False using NON_EMPTY by simp\n qed\n\n from J_UPPER J_LOWER have SJL: \"S!j\\last p_\\\" \n unfolding p_\\_def seg_def[abs_def] seg_end_def\n by (auto simp: last_map)\n\n from EFMT have SSS: \"{S!j}\\succs\\pE_\\\"\n unfolding pE_\\_def\n by auto\n\n\n {\n fix v\n assume \"v\\succs\"\n with SJL SSS have G: \"(S!j,v)\\pE_\\ \\ last p_\\\\UNIV\" by auto\n \n {\n fix j' succs'\n assume \"S ! j' = S ! j\" \"(j', succs') \\ set P'\"\n with J_UPPER P_bound S_idx_uniq EFMT have \"j'=j\" by auto\n with P_distinct `(j', succs') \\ set P'` EFMT have False by auto\n } note AUX3=this\n\n have G1: \"GS.pE_\\ (S,B,I,P' @ [(j, succs - {v})]) = pE_\\ - {(S!j, v)}\"\n unfolding GS.pE_\\_def using AUX3\n by (auto simp: EFMT)\n \n {\n assume \"succs\\{v}\"\n hence \"GS.pE_\\ (S,B,I,P' @ [(j, succs - {v})]) = GS.pE_\\ (S,B,I,P')\"\n unfolding GS.pE_\\_def by auto\n\n with G1 have \"GS.pE_\\ (S,B,I,P') = pE_\\ - {(S!j, v)}\" by simp\n } note G2 = this\n\n note G G1 G2\n } note AUX3 = this\n\n have \"sel_rem_last \\ SPEC (\\r. case r of \n (Some v,SBIP') \\ \\u. \n (u,v)\\(pE_\\\\last p_\\\\UNIV) \n \\ GS.\\ SBIP' = (p_\\,D_\\,pE_\\-{(u,v)})\n | _ \\ False)\"\n unfolding sel_rem_last_def\n apply (refine_rcg refine_vcg)\n\n using SNE apply (vc_solve simp: J_LOWER EFMT)\n\n apply (frule AUX3(1))\n\n apply safe\n\n apply (drule (1) AUX3(3)) apply (auto simp: EFMT GS.\\_def) []\n apply (drule AUX3(2)) apply (auto simp: GS.\\_def) []\n done\n } note SPEC_NE=this\n\n\n show ?thesis\n unfolding select_edge_def select_def \n apply (simp \n add: pw_le_iff refine_pw_simps prod_rel_sv \n split: option.splits prod.splits)\n apply (clarsimp simp: br_def GS_rel_def GS.\\_def)\n apply (intro impI allI conjI)\n\n using INVAR apply (simp add: pw_le_iff refine_pw_simps)\n\n apply (drule SPEC_E)\n apply (drule (1) inres_SPEC)\n apply (auto simp: GS.\\_def split: option.splits) []\n\n apply (drule SPEC_E)\n apply (drule (1) inres_SPEC)\n apply (auto simp: GS.\\_def split: option.splits) []\n\n apply (drule SPEC_E)\n apply (drule (1) inres_SPEC)\n apply (auto simp: GS.\\_def split: option.splits) []\n\n using INVAR apply (simp add: pw_le_iff refine_pw_simps)\n\n apply (drule SPEC_E)\n apply (drule (1) inres_SPEC)\n apply (auto simp: GS.\\_def split: option.splits) []\n\n using INVAR apply (simp add: pw_le_iff refine_pw_simps)\n\n using INVAR apply (simp add: pw_le_iff refine_pw_simps)\n \n apply (drule SPEC_NE)\n apply (drule (1) inres_SPEC)\n apply (auto simp: GS.\\_def split: option.splits prod.splits) []\n done\n qed\n\n lemma find_seg_idx_of_correct:\n assumes A: \"v\\\\set p_\\\"\n shows \"(find_seg (S_idx_of v)) = idx_of p_\\ v\"\n proof -\n note S_idx_of_correct[OF A] idx_of_props[OF p_\\_disjoint_sym A]\n from find_seg_correct[OF `S_idx_of v < length S`] have \n \"find_seg (S_idx_of v) < length p_\\\" \n and \"S!S_idx_of v \\ p_\\!find_seg (S_idx_of v)\"\n unfolding p_\\_def by auto\n from idx_of_uniq[OF p_\\_disjoint_sym this] `S ! S_idx_of v = v` \n show ?thesis by auto\n qed\n\n\n lemma idx_of_correct:\n assumes A: \"v\\\\set p_\\\"\n shows \"idx_of_impl v \\ SPEC (\\x. x=idx_of p_\\ v \\ x_is_set_S)\n apply (erule S_idx_of_correct)\n apply (simp add: find_seg_impl find_seg_idx_of_correct)\n by (metis find_seg_correct(2) find_seg_impl)\n\n lemma collapse_correct:\n assumes A: \"v\\\\set p_\\\"\n shows \"collapse_impl v \\\\GS_rel (SPEC (\\r. r=collapse v \\))\"\n proof -\n {\n fix i\n assume \"i\"\n hence ILEN: \"i_def)\n\n let ?SBIP' = \"(S, take (Suc i) B, I, P)\"\n\n {\n have [simp]: \"GS.seg_start ?SBIP' i = seg_start i\"\n by (simp add: GS.seg_start_def)\n\n have [simp]: \"GS.seg_end ?SBIP' i = seg_end (length B - 1)\"\n using ILEN by (simp add: GS.seg_end_def min_absorb2)\n\n {\n fix j\n assume B: \"seg_start i \\ j\" \"j < seg_end (length B - Suc 0)\"\n hence \"j length S\" .\n finally show ?thesis .\n qed\n\n have \"i \\ find_seg j \\ find_seg j < length B \n \\ seg_start (find_seg j) \\ j \\ j < seg_end (find_seg j)\" \n proof (intro conjI)\n show \"i\\find_seg j\"\n by (metis le_trans not_less B(1) find_seg_bounds(2) \n seg_end_less_start ILEN `j < length S`)\n qed (simp_all add: find_seg_bounds[OF `ji. S!j = S!i \\ Q i\"\n by blast\n } note AUX_ex_conj_SeqSI = this\n\n have \"GS.seg ?SBIP' i = UNION {i.. (S, take (Suc i) B, I, P) = collapse_aux p_\\ i\"\n unfolding GS.p_\\_def collapse_aux_def\n apply (simp add: min_absorb2 drop_map)\n apply (rule conjI)\n apply (auto \n simp: GS.seg_def[abs_def] GS.seg_start_def GS.seg_end_def take_map) []\n\n apply (simp add: AUX2)\n done\n } note AUX1 = this\n\n from A obtain i where [simp]: \"I v = Some (STACK i)\"\n using I_consistent set_p_\\_is_set_S\n by (auto simp: in_set_conv_nth)\n\n {\n have \"(collapse_aux p_\\ (idx_of p_\\ v), D_\\, pE_\\) =\n GS.\\ (S, take (Suc (idx_of p_\\ v)) B, I, P)\"\n unfolding GS.\\_def\n using idx_of_props[OF p_\\_disjoint_sym A]\n by (simp add: AUX1)\n } note ABS=this\n\n {\n have \"GS_invar (S, take (Suc (idx_of p_\\ v)) B, I, P)\"\n apply unfold_locales\n apply simp_all\n\n using B_in_bound B_sorted B_distinct\n apply (auto simp: sorted_take dest: in_set_takeD) [3]\n\n using B0 S_distinct apply auto [2]\n\n using I_consistent apply simp\n\n using P_sorted P_distinct P_bound apply auto [3]\n done\n } note INV=this\n\n show ?thesis\n unfolding collapse_impl_def\n apply (refine_rcg SPEC_refine_sv refine_vcg order_trans[OF idx_of_correct])\n\n apply fact\n apply (metis discrete)\n\n apply (simp add: collapse_def \\_def find_seg_impl)\n unfolding GS_rel_def\n apply (rule brI)\n apply (rule ABS)\n apply (rule INV)\n done\n qed\n\nend\n\ntext {* Technical adjustment for avoiding case-splits for definitions\n extracted from GS-locale *}\nlemma opt_GSdef: \"f \\ g \\ f s \\ case s of (S,B,I,P) \\ g (S,B,I,P)\" by auto\n\nlemma ext_def: \"f\\g \\ f x \\ g x\" by auto\n\ncontext fr_graph begin\n definition \"push_impl v s \\ GS.push_impl s v (E``{v})\" \n lemmas push_impl_def_opt = \n push_impl_def[abs_def, \n THEN ext_def, THEN opt_GSdef, unfolded GS.push_impl_def GS_sel_simps]\n\n text {* Definition for presentation *}\n lemma \"push_impl v (S,B,I,P) \\ (S@[v], B@[length S], I(v\\STACK (length S)),\n if E``{v}={} then P else P@[(length S,E``{v})])\"\n unfolding push_impl_def GS.push_impl_def GS.P_def GS.S_def\n by (auto simp: Let_def)\n\n lemma GS_\\_split: \n \"GS.\\ s = (p,D,pE) \\ (p=GS.p_\\ s \\ D=GS.D_\\ s \\ pE=GS.pE_\\ s)\"\n \"(p,D,pE) = GS.\\ s \\ (p=GS.p_\\ s \\ D=GS.D_\\ s \\ pE=GS.pE_\\ s)\"\n by (auto simp add: GS.\\_def)\n\n lemma push_refine:\n assumes A: \"(s,(p,D,pE))\\GS_rel\" \"(v,v')\\Id\"\n assumes B: \"v\\\\set p\" \"v\\D\"\n shows \"(push_impl v s, push v' (p,D,pE))\\GS_rel\"\n proof -\n from A have [simp]: \"p=GS.p_\\ s \\ D=GS.D_\\ s \\ pE=GS.pE_\\ s\" \"v'=v\" \n and INV: \"GS_invar s\"\n by (auto simp add: GS_rel_def br_def GS_\\_split)\n\n from INV B show ?thesis\n by (auto \n simp: GS_rel_def br_def GS_invar.push_correct push_impl_def push_def)\n qed\n\n definition \"pop_impl s \\ GS.pop_impl s\"\n lemmas pop_impl_def_opt = \n pop_impl_def[abs_def, THEN opt_GSdef, unfolded GS.pop_impl_def\n GS.mark_as_done_def GS.seg_start_def GS.seg_end_def \n GS_sel_simps]\n\n lemma pop_refine:\n assumes A: \"(s,(p,D,pE))\\GS_rel\"\n assumes B: \"p \\ []\" \"pE \\ last p \\ UNIV = {}\"\n shows \"pop_impl s \\ \\GS_rel (RETURN (pop (p,D,pE)))\"\n proof -\n from A have [simp]: \"p=GS.p_\\ s \\ D=GS.D_\\ s \\ pE=GS.pE_\\ s\" \n and INV: \"GS_invar s\"\n by (auto simp add: GS_rel_def br_def GS_\\_split)\n\n show ?thesis\n unfolding pop_impl_def[abs_def] pop_def\n apply (rule order_trans[OF GS_invar.pop_correct])\n using INV B\n apply (simp_all add: Un_commute RETURN_def) \n done\n qed\n\n thm pop_refine[no_vars]\n\n definition \"collapse_impl v s \\ GS.collapse_impl s v\"\n lemmas collapse_impl_def_opt = \n collapse_impl_def[abs_def, \n THEN ext_def, THEN opt_GSdef, unfolded GS.collapse_impl_def GS_sel_simps]\n\n lemma collapse_refine:\n assumes A: \"(s,(p,D,pE))\\GS_rel\" \"(v,v')\\Id\"\n assumes B: \"v'\\\\set p\"\n shows \"collapse_impl v s \\\\GS_rel (RETURN (collapse v' (p,D,pE)))\"\n proof -\n from A have [simp]: \"p=GS.p_\\ s \\ D=GS.D_\\ s \\ pE=GS.pE_\\ s\" \"v'=v\" \n and INV: \"GS_invar s\"\n by (auto simp add: GS_rel_def br_def GS_\\_split)\n\n show ?thesis\n unfolding collapse_impl_def[abs_def]\n apply (rule order_trans[OF GS_invar.collapse_correct])\n using INV B by (simp_all add: GS.\\_def RETURN_def)\n qed\n\n definition \"select_edge_impl s \\ GS.sel_rem_last s\"\n lemmas select_edge_impl_def_opt = \n select_edge_impl_def[abs_def, \n THEN opt_GSdef, \n unfolded GS.sel_rem_last_def GS.seg_start_def GS_sel_simps]\n\n lemma select_edge_refine: \n assumes A: \"(s,(p,D,pE))\\GS_rel\"\n assumes NE: \"p \\ []\"\n shows \"select_edge_impl s \\ \\(Id \\\\<^sub>r GS_rel) (select_edge (p,D,pE))\"\n proof -\n from A have [simp]: \"p=GS.p_\\ s \\ D=GS.D_\\ s \\ pE=GS.pE_\\ s\" \n and INV: \"GS_invar s\"\n by (auto simp add: GS_rel_def br_def GS_\\_split)\n\n from INV NE show ?thesis\n unfolding select_edge_impl_def\n using GS_invar.sel_rem_last_correct[OF INV] NE\n by (simp)\n qed\n\n definition \"initial_impl v0 I \\ GS_initial_impl I v0 (E``{v0})\"\n\n lemma initial_refine:\n \"\\v0\\D0; (I,D0)\\oGS_rel; (v0i,v0)\\Id\\ \n \\ (initial_impl v0i I,initial v0 D0)\\GS_rel\"\n unfolding initial_impl_def GS_rel_def br_def\n apply (simp_all add: GS_initial_correct)\n apply (auto simp: initial_def)\n done\n\n\n definition \"path_is_empty_impl s \\ GS.S s = []\"\n lemma path_is_empty_refine: \n \"GS_invar s \\ path_is_empty_impl s \\ GS.p_\\ s=[]\"\n unfolding path_is_empty_impl_def GS.p_\\_def GS_invar.empty_eq\n by auto\n\n definition (in GS) \"is_on_stack_impl v \n \\ case I v of Some (STACK _) \\ True | _ \\ False\"\n\n lemma (in GS_invar) is_on_stack_impl_correct:\n shows \"is_on_stack_impl v \\ v\\\\set p_\\\"\n unfolding is_on_stack_impl_def\n using I_consistent[of v]\n apply (force \n simp: set_p_\\_is_set_S in_set_conv_nth \n split: option.split node_state.split)\n done\n\n definition \"is_on_stack_impl v s \\ GS.is_on_stack_impl s v\"\n lemmas is_on_stack_impl_def_opt = \n is_on_stack_impl_def[abs_def, THEN ext_def, THEN opt_GSdef, \n unfolded GS.is_on_stack_impl_def GS_sel_simps]\n\n lemma is_on_stack_refine:\n \"\\ GS_invar s \\ \\ is_on_stack_impl v s \\ v\\\\set (GS.p_\\ s)\"\n unfolding is_on_stack_impl_def GS_rel_def br_def\n by (simp add: GS_invar.is_on_stack_impl_correct)\n\n\n definition (in GS) \"is_done_impl v \n \\ case I v of Some DONE \\ True | _ \\ False\"\n\n lemma (in GS_invar) is_done_impl_correct:\n shows \"is_done_impl v \\ v\\D_\\\"\n unfolding is_done_impl_def D_\\_def\n apply (auto split: option.split node_state.split)\n done\n\n definition \"is_done_oimpl v I \\ case I v of Some DONE \\ True | _ \\ False\"\n\n definition \"is_done_impl v s \\ GS.is_done_impl s v\"\n\n lemma is_done_orefine:\n \"\\ oGS_invar s \\ \\ is_done_oimpl v s \\ v\\oGS_\\ s\"\n unfolding is_done_oimpl_def oGS_rel_def br_def\n by (auto \n simp: oGS_invar_def oGS_\\_def \n split: option.splits node_state.split)\n\n lemma is_done_refine:\n \"\\ GS_invar s \\ \\ is_done_impl v s \\ v\\GS.D_\\ s\"\n unfolding is_done_impl_def GS_rel_def br_def\n by (simp add: GS_invar.is_done_impl_correct)\n\n lemma oinitial_refine: \"(Map.empty, {}) \\ oGS_rel\"\n by (auto simp: oGS_rel_def br_def oGS_\\_def oGS_invar_def)\n\nend\n\nsubsection {* Refined Skeleton Algorithm *}\n\ncontext fr_graph begin\n\n lemma I_to_outer:\n assumes \"((S, B, I, P), ([], D, {})) \\ GS_rel\"\n shows \"(I,D)\\oGS_rel\"\n using assms\n unfolding GS_rel_def oGS_rel_def br_def oGS_\\_def GS.\\_def GS.D_\\_def GS_invar_def oGS_invar_def\n apply (auto simp: GS.p_\\_def)\n done\n \n \n definition skeleton_impl :: \"'v oGS nres\" where\n \"skeleton_impl \\ do {\n stat_start_nres;\n let I=Map.empty;\n r \\ FOREACHi (\\it I. outer_invar it (oGS_\\ I)) V0 (\\v0 I0. do {\n if \\is_done_oimpl v0 I0 then do {\n let s = initial_impl v0 I0;\n\n (S,B,I,P)\\WHILEIT (invar v0 (oGS_\\ I0) o GS.\\)\n (\\s. \\path_is_empty_impl s) (\\s.\n do {\n (* Select edge from end of path *)\n (vo,s) \\ select_edge_impl s;\n\n case vo of \n Some v \\ do {\n if is_on_stack_impl v s then do {\n collapse_impl v s\n } else if \\is_done_impl v s then do {\n (* Edge to new node. Append to path *)\n RETURN (push_impl v s)\n } else do {\n (* Edge to done node. Skip *)\n RETURN s\n }\n }\n | None \\ do {\n (* No more outgoing edges from current node on path *)\n pop_impl s\n }\n }) s;\n RETURN I\n } else\n RETURN I0\n }) I;\n stat_stop_nres;\n RETURN r\n }\"\n\n subsubsection {* Correctness Theorem *}\n\n lemma \"skeleton_impl \\ \\oGS_rel skeleton\"\n using [[goals_limit = 1]]\n unfolding skeleton_impl_def skeleton_def\n apply (refine_rcg\n bind_refine'\n select_edge_refine push_refine \n pop_refine\n collapse_refine \n initial_refine\n oinitial_refine\n inj_on_id\n )\n using [[goals_limit = 5]]\n\n apply (vc_solve (nopre) solve: asm_rl I_to_outer\n simp: GS_rel_def br_def GS.\\_def oGS_rel_def oGS_\\_def \n is_on_stack_refine path_is_empty_refine is_done_refine is_done_orefine\n )\n\n done\n\n lemmas skeleton_refines \n = select_edge_refine push_refine pop_refine collapse_refine \n initial_refine oinitial_refine\n lemmas skeleton_refine_simps \n = GS_rel_def br_def GS.\\_def oGS_rel_def oGS_\\_def \n is_on_stack_refine path_is_empty_refine is_done_refine is_done_orefine\n\n text {* Short proof, for presentation *}\n context\n notes [[goals_limit = 1]]\n notes [refine] = inj_on_id bind_refine'\n begin\n lemma \"skeleton_impl \\ \\oGS_rel skeleton\"\n unfolding skeleton_impl_def skeleton_def\n by (refine_rcg skeleton_refines) \n (vc_solve (nopre) solve: asm_rl I_to_outer simp: skeleton_refine_simps)\n\n end\n\nend\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Gabow_SCC/Gabow_Skeleton.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.18952109590739918, "lm_q1q2_score": 0.09180024440789246}} {"text": "(*\n * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *)\n\ntheory FP_Eval_Tests\nimports\n Lib.FP_Eval\n \"HOL-Library.Sublist\"\nbegin\n\nsection \\Controlling evaluation\\\n\nsubsection \\Skeletons\\\n\ntext \\\n A \"skeleton\" is a subterm of a given term. For example,\n \"map (\\x. x + 1) [1, 2, 3]\"\n could have the following skeleton (among others):\n \"map (\\x. x + _) _\"\n\n The \"_\" stand for schematic variables with arbitrary names,\n or dummy patterns (which are implemented as unnamed schematics).\n\n FP_Eval uses skeletons internally to keep track of which parts of\n a term it has already evaluated. In other words, schematic variables\n indicate already-normalised subterms.\n\n There are two useful predefined skeletons:\n\\\nML_val \\ FP_Eval.skel0 \\\ntext \\\n which is a special directive to evaluate all subterms; and\n\\\nML_val \\ FP_Eval.skel_skip \\\ntext \\\n which tells FP_Eval to skip evaluation.\n\\\n\ntext \\\n If we use the full FP_Eval interface, we can input a skeleton manually\n and get the final skeleton as output.\n\n It's useful to input a nontrivial skeleton for the following reasons:\n \\ if most of the term is known to be normalised, this can\n save unnecessary computation.\n \\ if a tool runs FP_Eval on behalf of an end user, it may\n want to avoid evaluating function calls in the user's input terms.\n Alternatively, use explicit quotation terms\n (see \"Preventing evaluation\", below) if finer control is needed.\n\n The partial skeleton should match the structure of the input term.\n If there is any mismatch, FP_Eval tries to be conservative and\n evaluates the whole subterm (as if \"skel0\" had been given).\n However, this should not be relied upon.\n (FIXME: maybe stricter check in eval')\n\n By default, FP_Eval attempts full evaluation of the input, so it\n usually returns \"skel_skip\".\n\n However, evaluation is not complete when:\n \\ the input skeleton skips some subterms;\n \\ FP_Eval doesn't descend into un-applied lambdas;\n \\ evaluation delayed due to cong rules.\n In these cases, FP_Eval would return a partial skeleton.\n\\\n\n(* TODO: add examples *)\n\nsubsection \\Congruence rules\\\n\ntext \\\n Use FP_Eval.add_cong or the second argument of FP_Eval.make_rules.\n These accept weak congruence rules, e.g.:\n\\\nthm if_weak_cong option.case_cong_weak\n\ntext \\\n Note that @{thm let_weak_cong} contains a hidden eta expansion, which FP_Eval\n currently doesn't understand. Use our alternative:\n\\\nthm FP_Eval.let_weak_cong'\n\nML_val \\\n @{assert} (not (Thm.eq_thm_prop (@{thm let_weak_cong}, @{thm FP_Eval.let_weak_cong'})));\n\\\n\ntext \\\n Example: avoid evaluating both branches of an @{const If}\n\\\n\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs)\n val input = (@{cterm \"subseq [0::nat, 2, 4] [0, 1, 2, 3, 4, 5]\"}, Bound 0);\nin\n (* No cong rule -- blowup *)\n val r1 = eval @{thms list_emb_code} @{thms} input\n |> fst |> fst;\n (* if_weak_cong prevents early evaluation of branches *)\n val r2 = eval @{thms list_emb_code} @{thms if_weak_cong} input\n |> fst |> fst;\n\n (* Compare performance counters: *)\n val eqns = @{thms list_emb_code rel_simps simp_thms if_True if_False};\n val p1 = eval eqns @{thms} input |> snd;\n val p2 = eval eqns @{thms if_weak_cong} input |> snd;\nend\n\\\n\nsubsection \\Preventing evaluation\\\n\ntext \\\n Sometimes it is useful to prevent evaluation of any arguments.\n This can be done by adding a cong rule with no premises:\n\\\ncontext FP_Eval begin\ndefinition \"quote x \\ x\"\nlemma quote_cong:\n \"quote x = quote x\"\n by simp\nlemma quote:\n \"x \\ quote x\"\n by (simp add: quote_def)\nend\n\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\nin\n (* By default, fp_eval evaluates all subterms *)\n val r1 = eval @{thms fun_upd_def} @{thms}\n (@{cterm \"FP_Eval.quote (fun_upd f a b) c\"}, Bound 0);\n (* Use quote_cong to hold all quoted subterms.\n Note how the resulting skeleton indicates unevaluated subterms. *)\n val r2 = eval @{thms fun_upd_def} @{thms FP_Eval.quote_cong}\n (@{cterm \"FP_Eval.quote (fun_upd f a b) c\"}, Bound 0);\n (* Now remove the quote_cong hold. fp_eval continues evaluation\n according to the previous skeleton. *)\n val r3 = fst r2 |> apfst Thm.rhs_of\n |> eval @{thms fun_upd_def} @{thms};\nend;\n\\\n\n\nsection \\Tests\\\n\nsubsection \\Basic tests\\\n\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"2 + 2 :: nat\"}, Bound 0);\nin\n val ((result, Var _), counters) = eval @{thms arith_simps} @{thms} input;\n val _ = @{assert} (Thm.prop_of result aconv @{term \"(2 + 2 :: nat) \\ 4\"});\nend;\n\\\n\ntext \\fp_eval does not rewrite under lambda abstractions\\\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"(\\x. x + (2 + 2::nat))\"}, Bound 0);\nin\n val ((result, skel), _) = eval @{thms arith_simps} @{thms} input;\n val _ = @{assert} (not (is_Var skel) andalso Thm.is_reflexive result);\nend\n\\\n\n\nsubsection \\Cong rules\\\n\ntext \\Test for @{thm if_weak_cong}\\\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"subseq [2::int,3,5,7,11] [0,1,2,3,4,5,6,7,8,9,10,11,12,13]\"}, Bound 0);\nin\n val r1 = eval @{thms list_emb_code rel_simps refl if_True if_False} @{thms} input;\n val r2 = eval @{thms list_emb_code rel_simps refl if_True if_False} @{thms if_weak_cong} input;\n\n val _ = @{assert} (Thm.term_of (Thm.rhs_of (fst (fst r1))) = @{term True});\n val _ = @{assert} (Thm.term_of (Thm.rhs_of (fst (fst r2))) = @{term True});\n\n (* Compare performance counters: *)\n val (SOME r1_rewrs, SOME r2_rewrs) =\n apply2 (snd #> Symtab.make #> (fn t => Symtab.lookup t \"rewrites\")) (r1, r2);\n val _ = @{assert} (r1_rewrs > 10000);\n val _ = @{assert} (r2_rewrs < 100);\nend\n\\\n\n\nsubsection \\Advanced usage\\\n\nsubsubsection \\Triggering breakpoints\\\nML_val \\\nlocal\n fun break_4 t = Thm.term_of t = @{term \"4 :: nat\"};\n fun eval eqns congs break =\n FP_Eval.eval' @{context} (K (K ())) break false (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"map Suc [2 + 2 :: nat, 2 + 3, 2 + 4, 2 + 5, 2 + 6]\"}, Bound 0);\nin\n (* Normal evaluation *)\n val ((result, Var _), _) = eval @{thms list.map arith_simps} @{thms} (K false) input;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result) aconv\n @{term \"[Suc 4, Suc 5, Suc 6, Suc 7, Suc 8]\"});\n\n (* Evaluation stops after \"4\" is encountered *)\n val ((result2, skel), _) = eval @{thms list.map arith_simps} @{thms} break_4 input;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result2) aconv\n @{term \"map Suc [4::nat, 5, 2 + 4, 2 + 5, 2 + 6]\"});\n (* Skeleton indicates evaluation is unfinished *)\n val _ = @{assert} (not (is_Var skel));\nend;\n\\\n\nsubsubsection \\Rule set manipulation\\\nML_val \\\nlocal\n val rules0 = FP_Eval.empty_rules;\n val rules1 = FP_Eval.make_rules @{thms simp_thms arith_simps} @{thms if_weak_cong};\n val rules2 = FP_Eval.make_rules @{thms simp_thms if_False if_True fun_upd_apply}\n @{thms if_weak_cong option.case_cong_weak};\nin\n (* dest_rules returns rules *)\n val _ = @{assert} (apply2 length (FP_Eval.dest_rules rules1) <> (0, 0));\n (* test round-trip conversion *)\n val _ = @{assert} (let val (thms, congs) = FP_Eval.dest_rules rules2;\n val (thms', congs') = FP_Eval.dest_rules (FP_Eval.make_rules thms congs);\n in forall Thm.eq_thm_prop (thms ~~ thms')\n andalso forall Thm.eq_thm_prop (congs ~~ congs') end);\n (* test that merging succeeds and actually merges rules *)\n fun test_merge r1 r2 =\n let val (r1_eqns, r1_congs) = FP_Eval.dest_rules r1;\n val (r2_eqns, r2_congs) = FP_Eval.dest_rules r2;\n val (r12_eqns, r12_congs) = FP_Eval.dest_rules (FP_Eval.merge_rules (r1, r2));\n in eq_set Thm.eq_thm_prop (r12_eqns, union Thm.eq_thm_prop r1_eqns r2_eqns)\n andalso eq_set Thm.eq_thm_prop (r12_congs, union Thm.eq_thm_prop r1_congs r2_congs)\n end;\n\n val _ = @{assert} (test_merge rules0 rules1);\n val _ = @{assert} (test_merge rules0 rules2);\n val _ = @{assert} (test_merge rules1 rules2);\n\n (* test that rules with conflicting arity are not allowed *)\n val conflict_arity = FP_Eval.make_rules @{thms fun_upd_def} @{thms};\n val _ = @{assert} (is_none (try FP_Eval.merge_rules (rules2, conflict_arity)));\n (* test that installing different cong rules is not allowed *)\n val conflict_cong = FP_Eval.make_rules @{thms} @{thms if_weak_cong[OF refl]};\n val _ = @{assert} (is_none (try FP_Eval.merge_rules (rules2, conflict_cong)));\nend\n\\\n\nsubsubsection \\Ordering of rules\\\ntext \\\n In the current implementation, equations are picked based on the default\n Net ordering. This should be improved in the future.\n\\\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"list_all (\\x::nat. x \\ x) [100000, 314159, 2718281845]\"}, Bound 0);\n val basic_eqns = @{thms list_all_simps rel_simps simp_thms};\n fun get_counter cs x = the (Symtab.lookup (Symtab.make cs) x);\nin\n (* evaluate \\ slowly *)\n val ((r1, _), counters1) = eval basic_eqns @{thms} input;\n (* shortcut for \\ *)\n val ((r2, _), counters2) = eval (@{thms order.refl} @ basic_eqns) @{thms} input;\n val ((r3, _), counters3) = eval (basic_eqns @ @{thms order.refl}) @{thms} input;\n\n (* Bug: shortcut is never used -- no effect on runtime *)\n val _ = @{assert} (length (distinct op= [counters1, counters2, counters3]) = 1);\n\n (* desired outcome *)\n val ((r4, _), counters4) = eval @{thms list_all_simps simp_thms order.refl} @{thms} input;\n val _ = @{assert} (get_counter counters4 \"rewrites\" < get_counter counters1 \"rewrites\");\nend\n\\\n\n\nsubsection \\Miscellaneous and regression tests\\\n\ntext \\Test for partial arity and arg_conv\\\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"(if 2 + 2 = 4 then Suc else id) x\"}, FP_Eval.skel0);\n (* Need to build these manually, as @{cterm} itself does beta-eta normalisation *)\n val input_abs1 = (fold (fn x => fn f => Thm.apply f x)\n [@{cterm \"f::nat\\nat\"}, @{cterm \"4::nat\"}]\n @{cterm \"\\f. fun_upd (f::nat\\nat) (2+2) y\"},\n FP_Eval.skel0);\n val input_abs2 = (fold (fn x => fn f => Thm.apply f x)\n [@{cterm \"f::nat\\nat\"}, @{cterm \"4::nat\"}]\n @{cterm \"\\f x z. z + fun_upd (f::nat\\nat) (2+2) y x\"},\n FP_Eval.skel0);\n val Abs (_, _, Abs (_, _, Abs _)) $ _ $ _ = Thm.term_of (fst input_abs2); (* check *)\nin\n (* Head (= If) is rewritten *)\n val ((result, Var _), _) = eval @{thms arith_simps refl if_True} @{thms} input;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result) = @{term \"Suc x\"});\n\n (* Head is not rewritten *)\n val ((result2, Var _ $ _), _) = eval @{thms arith_simps refl if_False} @{thms} input;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result2) = @{term \"(if True then Suc else id) x\"});\n\n (* Head is Abs *)\n val ((result3, Var _), _) = eval @{thms arith_simps refl fun_upd_apply if_True} @{thms} input_abs1;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result3) = @{term \"y::nat\"});\n\n (* Partially applied Abs *)\n val ((result4, Abs _), _) = eval @{thms arith_simps refl fun_upd_apply if_True} @{thms} input_abs2;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result4) = @{term \"\\z. z + fun_upd (f::nat\\nat) (2+2) y 4\"});\nend;\n\\\n\ntext \\Check that skel_skip is not returned for intermediate Abs\\\nML_val \\\nlocal\n fun eval eqns congs = FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"map (\\((x, y), z). ((id x, id y), id z)) [((a::'a, b::'b), c::'c)]\"}, Bound 0);\nin\n val ((result, Var _), counters) = eval @{thms list.map prod.case arith_simps} @{thms} input;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result) = @{term \"[((id a::'a, id b::'b), id c::'c)]\"});\nend;\n\\\n\ntext \\Test conversion of some basic non-equation rules to equations\\\nML_val \\\nlet val thms = @{thms simp_thms rel_simps arith_simps};\nin @{assert} (length (map_filter FP_Eval.maybe_convert_eqn thms) = length thms) end\n\\\n\nend", "meta": {"author": "seL4", "repo": "l4v", "sha": "9ba34e269008732d4f89fb7a7e32337ffdd09ff9", "save_path": "github-repos/isabelle/seL4-l4v", "path": "github-repos/isabelle/seL4-l4v/l4v-9ba34e269008732d4f89fb7a7e32337ffdd09ff9/lib/test/FP_Eval_Tests.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.20181322226037884, "lm_q1q2_score": 0.08913545245860464}} {"text": "(*\n * Copyright 2018, Data61, CSIRO\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * @TAG(DATA61_BSD)\n *)\n\ntheory Time_Methods_Cmd_Test imports\n Lib.Time_Methods_Cmd\n Lib.Eisbach_Methods\n \"HOL-Library.Sublist\"\nbegin\n\ntext \\\n @{method time_methods} is a utility that runs several methods on the same\n proof goal, printing the running time of each one.\n\n Usage:\n\n apply (time_methods [(no_check)] [(skip_fail)]\n [name1:] \\method1\\\n [name2:] \\method2\\\n ...)\n\n Options:\n\n no_check: Don't check that the outputs of each method match.\n\n skip_fail: Don't print anything for failed methods.\n\\\n\nexperiment begin\n section \\Basic examples\\\n\n lemma\n \"A \\ B \\ A \\ B\"\n apply (time_methods\n \\erule disjI1\\\n \\erule disjI2\\)\n done\n\n text \\Give labels to methods:\\\n lemma\n \"A \\ B \\ A \\ B\"\n apply (time_methods\n label: \\erule disjI1\\\n \"another label\": \\erule disjI2\\)\n done\n\n text \\no_check prevents failing even if the method results differ.\\\n lemma\n \"A \\ B \\ A \\ B\"\n apply (time_methods (no_check)\n \\rule disjI1\\\n \\rule disjI2\\)\n apply assumption\n done\n\n text \\\n Fast and slow list reversals.\n \\\n lemma list_eval_rev_append:\n \"rev xs = rev xs @ []\"\n \"rev [] @ ys = ys\"\n \"rev (x # xs) @ ys = rev xs @ (x # ys)\"\n by auto\n\n lemma \"rev [0..100] = map ((-) 100) [0..100]\"\n \"rev [0..200] = map ((-) 200) [0..200]\"\n text \\evaluate everything but @{term rev}\\\n apply (all \\match conclusion in \"rev x = y\" for x y \\\n \\rule subst[where t = x], simp add: upto.simps\\\\)\n apply (all \\match conclusion in \"rev x = y\" for x y \\\n \\rule subst[where t = y], simp add: upto.simps\\\\)\n\n text \\evaluate @{term rev}\\\n apply (time_methods\n naive100: \\simp\\\n slow100: \\simp only: rev.simps append.simps\\\n fast100: \\subst list_eval_rev_append(1), simp only: list_eval_rev_append(2-3)\\\n )\n apply (time_methods\n naive200: \\simp\\\n slow200: \\simp only: rev.simps append.simps\\\n fast200: \\subst list_eval_rev_append(1), simp only: list_eval_rev_append(2-3)\\\n )\n done\n\n text \\\n Fast and slow subsequence testing.\n \\\n lemma\n \"subseq (map ((*) 2) [1 .. 5]) [1 .. 10]\"\n \"subseq (map ((*) 2) [1 .. 6]) [1 .. 12]\"\n \"subseq (map ((*) 2) [1 .. 7]) [1 .. 14]\"\n \"subseq (map ((*) 2) [1 .. 8]) [1 .. 16]\"\n apply (all \\match conclusion in \"subseq x y\" for x y \\\n \\rule subst[where t = x], simp add: upto.simps,\n rule subst[where t = y], simp add: upto.simps\\\\)\n\n apply (time_methods\n \"HOL simp\": \\simp\\\n\n \"l4v simp\": \\simp cong: if_cong cong del: if_weak_cong\\\n \\ \\exponential time!\\\n )+\n done\n\n text \\\n Which method is a better SAT solver?\n Instance 01 from the uf20-91 dataset at http://www.cs.ubc.ca/~hoos/SATLIB/benchm.html\n \\\n lemma \"\\x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20.\n (~x4 & x18 & ~x19) | (~x3 & ~x18 & x5) | (x5 & x8 & x15) | (x20 & ~x7 & x16) |\n (~x10 & x13 & x7) | (x12 & x9 & ~x17) | (~x17 & ~x19 & ~x5) | (x16 & ~x9 & ~x15) |\n (~x11 & x5 & x14) | (~x18 & x10 & ~x13) | (x3 & ~x11 & ~x12) | (x6 & x17 & x8) |\n (x18 & ~x14 & ~x1) | (x19 & x15 & ~x10) | (~x12 & ~x18 & x19) | (x8 & ~x4 & ~x7) |\n (x8 & x9 & ~x4) | (~x7 & ~x17 & x15) | (~x12 & x7 & x14) | (x10 & x11 & ~x8) |\n (~x2 & x15 & x11) | (~x9 & ~x6 & ~x1) | (x11 & ~x20 & x17) | (~x9 & x15 & ~x13) |\n (~x12 & x7 & x17) | (x18 & x2 & ~x20) | (~x20 & ~x12 & ~x4) | (~x19 & ~x11 & ~x14) |\n (x16 & ~x18 & x4) | (x1 & x17 & x19) | (x13 & ~x15 & ~x10) | (x12 & x14 & x13) |\n (~x12 & x14 & x7) | (x7 & ~x16 & ~x10) | (~x6 & ~x10 & ~x7) | (~x20 & ~x14 & x16) |\n (x19 & ~x17 & ~x11) | (x7 & ~x1 & x20) | (x5 & ~x12 & ~x15) | (x4 & x9 & x13) |\n (~x12 & x11 & x7) | (x5 & ~x19 & x8) | (~x1 & ~x16 & ~x17) | (~x20 & x14 & x15) |\n (~x13 & x4 & ~x10) | (~x14 & ~x7 & ~x10) | (x5 & ~x9 & ~x20) | (~x10 & ~x1 & x19) |\n (x16 & x15 & x1) | (~x16 & ~x3 & x11) | (x15 & x10 & ~x4) | (~x4 & x15 & x3) |\n (x10 & x16 & ~x11) | (x8 & ~x12 & x5) | (~x14 & x6 & ~x12) | (~x1 & ~x6 & ~x11) |\n (x13 & x5 & x1) | (x7 & x2 & ~x12) | (~x1 & x20 & ~x19) | (x2 & x13 & x8) |\n (~x15 & ~x18 & ~x4) | (x11 & ~x14 & ~x9) | (x6 & x15 & x2) | (~x5 & x12 & x15) |\n (x6 & ~x17 & ~x5) | (x13 & ~x5 & x19) | (~x20 & x1 & ~x14) | (~x9 & x17 & ~x15) |\n (x5 & ~x19 & x18) | (x12 & ~x8 & x10) | (x18 & ~x14 & x4) | (~x15 & x9 & ~x13) |\n (~x9 & x5 & x1) | (~x10 & x19 & x14) | (~x20 & ~x9 & ~x4) | (x9 & x2 & ~x19) |\n (x5 & ~x13 & x17) | (~x2 & x10 & x18) | (x18 & ~x3 & ~x11) | (~x7 & x9 & ~x17) |\n (x15 & x6 & x3) | (x2 & ~x3 & x13) | (~x12 & ~x3 & x2) | (x2 & x3 & ~x17) |\n (~x20 & x15 & x16) | (x5 & x17 & x19) | (x20 & x18 & ~x11) | (x9 & ~x1 & x5) |\n (x19 & ~x9 & ~x17) | (~x12 & x2 & ~x17)\"\n using [[meson_max_clauses=99]]\n apply (time_methods\n blast: \\blast\\\n metis: \\metis\\\n meson: \\meson\\\n smt: \\smt\\\n force: \\force\\\n fastforce: \\fastforce intro: ex_bool_eq[THEN iffD2]\\\n fastforce: \\fastforce simp: ex_bool_eq\\\n presburger: \\use ex_bool_eq[simp] in presburger\\\n )\n done\n\n section \\Other tests\\\n\n text \\Test ML interface\\\n lemma \"True\"\n apply (tactic \\\n let val method = SIMPLE_METHOD (simp_tac @{context} 1)\n fun dummy_callback _ _ = ()\n in (fn st => Time_Methods.time_methods false false dummy_callback [(NONE, method)] [] st\n |> (fn ([timing], st') => (tracing (Timing.message timing); st')))\n |> Method.NO_CONTEXT_TACTIC @{context}\n end\\)\n done\n\n text \\Check that we fail when the methods give different results\\\n lemma\n \"A \\ B\"\n apply (tactic \\\n let\n fun skip_dummy_state tac = fn st =>\n case Thm.prop_of st of\n Const (\"Pure.prop\", _) $ (Const (\"Pure.term\", _) $ Const (\"Pure.dummy_pattern\", _)) =>\n Seq.succeed st\n | _ => tac st;\n val methods = @{thms disjI1 disjI2}\n |> map (fn rule => (NONE, SIMPLE_METHOD (resolve_tac @{context} [rule] 1)))\n fun dummy_callback _ _ = ()\n in (fn st => Time_Methods.time_methods false false dummy_callback methods [] st\n |> (fn (timing, st') => error \"test failed: shouldn't reach here\")\n handle THM _ => Seq.succeed (Seq.Result st)) (* should reach here *)\n |> Method.NO_CONTEXT_TACTIC @{context}\n |> skip_dummy_state\n end\\)\n oops\n\n text \\Check that we propagate failures from the input methods\\\n lemma \"A\"\n apply (fails \\time_methods \\simp\\\\)\n oops\n\n text \\Check that we skip failing methods when skip_fail set\\\n lemma \"A \\ B \\ A\"\n apply (\n ( \\ \\roughly corresponds to \"time_methods (skip_fail) \\fail\\\",\n but errors if it calls the output callback\\\n tactic \\\n let\n fun timing_callback _ _ = error \"test failed: shouldn't reach here\"\n val methods = [(NONE, SIMPLE_METHOD no_tac)]\n in\n (fn st =>\n #2 (Time_Methods.time_methods false true timing_callback methods [] st))\n |> Method.NO_CONTEXT_TACTIC @{context}\n end\\)\n | time_methods (skip_fail) good_simp: \\simp\\)\n done\nend\n\nend\n", "meta": {"author": "CompSoftVer", "repo": "CSim2", "sha": "b09a4d77ea089168b1805db5204ac151df2b9eff", "save_path": "github-repos/isabelle/CompSoftVer-CSim2", "path": "github-repos/isabelle/CompSoftVer-CSim2/CSim2-b09a4d77ea089168b1805db5204ac151df2b9eff/lib/Time_Methods_Cmd_Test.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.17553806715374198, "lm_q1q2_score": 0.08571232343349737}} {"text": "(* Author: Norbert Schirmer\n Maintainer: Norbert Schirmer, norbert.schirmer at web de\n License: LGPL\n*)\n\n(* Title: UserGuide.thy\n Author: Norbert Schirmer, TU Muenchen\n\nCopyright (C) 2004-2008 Norbert Schirmer \nSome rights reserved, TU Muenchen\n\nThis library is free software; you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation; either version 2.1 of the\nLicense, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307\nUSA\n*)\n\nsection {* User Guide \\label{sec:UserGuide}*}\n(*<*)\ntheory UserGuide \nimports HeapList Vcg\n \"HOL-Statespace.StateSpaceSyntax\" \"HOL-Library.LaTeXsugar\"\nbegin \n(*>*)\n\n(*<*)\nsyntax\n \"_statespace_updates\" :: \"('a \\ 'b) \\ updbinds \\ ('a \\ 'b)\" (\"_\\_\\\" [900,0] 900)\n(*>*)\n\n\n\ntext {*\nWe introduce the verification environment with a couple\nof examples that illustrate how to use the different\nbits and pieces to verify programs. \n*}\n\n\nsubsection {* Basics *}\n\ntext {*\n\nFirst of all we have to decide how to represent the state space. There\nare currently two implementations. One is based on records the other\none on the concept called `statespace' that was introduced with\nIsabelle 2007 (see \\texttt{HOL/Statespace}) . In contrast to records a \n'satespace' does not define a new type, but provides a notion of state, \nbased on locales. Logically\nthe state is modelled as a function from (abstract) names to\n(abstract) values and the statespace infrastructure organises\ndistinctness of names an projection/injection of concrete values into\nthe abstract one. Towards the user the interface of records and\nstatespaces is quite similar. However, statespaces offer more\nflexibility, inherited from the locale infrastructure, in\nparticular multiple inheritance and renaming of components.\n\nIn this user guide we prefer statespaces, but give some comments on\nthe usage of records in Section \\ref{sec:records}. \n\n\n*}\n\nhoarestate vars = \n A :: nat\n I :: nat\n M :: nat\n N :: nat\n R :: nat\n S :: nat\n\ntext (in vars) {* The command \\isacommand{hoarestate} is a simple preprocessor\nfor the command \\isacommand{statespaces} which decorates the state\ncomponents with the suffix @{text \"_'\"}, to avoid cluttering the\nnamespace. Also note that underscores are printed as hyphens in this\ndocumentation. So what you see as @{term \"A_'\"} in this document is\nactually \\texttt{A\\_'}. Every component name becomes a fixed variable in\nthe locale @{text vars} and can no longer be used for logical\nvariables. \n\nLookup of a component @{term \"A_'\"} in a state @{term \"s\"} is written as\n@{term \"s\\A_'\"}, and update with a value @{term \"term v\"} as @{term \"s\\A_' := v\\\"}.\n\nTo deal with local and global variables in the context of procedures the\nprogram state is organised as a record containing the two componets @{const \"locals\"} \nand @{const \"globals\"}. The variables defined in hoarestate @{text \"vars\"} reside\nin the @{const \"locals\"} part.\n\n*}\n\ntext {*\n Here is a first example.\n*}\n\nlemma (in vars) \"\\\\ \\\\N = 5\\ \\N :== 2 * \\N \\\\N = 10\\\"\n apply vcg\n txt {* @{subgoals} *}\n apply simp\n txt {* @{subgoals} *}\n done\n\ntext {* We enable the locale of statespace @{text vars} by the\n\\texttt{in vars} directive. The verification condition generator is\ninvoked via the @{text vcg} method and leaves us with the expected\nsubgoal that can be proved by simplification. *}\n\ntext (in vars) {*\n If we refer to components (variables) of the state-space of the program\n we always mark these with @{text \"\\\"} (in assertions and also in the\n program itself). It is the acute-symbol and is present on\n most keyboards. The assertions of the Hoare tuple are\n ordinary Isabelle sets. As we usually want to refer to the state space\n in the assertions, we provide special brackets for them. They can be written \n as {\\verb+{| |}+} in ASCII or @{text \"\\ \\\"} with symbols. Internally,\n marking variables has two effects. First of all we refer to the implicit\n state and secondary we get rid of the suffix @{text \"_'\"}.\n So the assertion @{term \"{|\\N = 5|}\"} internally gets expanded to \n @{text \"{s. locals s \\N_' = 5}\"} written in ordinary set comprehension notation of\n Isabelle. It describes the set of states where the @{text \"N_'\"} component\n is equal to @{text \"5\"}. \n An empty context and an empty postcondition for abrupt termination can be\n omitted. The lemma above is a shorthand for \n @{text \"\\,{}\\ \\\\N = 5\\ \\N :== 2 * \\N \\\\N = 10\\,{}\"}.\n*}\n\ntext {* We can step through verification condition generation by the\nmethod @{text vcg_step}.\n*}\n\nlemma (in vars) \"\\,{}\\ \\\\N = 5\\ \\N :== 2 * \\N \\\\N = 10\\\"\n apply vcg_step\n txt {* @{subgoals} *}\n txt {* The last step of verification condition generation, \n transforms the inclusion of state sets to the corresponding \n predicate on components of the state space. \n *}\n apply vcg_step\n txt {* @{subgoals} *}\n by simp\n\ntext {*\nAlthough our assertions work semantically on the state space, stepping\nthrough verification condition generation ``feels'' like the expected\nsyntactic substitutions of traditional Hoare logic. This is achieved\nby light simplification on the assertions calculated by the Hoare rules.\n*}\n\nlemma (in vars) \"\\\\ \\\\N = 5\\ \\N :== 2 * \\N \\\\N = 10\\\"\n apply (rule HoarePartial.Basic)\n txt {* @{subgoals} *}\n apply (simp only: mem_Collect_eq)\n txt {* @{subgoals} *}\n apply (tactic \n {* Hoare.BasicSimpTac @{context} Hoare.Function false\n [] (K all_tac) 1*})\n txt {* @{subgoals} *}\n by simp\n\n\ntext {* The next example shows how we deal with the while loop. Note the\ninvariant annotation.\n*}\n\nlemma (in vars) \n \"\\,{}\\ \\\\M = 0 \\ \\S = 0\\\n WHILE \\M \\ a\n INV \\\\S = \\M * b\\\n DO \\S :== \\S + b;; \\M :== \\M + 1 OD\n \\\\S = a * b\\\"\n apply vcg\n txt {* @{subgoals [display]} *}\n txt {* The verification condition generator gives us three proof obligations,\n stemming from the path from the precondition to the invariant,\n from the invariant together with loop condition through the\n loop body to the invariant, and finally from the invariant together\n with the negated loop condition to the postcondition.*}\n apply auto\n done\n\nsubsection {* Procedures *}\n\nsubsubsection {* Declaration *}\n\ntext {*\nOur first procedure is a simple square procedure. We provide the\ncommand \\isacommand{procedures}, to declare and define a\nprocedure.\n*}\n\nprocedures\n Square (N::nat|R::nat) \n where I::nat in\n \"\\R :== \\N * \\N\"\n \n\n\ntext {* A procedure is given by the signature of the procedure\nfollowed by the procedure body. The signature consists of the name of\nthe procedure and a list of parameters together with their types. The\nparameters in front of the pipe @{text \"|\"} are value parameters and\nbehind the pipe are the result parameters. Value parameters model call\nby value semantics. The value of a result parameter at the end of the\nprocedure is passed back to the caller. Local variables follow the\n@{text \"where\"}. If there are no local variables the @{text \"where \\\nin\"} can be omitted. The variable @{term \"I\"} is actually unused in\nthe body, but is used in the examples below. *}\n\n\ntext {*\nThe procedures command provides convenient syntax\nfor procedure calls (that creates the proper @{term init}, @{term return} and\n@{term result} functions on the fly) and creates locales and statespaces to \nreason about the procedure. The purpose of locales is to set up logical contexts\nto support modular reasoning. Locales can be seen as freeze-dried proof contexts that\nget alive as you setup a new lemma or theorem (\\cite{Ballarin-04-locales}).\nThe locale the user deals with is named @{text \"Square_impl\"}.\n It defines the procedure name (internally @{term \"Square_'proc\"}), the procedure body \n(named @{text \"Square_body\"}) and the statespaces for parameters and local and\nglobal variables.\nMoreover it contains the \nassumption @{term \"\\ Square_'proc = Some Square_body\"}, which states \nthat the procedure is properly defined in the procedure context. \n\nThe purpose of the locale is to give us easy means to setup the context \nin which we prove programs correct. \nIn this locale the procedure context @{term \"\\\"} is fixed. \nSo we always use this letter for the procedure\nspecification. This is crucial, if we prove programs under the\nassumption of some procedure specifications.\n*}\n\n(*<*)\ncontext Square_impl\nbegin\n(*>*)\ntext {* The procedures command generates syntax, so that we can \neither write @{text \"CALL Square(\\I,\\R)\"} or @{term \"\\I :== CALL\nSquare(\\R)\"} for the procedure call. The internal term is the\nfollowing: \n*} \n\n(*<*) declare [[hoare_use_call_tr' = false]] (*>*) \ntext {* \\small @{term [display] \"CALL Square(\\I,\\R)\"} *} \n(*<*) declare [[hoare_use_call_tr' = true]] (*>*)\n\ntext {* Note the\n additional decoration (with the procedure name) of the parameter and\n local variable names.*}\n(*<*)\nend \n(*>*)\n\ntext {* The abstract syntax for the\nprocedure call is @{term \"call init p return result\"}. The @{term\n\"init\"} function copies the values of the actual parameters to the\nformal parameters, the @{term return} function copies the global\nvariables back (in our case there are no global variables), and the\n@{term \"result\"} function additionally copies the values of the formal\nresult parameters to the actual locations. Actual value parameters can\nbe all kind of expressions, since we only need their value. But result\nparameters must be proper ``lvalues'': variables (including\ndereferenced pointers) or array locations, since we have to assign\nvalues to them. \n*}\n\nsubsubsection {* Verification *}\n\ntext (in Square_impl) {*\nA procedure specification is an ordinary Hoare tuple. \nWe use the parameterless\ncall for the specification; @{text \"\\R :== PROC Square(\\N)\"} is syntactic sugar\nfor @{text \"Call Square_'proc\"}. This emphasises that the specification \ndescribes the internal behaviour of the procedure, whereas parameter passing\ncorresponds to the procedure call.\nThe following precondition fixes the current value @{text \"\\N\"} to the logical \nvariable @{term n}. \nUniversal quantification of @{term \"n\"} enables us to adapt \nthe specification to an actual parameter. The specification is\nused in the rule for procedure call when we come upon a call to @{term Square}. \nThus @{term \"n\"} plays the role of the auxiliary variable @{term \"Z\"}.\n*}\n\n\ntext {* To verify the procedure we need to verify the body. We use\na derived variant of the general recursion rule, tailored for non recursive procedures:\n@{thm [source] HoarePartial.ProcNoRec1}:\n\\begin{center}\n@{thm [mode=Rule,mode=ParenStmt] HoarePartial.ProcNoRec1 [no_vars]}\n\\end{center}\nThe naming convention for the rule \nis the following: The @{text \"1\"} expresses that we look at one\n procedure, and @{text NoRec} that the procedure is non\nrecursive. \n*} \n\n\nlemma (in Square_impl)\nshows \"\\n. \\\\\\\\N = n\\ \\R :== PROC Square(\\N) \\\\R = n * n\\\"\ntxt {* The directive @{text \"in\"} has the effect that\nthe context of the locale @{term \"Square_impl\"} is included to the current\nlemma, and that the lemma is added as a fact to the locale, after it is proven. The\nnext time locale @{term \"Square_impl\"} is invoked this lemma is immediately available\nas fact, which the verification condition generator can use.\n*}\napply (hoare_rule HoarePartial.ProcNoRec1)\n txt \"@{subgoals[display]}\"\n txt {* The method @{text \"hoare_rule\"}, like @{text \"rule\"} applies a \n single rule, but additionally does some ``obvious'' steps:\n It solves the canonical side-conditions of various Hoare-rules and it \n automatically expands the\n procedure body: With @{thm [source] Square_impl}: @{thm [names_short] Square_impl [no_vars]} we\n get the procedure body out of the procedure context @{term \"\\\"}; \n with @{thm [source] Square_body_def}: @{thm [names_short] Square_body_def [no_vars]} we\n can unfold the definition of the body.\n\n The proof is finished by the vcg and simp.\n *}\ntxt \"@{subgoals[display]}\"\nby vcg simp\n\ntext {* If the procedure is non recursive and there is no specification given, the\nverification condition generator automatically expands the body.*}\n\nlemma (in Square_impl) Square_spec: \nshows \"\\n. \\\\\\\\N = n\\ \\R :== PROC Square(\\N) \\\\R = n * n\\\"\n by vcg simp\n\ntext {* An important naming convention is to name the specification as\n@{text \"_spec\"}. The verification condition generator refers to\nthis name in order to search for a specification in the theorem database.\n*}\n\nsubsubsection {* Usage *}\n\n\ntext{* Let us see how we can use procedure specifications. *}\n(* FIXME: maybe don't show this at all *)\nlemma (in Square_impl)\n shows \"\\\\\\\\I = 2\\ \\R :== CALL Square(\\I) \\\\R = 4\\\"\n txt {* Remember that we have already proven @{thm [source] \"Square_spec\"} in the locale\n @{text \"Square_impl\"}. This is crucial for \n verification condition generation. When reaching a procedure call,\n it looks for the specification (by its name) and applies the\n rule @{thm [source,mode=ParenStmt] HoarePartial.ProcSpec} \ninstantiated with the specification\n (as last premise). \n Before we apply the verification condition generator, let us\n take some time to think of what we can expect.\n Let's look at the specification @{thm [source] Square_spec} again:\n @{thm [display] Square_spec [no_vars]}\n The specification talks about the formal parameters @{term \"N\"} and \n @{term R}. The precondition @{term \"\\\\N = n\\\"} just fixes the initial\n value of @{text N}.\n The actual parameters are @{term \"I\"} and @{term \"R\"}. We \n have to adapt the specification to this calling context.\n @{term \"\\n. \\\\ \\\\I = n\\ \\R :== CALL Square(\\I) \\\\R = n * n\\\"}.\n From the postcondition @{term \"\\\\R = n * n\\\"} we \n have to derive the actual postcondition @{term \"\\\\R = 4\\\"}. So\n we gain something like: @{term \"\\n * n = (4::nat)\\\"}.\n The precondition is @{term \"\\\\I = 2\\\"} and the specification \n tells us @{term \"\\\\I = n\\\"} for the pre-state. So the value of @{term n}\n is the value of @{term I} in the pre-state. So we arrive at\n @{term \"\\\\I = 2\\ \\ \\\\I * \\I = 4\\\"}.\n *}\n apply vcg_step\n txt \"@{subgoals[display]}\"\n txt {*\n The second set looks slightly more involved:\n @{term \"\\\\t. \\<^bsup>t\\<^esup>R = \\I * \\I \\ \\I * \\I = 4\\\"}, this is an artefact from the\n procedure call rule. Originally @{text \"\\I * \\I = 4\"} was @{text \"\\<^bsup>t\\<^esup>R = 4\"}. Where\n @{term \"t\"} denotes the final state of the procedure and the superscript notation\n allows to select a component from a particular state. \n *}\n apply vcg_step\n txt \"@{subgoals[display]}\"\n by simp\n \ntext {*\nThe adaption of the procedure specification to the actual calling \ncontext is done due to the @{term init}, @{term return} and @{term result} functions \nin the rule @{thm [source] HoarePartial.ProcSpec} (or in the variant \n@{thm [source] HoarePartial.ProcSpecNoAbrupt} which already\nincorporates the fact that the postcondition for abrupt termination\nis the empty set). For the readers interested in the internals, \nhere a version without vcg.\n*}\nlemma (in Square_impl)\n shows \"\\\\\\\\I = 2\\ \\R :== CALL Square(\\I) \\\\R = 4\\\"\n apply (rule HoarePartial.ProcSpecNoAbrupt [OF _ _ Square_spec])\n txt \"@{subgoals[display]}\"\n txt {* This is the raw verification condition, \n It is interesting to see how the auxiliary variable @{term \"Z\"} is\n actually used. It is unified with @{term n} of the specification and\n fixes the state after parameter passing. \n *}\n apply simp\n txt \"@{subgoals[display]}\"\n prefer 2\n apply vcg_step\n txt \"@{subgoals[display]}\"\n apply (auto intro: ext)\n done\n\n\n\nsubsubsection {* Recursion *}\n\ntext {* We want to define a procedure for the factorial. We first\ndefine a HOL function that calculates it, to specify the procedure later on.\n*}\n\nprimrec fac:: \"nat \\ nat\"\nwhere\n\"fac 0 = 1\" |\n\"fac (Suc n) = (Suc n) * fac n\"\n\n(*<*)\nlemma fac_simp [simp]: \"0 < i \\ fac i = i * fac (i - 1)\"\n by (cases i) simp_all\n(*>*)\n\ntext {* Now we define the procedure. *}\nprocedures\n Fac (N::nat | R::nat) \n \"IF \\N = 0 THEN \\R :== 1\n ELSE \\R :== CALL Fac(\\N - 1);;\n \\R :== \\N * \\R\n FI\"\n \ntext {*\nNow let us prove that our implementation of @{term \"Fac\"} meets its specification. \n*}\n\nlemma (in Fac_impl)\nshows \"\\n. \\\\ \\\\N = n\\ \\R :== PROC Fac(\\N) \\\\R = fac n\\\"\napply (hoare_rule HoarePartial.ProcRec1)\ntxt \"@{subgoals[display]}\"\napply vcg\ntxt \"@{subgoals[display]}\"\napply simp\ndone\n\ntext {* \nSince the factorial is implemented recursively,\nthe main ingredient of this proof is, to assume that the specification holds for \nthe recursive call of @{term Fac} and prove the body correct.\nThe assumption for recursive calls is added to the context by\nthe rule @{thm [source] HoarePartial.ProcRec1} \n(also derived from the general rule for mutually recursive procedures):\n\\begin{center}\n@{thm [mode=Rule,mode=ParenStmt] HoarePartial.ProcRec1 [no_vars]}\n\\end{center}\nThe verification condition generator infers the specification out of the\ncontext @{term \"\\\"} when it encounters a recursive call of the factorial.\n*}\n\nsubsection {* Global Variables and Heap \\label{sec:VcgHeap}*}\n\ntext {*\nNow we define and verify some procedures on heap-lists. We consider\nlist structures consisting of two fields, a content element @{term \"cont\"} and\na reference to the next list element @{term \"next\"}. We model this by the \nfollowing state space where every field has its own heap.\n*}\n\nhoarestate globals_heap =\n \"next\" :: \"ref \\ ref\"\n cont :: \"ref \\ nat\"\n\ntext {* It is mandatory to start the state name with `globals'. This is exploited\nby the syntax translations to store the components in the @{const globals} part\nof the state.\n*}\n\ntext {* Updates to global components inside a procedure are\nalways propagated to the caller. This is implicitly done by the\nparameter passing syntax translations. \n*}\n\ntext {* We first define an append function on lists. It takes two \nreferences as parameters. It appends the list referred to by the first\nparameter with the list referred to by the second parameter. The statespace\nof the global variables has to be imported.\n*}\n\nprocedures (imports globals_heap)\n append(p :: ref, q::ref | p::ref) \n \"IF \\p=Null THEN \\p :== \\q \n ELSE \\p\\\\next :== CALL append(\\p\\\\next,\\q) FI\"\n\n(*<*)\ncontext append_impl\nbegin\n(*>*)\ntext {*\nThe difference of a global and a local variable is that global\nvariables are automatically copied back to the procedure caller.\nWe can study this effect on the translation of @{term \"\\p :== CALL append(\\p,\\q)\"}:\n*}\n(*<*)\ndeclare [[hoare_use_call_tr' = false]]\n(*>*)\ntext {*\n@{term [display] \"\\p :== CALL append(\\p,\\q)\"}\n*}\n(*<*)\ndeclare [[hoare_use_call_tr' = true]]\nend\n(*>*)\n\ntext {* Below we give two specifications this time.\nOne captures the functional behaviour and focuses on the\nentities that are potentially modified by the procedure, the second one\nis a pure frame condition. \n*}\n\n\n\ntext {* \nThe functional specification below introduces two logical variables besides the\nstate space variable @{term \"\\\"}, namely @{term \"Ps\"} and @{term \"Qs\"}.\nThey are universally quantified and range over both the pre-and the postcondition, so \nthat we are able to properly instantiate the specification\nduring the proofs. The syntax @{text \"\\\\. \\\\\"} is a shorthand to fix the current \nstate: @{text \"{s. \\ = s \\}\"}. Moreover @{text \"\\<^bsup>\\\\<^esup>x\"} abbreviates \nthe lookup of variable @{text \"x\"} in the state \n@{text \\}. \n\nThe approach to specify procedures on lists\nbasically follows \\cite{MehtaN-CADE03}. From the pointer structure\nin the heap we (relationally) abstract to HOL lists of references. Then\nwe can specify further properties on the level of HOL lists, rather then \non the heap. The basic abstractions are: \n\n@{thm [display] Path.simps [no_vars]}\n\n@{term [show_types] \"Path x h y ps\"}: @{term ps} is a list of references that we can obtain\nout of the heap @{term h} by starting with the reference @{term x}, following\nthe references in @{term h} up to the reference @{term y}. \n\n\n@{thm [display] List_def [no_vars]}\n\nA list @{term \"List p h ps\"} is a path starting in @{term p} and ending up\nin @{term Null}.\n*}\n\n\nlemma (in append_impl) append_spec1: \nshows \"\\\\ Ps Qs. \n \\\\ \\\\. List \\p \\next Ps \\ List \\q \\next Qs \\ set Ps \\ set Qs = {}\\ \n \\p :== PROC append(\\p,\\q) \n \\List \\p \\next (Ps@Qs) \\ (\\x. x\\set Ps \\ \\next x = \\<^bsup>\\\\<^esup>next x)\\\"\napply (hoare_rule HoarePartial.ProcRec1)\ntxt {* @{subgoals [margin=80,display]} \nNote that @{term \"hoare_rule\"} takes care of multiple auxiliary variables! \n@{thm [source] HoarePartial.ProcRec1} has only one auxiliary variable, namely @{term Z}. \nBut the type of @{term Z} can be instantiated arbitrarily. So @{text \"hoare_rule\"} \ninstantiates @{term Z} with the tuple @{term \"(\\,Ps,Qs)\"} and derives a proper variant\nof the rule. Therefore @{text \"hoare_rule\"} depends on the proper quantification of\nauxiliary variables!\n*}\napply vcg\ntxt {* @{subgoals [display]} \nFor each branch of the @{text IF} statement we have one conjunct to prove. The\n@{text THEN} branch starts with @{text \"p = Null \\ \\\"} and the @{text ELSE} branch\nwith @{text \"p \\ Null \\ \\\"}. Let us focus on the @{text ELSE} branch, were the\nrecursive call to append occurs. First of all we have to prove that the precondition for\nthe recursive call is fulfilled. That means we have to provide some witnesses for\nthe lists @{term Psa} and @{term Qsa} which are referenced by @{text \"p\\next\"} (now\nwritten as @{term \"next p\"}) and @{term q}. Then we have to show that we can \nderive the overall postcondition from the postcondition of the recursive call. The\nstate components that have changed by the recursive call are the ones with the suffix\n@{text a}, like @{text nexta} and @{text pa}.\n*}\napply fastforce\ndone\n\n\ntext {* If the verification condition generator works on a procedure\ncall it checks whether it can find a modifies clause in the\ncontext. If one is present the procedure call is simplified before the\nHoare rule @{thm [source] HoarePartial.ProcSpec} is\napplied. Simplification of the procedure call means that the ``copy\nback'' of the global components is simplified. Only those components\nthat occur in the modifies clause are actually copied back. This\nsimplification is justified by the rule @{thm [source]\nHoarePartial.ProcModifyReturn}. \nSo after this simplification all global\ncomponents that do not appear in the modifies clause are treated\nas local variables. *}\n\ntext {* We study the effect of the modifies clause on the following \nexamples, where we want to prove that @{term \"append\"} does not change\nthe @{term \"cont\"} part of the heap.\n*}\nlemma (in append_impl)\nshows \"\\\\ \\\\cont=c\\ \\p :== CALL append(Null,Null) \\\\cont=c\\\" \nproof -\n note append_spec = append_spec1\n show ?thesis\n apply vcg\n txt {* @{subgoals [display]} *}\n txt {* Only focus on the very last line: @{term conta} is the heap component \n after the procedure call,\n and @{term cont} the heap component before the procedure call. Since\n we have not added the modified clause we do not know that they have\n to be equal. \n *}\n oops\n\ntext {*\nWe now add the frame condition.\nThe list in the modifies clause names all global state components that\nmay be changed by the procedure. Note that we know from the modifies clause\nthat the @{term cont} parts are not changed. Also a small\nside note on the syntax. We use ordinary brackets in the postcondition\nof the modifies clause, and also the state components do not carry the\nacute, because we explicitly note the state @{term t} here.\n*}\n\n\nlemma (in append_impl) append_modifies:\n shows \"\\\\. \\\\\\<^bsub>/UNIV\\<^esub> {\\} \\p :== PROC append(\\p,\\q) \n {t. t may_only_modify_globals \\ in [next]}\"\n apply (hoare_rule HoarePartial.ProcRec1)\n apply (vcg spec=modifies)\n done\n\ntext {* We tell the verification condition generator to use only the\nmodifies clauses and not to search for functional specifications by \nthe parameter @{text \"spec=modifies\"}. It also tries to solve the \nverification conditions automatically. Again it is crucial to name \nthe lemma with this naming scheme, since the verfication condition \ngenerator searches for these names. \n*}\n\ntext {* The modifies clause is equal to a state update specification\nof the following form. \n*}\n\nlemma (in append_impl) shows \"{t. t may_only_modify_globals Z in [next]} \n = \n {t. \\next. globals t=update id id next_' (K_statefun next) (globals Z)}\"\n apply (unfold mex_def meq_def)\n apply simp\n done\n\ntext {* Now that we have proven the frame-condition, it is available within\nthe locale @{text \"append_impl\"} and the @{text \"vcg\"} exploits it.*}\n\nlemma (in append_impl) \nshows \"\\\\ \\\\cont=c\\ \\p :== CALL append(Null,Null) \\\\cont=c\\\"\nproof -\n note append_spec = append_spec1\n show ?thesis\n apply vcg\n txt {* @{subgoals [display]} *}\n txt {* With a modifies clause present we know that no change to @{term cont}\n has occurred. \n *}\n by simp\nqed\n \n\ntext {*\nOf course we could add the modifies clause to the functional specification as \nwell. But separating both has the advantage that we split up the verification\nwork. We can make use of the modifies clause before we apply the\nfunctional specification in a fully automatic fashion.\n*}\n \n\ntext {* \nTo prove that a procedure respects the modifies clause, we only need\nthe modifies clauses of the procedures called in the body. We do not need\nthe functional specifications. So we can always prove the modifies\nclause without functional specifications, but we may need the modifies\nclause to prove the functional specifications. So usually the modifies clause is\nproved before the proof of the functional specification, so that it can already be used\nby the verification condition generator.\n*}\n\n\n \nsubsection {* Total Correctness *}\n\ntext {* When proving total correctness the additional proof burden to\nthe user is to come up with a well-founded relation and to prove that\ncertain states get smaller according to this relation. Proving that a\nrelation is well-founded can be quite hard. But fortunately there are\nways to construct and stick together relations so that they are\nwell-founded by construction. This infrastructure is already present\nin Isabelle/HOL. For example, @{term \"measure f\"} is always well-founded;\nthe lexicographic product of two well-founded relations is again\nwell-founded and the inverse image construction @{term \"inv_image\"} of\na well-founded relation is again well-founded. The constructions are\nbest explained by some equations:\n\n@{thm in_measure_iff [no_vars]}\\\\\n@{thm in_lex_iff [no_vars]}\\\\\n@{thm in_inv_image_iff [no_vars]}\n\nAnother useful construction is @{text \"<*mlex*>\"} which is a combination\nof a measure and a lexicographic product:\n\n@{thm in_mlex_iff [no_vars]}\\\\\nIn contrast to the lexicographic product it does not construct a product type.\nThe state may either decrease according to the measure function @{term f} or the\nmeasure stays the same and the state decreases because of the relation @{term r}.\n\nLets look at a loop:\n*}\n\nlemma (in vars) \n \"\\\\\\<^sub>t \\\\M = 0 \\ \\S = 0\\\n WHILE \\M \\ a\n INV \\\\S = \\M * b \\ \\M \\ a\\\n VAR MEASURE a - \\M\n DO \\S :== \\S + b;; \\M :== \\M + 1 OD\n \\\\S = a * b\\\"\napply vcg\ntxt {* @{subgoals [display]} \nThe first conjunct of the second subgoal is the proof obligation that the\nvariant decreases in the loop body. \n*}\nby auto\n\n\n\ntext {* The variant annotation is preceded by @{text VAR}. The capital @{text MEASURE}\nis a shorthand for @{text \"measure (\\s. a - \\<^bsup>s\\<^esup>M)\"}. Analogous there is a capital \n@{text \"<*MLEX*>\"}.\n*}\n\nlemma (in Fac_impl) Fac_spec': \nshows \"\\\\. \\\\\\<^sub>t {\\} \\R :== PROC Fac(\\N) \\\\R = fac \\<^bsup>\\\\<^esup>N\\\"\napply (hoare_rule HoareTotal.ProcRec1 [where r=\"measure (\\(s,p). \\<^bsup>s\\<^esup>N)\"])\ntxt {* In case of the factorial the parameter @{term N} decreases in every call. This\nis easily expressed by the measure function. Note that the well-founded relation for\nrecursive procedures is formally defined on tuples\ncontaining the state space and the procedure name.\n*}\ntxt {* @{subgoals [display]} \nThe initial call to the factorial is in state @{term \"\\\"}. Note that in the \nprecondition @{term \"{\\} \\ {\\'}\"}, @{term \"\\'\"} stems from the lemma we want to prove\nand @{term \"\\\"} stems from the recursion rule for total correctness. Both are\nsynonym for the initial state. To use the assumption in the Hoare context we\nhave to show that the call to the factorial is invoked on a smaller @{term N} compared\nto the initial @{text \"\\<^bsup>\\\\<^esup>N\"}.\n*}\napply vcg\ntxt {* @{subgoals [display]} \nThe tribute to termination is that we have to show @{text \"N - 1 < N\"} in case of\nthe recursive call.\n*}\nby simp\n\nlemma (in append_impl) append_spec2:\nshows \"\\\\ Ps Qs. \\\\\\<^sub>t \n \\\\. List \\p \\next Ps \\ List \\q \\next Qs \\ set Ps \\ set Qs = {}\\ \n \\p :== PROC append(\\p,\\q) \n \\List \\p \\next (Ps@Qs) \\ (\\x. x\\set Ps \\ \\next x = \\<^bsup>\\\\<^esup>next x)\\\"\napply (hoare_rule HoareTotal.ProcRec1\n [where r=\"measure (\\(s,p). length (list \\<^bsup>s\\<^esup>p \\<^bsup>s\\<^esup>next))\"])\ntxt {* In case of the append function the length of the list referenced by @{term p}\ndecreases in every recursive call.\n*}\ntxt {* @{subgoals [margin=80,display]} *}\napply vcg\napply (fastforce simp add: List_list)\ndone\n\ntext {*\nIn case of the lists above, we have used a relational list abstraction @{term List}\nto construct the HOL lists @{term Ps} and @{term Qs} for the pre- and postcondition.\nTo supply a proper measure function we use a functional abstraction @{term list}.\nThe functional abstraction can be defined by means of the relational list abstraction,\nsince the lists are already uniquely determined by the relational abstraction:\n\n@{thm islist_def [no_vars]}\\\\\n@{thm list_def [no_vars]}\n\n\\isacommand{lemma} @{thm List_conv_islist_list [no_vars]}\n*}\n\ntext {*\nThe next contrived example is taken from \\cite{Homeier-95-vcg}, to illustrate\na more complex termination criterion for mutually recursive procedures. The procedures\ndo not calculate anything useful.\n\n*}\n\n\nprocedures \n pedal(N::nat,M::nat) \n \"IF 0 < \\N THEN\n IF 0 < \\M THEN \n CALL coast(\\N- 1,\\M- 1) FI;;\n CALL pedal(\\N- 1,\\M)\n FI\"\n and\n \n coast(N::nat,M::nat) \n \"CALL pedal(\\N,\\M);;\n IF 0 < \\M THEN CALL coast(\\N,\\M- 1) FI\"\n\n\ntext {*\nIn the recursive calls in procedure @{text pedal} the first argument always decreases.\nIn the body of @{text coast} in the recursive call of @{text coast} the second\nargument decreases, but in the call to @{text pedal} no argument decreases. \nTherefore an relation only on the state space is insufficient. We have to\ntake the procedure names into account, too.\nWe consider the procedure @{text coast} to be ``bigger'' than @{text pedal}\nwhen we construct a well-founded relation on the product of state space and procedure\nnames.\n*}\n\nML {* ML_Thms.bind_thm (\"HoareTotal_ProcRec2\", Hoare.gen_proc_rec @{context} Hoare.Total 2)*}\n\n\ntext {*\n We provide the ML function {\\tt gen\\_proc\\_rec} to\nautomatically derive a convenient rule for recursion for a given number of mutually\nrecursive procedures.\n*}\n\n \nlemma (in pedal_coast_clique)\nshows \"(\\\\. \\\\\\<^sub>t {\\} PROC pedal(\\N,\\M) UNIV) \\\n (\\\\. \\\\\\<^sub>t {\\} PROC coast(\\N,\\M) UNIV)\"\napply (hoare_rule HoareTotal_ProcRec2 \n [where r= \"((\\(s,p). \\<^bsup>s\\<^esup>N) <*mlex*>\n (\\(s,p). \\<^bsup>s\\<^esup>M) <*mlex*>\n measure (\\(s,p). if p = coast_'proc then 1 else 0))\"])\n txt {* We can directly express the termination condition described above with\n the @{text \"<*mlex*>\"} construction. Either state component @{text N} decreases,\n or it stays the same and @{text M} decreases or this also stays the same, but\n then the procedure name has to decrease.*}\n txt {* @{subgoals [margin=80,display]} *}\napply simp_all\n txt {* @{subgoals [margin=75,display]} *}\nby (vcg,simp)+\n\ntext {* We can achieve the same effect without @{text \"<*mlex*>\"} by using\n the ordinary lexicographic product @{text \"<*lex*>\"}, @{text \"inv_image\"} and\n @{text \"measure\"} \n*}\n \nlemma (in pedal_coast_clique)\nshows \"(\\\\. \\\\\\<^sub>t {\\} PROC pedal(\\N,\\M) UNIV) \\\n (\\\\. \\\\\\<^sub>t {\\} PROC coast(\\N,\\M) UNIV)\"\napply (hoare_rule HoareTotal_ProcRec2\n [where r= \"inv_image (measure (\\m. m) <*lex*>\n measure (\\m. m) <*lex*> \n measure (\\p. if p = coast_'proc then 1 else 0))\n (\\(s,p). (\\<^bsup>s\\<^esup>N,\\<^bsup>s\\<^esup>M,p))\"])\n txt {* With the lexicographic product we construct a well-founded relation on\n triples of type @{typ \"(nat\\nat\\string)\"}. With @{term inv_image} we project\n the components out of the state-space and the procedure names to this\n triple.\n *}\n txt {* @{subgoals [margin=75,display]} *}\napply simp_all\nby (vcg,simp)+\n\ntext {* By doing some arithmetic we can express the termination condition with a single\nmeasure function.\n*}\n\nlemma (in pedal_coast_clique) \nshows \"(\\\\. \\\\\\<^sub>t {\\} PROC pedal(\\N,\\M) UNIV) \\\n (\\\\. \\\\\\<^sub>t {\\} PROC coast(\\N,\\M) UNIV)\"\napply(hoare_rule HoareTotal_ProcRec2\n [where r= \"measure (\\(s,p). \\<^bsup>s\\<^esup>N + \\<^bsup>s\\<^esup>M + (if p = coast_'proc then 1 else 0))\"])\napply simp_all\ntxt {* @{subgoals [margin=75,display]} *}\nby (vcg,simp,arith?)+\n\n\nsubsection {* Guards *}\n\ntext (in vars) {* The purpose of a guard is to guard the {\\bf (sub-) expressions} of a\nstatement against runtime faults. Typical runtime faults are array bound violations,\ndereferencing null pointers or arithmetical overflow. Guards make the potential\nruntime faults explicit, since the expressions themselves never ``fail'' because \nthey are ordinary HOL expressions. To relieve the user from typing in lots of standard\nguards for every subexpression, we supply some input syntax for the common\nlanguage constructs that automatically generate the guards.\nFor example the guarded assignment @{text \"\\M :==\\<^sub>g (\\M + 1) div \\N\"} gets expanded to \nguarded command @{term \"\\M :==\\<^sub>g (\\M + 1) div \\N\"}. Here @{term \"in_range\"} is\nuninterpreted by now. \n*}\n\nlemma (in vars) \"\\\\\\True\\ \\M :==\\<^sub>g (\\M + 1) div \\N \\True\\\"\napply vcg\ntxt {* @{subgoals} *}\noops\n\ntext {*\nThe user can supply on (overloaded) definition of @{text \"in_range\"}\nto fit to his needs.\n\nCurrently guards are generated for:\n\n\\begin{itemize}\n\\item overflow and underflow of numbers (@{text \"in_range\"}). For subtraction of\n natural numbers @{text \"a - b\"} the guard @{text \"b \\ a\"} is generated instead\n of @{text \"in_range\"} to guard against underflows.\n\\item division by @{text 0}\n\\item dereferencing of @{term Null} pointers\n\\item array bound violations\n\\end{itemize}\n\nFollowing (input) variants of guarded statements are available:\n\n\\begin{itemize}\n\\item Assignment: @{text \"\\ :==\\<^sub>g \\\"}\n\\item If: @{text \"IF\\<^sub>g \\\"}\n\\item While: @{text \"WHILE\\<^sub>g \\\"}\n\\item Call: @{text \"CALL\\<^sub>g \\\"} or @{text \"\\ :== CALL\\<^sub>g \\\"}\n\\end{itemize}\n*}\n\nsubsection {* Miscellaneous Techniques *}\n\n\n\nsubsubsection {* Modifies Clause *}\n\ntext {* We look at some issues regarding the modifies clause with the example\nof insertion sort for heap lists.\n*}\n\nprimrec sorted:: \"('a \\ 'a \\ bool) \\ 'a list \\ bool\"\nwhere\n\"sorted le [] = True\" |\n\"sorted le (x#xs) = ((\\y\\set xs. le x y) \\ sorted le xs)\"\n\nprocedures (imports globals_heap)\n insert(r::ref,p::ref | p::ref) \n \"IF \\r=Null THEN SKIP\n ELSE IF \\p=Null THEN \\p :== \\r;; \\p\\\\next :== Null\n ELSE IF \\r\\\\cont \\ \\p\\\\cont \n THEN \\r\\\\next :== \\p;; \\p:==\\r\n ELSE \\p\\\\next :== CALL insert(\\r,\\p\\\\next)\n FI\n FI\n FI\"\n\nlemma (in insert_impl) insert_modifies:\n \"\\\\. \\\\\\<^bsub>/UNIV\\<^esub> {\\} \\p :== PROC insert(\\r,\\p) \n {t. t may_only_modify_globals \\ in [next]}\"\n by (hoare_rule HoarePartial.ProcRec1) (vcg spec=modifies)\n\nlemma (in insert_impl) insert_spec:\n \"\\\\ Ps . \\\\ \n \\\\. List \\p \\next Ps \\ sorted (op \\) (map \\cont Ps) \\ \n \\r \\ Null \\ \\r \\ set Ps\\\n \\p :== PROC insert(\\r,\\p) \n \\\\Qs. List \\p \\next Qs \\ sorted (op \\) (map \\<^bsup>\\\\<^esup>cont Qs) \\\n set Qs = insert \\<^bsup>\\\\<^esup>r (set Ps) \\\n (\\x. x \\ set Qs \\ \\next x = \\<^bsup>\\\\<^esup>next x)\\\"\n (*<*)\n apply (hoare_rule HoarePartial.ProcRec1)\n apply vcg\n apply (intro conjI impI)\n apply fastforce\n apply fastforce\n apply fastforce\n apply (clarsimp) \n apply force\n done\n (*>*)\n\ntext {*\nIn the postcondition of the functional specification there is a small but \nimportant subtlety. Whenever we talk about the @{term \"cont\"} part we refer to \nthe one of the pre-state.\nThe reason is that we have separated out the information that @{term \"cont\"} is not \nmodified by the procedure, to the modifies clause. So whenever we talk about unmodified\nparts in the postcondition we have to use the pre-state part, or explicitly\nstate an equality in the postcondition.\nThe reason is simple. If the postcondition would talk about @{text \"\\cont\"}\ninstead of \\mbox{@{text \"\\<^bsup>\\\\<^esup>cont\"}}, we get a new instance of @{text \"cont\"} during\nverification and the postcondition would only state something about this\nnew instance. But as the verification condition generator uses the\nmodifies clause the caller of @{term \"insert\"} instead still has the\nold @{text \"cont\"} after the call. Thats the sense of the modifies clause.\nSo the caller and the specification simply talk about two different things,\nwithout being able to relate them (unless an explicit equality is added to\nthe specification). \n*}\n\n\nsubsubsection {* Annotations *}\n\ntext {*\nAnnotations (like loop invariants)\nare mere syntactic sugar of statements that are used by the @{text \"vcg\"}. \nLogically a statement with an annotation is\nequal to the statement without it. Hence annotations can be introduced by the user\nwhile building a proof:\n\n@{thm [source] HoarePartial.annotateI}: @{thm [mode=Rule] HoarePartial.annotateI [no_vars]} \n\nWhen introducing annotations it can easily happen that these mess around with the \nnesting of sequential composition. Then after stripping the annotations the resulting statement\nis no longer syntactically identical to original one, only equivalent modulo associativity of sequential composition. The following rule also deals with this case:\n\n@{thm [source] HoarePartial.annotate_normI}: @{thm [mode=Rule] HoarePartial.annotate_normI [no_vars]} \n*}\n\ntext_raw {* \\paragraph{Loop Annotations} \n\\mbox{}\n\\medskip\n\n\\mbox{}\n*}\n\nprocedures (imports globals_heap)\n insertSort(p::ref| p::ref) \n where r::ref q::ref in\n \"\\r:==Null;;\n WHILE (\\p \\ Null) DO\n \\q :== \\p;;\n \\p :== \\p\\\\next;;\n \\r :== CALL insert(\\q,\\r)\n OD;;\n \\p:==\\r\"\n\nlemma (in insertSort_impl) insertSort_modifies: \n shows\n \"\\\\. \\\\\\<^bsub>/UNIV\\<^esub> {\\} \\p :== PROC insertSort(\\p) \n {t. t may_only_modify_globals \\ in [next]}\"\napply (hoare_rule HoarePartial.ProcRec1)\napply (vcg spec=modifies)\ndone\n\n\n\n\ntext {* Insertion sort is not implemented recursively here, but with a \nloop. Note that the while loop is not annotated with an invariant in the\nprocedure definition. The invariant only comes into play during verification.\nTherefore we annotate the loop first, before we run the @{text \"vcg\"}. \n*}\n\nlemma (in insertSort_impl) insertSort_spec:\nshows \"\\\\ Ps. \n \\\\ \\\\. List \\p \\next Ps \\ \n \\p :== PROC insertSort(\\p)\n \\\\Qs. List \\p \\next Qs \\ sorted (op \\) (map \\<^bsup>\\\\<^esup>cont Qs) \\\n set Qs = set Ps\\\"\napply (hoare_rule HoarePartial.ProcRec1) \napply (hoare_rule anno= \n \"\\r :== Null;;\n WHILE \\p \\ Null\n INV \\\\Qs Rs. List \\p \\next Qs \\ List \\r \\next Rs \\ \n set Qs \\ set Rs = {} \\\n sorted (op \\) (map \\cont Rs) \\ set Qs \\ set Rs = set Ps \\\n \\cont = \\<^bsup>\\\\<^esup>cont \\\n DO \\q :== \\p;; \\p :== \\p\\\\next;; \\r :== CALL insert(\\q,\\r) OD;;\n \\p :== \\r\" in HoarePartial.annotateI)\napply vcg\ntxt {* @{text \"\\\"} *}\n(*<*)\n \n apply fastforce\n prefer 2\n apply fastforce\n apply (clarsimp)\n apply (rule_tac x=ps in exI)\n apply (intro conjI)\n apply (rule heap_eq_ListI1)\n apply assumption\n apply clarsimp\n apply (subgoal_tac \"x\\p \\ x \\ set Rs\")\n apply auto\n done\n(*>*)\n\ntext {* The method @{text \"hoare_rule\"} automatically solves the side-condition \n that the annotated\n program is the same as the original one after stripping the annotations. *}\n\ntext_raw {* \\paragraph{Specification Annotations} \n\\mbox{}\n\\medskip\n\n\\mbox{}\n*}\n\n\n\ntext {*\nWhen verifying a larger block of program text, it might be useful to split up\nthe block and to prove the parts in isolation. This is especially useful to\nisolate loops. On the level of the Hoare calculus\nthe parts can then be combined with the consequence rule. To automate this\nprocess we introduce the derived command @{term specAnno}, which allows to introduce\na Hoare tuple (inclusive auxiliary variables) in the program text:\n\n@{thm specAnno_def [no_vars]}\n\nThe whole annotation reduces to the body @{term \"c undefined\"}. The\ntype of the assertions @{term \"P\"}, @{term \"Q\"} and @{term \"A\"} is\n@{typ \"'a \\ 's set\"} and the type of command @{term c} is @{typ \"'a \\ ('s,'p,'f) com\"}.\nAll entities formally depend on an auxiliary (logical) variable of type @{typ \"'a\"}.\nThe body @{term \"c\"} formally also depends on this variable, since a nested annotation\nor loop invariant may also depend on this logical variable. But the raw body without\nannotations does not depend on the logical variable. The logical variable is only\nused by the verification condition generator. We express this by defining the\nwhole @{term specAnno} to be equivalent with the body applied to an arbitrary\nvariable.\n\nThe Hoare rule for @{text \"specAnno\"} is mainly an instance of the consequence rule:\n\n@{thm [mode=Rule,mode=ParenStmt] HoarePartial.SpecAnno [no_vars]}\n\nThe side-condition @{term \"\\Z. c Z = c undefined\"} expresses the intention of body @{term c}\nexplained above: The raw body is independent of the auxiliary variable. This\nside-condition is solved automatically by the @{text \"vcg\"}. The concrete syntax for \nthis specification annotation is shown in the following example: \n*}\n\nlemma (in vars) \"\\\\ {\\} \n \\I :== \\M;; \n ANNO \\. \\\\. \\I = \\<^bsup>\\\\<^esup>M\\\n \\M :== \\N;; \\N :== \\I \n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>I\\\n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>M\\\"\ntxt {* With the annotation we can name an intermediate state @{term \\}. Since the\n postcondition refers to @{term \"\\\"} we have to link the information about\n the equivalence of @{text \"\\<^bsup>\\\\<^esup>I\"} and @{text \"\\<^bsup>\\\\<^esup>M\"} in the specification in order\n to be able to derive the postcondition.\n *}\napply vcg_step\napply vcg_step\ntxt {* @{subgoals [display]} *}\ntxt {* The first subgoal is the isolated Hoare tuple. The second one is the\n side-condition of the consequence rule that allows us to derive the outermost\n pre/post condition from our inserted specification.\n @{text \"\\I = \\<^bsup>\\\\<^esup>M\"} is the precondition of the specification, \n The second conjunct is a simplified version of\n @{text \"\\t. \\<^bsup>t\\<^esup>M = \\N \\ \\<^bsup>t\\<^esup>N = \\I \\ \\<^bsup>t\\<^esup>M = \\<^bsup>\\\\<^esup>N \\ \\<^bsup>t\\<^esup>N = \\<^bsup>\\\\<^esup>M\"} expressing that the\n postcondition of the specification implies the outermost postcondition.\n *}\napply vcg\ntxt {* @{subgoals [display]} *}\napply simp\napply vcg\ntxt {* @{subgoals [display]} *}\nby simp\n\n\nlemma (in vars) \n \"\\\\ {\\} \n \\I :== \\M;; \n ANNO \\. \\\\. \\I = \\<^bsup>\\\\<^esup>M\\\n \\M :== \\N;; \\N :== \\I \n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>I\\\n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>M\\\"\napply vcg\ntxt {* @{subgoals [display]} *}\nby simp_all\n\ntext {* Note that @{text \"vcg_step\"} changes the order of sequential composition, to \nallow the user to decompose sequences by repeated calls to @{text \"vcg_step\"}, whereas\n@{text \"vcg\"} preserves the order.\n\nThe above example illustrates how we can introduce a new logical state variable \n@{term \"\\\"}. You can introduce multiple variables by using a tuple:\n\n\n\n*}\n\n\nlemma (in vars) \n \"\\\\ {\\} \n \\I :== \\M;; \n ANNO (n,i,m). \\\\I = \\<^bsup>\\\\<^esup>M \\ \\N=n \\ \\I=i \\ \\M=m\\\n \\M :== \\N;; \\N :== \\I \n \\\\M = n \\ \\N = i\\\n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>M\\\"\napply vcg\ntxt {* @{subgoals [display]} *}\nby simp_all\n\ntext_raw {* \\paragraph{Lemma Annotations} \n\\mbox{}\n\\medskip\n\n\\mbox{}\n\n*}\n\ntext {*\nThe specification annotations described before split the verification\ninto several Hoare triples which result in several subgoals. If we\ninstead want to proof the Hoare triples independently as\nseparate lemmas we can use the @{text \"LEMMA\"} annotation to plug together the\nlemmas. It\ninserts the lemma in the same fashion as the specification annotation.\n*}\nlemma (in vars) foo_lemma: \n \"\\n m. \\\\ \\\\N = n \\ \\M = m\\ \\N :== \\N + 1;; \\M :== \\M + 1 \n \\\\N = n + 1 \\ \\M = m + 1\\\"\n apply vcg\n apply simp\n done\n\nlemma (in vars) \n \"\\\\ \\\\N = n \\ \\M = m\\ \n LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END;; \n \\N :== \\N + 1 \n \\\\N = n + 2 \\ \\M = m + 1\\\"\n apply vcg\n apply simp\n done\n\nlemma (in vars)\n \"\\\\ \\\\N = n \\ \\M = m\\ \n LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END;;\n LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END\n \\\\N = n + 2 \\ \\M = m + 2\\\"\n apply vcg\n apply simp\n done\n\nlemma (in vars) \n \"\\\\ \\\\N = n \\ \\M = m\\ \n \\N :== \\N + 1;; \\M :== \\M + 1;;\n \\N :== \\N + 1;; \\M :== \\M + 1\n \\\\N = n + 2 \\ \\M = m + 2\\\"\n apply (hoare_rule anno= \n \"LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END;;\n LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END\"\n in HoarePartial.annotate_normI)\n apply vcg\n apply simp\n done\n\n\nsubsubsection {* Total Correctness of Nested Loops *}\n\ntext {*\nWhen proving termination of nested loops it is sometimes necessary to express that\nthe loop variable of the outer loop is not modified in the inner loop. To express this\none has to fix the value of the outer loop variable before the inner loop and use this value\nin the invariant of the inner loop. This can be achieved by surrounding the inner while loop\nwith an @{text \"ANNO\"} specification as explained previously. However, this\nleads to repeating the invariant of the inner loop three times: in the invariant itself and\nin the the pre- and postcondition of the @{text \"ANNO\"} specification. Moreover one has\nto deal with the additional subgoal introduced by @{text \"ANNO\"} that expresses how\nthe pre- and postcondition is connected to the invariant. To avoid this extra specification\nand verification work, we introduce an variant of the annotated while-loop, where one can\nintroduce logical variables by @{text \"FIX\"}. As for the @{text \"ANNO\"} specification\nmultiple logical variables can be introduced via a tuple (@{text \"FIX (a,b,c).\"}).\n\nThe Hoare logic rule for the augmented while-loop is a mixture of the invariant rule for\nloops and the consequence rule for @{text \"ANNO\"}:\n\n\\begin{center}\n@{thm [mode=Rule,mode=ParenStmt] HoareTotal.WhileAnnoFix' [no_vars]}\n\\end{center}\n\nThe first premise expresses that the precondition implies the invariant and that\nthe invariant together with the negated loop condition implies the postcondition. Since\nboth implications may depend on the choice of the auxiliary variable @{term \"Z\"} these two\nimplications are expressed in a single premise and not in two of them as for the usual while\nrule. The second premise is the preservation of the invariant by the loop body. And the third\npremise is the side-condition that the computational part of the body does not depend on\nthe auxiliary variable. Finally the last premise is the well-foundedness of the variant.\nThe last two premises are usually discharged automatically by the verification condition\ngenerator. Hence usually two subgoals remain for the user, stemming from the first two\npremises.\n\nThe following example illustrates the usage of this rule. The outer loop increments the\nloop variable @{term \"M\"} while the inner loop increments @{term \"N\"}. To discharge the\nproof obligation for the termination of the outer loop, we need to know that the inner loop\ndoes not mess around with @{term \"M\"}. This is expressed by introducing the logical variable\n@{term \"m\"} and fixing the value of @{term \"M\"} to it.\n*}\n\n\nlemma (in vars) \n \"\\\\\\<^sub>t \\\\M=0 \\ \\N=0\\ \n WHILE (\\M < i) \n INV \\\\M \\ i \\ (\\M \\ 0 \\ \\N = j) \\ \\N \\ j\\\n VAR MEASURE (i - \\M)\n DO\n \\N :== 0;;\n WHILE (\\N < j)\n FIX m. \n INV \\\\M=m \\ \\N \\ j\\\n VAR MEASURE (j - \\N)\n DO\n \\N :== \\N + 1\n OD;;\n \\M :== \\M + 1\n OD\n \\\\M=i \\ (\\M\\0 \\ \\N=j)\\\"\napply vcg\ntxt {* @{subgoals [display]} \n\nThe first subgoal is from the precondition to the invariant of the outer loop.\nThe fourth subgoal is from the invariant together with the negated loop condition \nof the outer loop to the postcondition. The subgoals two and three are from the body\nof the outer while loop which is mainly the inner while loop. Because we introduce the\nlogical variable @{term \"m\"} here, the while Rule described above is used instead of the\nordinary while Rule. That is why we end up with two subgoals for the inner loop. Subgoal\ntwo is from the invariant and the loop condition of the outer loop to the invariant\nof the inner loop. And at the same time from the invariant of the inner loop to the\ninvariant of the outer loop (together with the proof obligation that the measure of the\nouter loop decreases). The universal quantified variables @{term \"Ma\"} and @{term \"N\"} are\nthe ``fresh'' state variables introduced for the final state of the inner loop. \nThe equality @{term \"Ma=M\"} is the result of the equality @{text \"\\M=m\"} in the inner \ninvariant. Subgoal three is the preservation of the invariant by the\ninner loop body (together with the proof obligation that the measure of\nthe inner loop decreases).\n*}\n(*<*)\napply (simp)\napply (simp,arith)\napply (simp,arith)\ndone\n(*>*)\n\nsubsection {* Functional Correctness, Termination and Runtime Faults *}\n\ntext {*\nTotal correctness of a program with guards conceptually leads to three verification \ntasks.\n\\begin{itemize}\n\\item functional (partial) correctness \n\\item absence of runtime faults\n\\item termination\n\\end{itemize}\n\nIn case of a modifies specification the functional correctness part\ncan be solved automatically. But the absence of runtime faults and\ntermination may be non trivial. Fortunately the modifies clause is\nusually just a helpful companion of another specification that\nexpresses the ``real'' functional behaviour. Therefor the task to\nprove the absence of runtime faults and termination can be dealt with\nduring the proof of this functional specification. In most cases the\nabsence of runtime faults and termination heavily build on the\nfunctional specification parts. So after all there is no reason why\nwe should again prove the absence of runtime faults and termination\nfor the modifies clause. Therefor it suffices to have partial\ncorrectness of the modifies clause for a program were all guards are\nignored. This leads to the following pattern: *}\n\n\n\nprocedures foo (N::nat|M::nat) \n \"\\M :== \\M \n (* think of body with guards instead *)\"\n\n foo_spec: \"\\\\. \\\\\\<^sub>t (P \\) \\M :== PROC foo(\\N) (Q \\)\"\n foo_modifies: \"\\\\. \\\\\\<^bsub>/UNIV\\<^esub> {\\} \\M :== PROC foo(\\N) \n {t. t may_only_modify_globals \\ in []}\"\n\ntext {*\nThe verification condition generator can solve those modifies clauses automatically\nand can use them to simplify calls to @{text foo} even in the context of total\ncorrectness.\n*}\n\nsubsection {* Procedures and Locales \\label{sec:Locales}*}\n\n\n\ntext {*\nVerification of a larger program is organised on the granularity of procedures. \nWe proof the procedures in a bottom up fashion. Of course you can also always use Isabelle's\ndummy proof @{text \"sorry\"} to prototype your formalisation. So you can write the\ntheory in a bottom up fashion but actually prove the lemmas in any other order.\n \nHere are some explanations of handling of locales. In the examples below, consider\n@{text proc\\<^sub>1} and @{text proc\\<^sub>2} to be ``leaf'' procedures, which do not call any \nother procedure.\nProcedure @{text \"proc\"} directly calls @{text proc\\<^sub>1} and @{text proc\\<^sub>2}.\n\n\\isacommand{lemma} (\\isacommand{in} @{text \"proc\\<^sub>1_impl\"}) @{text \"proc\\<^sub>1_modifies\"}:\\\\\n\\isacommand{shows} @{text \"\\\"} \n\nAfter the proof of @{text \"proc\\<^sub>1_modifies\"}, the \\isacommand{in} directive \nstores the lemma in the\nlocale @{text \"proc\\<^sub>1_impl\"}. When we later on include @{text \"proc\\<^sub>1_impl\"} or prove \nanother theorem in locale @{text \"proc\\<^sub>1_impl\"} the lemma @{text \"proc\\<^sub>1_modifies\"}\nwill already be available as fact.\n\n\\isacommand{lemma} (\\isacommand{in} @{text \"proc\\<^sub>1_impl\"}) @{text \"proc\\<^sub>1_spec\"}:\\\\\n\\isacommand{shows} @{text \"\\\"} \n\n\\isacommand{lemma} (\\isacommand{in} @{text \"proc\\<^sub>2_impl\"}) @{text \"proc\\<^sub>2_modifies\"}:\\\\\n\\isacommand{shows} @{text \"\\\"} \n\n\\isacommand{lemma} (\\isacommand{in} @{text \"proc\\<^sub>2_impl\"}) @{text \"proc\\<^sub>2_spec\"}:\\\\\n\\isacommand{shows} @{text \"\\\"} \n\n\n\\isacommand{lemma} (\\isacommand{in} @{text \"proc_impl\"}) @{text \"proc_modifies\"}:\\\\\n\\isacommand{shows} @{text \"\\\"} \n\nNote that we do not explicitly include anything about @{text \"proc\\<^sub>1\"} or \n@{text \"proc\\<^sub>2\"} here. This is handled automatically. When defining\nan @{text impl}-locale it imports all @{text impl}-locales of procedures that are\ncalled in the body. In case of @{text \"proc_impl\"} this means, that @{text \"proc\\<^sub>1_impl\"}\nand @{text \"proc\\<^sub>2_impl\"} are imported. This has the neat effect that all theorems that\nare proven in @{text \"proc\\<^sub>1_impl\"} and @{text \"proc\\<^sub>2_impl\"} are also present\nin @{text \"proc_impl\"}.\n\n\\isacommand{lemma} (\\isacommand{in} @{text \"proc_impl\"}) @{text \"proc_spec\"}:\\\\\n\\isacommand{shows} @{text \"\\\"} \n\nAs we have seen in this example you only have to prove a procedure in its own\n@{text \"impl\"} locale. You do not have to include any other locale. \n*}\n\nsubsection {* Records \\label{sec:records}*}\n\ntext {*\nBefore @{term \"statespaces\"} where introduced the state was represented as a @{term \"record\"}.\nThis is still supported. Compared to the flexibility of statespaces there are some drawbacks\nin particular with respect to modularity. Even names of local variables and \nparameters are globally visible and records can only be extended in a linear fashion, whereas\nstatespaces also allow multiple inheritance. The usage of records is quite similar to the usage of statespaces. \nWe repeat the example of an append function for heap lists.\nFirst we define the global components. \nAgain the appearance of the prefix `globals' is mandatory. This is the way the syntax layer distinguishes local and global variables. \n*}\nrecord globals_list = \n next_' :: \"ref \\ ref\"\n cont_' :: \"ref \\ nat\"\n\n\ntext {* The local variables also have to be defined as a record before the actual definition\nof the procedure. The parent record @{text \"state\"} defines a generic @{term \"globals\"}\nfield as a place-holder for the record of global components. In contrast to the\nstatespace approach there is no single @{term \"locals\"} slot. The local components are\njust added to the record.\n*}\nrecord 'g list_vars = \"'g state\" +\n p_' :: \"ref\"\n q_' :: \"ref\"\n r_' :: \"ref\"\n root_' :: \"ref\"\n tmp_' :: \"ref\"\n\ntext {* Since the parameters and local variables are determined by the record, there are\nno type annotations or definitions of local variables while defining a procedure.\n*}\n\nprocedures\n append'(p,q|p) = \n \"IF \\p=Null THEN \\p :== \\q \n ELSE \\p \\\\next:== CALL append'(\\p\\\\next,\\q) FI\"\n\ntext {* As in the statespace approach, a locale called @{text \"append'_impl\"} is created.\nNote that we do not give any explicit information which global or local state-record to use.\nSince the records are already defined we rely on Isabelle's type inference. \nDealing with the locale is analogous to the case with statespaces.\n*}\n\nlemma (in append'_impl) append'_modifies: \n shows\n \"\\\\. \\\\ {\\} \\p :== PROC append'(\\p,\\q)\n {t. t may_only_modify_globals \\ in [next]}\"\n apply (hoare_rule HoarePartial.ProcRec1)\n apply (vcg spec=modifies)\n done\n\nlemma (in append'_impl) append'_spec:\n shows \"\\\\ Ps Qs. \\\\ \n \\\\. List \\p \\next Ps \\ List \\q \\next Qs \\ set Ps \\ set Qs = {}\\\n \\p :== PROC append'(\\p,\\q) \n \\List \\p \\next (Ps@Qs) \\ (\\x. x\\set Ps \\ \\next x = \\<^bsup>\\\\<^esup>next x)\\\"\n apply (hoare_rule HoarePartial.ProcRec1)\n apply vcg\n apply fastforce\n done\n\n\ntext {*\nHowever, in some corner cases the inferred state type in a procedure definition \ncan be too general which raises problems when attempting to proof a suitable \nspecifications in the locale.\nConsider for example the simple procedure body @{term \"\\p :== NULL\"} for a procedure\n@{text \"init\"}. \n*}\n\nprocedures init (|p) = \n \"\\p:== Null\"\n\n\ntext {*\nHere Isabelle can only\ninfer the local variable record. Since no reference to any global variable is\nmade the type fixed for the global variables (in the locale @{text \"init'_impl\"}) is a \ntype variable say @{typ \"'g\"} and not a @{term \"globals_list\"} record. Any specification\nmentioning @{term \"next\"} or @{term \"cont\"} restricts the state type and cannot be\nadded to the locale @{text \"init_impl\"}. Hence we have to restrict the body\n@{term \"\\p :== NULL\"} in the first place by adding a typing annotation:\n*}\n\nprocedures init' (|p) = \n \"\\p:== Null::(('a globals_list_scheme, 'b) list_vars_scheme, char list, 'c) com\"\n\n\nsubsubsection {* Extending State Spaces *}\ntext {*\nThe records in Isabelle are\nextensible \\cite{Nipkow-02-hol,NaraschewskiW-TPHOLs98}. In principle this can be exploited \nduring verification. The state space can be extended while we we add procedures.\nBut there is one major drawback:\n\\begin{itemize}\n \\item records can only be extended in a linear fashion (there is no multiple inheritance)\n\\end{itemize}\n\nYou can extend both the main state record as well as the record for the global variables.\n*}\n\nsubsubsection {* Mapping Variables to Record Fields *}\n\ntext {*\nGenerally the state space (global and local variables) is flat and all components\nare accessible from everywhere. Locality or globality of variables is achieved by\nthe proper @{text \"init\"} and @{text \"return\"}/@{text \"result\"} functions in procedure\ncalls. What is the best way to map programming language variables to the state records?\nOne way is to disambiguate all names, by using the procedure names as prefix or the\nstructure names for heap components. This leads to long names and lots of \nrecord components. But for local variables this is not necessary, since\nvariable @{term i} of procedure @{term A} and variable @{term \"i\"} of procedure @{term B}\ncan be mapped to the same record component, without any harm, provided they have the\nsame logical type. Therefor for local variables it is preferable to map them per type. You\nonly have to distinguish a variable with the same name if they have a different type.\nNote that all pointers just have logical type @{text \"ref\"}. So you even do not\nhave to distinguish between a pointer @{text p} to a integer and a pointer @{text p} to\na list.\nFor global components (global variables and heap structures) you have to disambiguate the\nname. But hopefully the field names of structures have different names anyway.\nAlso note that there is no notion of hiding of a global component by a local one in\nthe logic. You have to disambiguate global and local names!\nAs the names of the components show up in the specifications and the\nproof obligations, names are even more important as for programming. Try to\nfind meaningful and short names, to avoid cluttering up your reasoning.\n*}\n\n(*<*)\ntext {*\nin locales, includes, spec or impl?\nNames: per type not per procedure\\\ndowngrading total to partial\\\n*}\n(*>*)\ntext {**}\n(*<*)\nend\n(*>*)\n", "meta": {"author": "CompSoftVer", "repo": "CSim2", "sha": "b09a4d77ea089168b1805db5204ac151df2b9eff", "save_path": "github-repos/isabelle/CompSoftVer-CSim2", "path": "github-repos/isabelle/CompSoftVer-CSim2/CSim2-b09a4d77ea089168b1805db5204ac151df2b9eff/ConCSimpl/EmbSimpl/UserGuide.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.17781086294266127, "lm_q1q2_score": 0.0847410390165446}} {"text": "(*\n * Copyright 2019, Data61\n * Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n * ABN 41 687 119 230.\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * @TAG(DATA61_BSD)\n *)\n\ntheory FP_Eval_Tests\nimports\n Lib.FP_Eval\n \"HOL-Library.Sublist\"\nbegin\n\nsection \\Controlling evaluation\\\n\nsubsection \\Skeletons\\\n\ntext \\\n A \"skeleton\" is a subterm of a given term. For example,\n \"map (\\x. x + 1) [1, 2, 3]\"\n could have the following skeleton (among others):\n \"map (\\x. x + _) _\"\n\n The \"_\" stand for schematic variables with arbitrary names,\n or dummy patterns (which are implemented as unnamed schematics).\n\n FP_Eval uses skeletons internally to keep track of which parts of\n a term it has already evaluated. In other words, schematic variables\n indicate already-normalised subterms.\n\n There are two useful predefined skeletons:\n\\\nML_val \\ FP_Eval.skel0 \\\ntext \\\n which is a special directive to evaluate all subterms; and\n\\\nML_val \\ FP_Eval.skel_skip \\\ntext \\\n which tells FP_Eval to skip evaluation.\n\\\n\ntext \\\n If we use the full FP_Eval interface, we can input a skeleton manually\n and get the final skeleton as output.\n\n It's useful to input a nontrivial skeleton for the following reasons:\n \\ if most of the term is known to be normalised, this can\n save unnecessary computation.\n \\ if a tool runs FP_Eval on behalf of an end user, it may\n want to avoid evaluating function calls in the user's input terms.\n Alternatively, use explicit quotation terms\n (see \"Preventing evaluation\", below) if finer control is needed.\n\n The partial skeleton should match the structure of the input term.\n If there is any mismatch, FP_Eval tries to be conservative and\n evaluates the whole subterm (as if \"skel0\" had been given).\n However, this should not be relied upon.\n (FIXME: maybe stricter check in eval')\n\n By default, FP_Eval attempts full evaluation of the input, so it\n usually returns \"skel_skip\".\n\n However, evaluation is not complete when:\n \\ the input skeleton skips some subterms;\n \\ FP_Eval doesn't descend into un-applied lambdas;\n \\ evaluation delayed due to cong rules.\n In these cases, FP_Eval would return a partial skeleton.\n\\\n\n(* TODO: add examples *)\n\nsubsection \\Congruence rules\\\n\ntext \\\n Use FP_Eval.add_cong or the second argument of FP_Eval.make_rules.\n These accept weak congruence rules, e.g.:\n\\\nthm if_weak_cong option.case_cong_weak\n\ntext \\\n Note that @{thm let_weak_cong} contains a hidden eta expansion, which FP_Eval\n currently doesn't understand. Use our alternative:\n\\\nthm FP_Eval.let_weak_cong'\n\nML_val \\\n @{assert} (not (Thm.eq_thm_prop (@{thm let_weak_cong}, @{thm FP_Eval.let_weak_cong'})));\n\\\n\ntext \\\n Example: avoid evaluating both branches of an @{const If}\n\\\n\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs)\n val input = (@{cterm \"subseq [0::nat, 2, 4] [0, 1, 2, 3, 4, 5]\"}, Bound 0);\nin\n (* No cong rule -- blowup *)\n val r1 = eval @{thms list_emb_code} @{thms} input\n |> fst |> fst;\n (* if_weak_cong prevents early evaluation of branches *)\n val r2 = eval @{thms list_emb_code} @{thms if_weak_cong} input\n |> fst |> fst;\n\n (* Compare performance counters: *)\n val eqns = @{thms list_emb_code rel_simps simp_thms if_True if_False};\n val p1 = eval eqns @{thms} input |> snd;\n val p2 = eval eqns @{thms if_weak_cong} input |> snd;\nend\n\\\n\nsubsection \\Preventing evaluation\\\n\ntext \\\n Sometimes it is useful to prevent evaluation of any arguments.\n This can be done by adding a cong rule with no premises:\n\\\ncontext FP_Eval begin\ndefinition \"quote x \\ x\"\nlemma quote_cong:\n \"quote x = quote x\"\n by simp\nlemma quote:\n \"x \\ quote x\"\n by (simp add: quote_def)\nend\n\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\nin\n (* By default, fp_eval evaluates all subterms *)\n val r1 = eval @{thms fun_upd_def} @{thms}\n (@{cterm \"FP_Eval.quote (fun_upd f a b) c\"}, Bound 0);\n (* Use quote_cong to hold all quoted subterms.\n Note how the resulting skeleton indicates unevaluated subterms. *)\n val r2 = eval @{thms fun_upd_def} @{thms FP_Eval.quote_cong}\n (@{cterm \"FP_Eval.quote (fun_upd f a b) c\"}, Bound 0);\n (* Now remove the quote_cong hold. fp_eval continues evaluation\n according to the previous skeleton. *)\n val r3 = fst r2 |> apfst Thm.rhs_of\n |> eval @{thms fun_upd_def} @{thms};\nend;\n\\\n\n\nsection \\Tests\\\n\nsubsection \\Basic tests\\\n\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"2 + 2 :: nat\"}, Bound 0);\nin\n val ((result, Var _), counters) = eval @{thms arith_simps} @{thms} input;\n val _ = @{assert} (Thm.prop_of result aconv @{term \"(2 + 2 :: nat) \\ 4\"});\nend;\n\\\n\ntext \\fp_eval does not rewrite under lambda abstractions\\\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"(\\x. x + (2 + 2::nat))\"}, Bound 0);\nin\n val ((result, skel), _) = eval @{thms arith_simps} @{thms} input;\n val _ = @{assert} (not (is_Var skel) andalso Thm.is_reflexive result);\nend\n\\\n\n\nsubsection \\Cong rules\\\n\ntext \\Test for @{thm if_weak_cong}\\\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"subseq [2::int,3,5,7,11] [0,1,2,3,4,5,6,7,8,9,10,11,12,13]\"}, Bound 0);\nin\n val r1 = eval @{thms list_emb_code rel_simps refl if_True if_False} @{thms} input;\n val r2 = eval @{thms list_emb_code rel_simps refl if_True if_False} @{thms if_weak_cong} input;\n\n val _ = @{assert} (Thm.term_of (Thm.rhs_of (fst (fst r1))) = @{term True});\n val _ = @{assert} (Thm.term_of (Thm.rhs_of (fst (fst r2))) = @{term True});\n\n (* Compare performance counters: *)\n val (SOME r1_rewrs, SOME r2_rewrs) =\n apply2 (snd #> Symtab.make #> (fn t => Symtab.lookup t \"rewrites\")) (r1, r2);\n val _ = @{assert} (r1_rewrs > 10000);\n val _ = @{assert} (r2_rewrs < 100);\nend\n\\\n\n\nsubsection \\Advanced usage\\\n\nsubsubsection \\Triggering breakpoints\\\nML_val \\\nlocal\n fun break_4 t = Thm.term_of t = @{term \"4 :: nat\"};\n fun eval eqns congs break =\n FP_Eval.eval' @{context} (K (K ())) break false (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"map Suc [2 + 2 :: nat, 2 + 3, 2 + 4, 2 + 5, 2 + 6]\"}, Bound 0);\nin\n (* Normal evaluation *)\n val ((result, Var _), _) = eval @{thms list.map arith_simps} @{thms} (K false) input;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result) aconv\n @{term \"[Suc 4, Suc 5, Suc 6, Suc 7, Suc 8]\"});\n\n (* Evaluation stops after \"4\" is encountered *)\n val ((result2, skel), _) = eval @{thms list.map arith_simps} @{thms} break_4 input;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result2) aconv\n @{term \"map Suc [4::nat, 5, 2 + 4, 2 + 5, 2 + 6]\"});\n (* Skeleton indicates evaluation is unfinished *)\n val _ = @{assert} (not (is_Var skel));\nend;\n\\\n\nsubsubsection \\Rule set manipulation\\\nML_val \\\nlocal\n val rules0 = FP_Eval.empty_rules;\n val rules1 = FP_Eval.make_rules @{thms simp_thms arith_simps} @{thms if_weak_cong};\n val rules2 = FP_Eval.make_rules @{thms simp_thms if_False if_True fun_upd_apply}\n @{thms if_weak_cong option.case_cong_weak};\nin\n (* dest_rules returns rules *)\n val _ = @{assert} (apply2 length (FP_Eval.dest_rules rules1) <> (0, 0));\n (* test round-trip conversion *)\n val _ = @{assert} (let val (thms, congs) = FP_Eval.dest_rules rules2;\n val (thms', congs') = FP_Eval.dest_rules (FP_Eval.make_rules thms congs);\n in forall Thm.eq_thm_prop (thms ~~ thms')\n andalso forall Thm.eq_thm_prop (congs ~~ congs') end);\n (* test that merging succeeds and actually merges rules *)\n fun test_merge r1 r2 =\n let val (r1_eqns, r1_congs) = FP_Eval.dest_rules r1;\n val (r2_eqns, r2_congs) = FP_Eval.dest_rules r2;\n val (r12_eqns, r12_congs) = FP_Eval.dest_rules (FP_Eval.merge_rules (r1, r2));\n in eq_set Thm.eq_thm_prop (r12_eqns, union Thm.eq_thm_prop r1_eqns r2_eqns)\n andalso eq_set Thm.eq_thm_prop (r12_congs, union Thm.eq_thm_prop r1_congs r2_congs)\n end;\n\n val _ = @{assert} (test_merge rules0 rules1);\n val _ = @{assert} (test_merge rules0 rules2);\n val _ = @{assert} (test_merge rules1 rules2);\n\n (* test that rules with conflicting arity are not allowed *)\n val conflict_arity = FP_Eval.make_rules @{thms fun_upd_def} @{thms};\n val _ = @{assert} (is_none (try FP_Eval.merge_rules (rules2, conflict_arity)));\n (* test that installing different cong rules is not allowed *)\n val conflict_cong = FP_Eval.make_rules @{thms} @{thms if_weak_cong[OF refl]};\n val _ = @{assert} (is_none (try FP_Eval.merge_rules (rules2, conflict_cong)));\nend\n\\\n\nsubsubsection \\Ordering of rules\\\ntext \\\n In the current implementation, equations are picked based on the default\n Net ordering. This should be improved in the future.\n\\\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"list_all (\\x::nat. x \\ x) [100000, 314159, 2718281845]\"}, Bound 0);\n val basic_eqns = @{thms list_all_simps rel_simps simp_thms};\n fun get_counter cs x = the (Symtab.lookup (Symtab.make cs) x);\nin\n (* evaluate \\ slowly *)\n val ((r1, _), counters1) = eval basic_eqns @{thms} input;\n (* shortcut for \\ *)\n val ((r2, _), counters2) = eval (@{thms order.refl} @ basic_eqns) @{thms} input;\n val ((r3, _), counters3) = eval (basic_eqns @ @{thms order.refl}) @{thms} input;\n\n (* Bug: shortcut is never used -- no effect on runtime *)\n val _ = @{assert} (length (distinct op= [counters1, counters2, counters3]) = 1);\n\n (* desired outcome *)\n val ((r4, _), counters4) = eval @{thms list_all_simps simp_thms order.refl} @{thms} input;\n val _ = @{assert} (get_counter counters4 \"rewrites\" < get_counter counters1 \"rewrites\");\nend\n\\\n\n\nsubsection \\Miscellaneous and regression tests\\\n\ntext \\Test for partial arity and arg_conv\\\nML_val \\\nlocal\n fun eval eqns congs =\n FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"(if 2 + 2 = 4 then Suc else id) x\"}, FP_Eval.skel0);\n (* Need to build these manually, as @{cterm} itself does beta-eta normalisation *)\n val input_abs1 = (fold (fn x => fn f => Thm.apply f x)\n [@{cterm \"f::nat\\nat\"}, @{cterm \"4::nat\"}]\n @{cterm \"\\f. fun_upd (f::nat\\nat) (2+2) y\"},\n FP_Eval.skel0);\n val input_abs2 = (fold (fn x => fn f => Thm.apply f x)\n [@{cterm \"f::nat\\nat\"}, @{cterm \"4::nat\"}]\n @{cterm \"\\f x z. z + fun_upd (f::nat\\nat) (2+2) y x\"},\n FP_Eval.skel0);\n val Abs (_, _, Abs (_, _, Abs _)) $ _ $ _ = Thm.term_of (fst input_abs2); (* check *)\nin\n (* Head (= If) is rewritten *)\n val ((result, Var _), _) = eval @{thms arith_simps refl if_True} @{thms} input;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result) = @{term \"Suc x\"});\n\n (* Head is not rewritten *)\n val ((result2, Var _ $ _), _) = eval @{thms arith_simps refl if_False} @{thms} input;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result2) = @{term \"(if True then Suc else id) x\"});\n\n (* Head is Abs *)\n val ((result3, Var _), _) = eval @{thms arith_simps refl fun_upd_apply if_True} @{thms} input_abs1;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result3) = @{term \"y::nat\"});\n\n (* Partially applied Abs *)\n val ((result4, Abs _), _) = eval @{thms arith_simps refl fun_upd_apply if_True} @{thms} input_abs2;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result4) = @{term \"\\z. z + fun_upd (f::nat\\nat) (2+2) y 4\"});\nend;\n\\\n\ntext \\Check that skel_skip is not returned for intermediate Abs\\\nML_val \\\nlocal\n fun eval eqns congs = FP_Eval.eval @{context} (FP_Eval.make_rules eqns congs);\n val input = (@{cterm \"map (\\((x, y), z). ((id x, id y), id z)) [((a::'a, b::'b), c::'c)]\"}, Bound 0);\nin\n val ((result, Var _), counters) = eval @{thms list.map prod.case arith_simps} @{thms} input;\n val _ = @{assert} (Thm.term_of (Thm.rhs_of result) = @{term \"[((id a::'a, id b::'b), id c::'c)]\"});\nend;\n\\\n\ntext \\Test conversion of some basic non-equation rules to equations\\\nML_val \\\nlet val thms = @{thms simp_thms rel_simps arith_simps};\nin @{assert} (length (map_filter FP_Eval.maybe_convert_eqn thms) = length thms) end\n\\\n\nend", "meta": {"author": "CompSoftVer", "repo": "CSim2", "sha": "b09a4d77ea089168b1805db5204ac151df2b9eff", "save_path": "github-repos/isabelle/CompSoftVer-CSim2", "path": "github-repos/isabelle/CompSoftVer-CSim2/CSim2-b09a4d77ea089168b1805db5204ac151df2b9eff/lib/FP_Eval_Tests.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.19436781101874467, "lm_q1q2_score": 0.08360679856014719}} {"text": "(*\n * Copyright 2014, NICTA\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * @TAG(NICTA_BSD)\n *)\n\ntheory WhileLoopRules\nimports \"wp/NonDetMonadVCG\"\nbegin\n\nsection \"Well-ordered measures\"\n\n(* A version of \"measure\" that takes any wellorder, instead of\n * being fixed to \"nat\". *)\ndefinition measure' :: \"('a \\ 'b::wellorder) => ('a \\ 'a) set\"\nwhere \"measure' = (\\f. {(a, b). f a < f b})\"\n\nlemma in_measure'[simp, code_unfold]:\n \"((x,y) : measure' f) = (f x < f y)\"\n by (simp add:measure'_def)\n\nlemma wf_measure' [iff]: \"wf (measure' f)\"\n apply (clarsimp simp: measure'_def)\n apply (insert wf_inv_image [OF wellorder_class.wf, where f=f])\n apply (clarsimp simp: inv_image_def)\n done\n\nlemma wf_wellorder_measure: \"wf {(a, b). (M a :: 'a :: wellorder) < M b}\"\n apply (subgoal_tac \"wf (inv_image ({(a, b). a < b}) M)\")\n apply (clarsimp simp: inv_image_def)\n apply (rule wf_inv_image)\n apply (rule wellorder_class.wf)\n done\n\n\nsection \"whileLoop lemmas\"\n\ntext {*\n The following @{const whileLoop} definitions with additional\n invariant/variant annotations allow the user to annotate\n @{const whileLoop} terms with information that can be used\n by automated tools.\n*}\ndefinition\n \"whileLoop_inv (C :: 'a \\ 'b \\ bool) B x (I :: 'a \\ 'b \\ bool) (R :: (('a \\ 'b) \\ ('a \\ 'b)) set) \\ whileLoop C B x\"\n\ndefinition\n \"whileLoopE_inv (C :: 'a \\ 'b \\ bool) B x (I :: 'a \\ 'b \\ bool) (R :: (('a \\ 'b) \\ ('a \\ 'b)) set) \\ whileLoopE C B x\"\n\nlemma whileLoop_add_inv: \"whileLoop B C = (\\x. whileLoop_inv B C x I (measure' M))\"\n by (clarsimp simp: whileLoop_inv_def)\n\nlemma whileLoopE_add_inv: \"whileLoopE B C = (\\x. whileLoopE_inv B C x I (measure' M))\"\n by (clarsimp simp: whileLoopE_inv_def)\n\nsubsection \"Simple base rules\"\n\nlemma whileLoop_terminates_unfold:\n \"\\ whileLoop_terminates C B r s; (r', s') \\ fst (B r s); C r s \\\n \\ whileLoop_terminates C B r' s'\"\n apply (erule whileLoop_terminates.cases)\n apply simp\n apply force\n done\n\nlemma snd_whileLoop_first_step: \"\\ \\ snd (whileLoop C B r s); C r s \\ \\ \\ snd (B r s)\"\n apply (subst (asm) whileLoop_unroll)\n apply (clarsimp simp: bind_def condition_def)\n done\n\nlemma snd_whileLoopE_first_step: \"\\ \\ snd (whileLoopE C B r s); C r s \\ \\ \\ snd (B r s)\"\n apply (subgoal_tac \"\\ \\ snd (whileLoopE C B r s); C r s \\ \\ \\ snd ((lift B (Inr r)) s)\")\n apply (clarsimp simp: lift_def)\n apply (unfold whileLoopE_def)\n apply (erule snd_whileLoop_first_step)\n apply clarsimp\n done\n\nlemma snd_whileLoop_unfold:\n \"\\ \\ snd (whileLoop C B r s); C r s; (r', s') \\ fst (B r s) \\ \\ \\ snd (whileLoop C B r' s')\"\n apply (clarsimp simp: whileLoop_def)\n apply (auto simp: elim: whileLoop_results.cases whileLoop_terminates.cases\n intro: whileLoop_results.intros whileLoop_terminates.intros)\n done\n\nlemma snd_whileLoopE_unfold:\n \"\\ \\ snd (whileLoopE C B r s); (Inr r', s') \\ fst (B r s); C r s \\ \\ \\ snd (whileLoopE C B r' s')\"\n apply (clarsimp simp: whileLoopE_def)\n apply (drule snd_whileLoop_unfold)\n apply clarsimp\n apply (clarsimp simp: lift_def)\n apply assumption\n apply (clarsimp simp: lift_def)\n done\n\nlemma whileLoop_results_cong [cong]:\n assumes C: \"\\r s. C r s = C' r s\"\n and B:\"\\(r :: 'r) (s :: 's). C' r s \\ B r s = B' r s\"\n shows \"whileLoop_results C B = whileLoop_results C' B'\"\nproof -\n {\n fix x y C B C' B'\n have \"\\ (x, y) \\ whileLoop_results C B;\n \\(r :: 'r) (s :: 's). C r s = C' r s;\n \\r s. C' r s \\ B r s = B' r s \\\n \\ (x, y) \\ whileLoop_results C' B'\"\n apply (induct rule: whileLoop_results.induct)\n apply clarsimp\n apply clarsimp\n apply (rule whileLoop_results.intros, auto)[1]\n apply clarsimp\n apply (rule whileLoop_results.intros, auto)[1]\n done\n }\n\n thus ?thesis\n apply -\n apply (rule set_eqI, rule iffI)\n apply (clarsimp split: prod.splits)\n apply (clarsimp simp: C B split: prod.splits)\n apply (clarsimp split: prod.splits)\n apply (clarsimp simp: C [symmetric] B [symmetric] split: prod.splits)\n done\nqed\n\nlemma whileLoop_terminates_cong [cong]:\n assumes r: \"r = r'\"\n and s: \"s = s'\"\n and C: \"\\r s. C r s = C' r s\"\n and B: \"\\r s. C' r s \\ B r s = B' r s\"\n shows \"whileLoop_terminates C B r s = whileLoop_terminates C' B' r' s'\"\nproof (rule iffI)\n assume T: \"whileLoop_terminates C B r s\"\n show \"whileLoop_terminates C' B' r' s'\"\n apply (insert T r s)\n apply (induct arbitrary: r' s' rule: whileLoop_terminates.induct)\n apply (clarsimp simp: C)\n apply (erule whileLoop_terminates.intros)\n apply (clarsimp simp: C B split: prod.splits)\n apply (rule whileLoop_terminates.intros, assumption)\n apply (clarsimp simp: C B split: prod.splits)\n done\nnext\n assume T: \"whileLoop_terminates C' B' r' s'\"\n show \"whileLoop_terminates C B r s\"\n apply (insert T r s)\n apply (induct arbitrary: r s rule: whileLoop_terminates.induct)\n apply (rule whileLoop_terminates.intros)\n apply (clarsimp simp: C)\n apply (rule whileLoop_terminates.intros, fastforce simp: C)\n apply (clarsimp simp: C B split: prod.splits)\n done\nqed\n\nlemma whileLoop_cong [cong]:\n \"\\ \\r s. C r s = C' r s; \\r s. C r s \\ B r s = B' r s \\ \\ whileLoop C B = whileLoop C' B'\"\n apply (rule ext, clarsimp simp: whileLoop_def)\n done\n\nlemma whileLoopE_cong [cong]:\n \"\\ \\r s. C r s = C' r s ; \\r s. C r s \\ B r s = B' r s \\\n \\ whileLoopE C B = whileLoopE C' B'\"\n apply (clarsimp simp: whileLoopE_def)\n apply (rule whileLoop_cong [THEN arg_cong])\n apply (clarsimp split: sum.splits)\n apply (clarsimp split: sum.splits)\n apply (clarsimp simp: lift_def throwError_def split: sum.splits)\n done\n\nlemma whileLoop_terminates_wf:\n \"wf {(x, y). C (fst y) (snd y) \\ x \\ fst (B (fst y) (snd y)) \\ whileLoop_terminates C B (fst y) (snd y)}\"\n apply (rule wfI [where A=\"UNIV\" and B=\"{(r, s). whileLoop_terminates C B r s}\"])\n apply clarsimp\n apply clarsimp\n apply (erule whileLoop_terminates.induct)\n apply blast\n apply blast\n done\n\nsubsection \"Basic induction helper lemmas\"\n\nlemma whileLoop_results_induct_lemma1:\n \"\\ (a, b) \\ whileLoop_results C B; b = Some (x, y) \\ \\ \\ C x y\"\n apply (induct rule: whileLoop_results.induct, auto)\n done\n\nlemma whileLoop_results_induct_lemma1':\n \"\\ (a, b) \\ whileLoop_results C B; a \\ b \\ \\ \\x. a = Some x \\ C (fst x) (snd x)\"\n apply (induct rule: whileLoop_results.induct, auto)\n done\n\nlemma whileLoop_results_induct_lemma2 [consumes 1]:\n \"\\ (a, b) \\ whileLoop_results C B;\n a = Some (x :: 'a \\ 'b); b = Some y;\n P x; \\s t. \\ P s; t \\ fst (B (fst s) (snd s)); C (fst s) (snd s) \\ \\ P t \\ \\ P y\"\n apply (induct arbitrary: x y rule: whileLoop_results.induct)\n apply simp\n apply simp\n apply atomize\n apply fastforce\n done\n\nlemma whileLoop_results_induct_lemma3 [consumes 1]:\n assumes result: \"(Some (r, s), Some (r', s')) \\ whileLoop_results C B\"\n and inv_start: \"I r s\"\n and inv_step: \"\\r s r' s'. \\ I r s; C r s; (r', s') \\ fst (B r s) \\ \\ I r' s'\"\n shows \"I r' s'\"\n apply (rule whileLoop_results_induct_lemma2 [where P=\"split I\" and y=\"(r', s')\" and x=\"(r, s)\",\n simplified split_def, simplified])\n apply (rule result)\n apply simp\n apply simp\n apply fact\n apply (erule (1) inv_step)\n apply clarsimp\n done\n\nsubsection \"Inductive reasoning about whileLoop results\"\n\nlemma in_whileLoop_induct [consumes 1]:\n assumes in_whileLoop: \"(r', s') \\ fst (whileLoop C B r s)\"\n and init_I: \"\\ r s. \\ C r s \\ I r s r s\"\n and step:\n \"\\r s r' s' r'' s''.\n \\ C r s; (r', s') \\ fst (B r s);\n (r'', s'') \\ fst (whileLoop C B r' s');\n I r' s' r'' s'' \\ \\ I r s r'' s''\"\n shows \"I r s r' s'\"\nproof cases\n assume \"C r s\"\n\n {\n obtain a where a_def: \"a = Some (r, s)\"\n by blast\n obtain b where b_def: \"b = Some (r', s')\"\n by blast\n\n have \"\\ (a, b) \\ whileLoop_results C B; \\x. a = Some x; \\x. b = Some x \\\n \\ I (fst (the a)) (snd (the a)) (fst (the b)) (snd (the b))\"\n apply (induct rule: whileLoop_results.induct)\n apply (auto simp: init_I whileLoop_def intro: step)\n done\n\n hence \"(Some (r, s), Some (r', s')) \\ whileLoop_results C B\n \\ I r s r' s'\"\n by (clarsimp simp: a_def b_def)\n }\n\n thus ?thesis\n using in_whileLoop\n by (clarsimp simp: whileLoop_def)\nnext\n assume \"\\ C r s\"\n\n hence \"r' = r \\ s' = s\"\n using in_whileLoop\n by (subst (asm) whileLoop_unroll,\n clarsimp simp: condition_def return_def)\n\n thus ?thesis\n by (metis init_I `\\ C r s`)\nqed\n\nlemma snd_whileLoop_induct [consumes 1]:\n assumes induct: \"snd (whileLoop C B r s)\"\n and terminates: \"\\ whileLoop_terminates C B r s \\ I r s\"\n and init: \"\\ r s. \\ snd (B r s); C r s \\ \\ I r s\"\n and step: \"\\r s r' s' r'' s''.\n \\ C r s; (r', s') \\ fst (B r s);\n snd (whileLoop C B r' s');\n I r' s' \\ \\ I r s\"\n shows \"I r s\"\n apply (insert init induct)\n apply atomize\n apply (unfold whileLoop_def)\n apply clarsimp\n apply (erule disjE)\n apply (erule rev_mp)\n apply (induct \"Some (r, s)\" \"None :: ('a \\ 'b) option\"\n arbitrary: r s rule: whileLoop_results.induct)\n apply clarsimp\n apply clarsimp\n apply (erule (1) step)\n apply (clarsimp simp: whileLoop_def)\n apply clarsimp\n apply (metis terminates)\n done\n\nlemma whileLoop_terminatesE_induct [consumes 1]:\n assumes induct: \"whileLoop_terminatesE C B r s\"\n and init: \"\\r s. \\ C r s \\ I r s\"\n and step: \"\\r s r' s'. \\ C r s; \\(v', s') \\ fst (B r s). case v' of Inl _ \\ True | Inr r' \\ I r' s' \\ \\ I r s\"\n shows \"I r s\"\n apply (insert induct)\n apply (clarsimp simp: whileLoop_terminatesE_def)\n apply (subgoal_tac \"(\\r s. case (Inr r) of Inl x \\ True | Inr x \\ I x s) r s\")\n apply simp\n apply (induction rule: whileLoop_terminates.induct)\n apply (case_tac r)\n apply simp\n apply clarsimp\n apply (erule init)\n apply (clarsimp split: sum.splits)\n apply (rule step)\n apply simp\n apply (clarsimp simp: lift_def split: sum.splits)\n apply force\n done\n\nsubsection \"Direct reasoning about whileLoop components\"\n\nlemma fst_whileLoop_cond_false:\n assumes loop_result: \"(r', s') \\ fst (whileLoop C B r s)\"\n shows \"\\ C r' s'\"\n using loop_result\n by (rule in_whileLoop_induct, auto)\n\nlemma snd_whileLoop:\n assumes init_I: \"I r s\"\n and cond_I: \"C r s\"\n and non_term: \"\\r. \\ \\s. I r s \\ C r s \\ \\ snd (B r s) \\\n B r \\\\ \\r' s'. C r' s' \\ I r' s' \\\"\n shows \"snd (whileLoop C B r s)\"\n apply (clarsimp simp: whileLoop_def)\n apply (rotate_tac)\n apply (insert init_I cond_I)\n apply (induct rule: whileLoop_terminates.induct)\n apply clarsimp\n apply (cut_tac r=r in non_term)\n apply (clarsimp simp: exs_valid_def)\n apply (subst (asm) (2) whileLoop_results.simps)\n apply clarsimp\n apply (insert whileLoop_results.simps)\n apply fast\n done\n\nlemma whileLoop_terminates_inv:\n assumes init_I: \"I r s\"\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\\"\n assumes wf_R: \"wf R\"\n shows \"whileLoop_terminates C B r s\"\n apply (insert init_I)\n using wf_R\n apply (induction \"(r, s)\" arbitrary: r s)\n apply atomize\n apply (subst whileLoop_terminates_simps)\n apply clarsimp\n apply (erule use_valid)\n apply (rule hoare_strengthen_post, rule inv)\n apply force\n apply force\n done\n\nlemma not_snd_whileLoop:\n assumes init_I: \"I r s\"\n and inv_holds: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\!\"\n and wf_R: \"wf R\"\n shows \"\\ snd (whileLoop C B r s)\"\nproof -\n {\n fix x y\n have \"\\ (x, y) \\ whileLoop_results C B; x = Some (r, s); y = None \\ \\ False\"\n apply (insert init_I)\n apply (induct arbitrary: r s rule: whileLoop_results.inducts)\n apply simp\n apply simp\n apply (insert snd_validNF [OF inv_holds])[1]\n apply blast\n apply (drule use_validNF [OF _ inv_holds])\n apply simp\n apply clarsimp\n apply blast\n done\n }\n\n also have \"whileLoop_terminates C B r s\"\n apply (rule whileLoop_terminates_inv [where I=I, OF init_I _ wf_R])\n apply (insert inv_holds)\n apply (clarsimp simp: validNF_def)\n done\n\n ultimately show ?thesis\n by (clarsimp simp: whileLoop_def, blast)\nqed\n\nlemma valid_whileLoop:\n assumes first_step: \"\\s. P r s \\ I r s\"\n and inv_step: \"\\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\\"\n and final_step: \"\\r s. \\ I r s; \\ C r s \\ \\ Q r s\"\n shows \"\\ P r \\ whileLoop C B r \\ Q \\\"\nproof -\n {\n fix r' s' s\n assume inv: \"I r s\"\n assume step: \"(r', s') \\ fst (whileLoop C B r s)\"\n\n have \"I r' s'\"\n using step inv\n apply (induct rule: in_whileLoop_induct)\n apply simp\n apply (drule use_valid, rule inv_step, auto)\n done\n }\n\n thus ?thesis\n apply (clarsimp simp: valid_def)\n apply (drule first_step)\n apply (rule final_step, simp)\n apply (metis fst_whileLoop_cond_false)\n done\nqed\n\nlemma whileLoop_wp:\n \"\\ \\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\;\n \\r s. \\ I r s; \\ C r s \\ \\ Q r s \\ \\\n \\ I r \\ whileLoop C B r \\ Q \\\"\n by (rule valid_whileLoop)\n\nlemma whileLoop_wp_inv [wp]:\n \"\\ \\r. \\\\s. I r s \\ C r s\\ B r \\I\\; \\r s. \\I r s; \\ C r s\\ \\ Q r s \\\n \\ \\ I r \\ whileLoop_inv C B r I M \\ Q \\\"\n apply (clarsimp simp: whileLoop_inv_def)\n apply (rule valid_whileLoop [where P=I and I=I], auto)\n done\n\nlemma validE_whileLoopE:\n \"\\\\s. P r s \\ I r s; \n \\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\,\\ A \\;\n \\r s. \\ I r s; \\ C r s \\ \\ Q r s\n \\ \\ \\ P r \\ whileLoopE C B r \\ Q \\,\\ A \\\"\n apply (clarsimp simp: whileLoopE_def validE_def)\n apply (rule valid_whileLoop [where I=\"\\r s. (case r of Inl x \\ A x s | Inr x \\ I x s)\"\n and Q=\"\\r s. (case r of Inl x \\ A x s | Inr x \\ Q x s)\"])\n apply atomize\n apply (clarsimp simp: valid_def lift_def split: sum.splits)\n apply (clarsimp simp: valid_def lift_def split: sum.splits)\n apply (clarsimp split: sum.splits)\n done\n\nlemma whileLoopE_wp:\n \"\\ \\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\, \\ A \\;\n \\r s. \\ I r s; \\ C r s \\ \\ Q r s \\ \\\n \\ I r \\ whileLoopE C B r \\ Q \\, \\ A \\\"\n by (rule validE_whileLoopE)\n\nlemma exs_valid_whileLoop:\n assumes init_T: \"\\s. P s \\ T r s\"\n and iter_I: \"\\ r s0.\n \\ \\s. T r s \\ C r s \\ s = s0 \\\n B r \\\\\\r' s'. T r' s' \\ ((r', s'),(r, s0)) \\ R\\\"\n and wf_R: \"wf R\"\n and final_I: \"\\r s. \\ T r s; \\ C r s \\ \\ Q r s\"\n shows \"\\ P \\ whileLoop C B r \\\\ Q \\\"\nproof (clarsimp simp: exs_valid_def Bex_def)\n fix s\n assume \"P s\"\n\n {\n fix x\n have \"T (fst x) (snd x) \\\n \\r' s'. (r', s') \\ fst (whileLoop C B (fst x) (snd x)) \\ T r' s'\"\n using wf_R\n apply induction\n apply atomize\n apply (case_tac \"C (fst x) (snd x)\")\n apply (subst whileLoop_unroll)\n apply (clarsimp simp: condition_def bind_def' split: prod.splits)\n apply (cut_tac ?s0.0=b and r=a in iter_I)\n apply (clarsimp simp: exs_valid_def)\n apply blast\n apply (subst whileLoop_unroll)\n apply (clarsimp simp: condition_def bind_def' return_def)\n done\n }\n\n thus \"\\r' s'. (r', s') \\ fst (whileLoop C B r s) \\ Q r' s'\"\n by (metis `P s` fst_conv init_T snd_conv\n final_I fst_whileLoop_cond_false)\nqed\n\nlemma empty_fail_whileLoop:\n assumes body_empty_fail: \"\\r. empty_fail (B r)\"\n shows \"empty_fail (whileLoop C B r)\"\nproof -\n {\n fix s A\n assume empty: \"fst (whileLoop C B r s) = {}\"\n\n have cond_true: \"\\x s. fst (whileLoop C B x s) = {} \\ C x s\"\n apply (subst (asm) whileLoop_unroll)\n apply (clarsimp simp: condition_def return_def split: split_if_asm)\n done\n\n have \"snd (whileLoop C B r s)\"\n apply (rule snd_whileLoop [where I=\"\\x s. fst (whileLoop C B x s) = {}\"])\n apply fact\n apply (rule cond_true, fact)\n apply (clarsimp simp: exs_valid_def)\n apply (case_tac \"fst (B r s) = {}\")\n apply (metis empty_failD [OF body_empty_fail])\n apply (subst (asm) whileLoop_unroll)\n apply (fastforce simp: condition_def bind_def split_def cond_true)\n done\n }\n\n thus ?thesis\n by (clarsimp simp: empty_fail_def)\nqed\n\nlemma empty_fail_whileLoopE:\n assumes body_empty_fail: \"\\r. empty_fail (B r)\"\n shows \"empty_fail (whileLoopE C B r)\"\n apply (clarsimp simp: whileLoopE_def)\n apply (rule empty_fail_whileLoop)\n apply (insert body_empty_fail)\n apply (clarsimp simp: empty_fail_def lift_def throwError_def return_def split: sum.splits)\n done\n\nlemma whileLoop_results_bisim:\n assumes base: \"(a, b) \\ whileLoop_results C B\"\n and vars1: \"Q = (case a of Some (r, s) \\ Some (rt r, st s) | _ \\ None)\"\n and vars2: \"R = (case b of Some (r, s) \\ Some (rt r, st s) | _ \\ None)\"\n and inv_init: \"case a of Some (r, s) \\ I r s | _ \\ True\"\n and inv_step: \"\\r s r' s'. \\ I r s; C r s; (r', s') \\ fst (B r s) \\ \\ I r' s'\"\n and cond_match: \"\\r s. I r s \\ C r s = C' (rt r) (st s)\"\n and fail_step: \"\\r s. \\C r s; snd (B r s); I r s\\\n \\ (Some (rt r, st s), None) \\ whileLoop_results C' B'\"\n and refine: \"\\r s r' s'. \\ I r s; C r s; (r', s') \\ fst (B r s) \\\n \\ (rt r', st s') \\ fst (B' (rt r) (st s))\"\n shows \"(Q, R) \\ whileLoop_results C' B'\"\n apply (subst vars1)\n apply (subst vars2)\n apply (insert base inv_init)\n apply (induct rule: whileLoop_results.induct)\n apply clarsimp\n apply (subst (asm) cond_match)\n apply (clarsimp simp: option.splits)\n apply (clarsimp simp: option.splits)\n apply (clarsimp simp: option.splits)\n apply (metis fail_step)\n apply (case_tac z)\n apply (clarsimp simp: option.splits)\n apply (metis cond_match inv_step refine whileLoop_results.intros(3))\n apply (clarsimp simp: option.splits)\n apply (metis cond_match inv_step refine whileLoop_results.intros(3))\n done\n\nlemma whileLoop_terminates_liftE:\n \"whileLoop_terminatesE C (\\r. liftE (B r)) r s = whileLoop_terminates C B r s\"\n apply (subst eq_sym_conv)\n apply (clarsimp simp: whileLoop_terminatesE_def)\n apply (rule iffI)\n apply (erule whileLoop_terminates.induct)\n apply (rule whileLoop_terminates.intros)\n apply clarsimp\n apply (clarsimp simp: split_def)\n apply (rule whileLoop_terminates.intros(2))\n apply clarsimp\n apply (clarsimp simp: liftE_def in_bind return_def lift_def [abs_def]\n bind_def lift_def throwError_def o_def split: sum.splits\n cong: sum.case_cong)\n apply (drule (1) bspec)\n apply clarsimp\n apply (subgoal_tac \"case (Inr r) of Inl _ \\ True | Inr r \\\n whileLoop_terminates (\\r s. (\\r s. case r of Inl _ \\ False | Inr v \\ C v s) (Inr r) s)\n (\\r. (lift (\\r. liftE (B r)) (Inr r)) >>= (\\x. return (theRight x))) r s\")\n apply (clarsimp simp: liftE_def lift_def)\n apply (erule whileLoop_terminates.induct)\n apply (clarsimp simp: liftE_def lift_def split: sum.splits)\n apply (erule whileLoop_terminates.intros)\n apply (clarsimp simp: liftE_def split: sum.splits)\n apply (clarsimp simp: bind_def return_def split_def lift_def)\n apply (erule whileLoop_terminates.intros)\n apply force\n done\n\nlemma snd_X_return [simp]:\n \"\\A X s. snd ((A >>= (\\a. return (X a))) s) = snd (A s)\"\n by (clarsimp simp: return_def bind_def split_def)\n\nlemma whileLoopE_liftE:\n \"whileLoopE C (\\r. liftE (B r)) r = liftE (whileLoop C B r)\"\n apply (rule ext)\n apply (clarsimp simp: whileLoopE_def)\n apply (rule prod_eqI)\n apply (rule set_eqI, rule iffI)\n apply clarsimp\n apply (clarsimp simp: in_bind whileLoop_def liftE_def)\n apply (rule_tac x=\"b\" in exI)\n apply (rule_tac x=\"theRight a\" in exI)\n apply (rule conjI)\n apply (erule whileLoop_results_bisim [where rt=theRight and st=\"\\x. x\" and I=\"\\r s. case r of Inr x \\ True | _ \\ False\"],\n auto intro: whileLoop_results.intros intro!: bexI simp: bind_def return_def lift_def split: sum.splits)[1]\n apply (drule whileLoop_results_induct_lemma2 [where P=\"\\(r, s). case r of Inr x \\ True | _ \\ False\"] )\n apply (rule refl)\n apply (rule refl)\n apply clarsimp\n apply (clarsimp simp: return_def bind_def lift_def split: sum.splits)\n apply (clarsimp simp: return_def bind_def lift_def split: sum.splits)\n apply (clarsimp simp: in_bind whileLoop_def liftE_def)\n apply (erule whileLoop_results_bisim [where rt=Inr and st=\"\\x. x\" and I=\"\\r s. True\"],\n auto intro: whileLoop_results.intros intro!: bexI simp: bind_def return_def lift_def split: sum.splits)[1]\n apply (rule iffI)\n apply (clarsimp simp: whileLoop_def liftE_def del: notI)\n apply (erule disjE)\n apply (erule whileLoop_results_bisim [where rt=theRight and st=\"\\x. x\" and I=\"\\r s. case r of Inr x \\ True | _ \\ False\"],\n auto intro: whileLoop_results.intros intro!: bexI simp: bind_def return_def lift_def split: sum.splits)[1]\n apply (subst (asm) whileLoop_terminates_liftE [symmetric])\n apply (fastforce simp: whileLoop_def liftE_def whileLoop_terminatesE_def)\n apply (clarsimp simp: whileLoop_def liftE_def del: notI)\n apply (subst (asm) whileLoop_terminates_liftE [symmetric])\n apply (clarsimp simp: whileLoop_def liftE_def whileLoop_terminatesE_def)\n apply (erule disjE)\n apply (erule whileLoop_results_bisim [where rt=Inr and st=\"\\x. x\" and I=\"\\r s. True\"])\n apply (clarsimp split: option.splits)\n apply (clarsimp split: option.splits)\n apply (clarsimp split: option.splits)\n apply (auto intro: whileLoop_results.intros intro!: bexI simp: bind_def return_def lift_def split: sum.splits)\n done\n\nlemma validNF_whileLoop:\n assumes pre: \"\\s. P r s \\ I r s\"\n and inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\!\"\n and wf: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\P r\\ whileLoop C B r \\Q\\!\"\n apply rule\n apply (rule valid_whileLoop)\n apply fact\n apply (insert inv, clarsimp simp: validNF_def\n valid_def split: prod.splits, force)[1]\n apply (metis post_cond)\n apply (unfold no_fail_def)\n apply (intro allI impI)\n apply (rule not_snd_whileLoop [where I=I and R=R])\n apply (auto intro: assms)\n done\n\nlemma validNF_whileLoop_inv [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\!\"\n and wf: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoop_inv C B r I R \\Q\\!\"\n apply (clarsimp simp: whileLoop_inv_def)\n apply (rule validNF_whileLoop [where I=I and R=R])\n apply simp\n apply (rule inv)\n apply (rule wf)\n apply (metis post_cond)\n done\n\nlemma validNF_whileLoop_inv_measure [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ M r' s' < M r s \\!\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoop_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\!\"\n apply (clarsimp simp: whileLoop_inv_def)\n apply (rule validNF_whileLoop [where R=\"measure' (\\(r, s). M r s)\" and I=I])\n apply simp\n apply clarsimp\n apply (rule inv)\n apply simp\n apply (metis post_cond)\n done\n\nlemma validNF_whileLoop_inv_measure_twosteps:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ B r \\ \\r' s'. I r' s' \\!\"\n assumes measure: \"\\r m. \\\\s. I r s \\ C r s \\ M r s = m \\ B r \\ \\r' s'. M r' s' < m \\\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoop_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\!\"\n apply (rule validNF_whileLoop_inv_measure)\n apply (rule validNF_weaken_pre)\n apply (rule validNF_post_comb_conj_L)\n apply (rule inv)\n apply (rule measure)\n apply fast\n apply (metis post_cond)\n done\n\nlemma wf_custom_measure:\n \"\\ \\a b. (a, b) \\ R \\ f a < (f :: 'a \\ nat) b \\ \\ wf R\"\n by (metis in_measure wf_def wf_measure)\n\nlemma validNF_whileLoopE:\n assumes pre: \"\\s. P r s \\ I r s\"\n and inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\,\\ E \\!\"\n and wf: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\ P r \\ whileLoopE C B r \\ Q \\,\\ E \\!\"\n apply (unfold validE_NF_alt_def whileLoopE_def)\n apply (rule validNF_whileLoop [\n where I=\"\\r s. case r of Inl x \\ E x s | Inr x \\ I x s\"\n and R=\"{((r', s'), (r, s)). \\x x'. r' = Inl x' \\ r = Inr x}\n \\ {((r', s'), (r, s)). \\x x'. r' = Inr x' \\ r = Inr x \\ ((x', s'),(x, s)) \\ R}\"])\n apply (simp add: pre)\n apply (insert inv)[1]\n apply (fastforce simp: lift_def validNF_def valid_def\n validE_NF_def throwError_def no_fail_def return_def\n validE_def split: sum.splits prod.splits)\n apply (rule wf_Un)\n apply (rule wf_custom_measure [where f=\"\\(r, s). case r of Inl _ \\ 0 | _ \\ 1\"])\n apply clarsimp\n apply (insert wf_inv_image [OF wf, where f=\"\\(r, s). (theRight r, s)\"])\n apply (drule wf_Int1 [where r'=\"{((r', s'),(r, s)). (\\x. r = Inr x) \\ (\\x. r' = Inr x)}\"])\n apply (erule wf_subset)\n apply rule\n apply (clarsimp simp: inv_image_def split: prod.splits sum.splits)\n apply clarsimp\n apply rule\n apply rule\n apply clarsimp\n apply clarsimp\n apply (clarsimp split: sum.splits)\n apply (blast intro: post_cond)\n done\n\nlemma validNF_whileLoopE_inv [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\,\\ E \\!\"\n and wf_R: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoopE_inv C B r I R \\Q\\,\\E\\!\"\n apply (clarsimp simp: whileLoopE_inv_def)\n apply (metis validNF_whileLoopE [OF _ inv] post_cond wf_R)\n done\n\nlemma validNF_whileLoopE_inv_measure [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ M r' s' < M r s \\, \\ E \\!\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoopE_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\,\\E\\!\"\n apply (rule validNF_whileLoopE_inv)\n apply clarsimp\n apply (rule inv)\n apply clarsimp\n apply (metis post_cond)\n done\n\nlemma validNF_whileLoopE_inv_measure_twosteps:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ B r \\ \\r' s'. I r' s' \\, \\ E \\!\"\n assumes measure: \"\\r m. \\\\s. I r s \\ C r s \\ M r s = m \\ B r \\ \\r' s'. M r' s' < m \\, \\ \\_ _. True \\\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoopE_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\, \\E\\!\"\n apply (rule validNF_whileLoopE_inv_measure)\n apply (rule validE_NF_weaken_pre)\n apply (rule validE_NF_post_comb_conj_L)\n apply (rule inv)\n apply (rule measure)\n apply fast\n apply (metis post_cond)\n done\n\nlemma whileLoopE_wp_inv [wp]:\n \"\\ \\r. \\\\s. I r s \\ C r s\\ B r \\I\\,\\E\\; \\r s. \\I r s; \\ C r s\\ \\ Q r s \\\n \\ \\ I r \\ whileLoopE_inv C B r I M \\ Q \\,\\ E \\\"\n apply (clarsimp simp: whileLoopE_inv_def)\n apply (rule validE_whileLoopE [where I=I], auto)\n done\n\nsubsection \"Stronger whileLoop rules\"\n\nlemma whileLoop_rule_strong:\n assumes init_U: \"\\ \\s'. s' = s \\ whileLoop C B r \\ \\r s. (r, s) \\ fst Q \\\"\n and path_exists: \"\\r'' s''. \\ (r'', s'') \\ fst Q \\ \\ \\ \\s'. s' = s \\ whileLoop C B r \\\\ \\r s. r = r'' \\ s = s'' \\\"\n and loop_fail: \"snd Q \\ snd (whileLoop C B r s)\"\n and loop_nofail: \"\\ snd Q \\ \\ \\s'. s' = s \\ whileLoop C B r \\ \\_ _. True \\!\"\n shows \"whileLoop C B r s = Q\"\n using assms\n apply atomize\n apply (clarsimp simp: valid_def exs_valid_def validNF_def no_fail_def)\n apply rule\n apply blast\n apply blast\n apply blast\n done\n\nlemma whileLoop_rule_strong_no_fail:\n assumes init_U: \"\\ \\s'. s' = s \\ whileLoop C B r \\ \\r s. (r, s) \\ fst Q \\!\"\n and path_exists: \"\\r'' s''. \\ (r'', s'') \\ fst Q \\ \\ \\ \\s'. s' = s \\ whileLoop C B r \\\\ \\r s. r = r'' \\ s = s'' \\\"\n and loop_no_fail: \"\\ snd Q\"\n shows \"whileLoop C B r s = Q\"\n apply (rule whileLoop_rule_strong)\n apply (metis init_U validNF_valid)\n apply (metis path_exists)\n apply (metis loop_no_fail)\n apply (metis (lifting, no_types) init_U validNF_chain)\n done\n\nsubsection \"Miscellaneous rules\"\n\n(* Failure of one whileLoop implies the failure of another whileloop\n * which will only ever fail more. *)\nlemma snd_whileLoop_subset:\n assumes a_fails: \"snd (whileLoop C A r s)\"\n and b_success_step:\n \"\\r s r' s'. \\ C r s; (r', s') \\ fst (A r s); \\ snd (B r s) \\\n \\ (r', s') \\ fst (B r s)\"\n and b_fail_step: \"\\r s. \\ C r s; snd (A r s) \\ \\ snd (B r s) \"\n shows \"snd (whileLoop C B r s)\"\n apply (insert a_fails)\n apply (induct rule: snd_whileLoop_induct)\n apply (unfold whileLoop_def snd_conv)[1]\n apply (rule disjCI, simp)\n apply rotate_tac\n apply (induct rule: whileLoop_terminates.induct)\n apply (subst (asm) whileLoop_terminates.simps)\n apply simp\n apply (subst (asm) (3) whileLoop_terminates.simps, clarsimp)\n apply (subst whileLoop_results.simps, clarsimp)\n apply (rule classical)\n apply (frule b_success_step, assumption, simp)\n apply (drule (1) bspec)\n apply clarsimp\n apply (frule (1) b_fail_step)\n apply (metis snd_whileLoop_first_step)\n apply (metis b_success_step snd_whileLoop_first_step snd_whileLoop_unfold)\n done\n\nend\n", "meta": {"author": "8l", "repo": "AutoCorres", "sha": "47d800912e6e0d9b1b8009660e8b20c785a2ea8b", "save_path": "github-repos/isabelle/8l-AutoCorres", "path": "github-repos/isabelle/8l-AutoCorres/AutoCorres-47d800912e6e0d9b1b8009660e8b20c785a2ea8b/lib/WhileLoopRules.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.16667540675766923, "lm_q1q2_score": 0.08203565772256252}} {"text": "(*<*)\ntheory Isar\nimports LaTeXsugar\nbegin\ndeclare [[quick_and_dirty]]\n(*>*)\ntext{*\nApply-scripts are unreadable and hard to maintain. The language of choice\nfor larger proofs is \\concept{Isar}. The two key features of Isar are:\n\\begin{itemize}\n\\item It is structured, not linear.\n\\item It is readable without its being run because\nyou need to state what you are proving at any given point.\n\\end{itemize}\nWhereas apply-scripts are like assembly language programs, Isar proofs\nare like structured programs with comments. A typical Isar proof looks like this:\n*}text{*\n\\begin{tabular}{@ {}l}\n\\isacom{proof}\\\\\n\\quad\\isacom{assume} @{text\"\\\"\"}$\\mathit{formula}_0$@{text\"\\\"\"}\\\\\n\\quad\\isacom{have} @{text\"\\\"\"}$\\mathit{formula}_1$@{text\"\\\"\"} \\quad\\isacom{by} @{text simp}\\\\\n\\quad\\vdots\\\\\n\\quad\\isacom{have} @{text\"\\\"\"}$\\mathit{formula}_n$@{text\"\\\"\"} \\quad\\isacom{by} @{text blast}\\\\\n\\quad\\isacom{show} @{text\"\\\"\"}$\\mathit{formula}_{n+1}$@{text\"\\\"\"} \\quad\\isacom{by} @{text \\}\\\\\n\\isacom{qed}\n\\end{tabular}\n*}text{*\nIt proves $\\mathit{formula}_0 \\Longrightarrow \\mathit{formula}_{n+1}$\n(provided each proof step succeeds).\nThe intermediate \\isacom{have} statements are merely stepping stones\non the way towards the \\isacom{show} statement that proves the actual\ngoal. In more detail, this is the Isar core syntax:\n\\medskip\n\n\\begin{tabular}{@ {}lcl@ {}}\n\\textit{proof} &=& \\indexed{\\isacom{by}}{by} \\textit{method}\\\\\n &$\\mid$& \\indexed{\\isacom{proof}}{proof} [\\textit{method}] \\ \\textit{step}$^*$ \\ \\indexed{\\isacom{qed}}{qed}\n\\end{tabular}\n\\medskip\n\n\\begin{tabular}{@ {}lcl@ {}}\n\\textit{step} &=& \\indexed{\\isacom{fix}}{fix} \\textit{variables} \\\\\n &$\\mid$& \\indexed{\\isacom{assume}}{assume} \\textit{proposition} \\\\\n &$\\mid$& [\\indexed{\\isacom{from}}{from} \\textit{fact}$^+$] (\\indexed{\\isacom{have}}{have} $\\mid$ \\indexed{\\isacom{show}}{show}) \\ \\textit{proposition} \\ \\textit{proof}\n\\end{tabular}\n\\medskip\n\n\\begin{tabular}{@ {}lcl@ {}}\n\\textit{proposition} &=& [\\textit{name}:] @{text\"\\\"\"}\\textit{formula}@{text\"\\\"\"}\n\\end{tabular}\n\\medskip\n\n\\begin{tabular}{@ {}lcl@ {}}\n\\textit{fact} &=& \\textit{name} \\ $\\mid$ \\ \\dots\n\\end{tabular}\n\\medskip\n\n\\noindent A proof can either be an atomic \\isacom{by} with a single proof\nmethod which must finish off the statement being proved, for example @{text\nauto}, or it can be a \\isacom{proof}--\\isacom{qed} block of multiple\nsteps. Such a block can optionally begin with a proof method that indicates\nhow to start off the proof, e.g., \\mbox{@{text\"(induction xs)\"}}.\n\nA step either assumes a proposition or states a proposition\ntogether with its proof. The optional \\isacom{from} clause\nindicates which facts are to be used in the proof.\nIntermediate propositions are stated with \\isacom{have}, the overall goal\nis stated with \\isacom{show}. A step can also introduce new local variables with\n\\isacom{fix}. Logically, \\isacom{fix} introduces @{text\"\\\"}-quantified\nvariables, \\isacom{assume} introduces the assumption of an implication\n(@{text\"\\\"}) and \\isacom{have}/\\isacom{show} introduce the conclusion.\n\nPropositions are optionally named formulas. These names can be referred to in\nlater \\isacom{from} clauses. In the simplest case, a fact is such a name.\nBut facts can also be composed with @{text OF} and @{text of} as shown in\n\\autoref{sec:forward-proof} --- hence the \\dots\\ in the above grammar. Note\nthat assumptions, intermediate \\isacom{have} statements and global lemmas all\nhave the same status and are thus collectively referred to as\n\\conceptidx{facts}{fact}.\n\nFact names can stand for whole lists of facts. For example, if @{text f} is\ndefined by command \\isacom{fun}, @{text\"f.simps\"} refers to the whole list of\nrecursion equations defining @{text f}. Individual facts can be selected by\nwriting @{text\"f.simps(2)\"}, whole sublists by writing @{text\"f.simps(2-4)\"}.\n\n\n\\section{Isar by Example}\n\nWe show a number of proofs of Cantor's theorem that a function from a set to\nits powerset cannot be surjective, illustrating various features of Isar. The\nconstant @{const surj} is predefined.\n*}\n\nlemma \"\\ surj(f :: 'a \\ 'a set)\"\nproof\n assume 0: \"surj f\"\n from 0 have 1: \"\\A. \\a. A = f a\" by(simp add: surj_def)\n from 1 have 2: \"\\a. {x. x \\ f x} = f a\" by blast\n from 2 show \"False\" by blast\nqed\n\ntext{*\nThe \\isacom{proof} command lacks an explicit method by which to perform\nthe proof. In such cases Isabelle tries to use some standard introduction\nrule, in the above case for @{text\"\\\"}:\n\\[\n\\inferrule{\n\\mbox{@{thm (prem 1) notI}}}\n{\\mbox{@{thm (concl) notI}}}\n\\]\nIn order to prove @{prop\"~ P\"}, assume @{text P} and show @{text False}.\nThus we may assume @{prop\"surj f\"}. The proof shows that names of propositions\nmay be (single!) digits --- meaningful names are hard to invent and are often\nnot necessary. Both \\isacom{have} steps are obvious. The second one introduces\nthe diagonal set @{term\"{x. x \\ f x}\"}, the key idea in the proof.\nIf you wonder why @{text 2} directly implies @{text False}: from @{text 2}\nit follows that @{prop\"a \\ f a \\ a \\ f a\"}.\n\n\\subsection{\\indexed{@{text this}}{this}, \\indexed{\\isacom{then}}{then}, \\indexed{\\isacom{hence}}{hence} and \\indexed{\\isacom{thus}}{thus}}\n\nLabels should be avoided. They interrupt the flow of the reader who has to\nscan the context for the point where the label was introduced. Ideally, the\nproof is a linear flow, where the output of one step becomes the input of the\nnext step, piping the previously proved fact into the next proof, like\nin a UNIX pipe. In such cases the predefined name @{text this} can be used\nto refer to the proposition proved in the previous step. This allows us to\neliminate all labels from our proof (we suppress the \\isacom{lemma} statement):\n*}\n(*<*)\nlemma \"\\ surj(f :: 'a \\ 'a set)\"\n(*>*)\nproof\n assume \"surj f\"\n from this have \"\\a. {x. x \\ f x} = f a\" by(auto simp: surj_def)\n from this show \"False\" by blast\nqed\n\ntext{* We have also taken the opportunity to compress the two \\isacom{have}\nsteps into one.\n\nTo compact the text further, Isar has a few convenient abbreviations:\n\\medskip\n\n\\begin{tabular}{r@ {\\quad=\\quad}l}\n\\isacom{then} & \\isacom{from} @{text this}\\\\\n\\isacom{thus} & \\isacom{then} \\isacom{show}\\\\\n\\isacom{hence} & \\isacom{then} \\isacom{have}\n\\end{tabular}\n\\medskip\n\n\\noindent\nWith the help of these abbreviations the proof becomes\n*}\n(*<*)\nlemma \"\\ surj(f :: 'a \\ 'a set)\"\n(*>*)\nproof\n assume \"surj f\"\n hence \"\\a. {x. x \\ f x} = f a\" by(auto simp: surj_def)\n thus \"False\" by blast\nqed\ntext{*\n\nThere are two further linguistic variations:\n\\medskip\n\n\\begin{tabular}{r@ {\\quad=\\quad}l}\n(\\isacom{have}$\\mid$\\isacom{show}) \\ \\textit{prop} \\ \\indexed{\\isacom{using}}{using} \\ \\textit{facts}\n&\n\\isacom{from} \\ \\textit{facts} \\ (\\isacom{have}$\\mid$\\isacom{show}) \\ \\textit{prop}\\\\\n\\indexed{\\isacom{with}}{with} \\ \\textit{facts} & \\isacom{from} \\ \\textit{facts} \\isa{this}\n\\end{tabular}\n\\medskip\n\n\\noindent The \\isacom{using} idiom de-emphasizes the used facts by moving them\nbehind the proposition.\n\n\\subsection{Structured Lemma Statements: \\indexed{\\isacom{fixes}}{fixes}, \\indexed{\\isacom{assumes}}{assumes}, \\indexed{\\isacom{shows}}{shows}}\n\\index{lemma@\\isacom{lemma}}\nLemmas can also be stated in a more structured fashion. To demonstrate this\nfeature with Cantor's theorem, we rephrase @{prop\"\\ surj f\"}\na little:\n*}\n\nlemma\n fixes f :: \"'a \\ 'a set\"\n assumes s: \"surj f\"\n shows \"False\"\n\ntxt{* The optional \\isacom{fixes} part allows you to state the types of\nvariables up front rather than by decorating one of their occurrences in the\nformula with a type constraint. The key advantage of the structured format is\nthe \\isacom{assumes} part that allows you to name each assumption; multiple\nassumptions can be separated by \\isacom{and}. The\n\\isacom{shows} part gives the goal. The actual theorem that will come out of\nthe proof is @{prop\"surj f \\ False\"}, but during the proof the assumption\n@{prop\"surj f\"} is available under the name @{text s} like any other fact.\n*}\n\nproof -\n have \"\\ a. {x. x \\ f x} = f a\" using s\n by(auto simp: surj_def)\n thus \"False\" by blast\nqed\n\ntext{*\n\\begin{warn}\nNote the hyphen after the \\isacom{proof} command.\nIt is the null method that does nothing to the goal. Leaving it out would be asking\nIsabelle to try some suitable introduction rule on the goal @{const False} --- but\nthere is no such rule and \\isacom{proof} would fail.\n\\end{warn}\nIn the \\isacom{have} step the assumption @{prop\"surj f\"} is now\nreferenced by its name @{text s}. The duplication of @{prop\"surj f\"} in the\nabove proofs (once in the statement of the lemma, once in its proof) has been\neliminated.\n\nStating a lemma with \\isacom{assumes}-\\isacom{shows} implicitly introduces the\nname \\indexed{@{text assms}}{assms} that stands for the list of all assumptions. You can refer\nto individual assumptions by @{text\"assms(1)\"}, @{text\"assms(2)\"}, etc.,\nthus obviating the need to name them individually.\n\n\\section{Proof Patterns}\n\nWe show a number of important basic proof patterns. Many of them arise from\nthe rules of natural deduction that are applied by \\isacom{proof} by\ndefault. The patterns are phrased in terms of \\isacom{show} but work for\n\\isacom{have} and \\isacom{lemma}, too.\n\nWe start with two forms of \\concept{case analysis}:\nstarting from a formula @{text P} we have the two cases @{text P} and\n@{prop\"~P\"}, and starting from a fact @{prop\"P \\ Q\"}\nwe have the two cases @{text P} and @{text Q}:\n*}text_raw{*\n\\begin{tabular}{@ {}ll@ {}}\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n*}\n(*<*)lemma \"R\" proof-(*>*)\nshow \"R\"\nproof cases\n assume \"P\"\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"R\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nnext\n assume \"\\ P\"\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"R\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nqed(*<*)oops(*>*)\ntext_raw {* }\n\\end{minipage}\\index{cases@@{text cases}}\n&\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n*}\n(*<*)lemma \"R\" proof-(*>*)\nhave \"P \\ Q\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nthen show \"R\"\nproof\n assume \"P\"\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"R\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nnext\n assume \"Q\"\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"R\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nqed(*<*)oops(*>*)\n\ntext_raw {* }\n\\end{minipage}\n\\end{tabular}\n\\medskip\n\\begin{isamarkuptext}%\nHow to prove a logical equivalence:\n\\end{isamarkuptext}%\n\\isa{%\n*}\n(*<*)lemma \"P\\Q\" proof-(*>*)\nshow \"P \\ Q\"\nproof\n assume \"P\"\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"Q\" (*<*)sorry(*>*) text_raw{*\\ $\\dots$\\\\*}\nnext\n assume \"Q\"\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"P\" (*<*)sorry(*>*) text_raw{*\\ $\\dots$\\\\*}\nqed(*<*)qed(*>*)\ntext_raw {* }\n\\medskip\n\\begin{isamarkuptext}%\nProofs by contradiction (@{thm[source] ccontr} stands for ``classical contradiction''):\n\\end{isamarkuptext}%\n\\begin{tabular}{@ {}ll@ {}}\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n*}\n(*<*)lemma \"\\ P\" proof-(*>*)\nshow \"\\ P\"\nproof\n assume \"P\"\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"False\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nqed(*<*)oops(*>*)\n\ntext_raw {* }\n\\end{minipage}\n&\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n*}\n(*<*)lemma \"P\" proof-(*>*)\nshow \"P\"\nproof (rule ccontr)\n assume \"\\P\"\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"False\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nqed(*<*)oops(*>*)\n\ntext_raw {* }\n\\end{minipage}\n\\end{tabular}\n\\medskip\n\\begin{isamarkuptext}%\nHow to prove quantified formulas:\n\\end{isamarkuptext}%\n\\begin{tabular}{@ {}ll@ {}}\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n*}\n(*<*)lemma \"ALL x. P x\" proof-(*>*)\nshow \"\\x. P(x)\"\nproof\n fix x\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"P(x)\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nqed(*<*)oops(*>*)\n\ntext_raw {* }\n\\end{minipage}\n&\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n*}\n(*<*)lemma \"EX x. P(x)\" proof-(*>*)\nshow \"\\x. P(x)\"\nproof\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"P(witness)\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nqed\n(*<*)oops(*>*)\n\ntext_raw {* }\n\\end{minipage}\n\\end{tabular}\n\\medskip\n\\begin{isamarkuptext}%\nIn the proof of \\noquotes{@{prop[source]\"\\x. P(x)\"}},\nthe step \\indexed{\\isacom{fix}}{fix}~@{text x} introduces a locally fixed variable @{text x}\ninto the subproof, the proverbial ``arbitrary but fixed value''.\nInstead of @{text x} we could have chosen any name in the subproof.\nIn the proof of \\noquotes{@{prop[source]\"\\x. P(x)\"}},\n@{text witness} is some arbitrary\nterm for which we can prove that it satisfies @{text P}.\n\nHow to reason forward from \\noquotes{@{prop[source] \"\\x. P(x)\"}}:\n\\end{isamarkuptext}%\n*}\n(*<*)lemma True proof- assume 1: \"EX x. P x\"(*>*)\nhave \"\\x. P(x)\" (*<*)by(rule 1)(*>*)text_raw{*\\ $\\dots$\\\\*}\nthen obtain x where p: \"P(x)\" by blast\n(*<*)oops(*>*)\ntext{*\nAfter the \\indexed{\\isacom{obtain}}{obtain} step, @{text x} (we could have chosen any name)\nis a fixed local\nvariable, and @{text p} is the name of the fact\n\\noquotes{@{prop[source] \"P(x)\"}}.\nThis pattern works for one or more @{text x}.\nAs an example of the \\isacom{obtain} command, here is the proof of\nCantor's theorem in more detail:\n*}\n\nlemma \"\\ surj(f :: 'a \\ 'a set)\"\nproof\n assume \"surj f\"\n hence \"\\a. {x. x \\ f x} = f a\" by(auto simp: surj_def)\n then obtain a where \"{x. x \\ f x} = f a\" by blast\n hence \"a \\ f a \\ a \\ f a\" by blast\n thus \"False\" by blast\nqed\n\ntext_raw{*\n\\begin{isamarkuptext}%\n\nFinally, how to prove set equality and subset relationship:\n\\end{isamarkuptext}%\n\\begin{tabular}{@ {}ll@ {}}\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n*}\n(*<*)lemma \"A = (B::'a set)\" proof-(*>*)\nshow \"A = B\"\nproof\n show \"A \\ B\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nnext\n show \"B \\ A\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nqed(*<*)qed(*>*)\n\ntext_raw {* }\n\\end{minipage}\n&\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n*}\n(*<*)lemma \"A <= (B::'a set)\" proof-(*>*)\nshow \"A \\ B\"\nproof\n fix x\n assume \"x \\ A\"\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"x \\ B\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nqed(*<*)qed(*>*)\n\ntext_raw {* }\n\\end{minipage}\n\\end{tabular}\n\\begin{isamarkuptext}%\n\\section{Streamlining Proofs}\n\n\\subsection{Pattern Matching and Quotations}\n\nIn the proof patterns shown above, formulas are often duplicated.\nThis can make the text harder to read, write and maintain. Pattern matching\nis an abbreviation mechanism to avoid such duplication. Writing\n\\begin{quote}\n\\isacom{show} \\ \\textit{formula} @{text\"(\"}\\indexed{\\isacom{is}}{is} \\textit{pattern}@{text\")\"}\n\\end{quote}\nmatches the pattern against the formula, thus instantiating the unknowns in\nthe pattern for later use. As an example, consider the proof pattern for\n@{text\"\\\"}:\n\\end{isamarkuptext}%\n*}\n(*<*)lemma \"formula\\<^sub>1 \\ formula\\<^sub>2\" proof-(*>*)\nshow \"formula\\<^sub>1 \\ formula\\<^sub>2\" (is \"?L \\ ?R\")\nproof\n assume \"?L\"\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"?R\" (*<*)sorry(*>*) text_raw{*\\ $\\dots$\\\\*}\nnext\n assume \"?R\"\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show \"?L\" (*<*)sorry(*>*) text_raw{*\\ $\\dots$\\\\*}\nqed(*<*)qed(*>*)\n\ntext{* Instead of duplicating @{text\"formula\\<^sub>i\"} in the text, we introduce\nthe two abbreviations @{text\"?L\"} and @{text\"?R\"} by pattern matching.\nPattern matching works wherever a formula is stated, in particular\nwith \\isacom{have} and \\isacom{lemma}.\n\nThe unknown \\indexed{@{text\"?thesis\"}}{thesis} is implicitly matched against any goal stated by\n\\isacom{lemma} or \\isacom{show}. Here is a typical example: *}\n\nlemma \"formula\"\nproof -\n text_raw{*\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}*}\n show ?thesis (*<*)sorry(*>*) text_raw{*\\ $\\dots$\\\\*}\nqed\n\ntext{* \nUnknowns can also be instantiated with \\indexed{\\isacom{let}}{let} commands\n\\begin{quote}\n\\isacom{let} @{text\"?t\"} = @{text\"\\\"\"}\\textit{some-big-term}@{text\"\\\"\"}\n\\end{quote}\nLater proof steps can refer to @{text\"?t\"}:\n\\begin{quote}\n\\isacom{have} @{text\"\\\"\"}\\dots @{text\"?t\"} \\dots@{text\"\\\"\"}\n\\end{quote}\n\\begin{warn}\nNames of facts are introduced with @{text\"name:\"} and refer to proved\ntheorems. Unknowns @{text\"?X\"} refer to terms or formulas.\n\\end{warn}\n\nAlthough abbreviations shorten the text, the reader needs to remember what\nthey stand for. Similarly for names of facts. Names like @{text 1}, @{text 2}\nand @{text 3} are not helpful and should only be used in short proofs. For\nlonger proofs, descriptive names are better. But look at this example:\n\\begin{quote}\n\\isacom{have} \\ @{text\"x_gr_0: \\\"x > 0\\\"\"}\\\\\n$\\vdots$\\\\\n\\isacom{from} @{text \"x_gr_0\"} \\dots\n\\end{quote}\nThe name is longer than the fact it stands for! Short facts do not need names;\none can refer to them easily by quoting them:\n\\begin{quote}\n\\isacom{have} \\ @{text\"\\\"x > 0\\\"\"}\\\\\n$\\vdots$\\\\\n\\isacom{from} @{text \"`x>0`\"} \\dots\\index{$IMP053@@{text\"`...`\"}}\n\\end{quote}\nNote that the quotes around @{text\"x>0\"} are \\conceptnoidx{back quotes}.\nThey refer to the fact not by name but by value.\n\n\\subsection{\\indexed{\\isacom{moreover}}{moreover}}\n\\index{ultimately@\\isacom{ultimately}}\n\nSometimes one needs a number of facts to enable some deduction. Of course\none can name these facts individually, as shown on the right,\nbut one can also combine them with \\isacom{moreover}, as shown on the left:\n*}text_raw{*\n\\begin{tabular}{@ {}ll@ {}}\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n*}\n(*<*)lemma \"P\" proof-(*>*)\nhave \"P\\<^sub>1\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nmoreover have \"P\\<^sub>2\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nmoreover\ntext_raw{*\\\\$\\vdots$\\\\\\hspace{-1.4ex}*}(*<*)have \"True\" ..(*>*)\nmoreover have \"P\\<^sub>n\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nultimately have \"P\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\n(*<*)oops(*>*)\n\ntext_raw {* }\n\\end{minipage}\n&\n\\qquad\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n*}\n(*<*)lemma \"P\" proof-(*>*)\nhave lab\\<^sub>1: \"P\\<^sub>1\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nhave lab\\<^sub>2: \"P\\<^sub>2\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$*}\ntext_raw{*\\\\$\\vdots$\\\\\\hspace{-1.4ex}*}\nhave lab\\<^sub>n: \"P\\<^sub>n\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nfrom lab\\<^sub>1 lab\\<^sub>2 text_raw{*\\ $\\dots$\\\\*}\nhave \"P\" (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\n(*<*)oops(*>*)\n\ntext_raw {* }\n\\end{minipage}\n\\end{tabular}\n\\begin{isamarkuptext}%\nThe \\isacom{moreover} version is no shorter but expresses the structure more\nclearly and avoids new names.\n\n\\subsection{Raw Proof Blocks}\n\nSometimes one would like to prove some lemma locally within a proof,\na lemma that shares the current context of assumptions but that\nhas its own assumptions and is generalized over its locally fixed\nvariables at the end. This is what a \\concept{raw proof block} does:\n\\begin{quote}\\index{$IMP053@@{text\"{ ... }\"} (proof block)}\n@{text\"{\"} \\isacom{fix} @{text\"x\\<^sub>1 \\ x\\<^sub>n\"}\\\\\n\\mbox{}\\ \\ \\ \\isacom{assume} @{text\"A\\<^sub>1 \\ A\\<^sub>m\"}\\\\\n\\mbox{}\\ \\ \\ $\\vdots$\\\\\n\\mbox{}\\ \\ \\ \\isacom{have} @{text\"B\"}\\\\\n@{text\"}\"}\n\\end{quote}\nproves @{text\"\\ A\\<^sub>1; \\ ; A\\<^sub>m \\ \\ B\"}\nwhere all @{text\"x\\<^sub>i\"} have been replaced by unknowns @{text\"?x\\<^sub>i\"}.\n\\begin{warn}\nThe conclusion of a raw proof block is \\emph{not} indicated by \\isacom{show}\nbut is simply the final \\isacom{have}.\n\\end{warn}\n\nAs an example we prove a simple fact about divisibility on integers.\nThe definition of @{text \"dvd\"} is @{thm dvd_def}.\n\\end{isamarkuptext}%\n*}\n\nlemma fixes a b :: int assumes \"b dvd (a+b)\" shows \"b dvd a\"\nproof -\n { fix k assume k: \"a+b = b*k\"\n have \"\\k'. a = b*k'\"\n proof\n show \"a = b*(k - 1)\" using k by(simp add: algebra_simps)\n qed }\n then show ?thesis using assms by(auto simp add: dvd_def)\nqed\n\ntext{* Note that the result of a raw proof block has no name. In this example\nit was directly piped (via \\isacom{then}) into the final proof, but it can\nalso be named for later reference: you simply follow the block directly by a\n\\isacom{note} command:\n\\begin{quote}\n\\indexed{\\isacom{note}}{note} \\ @{text\"name = this\"}\n\\end{quote}\nThis introduces a new name @{text name} that refers to @{text this},\nthe fact just proved, in this case the preceding block. In general,\n\\isacom{note} introduces a new name for one or more facts.\n\n\\subsection*{Exercises}\n\n\\exercise\nGive a readable, structured proof of the following lemma:\n*}\nlemma assumes T: \"\\x y. T x y \\ T y x\"\n and A: \"\\x y. A x y \\ A y x \\ x = y\"\n and TA: \"\\x y. T x y \\ A x y\" and \"A x y\"\n shows \"T x y\"\n(*<*)oops(*>*)\ntext{*\n\\endexercise\n\n\\exercise\nGive a readable, structured proof of the following lemma:\n*}\nlemma \"(\\ys zs. xs = ys @ zs \\ length ys = length zs)\n \\ (\\ys zs. xs = ys @ zs \\ length ys = length zs + 1)\"\n(*<*)oops(*>*)\ntext{*\nHint: There are predefined functions @{const_typ take} and @{const_typ drop}\nsuch that @{text\"take k [x\\<^sub>1,\\] = [x\\<^sub>1,\\,x\\<^sub>k]\"} and\n@{text\"drop k [x\\<^sub>1,\\] = [x\\<^bsub>k+1\\<^esub>,\\]\"}. Let sledgehammer find and apply\nthe relevant @{const take} and @{const drop} lemmas for you.\n\\endexercise\n\n\n\\section{Case Analysis and Induction}\n\n\\subsection{Datatype Case Analysis}\n\\index{case analysis|(}\n\nWe have seen case analysis on formulas. Now we want to distinguish\nwhich form some term takes: is it @{text 0} or of the form @{term\"Suc n\"},\nis it @{term\"[]\"} or of the form @{term\"x#xs\"}, etc. Here is a typical example\nproof by case analysis on the form of @{text xs}:\n*}\n\nlemma \"length(tl xs) = length xs - 1\"\nproof (cases xs)\n assume \"xs = []\"\n thus ?thesis by simp\nnext\n fix y ys assume \"xs = y#ys\"\n thus ?thesis by simp\nqed\n\ntext{*\\index{cases@@{text\"cases\"}|(}Function @{text tl} (''tail'') is defined by @{thm list.sel(2)} and\n@{thm list.sel(3)}. Note that the result type of @{const length} is @{typ nat}\nand @{prop\"0 - 1 = (0::nat)\"}.\n\nThis proof pattern works for any term @{text t} whose type is a datatype.\nThe goal has to be proved for each constructor @{text C}:\n\\begin{quote}\n\\isacom{fix} \\ @{text\"x\\<^sub>1 \\ x\\<^sub>n\"} \\isacom{assume} @{text\"\\\"t = C x\\<^sub>1 \\ x\\<^sub>n\\\"\"}\n\\end{quote}\\index{case@\\isacom{case}|(}\nEach case can be written in a more compact form by means of the \\isacom{case}\ncommand:\n\\begin{quote}\n\\isacom{case} @{text \"(C x\\<^sub>1 \\ x\\<^sub>n)\"}\n\\end{quote}\nThis is equivalent to the explicit \\isacom{fix}-\\isacom{assume} line\nbut also gives the assumption @{text\"\\\"t = C x\\<^sub>1 \\ x\\<^sub>n\\\"\"} a name: @{text C},\nlike the constructor.\nHere is the \\isacom{case} version of the proof above:\n*}\n(*<*)lemma \"length(tl xs) = length xs - 1\"(*>*)\nproof (cases xs)\n case Nil\n thus ?thesis by simp\nnext\n case (Cons y ys)\n thus ?thesis by simp\nqed\n\ntext{* Remember that @{text Nil} and @{text Cons} are the alphanumeric names\nfor @{text\"[]\"} and @{text\"#\"}. The names of the assumptions\nare not used because they are directly piped (via \\isacom{thus})\ninto the proof of the claim.\n\\index{case analysis|)}\n\n\\subsection{Structural Induction}\n\\index{induction|(}\n\\index{structural induction|(}\n\nWe illustrate structural induction with an example based on natural numbers:\nthe sum (@{text\"\\\"}) of the first @{text n} natural numbers\n(@{text\"{0..n::nat}\"}) is equal to \\mbox{@{term\"n*(n+1) div 2::nat\"}}.\nNever mind the details, just focus on the pattern:\n*}\n\nlemma \"\\{0..n::nat} = n*(n+1) div 2\"\nproof (induction n)\n show \"\\{0..0::nat} = 0*(0+1) div 2\" by simp\nnext\n fix n assume \"\\{0..n::nat} = n*(n+1) div 2\"\n thus \"\\{0..Suc n} = Suc n*(Suc n+1) div 2\" by simp\nqed\n\ntext{* Except for the rewrite steps, everything is explicitly given. This\nmakes the proof easily readable, but the duplication means it is tedious to\nwrite and maintain. Here is how pattern\nmatching can completely avoid any duplication: *}\n\nlemma \"\\{0..n::nat} = n*(n+1) div 2\" (is \"?P n\")\nproof (induction n)\n show \"?P 0\" by simp\nnext\n fix n assume \"?P n\"\n thus \"?P(Suc n)\" by simp\nqed\n\ntext{* The first line introduces an abbreviation @{text\"?P n\"} for the goal.\nPattern matching @{text\"?P n\"} with the goal instantiates @{text\"?P\"} to the\nfunction @{term\"\\n. \\{0..n::nat} = n*(n+1) div 2\"}. Now the proposition to\nbe proved in the base case can be written as @{text\"?P 0\"}, the induction\nhypothesis as @{text\"?P n\"}, and the conclusion of the induction step as\n@{text\"?P(Suc n)\"}.\n\nInduction also provides the \\isacom{case} idiom that abbreviates\nthe \\isacom{fix}-\\isacom{assume} step. The above proof becomes\n*}\n(*<*)lemma \"\\{0..n::nat} = n*(n+1) div 2\"(*>*)\nproof (induction n)\n case 0\n show ?case by simp\nnext\n case (Suc n)\n thus ?case by simp\nqed\n\ntext{*\nThe unknown @{text\"?case\"}\\index{case?@@{text\"?case\"}|(} is set in each case to the required\nclaim, i.e., @{text\"?P 0\"} and \\mbox{@{text\"?P(Suc n)\"}} in the above proof,\nwithout requiring the user to define a @{text \"?P\"}. The general\npattern for induction over @{typ nat} is shown on the left-hand side:\n*}text_raw{*\n\\begin{tabular}{@ {}ll@ {}}\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n*}\n(*<*)lemma \"P(n::nat)\" proof -(*>*)\nshow \"P(n)\"\nproof (induction n)\n case 0\n text_raw{*\\\\\\mbox{}\\ \\ $\\vdots$\\\\\\mbox{}\\hspace{-1ex}*}\n show ?case (*<*)sorry(*>*) text_raw{*\\ $\\dots$\\\\*}\nnext\n case (Suc n)\n text_raw{*\\\\\\mbox{}\\ \\ $\\vdots$\\\\\\mbox{}\\hspace{-1ex}*}\n show ?case (*<*)sorry(*>*) text_raw{*\\ $\\dots$\\\\*}\nqed(*<*)qed(*>*)\n\ntext_raw {* }\n\\end{minipage}\n&\n\\begin{minipage}[t]{.4\\textwidth}\n~\\\\\n~\\\\\n\\isacom{let} @{text\"?case = \\\"P(0)\\\"\"}\\\\\n~\\\\\n~\\\\\n~\\\\[1ex]\n\\isacom{fix} @{text n} \\isacom{assume} @{text\"Suc: \\\"P(n)\\\"\"}\\\\\n\\isacom{let} @{text\"?case = \\\"P(Suc n)\\\"\"}\\\\\n\\end{minipage}\n\\end{tabular}\n\\medskip\n*}\ntext{*\nOn the right side you can see what the \\isacom{case} command\non the left stands for.\n\nIn case the goal is an implication, induction does one more thing: the\nproposition to be proved in each case is not the whole implication but only\nits conclusion; the premises of the implication are immediately made\nassumptions of that case. That is, if in the above proof we replace\n\\isacom{show}~@{text\"\\\"P(n)\\\"\"} by\n\\mbox{\\isacom{show}~@{text\"\\\"A(n) \\ P(n)\\\"\"}}\nthen \\isacom{case}~@{text 0} stands for\n\\begin{quote}\n\\isacom{assume} \\ @{text\"0: \\\"A(0)\\\"\"}\\\\\n\\isacom{let} @{text\"?case = \\\"P(0)\\\"\"}\n\\end{quote}\nand \\isacom{case}~@{text\"(Suc n)\"} stands for\n\\begin{quote}\n\\isacom{fix} @{text n}\\\\\n\\isacom{assume} @{text\"Suc:\"}\n \\begin{tabular}[t]{l}@{text\"\\\"A(n) \\ P(n)\\\"\"}\\\\@{text\"\\\"A(Suc n)\\\"\"}\\end{tabular}\\\\\n\\isacom{let} @{text\"?case = \\\"P(Suc n)\\\"\"}\n\\end{quote}\nThe list of assumptions @{text Suc} is actually subdivided\ninto @{text\"Suc.IH\"}, the induction hypotheses (here @{text\"A(n) \\ P(n)\"}),\nand @{text\"Suc.prems\"}, the premises of the goal being proved\n(here @{text\"A(Suc n)\"}).\n\nInduction works for any datatype.\nProving a goal @{text\"\\ A\\<^sub>1(x); \\; A\\<^sub>k(x) \\ \\ P(x)\"}\nby induction on @{text x} generates a proof obligation for each constructor\n@{text C} of the datatype. The command \\isacom{case}~@{text\"(C x\\<^sub>1 \\ x\\<^sub>n)\"}\nperforms the following steps:\n\\begin{enumerate}\n\\item \\isacom{fix} @{text\"x\\<^sub>1 \\ x\\<^sub>n\"}\n\\item \\isacom{assume} the induction hypotheses (calling them @{text C.IH}\\index{IH@@{text\".IH\"}})\n and the premises \\mbox{@{text\"A\\<^sub>i(C x\\<^sub>1 \\ x\\<^sub>n)\"}} (calling them @{text\"C.prems\"}\\index{prems@@{text\".prems\"}})\n and calling the whole list @{text C}\n\\item \\isacom{let} @{text\"?case = \\\"P(C x\\<^sub>1 \\ x\\<^sub>n)\\\"\"}\n\\end{enumerate}\n\\index{structural induction|)}\n\n\\subsection{Rule Induction}\n\\index{rule induction|(}\n\nRecall the inductive and recursive definitions of even numbers in\n\\autoref{sec:inductive-defs}:\n*}\n\ninductive ev :: \"nat \\ bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\ ev(Suc(Suc n))\"\n\nfun evn :: \"nat \\ bool\" where\n\"evn 0 = True\" |\n\"evn (Suc 0) = False\" |\n\"evn (Suc(Suc n)) = evn n\"\n\ntext{* We recast the proof of @{prop\"ev n \\ evn n\"} in Isar. The\nleft column shows the actual proof text, the right column shows\nthe implicit effect of the two \\isacom{case} commands:*}text_raw{*\n\\begin{tabular}{@ {}l@ {\\qquad}l@ {}}\n\\begin{minipage}[t]{.5\\textwidth}\n\\isa{%\n*}\n\nlemma \"ev n \\ evn n\"\nproof(induction rule: ev.induct)\n case ev0\n show ?case by simp\nnext\n case evSS\n\n\n\n thus ?case by simp\nqed\n\ntext_raw {* }\n\\end{minipage}\n&\n\\begin{minipage}[t]{.5\\textwidth}\n~\\\\\n~\\\\\n\\isacom{let} @{text\"?case = \\\"evn 0\\\"\"}\\\\\n~\\\\\n~\\\\\n\\isacom{fix} @{text n}\\\\\n\\isacom{assume} @{text\"evSS:\"}\n \\begin{tabular}[t]{l} @{text\"\\\"ev n\\\"\"}\\\\@{text\"\\\"evn n\\\"\"}\\end{tabular}\\\\\n\\isacom{let} @{text\"?case = \\\"evn(Suc(Suc n))\\\"\"}\\\\\n\\end{minipage}\n\\end{tabular}\n\\medskip\n*}\ntext{*\nThe proof resembles structural induction, but the induction rule is given\nexplicitly and the names of the cases are the names of the rules in the\ninductive definition.\nLet us examine the two assumptions named @{thm[source]evSS}:\n@{prop \"ev n\"} is the premise of rule @{thm[source]evSS}, which we may assume\nbecause we are in the case where that rule was used; @{prop\"evn n\"}\nis the induction hypothesis.\n\\begin{warn}\nBecause each \\isacom{case} command introduces a list of assumptions\nnamed like the case name, which is the name of a rule of the inductive\ndefinition, those rules now need to be accessed with a qualified name, here\n@{thm[source] ev.ev0} and @{thm[source] ev.evSS}.\n\\end{warn}\n\nIn the case @{thm[source]evSS} of the proof above we have pretended that the\nsystem fixes a variable @{text n}. But unless the user provides the name\n@{text n}, the system will just invent its own name that cannot be referred\nto. In the above proof, we do not need to refer to it, hence we do not give\nit a specific name. In case one needs to refer to it one writes\n\\begin{quote}\n\\isacom{case} @{text\"(evSS m)\"}\n\\end{quote}\nlike \\isacom{case}~@{text\"(Suc n)\"} in earlier structural inductions.\nThe name @{text m} is an arbitrary choice. As a result,\ncase @{thm[source] evSS} is derived from a renamed version of\nrule @{thm[source] evSS}: @{text\"ev m \\ ev(Suc(Suc m))\"}.\nHere is an example with a (contrived) intermediate step that refers to @{text m}:\n*}\n\nlemma \"ev n \\ evn n\"\nproof(induction rule: ev.induct)\n case ev0 show ?case by simp\nnext\n case (evSS m)\n have \"evn(Suc(Suc m)) = evn m\" by simp\n thus ?case using `evn m` by blast\nqed\n\ntext{*\n\\indent\nIn general, let @{text I} be a (for simplicity unary) inductively defined\npredicate and let the rules in the definition of @{text I}\nbe called @{text \"rule\\<^sub>1\"}, \\dots, @{text \"rule\\<^sub>n\"}. A proof by rule\ninduction follows this pattern:\\index{inductionrule@@{text\"induction ... rule:\"}}\n*}\n\n(*<*)\ninductive I where rule\\<^sub>1: \"I()\" | rule\\<^sub>2: \"I()\" | rule\\<^sub>n: \"I()\"\nlemma \"I x \\ P x\" proof-(*>*)\nshow \"I x \\ P x\"\nproof(induction rule: I.induct)\n case rule\\<^sub>1\n text_raw{*\\\\[-.4ex]\\mbox{}\\ \\ $\\vdots$\\\\[-.4ex]\\mbox{}\\hspace{-1ex}*}\n show ?case (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nnext\n text_raw{*\\\\[-.4ex]$\\vdots$\\\\[-.4ex]\\mbox{}\\hspace{-1ex}*}\n(*<*)\n case rule\\<^sub>2\n show ?case sorry\n(*>*)\nnext\n case rule\\<^sub>n\n text_raw{*\\\\[-.4ex]\\mbox{}\\ \\ $\\vdots$\\\\[-.4ex]\\mbox{}\\hspace{-1ex}*}\n show ?case (*<*)sorry(*>*)text_raw{*\\ $\\dots$\\\\*}\nqed(*<*)qed(*>*)\n\ntext{*\nOne can provide explicit variable names by writing\n\\isacom{case}~@{text\"(rule\\<^sub>i x\\<^sub>1 \\ x\\<^sub>k)\"}, thus renaming the first @{text k}\nfree variables in rule @{text i} to @{text\"x\\<^sub>1 \\ x\\<^sub>k\"},\ngoing through rule @{text i} from left to right.\n\n\\subsection{Assumption Naming}\n\\label{sec:assm-naming}\n\nIn any induction, \\isacom{case}~@{text name} sets up a list of assumptions\nalso called @{text name}, which is subdivided into three parts:\n\\begin{description}\n\\item[@{text name.IH}]\\index{IH@@{text\".IH\"}} contains the induction hypotheses.\n\\item[@{text name.hyps}]\\index{hyps@@{text\".hyps\"}} contains all the other hypotheses of this case in the\ninduction rule. For rule inductions these are the hypotheses of rule\n@{text name}, for structural inductions these are empty.\n\\item[@{text name.prems}]\\index{prems@@{text\".prems\"}} contains the (suitably instantiated) premises\nof the statement being proved, i.e., the @{text A\\<^sub>i} when\nproving @{text\"\\ A\\<^sub>1; \\; A\\<^sub>n \\ \\ A\"}.\n\\end{description}\n\\begin{warn}\nProof method @{text induct} differs from @{text induction}\nonly in this naming policy: @{text induct} does not distinguish\n@{text IH} from @{text hyps} but subsumes @{text IH} under @{text hyps}.\n\\end{warn}\n\nMore complicated inductive proofs than the ones we have seen so far\noften need to refer to specific assumptions --- just @{text name} or even\n@{text name.prems} and @{text name.IH} can be too unspecific.\nThis is where the indexing of fact lists comes in handy, e.g.,\n@{text\"name.IH(2)\"} or @{text\"name.prems(1-2)\"}.\n\n\\subsection{Rule Inversion}\n\\label{sec:rule-inversion}\n\\index{rule inversion|(}\n\nRule inversion is case analysis of which rule could have been used to\nderive some fact. The name \\conceptnoidx{rule inversion} emphasizes that we are\nreasoning backwards: by which rules could some given fact have been proved?\nFor the inductive definition of @{const ev}, rule inversion can be summarized\nlike this:\n@{prop[display]\"ev n \\ n = 0 \\ (EX k. n = Suc(Suc k) \\ ev k)\"}\nThe realisation in Isabelle is a case analysis.\nA simple example is the proof that @{prop\"ev n \\ ev (n - 2)\"}. We\nalready went through the details informally in \\autoref{sec:Logic:even}. This\nis the Isar proof:\n*}\n(*<*)\nnotepad\nbegin fix n\n(*>*)\n assume \"ev n\"\n from this have \"ev(n - 2)\"\n proof cases\n case ev0 thus \"ev(n - 2)\" by (simp add: ev.ev0)\n next\n case (evSS k) thus \"ev(n - 2)\" by (simp add: ev.evSS)\n qed\n(*<*)\nend\n(*>*)\n\ntext{* The key point here is that a case analysis over some inductively\ndefined predicate is triggered by piping the given fact\n(here: \\isacom{from}~@{text this}) into a proof by @{text cases}.\nLet us examine the assumptions available in each case. In case @{text ev0}\nwe have @{text\"n = 0\"} and in case @{text evSS} we have @{prop\"n = Suc(Suc k)\"}\nand @{prop\"ev k\"}. In each case the assumptions are available under the name\nof the case; there is no fine-grained naming schema like there is for induction.\n\nSometimes some rules could not have been used to derive the given fact\nbecause constructors clash. As an extreme example consider\nrule inversion applied to @{prop\"ev(Suc 0)\"}: neither rule @{text ev0} nor\nrule @{text evSS} can yield @{prop\"ev(Suc 0)\"} because @{text\"Suc 0\"} unifies\nneither with @{text 0} nor with @{term\"Suc(Suc n)\"}. Impossible cases do not\nhave to be proved. Hence we can prove anything from @{prop\"ev(Suc 0)\"}:\n*}\n(*<*)\nnotepad begin fix P\n(*>*)\n assume \"ev(Suc 0)\" then have P by cases\n(*<*)\nend\n(*>*)\n\ntext{* That is, @{prop\"ev(Suc 0)\"} is simply not provable: *}\n\nlemma \"\\ ev(Suc 0)\"\nproof\n assume \"ev(Suc 0)\" then show False by cases\nqed\n\ntext{* Normally not all cases will be impossible. As a simple exercise,\nprove that \\mbox{@{prop\"\\ ev(Suc(Suc(Suc 0)))\"}.}\n\n\\subsection{Advanced Rule Induction}\n\\label{sec:advanced-rule-induction}\n\nSo far, rule induction was always applied to goals of the form @{text\"I x y z \\ \\\"}\nwhere @{text I} is some inductively defined predicate and @{text x}, @{text y}, @{text z}\nare variables. In some rare situations one needs to deal with an assumption where\nnot all arguments @{text r}, @{text s}, @{text t} are variables:\n\\begin{isabelle}\n\\isacom{lemma} @{text\"\\\"I r s t \\ \\\\\"\"}\n\\end{isabelle}\nApplying the standard form of\nrule induction in such a situation will lead to strange and typically unprovable goals.\nWe can easily reduce this situation to the standard one by introducing\nnew variables @{text x}, @{text y}, @{text z} and reformulating the goal like this:\n\\begin{isabelle}\n\\isacom{lemma} @{text\"\\\"I x y z \\ x = r \\ y = s \\ z = t \\ \\\\\"\"}\n\\end{isabelle}\nStandard rule induction will work fine now, provided the free variables in\n@{text r}, @{text s}, @{text t} are generalized via @{text\"arbitrary\"}.\n\nHowever, induction can do the above transformation for us, behind the curtains, so we never\nneed to see the expanded version of the lemma. This is what we need to write:\n\\begin{isabelle}\n\\isacom{lemma} @{text\"\\\"I r s t \\ \\\\\"\"}\\isanewline\n\\isacom{proof}@{text\"(induction \\\"r\\\" \\\"s\\\" \\\"t\\\" arbitrary: \\ rule: I.induct)\"}\\index{inductionrule@@{text\"induction ... rule:\"}}\\index{arbitrary@@{text\"arbitrary:\"}}\n\\end{isabelle}\nLike for rule inversion, cases that are impossible because of constructor clashes\nwill not show up at all. Here is a concrete example: *}\n\nlemma \"ev (Suc m) \\ \\ ev m\"\nproof(induction \"Suc m\" arbitrary: m rule: ev.induct)\n fix n assume IH: \"\\m. n = Suc m \\ \\ ev m\"\n show \"\\ ev (Suc n)\"\n proof --\"contradiction\"\n assume \"ev(Suc n)\"\n thus False\n proof cases --\"rule inversion\"\n fix k assume \"n = Suc k\" \"ev k\"\n thus False using IH by auto\n qed\n qed\nqed\n\ntext{*\nRemarks:\n\\begin{itemize}\n\\item \nInstead of the \\isacom{case} and @{text ?case} magic we have spelled all formulas out.\nThis is merely for greater clarity.\n\\item\nWe only need to deal with one case because the @{thm[source] ev0} case is impossible.\n\\item\nThe form of the @{text IH} shows us that internally the lemma was expanded as explained\nabove: \\noquotes{@{prop[source]\"ev x \\ x = Suc m \\ \\ ev m\"}}.\n\\item\nThe goal @{prop\"\\ ev (Suc n)\"} may surprise. The expanded version of the lemma\nwould suggest that we have a \\isacom{fix} @{text m} \\isacom{assume} @{prop\"Suc(Suc n) = Suc m\"}\nand need to show @{prop\"\\ ev m\"}. What happened is that Isabelle immediately\nsimplified @{prop\"Suc(Suc n) = Suc m\"} to @{prop\"Suc n = m\"} and could then eliminate\n@{text m}. Beware of such nice surprises with this advanced form of induction.\n\\end{itemize}\n\\begin{warn}\nThis advanced form of induction does not support the @{text IH}\nnaming schema explained in \\autoref{sec:assm-naming}:\nthe induction hypotheses are instead found under the name @{text hyps},\nas they are for the simpler\n@{text induct} method.\n\\end{warn}\n\\index{induction|)}\n\\index{cases@@{text\"cases\"}|)}\n\\index{case@\\isacom{case}|)}\n\\index{case?@@{text\"?case\"}|)}\n\\index{rule induction|)}\n\\index{rule inversion|)}\n\n\\subsection*{Exercises}\n\n\n\\exercise\nGive a structured proof by rule inversion:\n*}\n\nlemma assumes a: \"ev(Suc(Suc n))\" shows \"ev n\"\n(*<*)oops(*>*)\n\ntext{*\n\\endexercise\n\n\\begin{exercise}\nGive a structured proof of @{prop \"\\ ev(Suc(Suc(Suc 0)))\"}\nby rule inversions. If there are no cases to be proved you can close\na proof immediately with \\isacom{qed}.\n\\end{exercise}\n\n\\begin{exercise}\nRecall predicate @{text star} from \\autoref{sec:star} and @{text iter}\nfrom Exercise~\\ref{exe:iter}. Prove @{prop \"iter r n x y \\ star r x y\"}\nin a structured style; do not just sledgehammer each case of the\nrequired induction.\n\\end{exercise}\n\n\\begin{exercise}\nDefine a recursive function @{text \"elems ::\"} @{typ\"'a list \\ 'a set\"}\nand prove @{prop \"x : elems xs \\ \\ys zs. xs = ys @ x # zs \\ x \\ elems ys\"}.\n\\end{exercise}\n\n\\begin{exercise}\nExtend Exercise~\\ref{exe:cfg} with a function that checks if some\n\\mbox{@{text \"alpha list\"}} is a balanced\nstring of parentheses. More precisely, define a \\mbox{recursive} function\n@{text \"balanced :: nat \\ alpha list \\ bool\"} such that @{term\"balanced n w\"}\nis true iff (informally) @{text\"S (a\\<^sup>n @ w)\"}. Formally, prove that\n@{prop \"balanced n w \\ S (replicate n a @ w)\"} where\n@{const replicate} @{text\"::\"} @{typ\"nat \\ 'a \\ 'a list\"} is predefined\nand @{term\"replicate n x\"} yields the list @{text\"[x, \\, x]\"} of length @{text n}.\n\\end{exercise}\n*}\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/Doc/Prog_Prove/Isar.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4843800693903656, "lm_q2_score": 0.16885695423297592, "lm_q1q2_score": 0.08179094320841467}} {"text": "(*<*)\ntheory Isar\nimports LaTeXsugar\nbegin\ndeclare [[quick_and_dirty]]\n(*>*)\ntext\\\nApply-scripts are unreadable and hard to maintain. The language of choice\nfor larger proofs is \\concept{Isar}. The two key features of Isar are:\n\\begin{itemize}\n\\item It is structured, not linear.\n\\item It is readable without its being run because\nyou need to state what you are proving at any given point.\n\\end{itemize}\nWhereas apply-scripts are like assembly language programs, Isar proofs\nare like structured programs with comments. A typical Isar proof looks like this:\n\\text\\\n\\begin{tabular}{@ {}l}\n\\isacom{proof}\\\\\n\\quad\\isacom{assume} \\\"\\$\\mathit{formula}_0$\\\"\\\\\\\n\\quad\\isacom{have} \\\"\\$\\mathit{formula}_1$\\\"\\ \\quad\\isacom{by} \\simp\\\\\\\n\\quad\\vdots\\\\\n\\quad\\isacom{have} \\\"\\$\\mathit{formula}_n$\\\"\\ \\quad\\isacom{by} \\blast\\\\\\\n\\quad\\isacom{show} \\\"\\$\\mathit{formula}_{n+1}$\\\"\\ \\quad\\isacom{by} \\\\\\\\\\\n\\isacom{qed}\n\\end{tabular}\n\\text\\\nIt proves $\\mathit{formula}_0 \\Longrightarrow \\mathit{formula}_{n+1}$\n(provided each proof step succeeds).\nThe intermediate \\isacom{have} statements are merely stepping stones\non the way towards the \\isacom{show} statement that proves the actual\ngoal. In more detail, this is the Isar core syntax:\n\\medskip\n\n\\begin{tabular}{@ {}lcl@ {}}\n\\textit{proof} &=& \\indexed{\\isacom{by}}{by} \\textit{method}\\\\\n &$\\mid$& \\indexed{\\isacom{proof}}{proof} [\\textit{method}] \\ \\textit{step}$^*$ \\ \\indexed{\\isacom{qed}}{qed}\n\\end{tabular}\n\\medskip\n\n\\begin{tabular}{@ {}lcl@ {}}\n\\textit{step} &=& \\indexed{\\isacom{fix}}{fix} \\textit{variables} \\\\\n &$\\mid$& \\indexed{\\isacom{assume}}{assume} \\textit{proposition} \\\\\n &$\\mid$& [\\indexed{\\isacom{from}}{from} \\textit{fact}$^+$] (\\indexed{\\isacom{have}}{have} $\\mid$ \\indexed{\\isacom{show}}{show}) \\ \\textit{proposition} \\ \\textit{proof}\n\\end{tabular}\n\\medskip\n\n\\begin{tabular}{@ {}lcl@ {}}\n\\textit{proposition} &=& [\\textit{name}:] \\\"\\\\textit{formula}\\\"\\\n\\end{tabular}\n\\medskip\n\n\\begin{tabular}{@ {}lcl@ {}}\n\\textit{fact} &=& \\textit{name} \\ $\\mid$ \\ \\dots\n\\end{tabular}\n\\medskip\n\n\\noindent A proof can either be an atomic \\isacom{by} with a single proof\nmethod which must finish off the statement being proved, for example \\auto\\, or it can be a \\isacom{proof}--\\isacom{qed} block of multiple\nsteps. Such a block can optionally begin with a proof method that indicates\nhow to start off the proof, e.g., \\mbox{\\(induction xs)\\}.\n\nA step either assumes a proposition or states a proposition\ntogether with its proof. The optional \\isacom{from} clause\nindicates which facts are to be used in the proof.\nIntermediate propositions are stated with \\isacom{have}, the overall goal\nis stated with \\isacom{show}. A step can also introduce new local variables with\n\\isacom{fix}. Logically, \\isacom{fix} introduces \\\\\\-quantified\nvariables, \\isacom{assume} introduces the assumption of an implication\n(\\\\\\) and \\isacom{have}/\\isacom{show} introduce the conclusion.\n\nPropositions are optionally named formulas. These names can be referred to in\nlater \\isacom{from} clauses. In the simplest case, a fact is such a name.\nBut facts can also be composed with \\OF\\ and \\of\\ as shown in\n\\autoref{sec:forward-proof} --- hence the \\dots\\ in the above grammar. Note\nthat assumptions, intermediate \\isacom{have} statements and global lemmas all\nhave the same status and are thus collectively referred to as\n\\conceptidx{facts}{fact}.\n\nFact names can stand for whole lists of facts. For example, if \\f\\ is\ndefined by command \\isacom{fun}, \\f.simps\\ refers to the whole list of\nrecursion equations defining \\f\\. Individual facts can be selected by\nwriting \\f.simps(2)\\, whole sublists by writing \\f.simps(2-4)\\.\n\n\n\\section{Isar by Example}\n\nWe show a number of proofs of Cantor's theorem that a function from a set to\nits powerset cannot be surjective, illustrating various features of Isar. The\nconstant \\<^const>\\surj\\ is predefined.\n\\\n\nlemma \"\\ surj(f :: 'a \\ 'a set)\"\nproof\n assume 0: \"surj f\"\n from 0 have 1: \"\\A. \\a. A = f a\" by(simp add: surj_def)\n from 1 have 2: \"\\a. {x. x \\ f x} = f a\" by blast\n from 2 show \"False\" by blast\nqed\n\ntext\\\nThe \\isacom{proof} command lacks an explicit method by which to perform\nthe proof. In such cases Isabelle tries to use some standard introduction\nrule, in the above case for \\\\\\:\n\\[\n\\inferrule{\n\\mbox{@{thm (prem 1) notI}}}\n{\\mbox{@{thm (concl) notI}}}\n\\]\nIn order to prove \\<^prop>\\~ P\\, assume \\P\\ and show \\False\\.\nThus we may assume \\mbox{\\noquotes{@{prop [source] \"surj f\"}}}. The proof shows that names of propositions\nmay be (single!) digits --- meaningful names are hard to invent and are often\nnot necessary. Both \\isacom{have} steps are obvious. The second one introduces\nthe diagonal set \\<^term>\\{x. x \\ f x}\\, the key idea in the proof.\nIf you wonder why \\2\\ directly implies \\False\\: from \\2\\\nit follows that \\<^prop>\\a \\ f a \\ a \\ f a\\.\n\n\\subsection{\\indexed{\\this\\}{this}, \\indexed{\\isacom{then}}{then}, \\indexed{\\isacom{hence}}{hence} and \\indexed{\\isacom{thus}}{thus}}\n\nLabels should be avoided. They interrupt the flow of the reader who has to\nscan the context for the point where the label was introduced. Ideally, the\nproof is a linear flow, where the output of one step becomes the input of the\nnext step, piping the previously proved fact into the next proof, like\nin a UNIX pipe. In such cases the predefined name \\this\\ can be used\nto refer to the proposition proved in the previous step. This allows us to\neliminate all labels from our proof (we suppress the \\isacom{lemma} statement):\n\\\n(*<*)\nlemma \"\\ surj(f :: 'a \\ 'a set)\"\n(*>*)\nproof\n assume \"surj f\"\n from this have \"\\a. {x. x \\ f x} = f a\" by(auto simp: surj_def)\n from this show \"False\" by blast\nqed\n\ntext\\We have also taken the opportunity to compress the two \\isacom{have}\nsteps into one.\n\nTo compact the text further, Isar has a few convenient abbreviations:\n\\medskip\n\n\\begin{tabular}{r@ {\\quad=\\quad}l}\n\\isacom{then} & \\isacom{from} \\this\\\\\\\n\\isacom{thus} & \\isacom{then} \\isacom{show}\\\\\n\\isacom{hence} & \\isacom{then} \\isacom{have}\n\\end{tabular}\n\\medskip\n\n\\noindent\nWith the help of these abbreviations the proof becomes\n\\\n(*<*)\nlemma \"\\ surj(f :: 'a \\ 'a set)\"\n(*>*)\nproof\n assume \"surj f\"\n hence \"\\a. {x. x \\ f x} = f a\" by(auto simp: surj_def)\n thus \"False\" by blast\nqed\ntext\\\n\nThere are two further linguistic variations:\n\\medskip\n\n\\begin{tabular}{r@ {\\quad=\\quad}l}\n(\\isacom{have}$\\mid$\\isacom{show}) \\ \\textit{prop} \\ \\indexed{\\isacom{using}}{using} \\ \\textit{facts}\n&\n\\isacom{from} \\ \\textit{facts} \\ (\\isacom{have}$\\mid$\\isacom{show}) \\ \\textit{prop}\\\\\n\\indexed{\\isacom{with}}{with} \\ \\textit{facts} & \\isacom{from} \\ \\textit{facts} \\isa{this}\n\\end{tabular}\n\\medskip\n\n\\noindent The \\isacom{using} idiom de-emphasizes the used facts by moving them\nbehind the proposition.\n\n\\subsection{Structured Lemma Statements: \\indexed{\\isacom{fixes}}{fixes}, \\indexed{\\isacom{assumes}}{assumes}, \\indexed{\\isacom{shows}}{shows}}\n\\index{lemma@\\isacom{lemma}}\nLemmas can also be stated in a more structured fashion. To demonstrate this\nfeature with Cantor's theorem, we rephrase \\noquotes{@{prop[source]\"\\ surj f\"}}\na little:\n\\\n\nlemma\n fixes f :: \"'a \\ 'a set\"\n assumes s: \"surj f\"\n shows \"False\"\n\ntxt\\The optional \\isacom{fixes} part allows you to state the types of\nvariables up front rather than by decorating one of their occurrences in the\nformula with a type constraint. The key advantage of the structured format is\nthe \\isacom{assumes} part that allows you to name each assumption; multiple\nassumptions can be separated by \\isacom{and}. The\n\\isacom{shows} part gives the goal. The actual theorem that will come out of\nthe proof is \\noquotes{@{prop[source]\"surj f \\ False\"}}, but during the proof the assumption\n\\noquotes{@{prop[source]\"surj f\"}} is available under the name \\s\\ like any other fact.\n\\\n\nproof -\n have \"\\ a. {x. x \\ f x} = f a\" using s\n by(auto simp: surj_def)\n thus \"False\" by blast\nqed\n\ntext\\\n\\begin{warn}\nNote the hyphen after the \\isacom{proof} command.\nIt is the null method that does nothing to the goal. Leaving it out would be asking\nIsabelle to try some suitable introduction rule on the goal \\<^const>\\False\\ --- but\nthere is no such rule and \\isacom{proof} would fail.\n\\end{warn}\nIn the \\isacom{have} step the assumption \\noquotes{@{prop[source]\"surj f\"}} is now\nreferenced by its name \\s\\. The duplication of \\noquotes{@{prop[source]\"surj f\"}} in the\nabove proofs (once in the statement of the lemma, once in its proof) has been\neliminated.\n\nStating a lemma with \\isacom{assumes}-\\isacom{shows} implicitly introduces the\nname \\indexed{\\assms\\}{assms} that stands for the list of all assumptions. You can refer\nto individual assumptions by \\assms(1)\\, \\assms(2)\\, etc.,\nthus obviating the need to name them individually.\n\n\\section{Proof Patterns}\n\nWe show a number of important basic proof patterns. Many of them arise from\nthe rules of natural deduction that are applied by \\isacom{proof} by\ndefault. The patterns are phrased in terms of \\isacom{show} but work for\n\\isacom{have} and \\isacom{lemma}, too.\n\n\\ifsem\\else\n\\subsection{Logic}\n\\fi\n\nWe start with two forms of \\concept{case analysis}:\nstarting from a formula \\P\\ we have the two cases \\P\\ and\n\\<^prop>\\~P\\, and starting from a fact \\<^prop>\\P \\ Q\\\nwe have the two cases \\P\\ and \\Q\\:\n\\text_raw\\\n\\begin{tabular}{@ {}ll@ {}}\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n\\\n(*<*)lemma \"R\" proof-(*>*)\nshow \"R\"\nproof cases\n assume \"P\"\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"R\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nnext\n assume \"\\ P\"\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"R\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nqed(*<*)oops(*>*)\ntext_raw \\}\n\\end{minipage}\\index{cases@\\cases\\}\n&\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n\\\n(*<*)lemma \"R\" proof-(*>*)\nhave \"P \\ Q\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nthen show \"R\"\nproof\n assume \"P\"\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"R\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nnext\n assume \"Q\"\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"R\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nqed(*<*)oops(*>*)\n\ntext_raw \\}\n\\end{minipage}\n\\end{tabular}\n\\medskip\n\\begin{isamarkuptext}%\nHow to prove a logical equivalence:\n\\end{isamarkuptext}%\n\\isa{%\n\\\n(*<*)lemma \"P\\Q\" proof-(*>*)\nshow \"P \\ Q\"\nproof\n assume \"P\"\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"Q\" (*<*)sorry(*>*) text_raw\\\\ \\isasymproof\\\\\\\nnext\n assume \"Q\"\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"P\" (*<*)sorry(*>*) text_raw\\\\ \\isasymproof\\\\\\\nqed(*<*)qed(*>*)\ntext_raw \\}\n\\medskip\n\\begin{isamarkuptext}%\nProofs by contradiction (@{thm[source] ccontr} stands for ``classical contradiction''):\n\\end{isamarkuptext}%\n\\begin{tabular}{@ {}ll@ {}}\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n\\\n(*<*)lemma \"\\ P\" proof-(*>*)\nshow \"\\ P\"\nproof\n assume \"P\"\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"False\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nqed(*<*)oops(*>*)\n\ntext_raw \\}\n\\end{minipage}\n&\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n\\\n(*<*)lemma \"P\" proof-(*>*)\nshow \"P\"\nproof (rule ccontr)\n assume \"\\P\"\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"False\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nqed(*<*)oops(*>*)\n\ntext_raw \\}\n\\end{minipage}\n\\end{tabular}\n\\medskip\n\\begin{isamarkuptext}%\nHow to prove quantified formulas:\n\\end{isamarkuptext}%\n\\begin{tabular}{@ {}ll@ {}}\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n\\\n(*<*)lemma \"\\x. P x\" proof-(*>*)\nshow \"\\x. P(x)\"\nproof\n fix x\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"P(x)\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nqed(*<*)oops(*>*)\n\ntext_raw \\}\n\\end{minipage}\n&\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n\\\n(*<*)lemma \"\\x. P(x)\" proof-(*>*)\nshow \"\\x. P(x)\"\nproof\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"P(witness)\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nqed\n(*<*)oops(*>*)\n\ntext_raw \\}\n\\end{minipage}\n\\end{tabular}\n\\medskip\n\\begin{isamarkuptext}%\nIn the proof of \\noquotes{@{prop[source]\"\\x. P(x)\"}},\nthe step \\indexed{\\isacom{fix}}{fix}~\\x\\ introduces a locally fixed variable \\x\\\ninto the subproof, the proverbial ``arbitrary but fixed value''.\nInstead of \\x\\ we could have chosen any name in the subproof.\nIn the proof of \\noquotes{@{prop[source]\"\\x. P(x)\"}},\n\\witness\\ is some arbitrary\nterm for which we can prove that it satisfies \\P\\.\n\nHow to reason forward from \\noquotes{@{prop[source] \"\\x. P(x)\"}}:\n\\end{isamarkuptext}%\n\\\n(*<*)lemma True proof- assume 1: \"\\x. P x\"(*>*)\nhave \"\\x. P(x)\" (*<*)by(rule 1)(*>*)text_raw\\\\ \\isasymproof\\\\\\\nthen obtain x where p: \"P(x)\" by blast\n(*<*)oops(*>*)\ntext\\\nAfter the \\indexed{\\isacom{obtain}}{obtain} step, \\x\\ (we could have chosen any name)\nis a fixed local\nvariable, and \\p\\ is the name of the fact\n\\noquotes{@{prop[source] \"P(x)\"}}.\nThis pattern works for one or more \\x\\.\nAs an example of the \\isacom{obtain} command, here is the proof of\nCantor's theorem in more detail:\n\\\n\nlemma \"\\ surj(f :: 'a \\ 'a set)\"\nproof\n assume \"surj f\"\n hence \"\\a. {x. x \\ f x} = f a\" by(auto simp: surj_def)\n then obtain a where \"{x. x \\ f x} = f a\" by blast\n hence \"a \\ f a \\ a \\ f a\" by blast\n thus \"False\" by blast\nqed\n\ntext_raw\\\n\\begin{isamarkuptext}%\n\nFinally, how to prove set equality and subset relationship:\n\\end{isamarkuptext}%\n\\begin{tabular}{@ {}ll@ {}}\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n\\\n(*<*)lemma \"A = (B::'a set)\" proof-(*>*)\nshow \"A = B\"\nproof\n show \"A \\ B\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nnext\n show \"B \\ A\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nqed(*<*)qed(*>*)\n\ntext_raw \\}\n\\end{minipage}\n&\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n\\\n(*<*)lemma \"A <= (B::'a set)\" proof-(*>*)\nshow \"A \\ B\"\nproof\n fix x\n assume \"x \\ A\"\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"x \\ B\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nqed(*<*)qed(*>*)\n\ntext_raw \\}\n\\end{minipage}\n\\end{tabular}\n\\begin{isamarkuptext}%\n\n\\ifsem\\else\n\\subsection{Chains of (In)Equations}\n\nIn textbooks, chains of equations (and inequations) are often displayed like this:\n\\begin{quote}\n\\begin{tabular}{@ {}l@ {\\qquad}l@ {}}\n$t_1 = t_2$ & \\isamath{\\,\\langle\\mathit{justification}\\rangle}\\\\\n$\\phantom{t_1} = t_3$ & \\isamath{\\,\\langle\\mathit{justification}\\rangle}\\\\\n\\quad $\\vdots$\\\\\n$\\phantom{t_1} = t_n$ & \\isamath{\\,\\langle\\mathit{justification}\\rangle}\n\\end{tabular}\n\\end{quote}\nThe Isar equivalent is this:\n\n\\begin{samepage}\n\\begin{quote}\n\\isacom{have} \\\"t\\<^sub>1 = t\\<^sub>2\"\\ \\isasymproof\\\\\n\\isacom{also have} \\\"... = t\\<^sub>3\"\\ \\isasymproof\\\\\n\\quad $\\vdots$\\\\\n\\isacom{also have} \\\"... = t\\<^sub>n\"\\ \\isasymproof \\\\\n\\isacom{finally show} \\\"t\\<^sub>1 = t\\<^sub>n\"\\\\ \\texttt{.}\n\\end{quote}\n\\end{samepage}\n\n\\noindent\nThe ``\\...\\'' and ``\\.\\'' deserve some explanation:\n\\begin{description}\n\\item[``\\...\\''] is literally three dots. It is the name of an unknown that Isar\nautomatically instantiates with the right-hand side of the previous equation.\nIn general, if \\this\\ is the theorem \\<^term>\\p t\\<^sub>1 t\\<^sub>2\\ then ``\\...\\''\nstands for \\t\\<^sub>2\\.\n\\item[``\\.\\''] (a single dot) is a proof method that solves a goal by one of the\nassumptions. This works here because the result of \\isacom{finally}\nis the theorem \\mbox{\\t\\<^sub>1 = t\\<^sub>n\\},\n\\isacom{show} \\\"t\\<^sub>1 = t\\<^sub>n\"\\ states the theorem explicitly,\nand ``\\.\\'' proves the theorem with the result of \\isacom{finally}.\n\\end{description}\nThe above proof template also works for arbitrary mixtures of \\=\\, \\\\\\ and \\<\\,\nfor example:\n\\begin{quote}\n\\isacom{have} \\\"t\\<^sub>1 < t\\<^sub>2\"\\ \\isasymproof\\\\\n\\isacom{also have} \\\"... = t\\<^sub>3\"\\ \\isasymproof\\\\\n\\quad $\\vdots$\\\\\n\\isacom{also have} \\\"... \\ t\\<^sub>n\"\\ \\isasymproof \\\\\n\\isacom{finally show} \\\"t\\<^sub>1 < t\\<^sub>n\"\\\\ \\texttt{.}\n\\end{quote}\nThe relation symbol in the \\isacom{finally} step needs to be the most precise one\npossible. In the example above, you must not write \\t\\<^sub>1 \\ t\\<^sub>n\\ instead of \\mbox{\\t\\<^sub>1 < t\\<^sub>n\\}.\n\n\\begin{warn}\nIsabelle only supports \\=\\, \\\\\\ and \\<\\ but not \\\\\\ and \\>\\\nin (in)equation chains (by default).\n\\end{warn}\n\nIf you want to go beyond merely using the above proof patterns and want to\nunderstand what \\isacom{also} and \\isacom{finally} mean, read on.\nThere is an Isar theorem variable called \\calculation\\, similar to \\this\\.\nWhen the first \\isacom{also} in a chain is encountered, Isabelle sets\n\\calculation := this\\. In each subsequent \\isacom{also} step,\nIsabelle composes the theorems \\calculation\\ and \\this\\ (i.e.\\ the two previous\n(in)equalities) using some predefined set of rules including transitivity\nof \\=\\, \\\\\\ and \\<\\ but also mixed rules like \\<^prop>\\\\ x \\ y; y < z \\ \\ x < z\\.\nThe result of this composition is assigned to \\calculation\\. Consider\n\\begin{quote}\n\\isacom{have} \\\"t\\<^sub>1 \\ t\\<^sub>2\"\\ \\isasymproof\\\\\n\\isacom{also} \\isacom{have} \\\"... < t\\<^sub>3\"\\ \\isasymproof\\\\\n\\isacom{also} \\isacom{have} \\\"... = t\\<^sub>4\"\\ \\isasymproof\\\\\n\\isacom{finally show} \\\"t\\<^sub>1 < t\\<^sub>4\"\\\\ \\texttt{.}\n\\end{quote}\nAfter the first \\isacom{also}, \\calculation\\ is \\\"t\\<^sub>1 \\ t\\<^sub>2\"\\,\nand after the second \\isacom{also}, \\calculation\\ is \\\"t\\<^sub>1 < t\\<^sub>3\"\\.\nThe command \\isacom{finally} is short for \\isacom{also from} \\calculation\\.\nTherefore the \\isacom{also} hidden in \\isacom{finally} sets \\calculation\\\nto \\t\\<^sub>1 < t\\<^sub>4\\ and the final ``\\texttt{.}'' succeeds.\n\nFor more information on this style of proof see \\<^cite>\\\"BauerW-TPHOLs01\"\\.\n\\fi\n\n\\section{Streamlining Proofs}\n\n\\subsection{Pattern Matching and Quotations}\n\nIn the proof patterns shown above, formulas are often duplicated.\nThis can make the text harder to read, write and maintain. Pattern matching\nis an abbreviation mechanism to avoid such duplication. Writing\n\\begin{quote}\n\\isacom{show} \\ \\textit{formula} \\(\\\\indexed{\\isacom{is}}{is} \\textit{pattern}\\)\\\n\\end{quote}\nmatches the pattern against the formula, thus instantiating the unknowns in\nthe pattern for later use. As an example, consider the proof pattern for\n\\\\\\:\n\\end{isamarkuptext}%\n\\\n(*<*)lemma \"formula\\<^sub>1 \\ formula\\<^sub>2\" proof-(*>*)\nshow \"formula\\<^sub>1 \\ formula\\<^sub>2\" (is \"?L \\ ?R\")\nproof\n assume \"?L\"\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"?R\" (*<*)sorry(*>*) text_raw\\\\ \\isasymproof\\\\\\\nnext\n assume \"?R\"\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show \"?L\" (*<*)sorry(*>*) text_raw\\\\ \\isasymproof\\\\\\\nqed(*<*)qed(*>*)\n\ntext\\Instead of duplicating \\formula\\<^sub>i\\ in the text, we introduce\nthe two abbreviations \\?L\\ and \\?R\\ by pattern matching.\nPattern matching works wherever a formula is stated, in particular\nwith \\isacom{have} and \\isacom{lemma}.\n\nThe unknown \\indexed{\\?thesis\\}{thesis} is implicitly matched against any goal stated by\n\\isacom{lemma} or \\isacom{show}. Here is a typical example:\\\n\nlemma \"formula\"\nproof -\n text_raw\\\\\\\\mbox{}\\quad$\\vdots$\\\\\\mbox{}\\hspace{-1.4ex}\\\n show ?thesis (*<*)sorry(*>*) text_raw\\\\ \\isasymproof\\\\\\\nqed\n\ntext\\\nUnknowns can also be instantiated with \\indexed{\\isacom{let}}{let} commands\n\\begin{quote}\n\\isacom{let} \\?t\\ = \\\"\\\\textit{some-big-term}\\\"\\\n\\end{quote}\nLater proof steps can refer to \\?t\\:\n\\begin{quote}\n\\isacom{have} \\\"\\\\dots \\?t\\ \\dots\\\"\\\n\\end{quote}\n\\begin{warn}\nNames of facts are introduced with \\name:\\ and refer to proved\ntheorems. Unknowns \\?X\\ refer to terms or formulas.\n\\end{warn}\n\nAlthough abbreviations shorten the text, the reader needs to remember what\nthey stand for. Similarly for names of facts. Names like \\1\\, \\2\\\nand \\3\\ are not helpful and should only be used in short proofs. For\nlonger proofs, descriptive names are better. But look at this example:\n\\begin{quote}\n\\isacom{have} \\ \\x_gr_0: \"x > 0\"\\\\\\\n$\\vdots$\\\\\n\\isacom{from} \\x_gr_0\\ \\dots\n\\end{quote}\nThe name is longer than the fact it stands for! Short facts do not need names;\none can refer to them easily by quoting them:\n\\begin{quote}\n\\isacom{have} \\ \\\"x > 0\"\\\\\\\n$\\vdots$\\\\\n\\isacom{from} \\\\x > 0\\\\ \\dots\\index{$IMP053@\\`...`\\}\n\\end{quote}\nThe outside quotes in \\\\x > 0\\\\ are the standard renderings of the symbols \\texttt{\\textbackslash} and \\texttt{\\textbackslash}.\nThey refer to the fact not by name but ``by value''.\n\n\\subsection{\\indexed{\\isacom{moreover}}{moreover}}\n\\index{ultimately@\\isacom{ultimately}}\n\nSometimes one needs a number of facts to enable some deduction. Of course\none can name these facts individually, as shown on the right,\nbut one can also combine them with \\isacom{moreover}, as shown on the left:\n\\text_raw\\\n\\begin{tabular}{@ {}ll@ {}}\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n\\\n(*<*)lemma \"P\" proof-(*>*)\nhave \"P\\<^sub>1\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nmoreover have \"P\\<^sub>2\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nmoreover\ntext_raw\\\\\\$\\vdots$\\\\\\hspace{-1.4ex}\\(*<*)have \"True\" ..(*>*)\nmoreover have \"P\\<^sub>n\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nultimately have \"P\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\n(*<*)oops(*>*)\n\ntext_raw \\}\n\\end{minipage}\n&\n\\qquad\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n\\\n(*<*)lemma \"P\" proof-(*>*)\nhave lab\\<^sub>1: \"P\\<^sub>1\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nhave lab\\<^sub>2: \"P\\<^sub>2\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\ntext_raw\\\\\\$\\vdots$\\\\\\hspace{-1.4ex}\\\nhave lab\\<^sub>n: \"P\\<^sub>n\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nfrom lab\\<^sub>1 lab\\<^sub>2 text_raw\\\\ $\\dots$\\\\\\\nhave \"P\" (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\n(*<*)oops(*>*)\n\ntext_raw \\}\n\\end{minipage}\n\\end{tabular}\n\\begin{isamarkuptext}%\nThe \\isacom{moreover} version is no shorter but expresses the structure\na bit more clearly and avoids new names.\n\n\\subsection{Local Lemmas}\n\nSometimes one would like to prove some lemma locally within a proof,\na lemma that shares the current context of assumptions but that\nhas its own assumptions and is generalized over its locally fixed\nvariables at the end. This is simply an extension of the basic\n\\indexed{\\isacom{have}}{have} construct:\n\\begin{quote}\n\\indexed{\\isacom{have}}{have} \\B\\\\\n \\indexed{\\isacom{if}}{if} \\name:\\ \\A\\<^sub>1 \\ A\\<^sub>m\\\\\n \\indexed{\\isacom{for}}{for} \\x\\<^sub>1 \\ x\\<^sub>n\\\\\\\n\\isasymproof\n\\end{quote}\nproves \\\\ A\\<^sub>1; \\ ; A\\<^sub>m \\ \\ B\\\nwhere all \\x\\<^sub>i\\ have been replaced by unknowns \\?x\\<^sub>i\\.\nAs an example we prove a simple fact about divisibility on integers.\nThe definition of \\dvd\\ is @{thm dvd_def}.\n\\end{isamarkuptext}%\n\\\n\nlemma fixes a b :: int assumes \"b dvd (a+b)\" shows \"b dvd a\"\nproof -\n have \"\\k'. a = b*k'\" if asm: \"a+b = b*k\" for k\n proof\n show \"a = b*(k - 1)\" using asm by(simp add: algebra_simps)\n qed\n then show ?thesis using assms by(auto simp add: dvd_def)\nqed\n\ntext\\\n\n\\subsection*{Exercises}\n\n\\exercise\nGive a readable, structured proof of the following lemma:\n\\\nlemma assumes T: \"\\x y. T x y \\ T y x\"\n and A: \"\\x y. A x y \\ A y x \\ x = y\"\n and TA: \"\\x y. T x y \\ A x y\" and \"A x y\"\n shows \"T x y\"\n(*<*)oops(*>*)\ntext\\\n\\endexercise\n\n\\exercise\nGive a readable, structured proof of the following lemma:\n\\\nlemma \"\\ys zs. xs = ys @ zs \\\n (length ys = length zs \\ length ys = length zs + 1)\"\n(*<*)oops(*>*)\ntext\\\nHint: There are predefined functions @{const_typ take} and @{const_typ drop}\nsuch that \\take k [x\\<^sub>1,\\] = [x\\<^sub>1,\\,x\\<^sub>k]\\ and\n\\drop k [x\\<^sub>1,\\] = [x\\<^bsub>k+1\\<^esub>,\\]\\. Let sledgehammer find and apply\nthe relevant \\<^const>\\take\\ and \\<^const>\\drop\\ lemmas for you.\n\\endexercise\n\n\n\\section{Case Analysis and Induction}\n\n\\subsection{Datatype Case Analysis}\n\\index{case analysis|(}\n\nWe have seen case analysis on formulas. Now we want to distinguish\nwhich form some term takes: is it \\0\\ or of the form \\<^term>\\Suc n\\,\nis it \\<^term>\\[]\\ or of the form \\<^term>\\x#xs\\, etc. Here is a typical example\nproof by case analysis on the form of \\xs\\:\n\\\n\nlemma \"length(tl xs) = length xs - 1\"\nproof (cases xs)\n assume \"xs = []\"\n thus ?thesis by simp\nnext\n fix y ys assume \"xs = y#ys\"\n thus ?thesis by simp\nqed\n\ntext\\\\index{cases@\\cases\\|(}Function \\tl\\ (''tail'') is defined by @{thm list.sel(2)} and\n@{thm list.sel(3)}. Note that the result type of \\<^const>\\length\\ is \\<^typ>\\nat\\\nand \\<^prop>\\0 - 1 = (0::nat)\\.\n\nThis proof pattern works for any term \\t\\ whose type is a datatype.\nThe goal has to be proved for each constructor \\C\\:\n\\begin{quote}\n\\isacom{fix} \\ \\x\\<^sub>1 \\ x\\<^sub>n\\ \\isacom{assume} \\\"t = C x\\<^sub>1 \\ x\\<^sub>n\"\\\n\\end{quote}\\index{case@\\isacom{case}|(}\nEach case can be written in a more compact form by means of the \\isacom{case}\ncommand:\n\\begin{quote}\n\\isacom{case} \\(C x\\<^sub>1 \\ x\\<^sub>n)\\\n\\end{quote}\nThis is equivalent to the explicit \\isacom{fix}-\\isacom{assume} line\nbut also gives the assumption \\\"t = C x\\<^sub>1 \\ x\\<^sub>n\"\\ a name: \\C\\,\nlike the constructor.\nHere is the \\isacom{case} version of the proof above:\n\\\n(*<*)lemma \"length(tl xs) = length xs - 1\"(*>*)\nproof (cases xs)\n case Nil\n thus ?thesis by simp\nnext\n case (Cons y ys)\n thus ?thesis by simp\nqed\n\ntext\\Remember that \\Nil\\ and \\Cons\\ are the alphanumeric names\nfor \\[]\\ and \\#\\. The names of the assumptions\nare not used because they are directly piped (via \\isacom{thus})\ninto the proof of the claim.\n\\index{case analysis|)}\n\n\\subsection{Structural Induction}\n\\index{induction|(}\n\\index{structural induction|(}\n\nWe illustrate structural induction with an example based on natural numbers:\nthe sum (\\\\\\) of the first \\n\\ natural numbers\n(\\{0..n::nat}\\) is equal to \\mbox{\\<^term>\\n*(n+1) div 2::nat\\}.\nNever mind the details, just focus on the pattern:\n\\\n\nlemma \"\\{0..n::nat} = n*(n+1) div 2\"\nproof (induction n)\n show \"\\{0..0::nat} = 0*(0+1) div 2\" by simp\nnext\n fix n assume \"\\{0..n::nat} = n*(n+1) div 2\"\n thus \"\\{0..Suc n} = Suc n*(Suc n+1) div 2\" by simp\nqed\n\ntext\\Except for the rewrite steps, everything is explicitly given. This\nmakes the proof easily readable, but the duplication means it is tedious to\nwrite and maintain. Here is how pattern\nmatching can completely avoid any duplication:\\\n\nlemma \"\\{0..n::nat} = n*(n+1) div 2\" (is \"?P n\")\nproof (induction n)\n show \"?P 0\" by simp\nnext\n fix n assume \"?P n\"\n thus \"?P(Suc n)\" by simp\nqed\n\ntext\\The first line introduces an abbreviation \\?P n\\ for the goal.\nPattern matching \\?P n\\ with the goal instantiates \\?P\\ to the\nfunction \\<^term>\\\\n. \\{0..n::nat} = n*(n+1) div 2\\. Now the proposition to\nbe proved in the base case can be written as \\?P 0\\, the induction\nhypothesis as \\?P n\\, and the conclusion of the induction step as\n\\?P(Suc n)\\.\n\nInduction also provides the \\isacom{case} idiom that abbreviates\nthe \\isacom{fix}-\\isacom{assume} step. The above proof becomes\n\\\n(*<*)lemma \"\\{0..n::nat} = n*(n+1) div 2\"(*>*)\nproof (induction n)\n case 0\n show ?case by simp\nnext\n case (Suc n)\n thus ?case by simp\nqed\n\ntext\\\nThe unknown \\?case\\\\index{case?@\\?case\\|(} is set in each case to the required\nclaim, i.e., \\?P 0\\ and \\mbox{\\?P(Suc n)\\} in the above proof,\nwithout requiring the user to define a \\?P\\. The general\npattern for induction over \\<^typ>\\nat\\ is shown on the left-hand side:\n\\text_raw\\\n\\begin{tabular}{@ {}ll@ {}}\n\\begin{minipage}[t]{.4\\textwidth}\n\\isa{%\n\\\n(*<*)lemma \"P(n::nat)\" proof -(*>*)\nshow \"P(n)\"\nproof (induction n)\n case 0\n text_raw\\\\\\\\mbox{}\\ \\ $\\vdots$\\\\\\mbox{}\\hspace{-1ex}\\\n show ?case (*<*)sorry(*>*) text_raw\\\\ \\isasymproof\\\\\\\nnext\n case (Suc n)\n text_raw\\\\\\\\mbox{}\\ \\ $\\vdots$\\\\\\mbox{}\\hspace{-1ex}\\\n show ?case (*<*)sorry(*>*) text_raw\\\\ \\isasymproof\\\\\\\nqed(*<*)qed(*>*)\n\ntext_raw \\}\n\\end{minipage}\n&\n\\begin{minipage}[t]{.4\\textwidth}\n~\\\\\n~\\\\\n\\isacom{let} \\?case = \"P(0)\"\\\\\\\n~\\\\\n~\\\\\n~\\\\[1ex]\n\\isacom{fix} \\n\\ \\isacom{assume} \\Suc: \"P(n)\"\\\\\\\n\\isacom{let} \\?case = \"P(Suc n)\"\\\\\\\n\\end{minipage}\n\\end{tabular}\n\\medskip\n\\\ntext\\\nOn the right side you can see what the \\isacom{case} command\non the left stands for.\n\nIn case the goal is an implication, induction does one more thing: the\nproposition to be proved in each case is not the whole implication but only\nits conclusion; the premises of the implication are immediately made\nassumptions of that case. That is, if in the above proof we replace\n\\isacom{show}~\\\"P(n)\"\\ by\n\\mbox{\\isacom{show}~\\\"A(n) \\ P(n)\"\\}\nthen \\isacom{case}~\\0\\ stands for\n\\begin{quote}\n\\isacom{assume} \\ \\0: \"A(0)\"\\\\\\\n\\isacom{let} \\?case = \"P(0)\"\\\n\\end{quote}\nand \\isacom{case}~\\(Suc n)\\ stands for\n\\begin{quote}\n\\isacom{fix} \\n\\\\\\\n\\isacom{assume} \\Suc:\\\n \\begin{tabular}[t]{l}\\\"A(n) \\ P(n)\"\\\\\\\\\"A(Suc n)\"\\\\end{tabular}\\\\\n\\isacom{let} \\?case = \"P(Suc n)\"\\\n\\end{quote}\nThe list of assumptions \\Suc\\ is actually subdivided\ninto \\Suc.IH\\, the induction hypotheses (here \\A(n) \\ P(n)\\),\nand \\Suc.prems\\, the premises of the goal being proved\n(here \\A(Suc n)\\).\n\nInduction works for any datatype.\nProving a goal \\\\ A\\<^sub>1(x); \\; A\\<^sub>k(x) \\ \\ P(x)\\\nby induction on \\x\\ generates a proof obligation for each constructor\n\\C\\ of the datatype. The command \\isacom{case}~\\(C x\\<^sub>1 \\ x\\<^sub>n)\\\nperforms the following steps:\n\\begin{enumerate}\n\\item \\isacom{fix} \\x\\<^sub>1 \\ x\\<^sub>n\\\n\\item \\isacom{assume} the induction hypotheses (calling them \\C.IH\\\\index{IH@\\.IH\\})\n and the premises \\mbox{\\A\\<^sub>i(C x\\<^sub>1 \\ x\\<^sub>n)\\} (calling them \\C.prems\\\\index{prems@\\.prems\\})\n and calling the whole list \\C\\\n\\item \\isacom{let} \\?case = \"P(C x\\<^sub>1 \\ x\\<^sub>n)\"\\\n\\end{enumerate}\n\\index{structural induction|)}\n\n\n\\ifsem\\else\n\\subsection{Computation Induction}\n\\index{rule induction}\n\nIn \\autoref{sec:recursive-funs} we introduced computation induction and\nits realization in Isabelle: the definition\nof a recursive function \\f\\ via \\isacom{fun} proves the corresponding computation\ninduction rule called \\f.induct\\. Induction with this rule looks like in\n\\autoref{sec:recursive-funs}, but now with \\isacom{proof} instead of \\isacom{apply}:\n\\begin{quote}\n\\isacom{proof} (\\induction x\\<^sub>1 \\ x\\<^sub>k rule: f.induct\\)\n\\end{quote}\nJust as for structural induction, this creates several cases, one for each\ndefining equation for \\f\\. By default (if the equations have not been named\nby the user), the cases are numbered. That is, they are started by\n\\begin{quote}\n\\isacom{case} (\\i x y ...\\)\n\\end{quote}\nwhere \\i = 1,...,n\\, \\n\\ is the number of equations defining \\f\\,\nand \\x y ...\\ are the variables in equation \\i\\. Note the following:\n\\begin{itemize}\n\\item\nAlthough \\i\\ is an Isar name, \\i.IH\\ (or similar) is not. You need\ndouble quotes: \"\\i.IH\\\". When indexing the name, write \"\\i.IH\\\"(1),\nnot \"\\i.IH\\(1)\".\n\\item\nIf defining equations for \\f\\ overlap, \\isacom{fun} instantiates them to make\nthem nonoverlapping. This means that one user-provided equation may lead to\nseveral equations and thus to several cases in the induction rule.\nThese have names of the form \"\\i_j\\\", where \\i\\ is the number of the original\nequation and the system-generated \\j\\ indicates the subcase.\n\\end{itemize}\nIn Isabelle/jEdit, the \\induction\\ proof method displays a proof skeleton\nwith all \\isacom{case}s. This is particularly useful for computation induction\nand the following rule induction.\n\\fi\n\n\n\\subsection{Rule Induction}\n\\index{rule induction|(}\n\nRecall the inductive and recursive definitions of even numbers in\n\\autoref{sec:inductive-defs}:\n\\\n\ninductive ev :: \"nat \\ bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\ ev(Suc(Suc n))\"\n\nfun evn :: \"nat \\ bool\" where\n\"evn 0 = True\" |\n\"evn (Suc 0) = False\" |\n\"evn (Suc(Suc n)) = evn n\"\n\ntext\\We recast the proof of \\<^prop>\\ev n \\ evn n\\ in Isar. The\nleft column shows the actual proof text, the right column shows\nthe implicit effect of the two \\isacom{case} commands:\\text_raw\\\n\\begin{tabular}{@ {}l@ {\\qquad}l@ {}}\n\\begin{minipage}[t]{.5\\textwidth}\n\\isa{%\n\\\n\nlemma \"ev n \\ evn n\"\nproof(induction rule: ev.induct)\n case ev0\n show ?case by simp\nnext\n case evSS\n\n\n\n thus ?case by simp\nqed\n\ntext_raw \\}\n\\end{minipage}\n&\n\\begin{minipage}[t]{.5\\textwidth}\n~\\\\\n~\\\\\n\\isacom{let} \\?case = \"evn 0\"\\\\\\\n~\\\\\n~\\\\\n\\isacom{fix} \\n\\\\\\\n\\isacom{assume} \\evSS:\\\n \\begin{tabular}[t]{l} \\\"ev n\"\\\\\\\\\"evn n\"\\\\end{tabular}\\\\\n\\isacom{let} \\?case = \"evn(Suc(Suc n))\"\\\\\\\n\\end{minipage}\n\\end{tabular}\n\\medskip\n\\\ntext\\\nThe proof resembles structural induction, but the induction rule is given\nexplicitly and the names of the cases are the names of the rules in the\ninductive definition.\nLet us examine the two assumptions named @{thm[source]evSS}:\n\\<^prop>\\ev n\\ is the premise of rule @{thm[source]evSS}, which we may assume\nbecause we are in the case where that rule was used; \\<^prop>\\evn n\\\nis the induction hypothesis.\n\\begin{warn}\nBecause each \\isacom{case} command introduces a list of assumptions\nnamed like the case name, which is the name of a rule of the inductive\ndefinition, those rules now need to be accessed with a qualified name, here\n@{thm[source] ev.ev0} and @{thm[source] ev.evSS}.\n\\end{warn}\n\nIn the case @{thm[source]evSS} of the proof above we have pretended that the\nsystem fixes a variable \\n\\. But unless the user provides the name\n\\n\\, the system will just invent its own name that cannot be referred\nto. In the above proof, we do not need to refer to it, hence we do not give\nit a specific name. In case one needs to refer to it one writes\n\\begin{quote}\n\\isacom{case} \\(evSS m)\\\n\\end{quote}\nlike \\isacom{case}~\\(Suc n)\\ in earlier structural inductions.\nThe name \\m\\ is an arbitrary choice. As a result,\ncase @{thm[source] evSS} is derived from a renamed version of\nrule @{thm[source] evSS}: \\ev m \\ ev(Suc(Suc m))\\.\nHere is an example with a (contrived) intermediate step that refers to \\m\\:\n\\\n\nlemma \"ev n \\ evn n\"\nproof(induction rule: ev.induct)\n case ev0 show ?case by simp\nnext\n case (evSS m)\n have \"evn(Suc(Suc m)) = evn m\" by simp\n thus ?case using `evn m` by blast\nqed\n\ntext\\\n\\indent\nIn general, let \\I\\ be a (for simplicity unary) inductively defined\npredicate and let the rules in the definition of \\I\\\nbe called \\rule\\<^sub>1\\, \\dots, \\rule\\<^sub>n\\. A proof by rule\ninduction follows this pattern:\\index{inductionrule@\\induction ... rule:\\}\n\\\n\n(*<*)\ninductive I where rule\\<^sub>1: \"I()\" | rule\\<^sub>2: \"I()\" | rule\\<^sub>n: \"I()\"\nlemma \"I x \\ P x\" proof-(*>*)\nshow \"I x \\ P x\"\nproof(induction rule: I.induct)\n case rule\\<^sub>1\n text_raw\\\\\\[-.4ex]\\mbox{}\\ \\ $\\vdots$\\\\[-.4ex]\\mbox{}\\hspace{-1ex}\\\n show ?case (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nnext\n text_raw\\\\\\[-.4ex]$\\vdots$\\\\[-.4ex]\\mbox{}\\hspace{-1ex}\\\n(*<*)\n case rule\\<^sub>2\n show ?case sorry\n(*>*)\nnext\n case rule\\<^sub>n\n text_raw\\\\\\[-.4ex]\\mbox{}\\ \\ $\\vdots$\\\\[-.4ex]\\mbox{}\\hspace{-1ex}\\\n show ?case (*<*)sorry(*>*)text_raw\\\\ \\isasymproof\\\\\\\nqed(*<*)qed(*>*)\n\ntext\\\nOne can provide explicit variable names by writing\n\\isacom{case}~\\(rule\\<^sub>i x\\<^sub>1 \\ x\\<^sub>k)\\, thus renaming the first \\k\\\nfree variables in rule \\i\\ to \\x\\<^sub>1 \\ x\\<^sub>k\\,\ngoing through rule \\i\\ from left to right.\n\n\\subsection{Assumption Naming}\n\\label{sec:assm-naming}\n\nIn any induction, \\isacom{case}~\\name\\ sets up a list of assumptions\nalso called \\name\\, which is subdivided into three parts:\n\\begin{description}\n\\item[\\name.IH\\]\\index{IH@\\.IH\\} contains the induction hypotheses.\n\\item[\\name.hyps\\]\\index{hyps@\\.hyps\\} contains all the other hypotheses of this case in the\ninduction rule. For rule inductions these are the hypotheses of rule\n\\name\\, for structural inductions these are empty.\n\\item[\\name.prems\\]\\index{prems@\\.prems\\} contains the (suitably instantiated) premises\nof the statement being proved, i.e., the \\A\\<^sub>i\\ when\nproving \\\\ A\\<^sub>1; \\; A\\<^sub>n \\ \\ A\\.\n\\end{description}\n\\begin{warn}\nProof method \\induct\\ differs from \\induction\\\nonly in this naming policy: \\induct\\ does not distinguish\n\\IH\\ from \\hyps\\ but subsumes \\IH\\ under \\hyps\\.\n\\end{warn}\n\nMore complicated inductive proofs than the ones we have seen so far\noften need to refer to specific assumptions --- just \\name\\ or even\n\\name.prems\\ and \\name.IH\\ can be too unspecific.\nThis is where the indexing of fact lists comes in handy, e.g.,\n\\name.IH(2)\\ or \\name.prems(1-2)\\.\n\n\\subsection{Rule Inversion}\n\\label{sec:rule-inversion}\n\\index{rule inversion|(}\n\nRule inversion is case analysis of which rule could have been used to\nderive some fact. The name \\conceptnoidx{rule inversion} emphasizes that we are\nreasoning backwards: by which rules could some given fact have been proved?\nFor the inductive definition of \\<^const>\\ev\\, rule inversion can be summarized\nlike this:\n@{prop[display]\"ev n \\ n = 0 \\ (\\k. n = Suc(Suc k) \\ ev k)\"}\nThe realisation in Isabelle is a case analysis.\nA simple example is the proof that \\<^prop>\\ev n \\ ev (n - 2)\\. We\nalready went through the details informally in \\autoref{sec:Logic:even}. This\nis the Isar proof:\n\\\n(*<*)\nnotepad\nbegin fix n\n(*>*)\n assume \"ev n\"\n from this have \"ev(n - 2)\"\n proof cases\n case ev0 thus \"ev(n - 2)\" by (simp add: ev.ev0)\n next\n case (evSS k) thus \"ev(n - 2)\" by (simp add: ev.evSS)\n qed\n(*<*)\nend\n(*>*)\n\ntext\\The key point here is that a case analysis over some inductively\ndefined predicate is triggered by piping the given fact\n(here: \\isacom{from}~\\this\\) into a proof by \\cases\\.\nLet us examine the assumptions available in each case. In case \\ev0\\\nwe have \\n = 0\\ and in case \\evSS\\ we have \\<^prop>\\n = Suc(Suc k)\\\nand \\<^prop>\\ev k\\. In each case the assumptions are available under the name\nof the case; there is no fine-grained naming schema like there is for induction.\n\nSometimes some rules could not have been used to derive the given fact\nbecause constructors clash. As an extreme example consider\nrule inversion applied to \\<^prop>\\ev(Suc 0)\\: neither rule \\ev0\\ nor\nrule \\evSS\\ can yield \\<^prop>\\ev(Suc 0)\\ because \\Suc 0\\ unifies\nneither with \\0\\ nor with \\<^term>\\Suc(Suc n)\\. Impossible cases do not\nhave to be proved. Hence we can prove anything from \\<^prop>\\ev(Suc 0)\\:\n\\\n(*<*)\nnotepad begin fix P\n(*>*)\n assume \"ev(Suc 0)\" then have P by cases\n(*<*)\nend\n(*>*)\n\ntext\\That is, \\<^prop>\\ev(Suc 0)\\ is simply not provable:\\\n\nlemma \"\\ ev(Suc 0)\"\nproof\n assume \"ev(Suc 0)\" then show False by cases\nqed\n\ntext\\Normally not all cases will be impossible. As a simple exercise,\nprove that \\mbox{\\<^prop>\\\\ ev(Suc(Suc(Suc 0)))\\.}\n\n\\subsection{Advanced Rule Induction}\n\\label{sec:advanced-rule-induction}\n\nSo far, rule induction was always applied to goals of the form \\I x y z \\ \\\\\nwhere \\I\\ is some inductively defined predicate and \\x\\, \\y\\, \\z\\\nare variables. In some rare situations one needs to deal with an assumption where\nnot all arguments \\r\\, \\s\\, \\t\\ are variables:\n\\begin{isabelle}\n\\isacom{lemma} \\\"I r s t \\ \\\"\\\n\\end{isabelle}\nApplying the standard form of\nrule induction in such a situation will lead to strange and typically unprovable goals.\nWe can easily reduce this situation to the standard one by introducing\nnew variables \\x\\, \\y\\, \\z\\ and reformulating the goal like this:\n\\begin{isabelle}\n\\isacom{lemma} \\\"I x y z \\ x = r \\ y = s \\ z = t \\ \\\"\\\n\\end{isabelle}\nStandard rule induction will work fine now, provided the free variables in\n\\r\\, \\s\\, \\t\\ are generalized via \\arbitrary\\.\n\nHowever, induction can do the above transformation for us, behind the curtains, so we never\nneed to see the expanded version of the lemma. This is what we need to write:\n\\begin{isabelle}\n\\isacom{lemma} \\\"I r s t \\ \\\"\\\\isanewline\n\\isacom{proof}\\(induction \"r\" \"s\" \"t\" arbitrary: \\ rule: I.induct)\\\\index{inductionrule@\\induction ... rule:\\}\\index{arbitrary@\\arbitrary:\\}\n\\end{isabelle}\nLike for rule inversion, cases that are impossible because of constructor clashes\nwill not show up at all. Here is a concrete example:\\\n\nlemma \"ev (Suc m) \\ \\ ev m\"\nproof(induction \"Suc m\" arbitrary: m rule: ev.induct)\n fix n assume IH: \"\\m. n = Suc m \\ \\ ev m\"\n show \"\\ ev (Suc n)\"\n proof \\ \\contradiction\\\n assume \"ev(Suc n)\"\n thus False\n proof cases \\ \\rule inversion\\\n fix k assume \"n = Suc k\" \"ev k\"\n thus False using IH by auto\n qed\n qed\nqed\n\ntext\\\nRemarks:\n\\begin{itemize}\n\\item \nInstead of the \\isacom{case} and \\?case\\ magic we have spelled all formulas out.\nThis is merely for greater clarity.\n\\item\nWe only need to deal with one case because the @{thm[source] ev0} case is impossible.\n\\item\nThe form of the \\IH\\ shows us that internally the lemma was expanded as explained\nabove: \\noquotes{@{prop[source]\"ev x \\ x = Suc m \\ \\ ev m\"}}.\n\\item\nThe goal \\<^prop>\\\\ ev (Suc n)\\ may surprise. The expanded version of the lemma\nwould suggest that we have a \\isacom{fix} \\m\\ \\isacom{assume} \\<^prop>\\Suc(Suc n) = Suc m\\\nand need to show \\<^prop>\\\\ ev m\\. What happened is that Isabelle immediately\nsimplified \\<^prop>\\Suc(Suc n) = Suc m\\ to \\<^prop>\\Suc n = m\\ and could then eliminate\n\\m\\. Beware of such nice surprises with this advanced form of induction.\n\\end{itemize}\n\\begin{warn}\nThis advanced form of induction does not support the \\IH\\\nnaming schema explained in \\autoref{sec:assm-naming}:\nthe induction hypotheses are instead found under the name \\hyps\\,\nas they are for the simpler\n\\induct\\ method.\n\\end{warn}\n\\index{induction|)}\n\\index{cases@\\cases\\|)}\n\\index{case@\\isacom{case}|)}\n\\index{case?@\\?case\\|)}\n\\index{rule induction|)}\n\\index{rule inversion|)}\n\n\\subsection*{Exercises}\n\n\n\\exercise\nGive a structured proof by rule inversion:\n\\\n\nlemma assumes a: \"ev(Suc(Suc n))\" shows \"ev n\"\n(*<*)oops(*>*)\n\ntext\\\n\\endexercise\n\n\\begin{exercise}\nGive a structured proof of \\<^prop>\\\\ ev(Suc(Suc(Suc 0)))\\\nby rule inversions. If there are no cases to be proved you can close\na proof immediately with \\isacom{qed}.\n\\end{exercise}\n\n\\begin{exercise}\nRecall predicate \\star\\ from \\autoref{sec:star} and \\iter\\\nfrom Exercise~\\ref{exe:iter}. Prove \\<^prop>\\iter r n x y \\ star r x y\\\nin a structured style; do not just sledgehammer each case of the\nrequired induction.\n\\end{exercise}\n\n\\begin{exercise}\nDefine a recursive function \\elems ::\\ \\<^typ>\\'a list \\ 'a set\\\nand prove \\<^prop>\\x \\ elems xs \\ \\ys zs. xs = ys @ x # zs \\ x \\ elems ys\\.\n\\end{exercise}\n\n\\begin{exercise}\nExtend Exercise~\\ref{exe:cfg} with a function that checks if some\n\\mbox{\\alpha list\\} is a balanced\nstring of parentheses. More precisely, define a \\mbox{recursive} function\n\\balanced :: nat \\ alpha list \\ bool\\ such that \\<^term>\\balanced n w\\\nis true iff (informally) \\S (a\\<^sup>n @ w)\\. Formally, prove that\n\\<^prop>\\balanced n w \\ S (replicate n a @ w)\\ where\n\\<^const>\\replicate\\ \\::\\ \\<^typ>\\nat \\ 'a \\ 'a list\\ is predefined\nand \\<^term>\\replicate n x\\ yields the list \\[x, \\, x]\\ of length \\n\\.\n\\end{exercise}\n\\\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/Doc/Prog_Prove/Isar.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4035668537353745, "lm_q2_score": 0.19930800503802074, "lm_q1q2_score": 0.0804341045174682}} {"text": "(*\n * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *)\n\ntheory TacticTutorial imports\n Main\nbegin\n\n\\ \\\n This is a simple lemma with a boring proof. We're going to replicate it in\n ML.\n\\\nlemma my_conj_commute: \"(A \\ B) = (B \\ A)\"\n apply (rule iffI)\n apply (rule conjI)\n apply (erule conjunct2)\n apply (erule conjunct1)\n apply (erule conjE)\n apply (rule conjI)\n apply assumption\n apply assumption\n done\n\n\\ \\\n The goal of this exercise is *not* for you to have a deep and comprehensive\n understanding of every utility available to you that concerns ML tactic\n internals. The goal is for you to know the basics needed to understand the\n (somewhat sparse) documentation on tactics and how they work, and to not get\n too confused when you see them in the wild.\n\n However, if you *do* come up with an interesting example that demonstrates a\n principle really well, or you discover a cool and useful trick, feel free to\n add it here!\n\\\n\nsection \"Starting a proof\"\nML \\\n \\ \\\n To start off a proof for some statement, we use @{ML \"Goal.init\"}.\n \\\n\n val goal_cterm = @{cterm \"Trueprop ((A \\ B) = (B \\ A))\"};\n val proof_state = Goal.init goal_cterm;\n\n \\ \\\n At this point, @{ML proof_state} looks like this:\n\n Subgoal (Protected) goal\n vvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvv\n (A /\\ B) = (B /\\ A) ==> ((A /\\ B) = (B /\\ A))\n\n This says \"if you prove the subgoal(s), then you have proven the goal\".\n This looks very similar to how theorems are presented; in a theorem, the\n subgoals would be called premises and the goal would be called the\n conclusion.\n\n In fact, in Isabelle a proof state *is* a special kind of theorem: we start\n off with the uncontroversial claim that our goal implies itself, then\n transform that theorem into one with *no* subgoals.\n\n In this tutorial, the section \"Proof States\" outlines the difference\n between a \"normal\" thm and a proof state, specifically what it means for\n the goal to be \"protected\".\n\n This topic is covered in the Isabelle implementation manual, section 4.1\n (\"Goals\").\n \\\n\\\n\nsubsection \"What's this Trueprop thing?\"\nML \\\n \\ \\\n Isabelle lemmas can only talk about results in @{type prop}, but @{term \"x\n = y\"} is in @{type bool} (this distinction is what lets Isabelle handle\n different logics generically, like HOL vs FOL vs ZF. This idea is explained\n in more detail in the old Isabelle introduction, chapter 2 (\"Formalizing\n logical rules in Isabelle\")).\n \n `Trueprop` is a wrapper that does the conversion from a HOL bool to an\n Isabelle prop. However, other things are props by default, and don't need\n the `Trueprop` wrapper.\n \\\n\n val prop_cterm = @{cterm \"(A \\ B) :: prop\"};\n\n val another_prop_cterm = @{cterm \"(A \\ B) :: prop\"}\n\\\n\nsection \"Modifying proof state\"\nML \\\n \\ \\\n To recap, our @{ML proof_state} is currently this:\n \n Subgoal Goal\n vvvvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvv\n ((A /\\ B) = (B /\\ A)) ==> ((A /\\ B) = (B /\\ A))\n \n If you were writing an apply script, you'd use @{method rule} here. The\n equivalent is @{ML resolve_tac}.\n \\\n\n val proof_state =\n proof_state |> resolve_tac @{context} @{thms iffI} 1 |> Seq.hd;\n\n \\ \\\n Now our proof state looks like this:\n\n Subgoal 1 Subgoal 2 Goal\n vvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvv\n (A /\\ B ==> B /\\ A) ==> (B /\\ A ==> A /\\ B) ==> ((A /\\ B) = (B /\\ A))\n\n Our old subgoal is gone, and has been replaced by the subgoals introduced\n by @{thm iffI}.\n \\\n\n \\ \\\n Let's look at the signature of `resolve_tac`:\n\n @{ML \"resolve_tac: Proof.context -> thm list -> int -> tactic\"}\n\n - The proof context is the same mysterious global state that gets passed\n around all over the place in most Isabelle/ML code.\n\n - The thm list is the list of facts that `resolve_tac` will try and use to\n change the subgoal (like @{method rule}).\n\n - The int (`1` in our call) specifies which subgoal to work on. Notice that\n this means we can't use it to modify the final goal.\n\n The result of `resolve_tac` is a tactic, which is a type alias for\n @{ML_type \"thm -> thm Seq.seq\"}. A tactic takes a thm (a proof state) and\n produces a lazy list of new thms (new proof states). We get the first such\n new proof state with @{ML \"Seq.hd\"}\n\n A tactic can succeed or fail.\n - If it failed, the resulting `seq` will be empty.\n - If it succeeded, the `seq` will have one or more new proof states (for\n example, if we passed more than one thm to `resolve_tac`, we'd get a\n result for each successfully resolved thm).\n For now, we're going to use tactics that will return either zero or one new\n proof states.\n\n The signature @{ML_type \"int -> tactic\"} *almost always* means \"a tactic\n that can be applied to a specific subgoal\", but sometimes the int means\n something else.\n\n Now that we have two subgoals, we can see what happens if we use a rule on\n something other than the first subgoal.\n \\\n\n val after_rule_on_2nd_subgoal =\n proof_state |> resolve_tac @{context} @{thms conjI} 2 |> Seq.hd;\n\n \\ \\\n The proof state @{ML after_rule_on_2nd_subgoal} looks like this:\n\n Subgoal 1 (old) Subgoal 2 (new) Subgoal 3 (new) Goal\n vvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvv vvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvvv\n (A /\\ B ==> B /\\ A) ==> (B /\\ A ==> A) ==> (B /\\ A ==> B) ==> ((A /\\ B) = (B /\\ A))\n\n The result isn't very surprising, if you're used to using `rule`.\n `resolve_tac` matched the conclusion of @{thm conjI} against the conclusion\n of the second subgoal of @{ML proof_state}, then asks us to prove the\n premises of @{thm conjI} with the premises of the (original) second\n subgoal.\n \\\n\\\n\nsubsection \"Subgoals and apply scripts\"\n\\ \\\n If we look at the definition of @{method rule}, we see that it uses @{ML\n \"HEADGOAL\"} and @{ML \"Classical.rule_tac\"}.\n - `rule_tac` is like `resolve_tac` plus some extra features.\n - `HEADGOAL` turns a tactic that can be applied to a subgoal\n (@{ML_type \"int -> tactic\"}) into one that only applies to the first\n subgoal.\n\n In fact, most apply-script methods will only use tactics that modify the\n first subgoal. @{method tactic} lets us use an ML tactic in an apply script.\n Let's use it to apply a tactic to the second subgoal.\n\\\nlemma \"X \\ Y \\ A \\ B\"\n apply (erule disjE)\n apply (tactic \\resolve_tac @{context} @{thms conjI} 2\\)\n oops\n\nsubsection \"Elimination and assumption\"\nML \\\n \\ \\\n The equivalent of @{method erule} is @{ML eresolve_tac}. Let's use it to\n solve subgoal 1, continuing from where we left off with @{ML proof_state}.\n \\\n val after_conjI =\n proof_state |> resolve_tac @{context} @{thms conjI} 1 |> Seq.hd;\n\n val after_conjunct2 =\n after_conjI |> eresolve_tac @{context} @{thms conjunct2} 1 |> Seq.hd;\n\n \\ \\\n Notice that, since `eresolve_tac` replaces the matched premise with any\n additional premises of the matched rule, and since `conjunct2` doesn't have\n any such premises, the relevant subgoal has just... disappeared!\n\n Let's deal with the rest of the subgoals, following the original apply\n script.\n \\\n val after_conjunct1 =\n after_conjunct2 |> eresolve_tac @{context} @{thms conjunct1} 1 |> Seq.hd;\n\n val after_conjE =\n after_conjunct1 |> eresolve_tac @{context} @{thms conjE} 1 |> Seq.hd;\n\n val after_conjI =\n after_conjE |> resolve_tac @{context} @{thms conjI} 1 |> Seq.hd;\n\n \\ \\\n The equivalent of @{method assumption} is @{ML assume_tac}.\n \\\n val after_assumptions =\n after_conjI |> assume_tac @{context} 1 |> Seq.hd\n |> assume_tac @{context} 1 |> Seq.hd;\n\\\n\nsubsection \"Finishing off\"\nML \\\n \\ \\\n We're done! Our proof state consists of just the original goal, with no\n subgoals. We can confirm this (and \"unwrap\" our goal from the special\n protection set up by @{ML Goal.init}):\n \\\n val final_thm = Goal.finish @{context} after_assumptions;\n\n \\ \\\n Actually, we're not *quite* done. Our theorem has free variables, whereas a\n global fact must not have free variables that don't refer to something in\n the local context. This means we need to convert our free variables into\n bound ones. Thankfully there's a utility for doing that conversion.\n \\\n \\ \\\n TODO: the 'correct' way to do this is using @{ML \"Variable.export\"}, but\n it's not clear how to actually use that here (what's the \"destination\"\n context?).\n \\\n val final_thm = Thm.forall_intr_frees final_thm;\n\n \\ \\\n We can give our new thm a name so we can refer to it.\n \\\n val add_thm = Local_Theory.note ((@{binding my_cool_ML_thm}, []), [final_thm]) #> snd;\n\n \\ \\\n TODO: these are... magic incantations. What do they do?\n \\\n add_thm |> Named_Target.theory_map |> Theory.setup;\n\\\nthm my_cool_ML_thm\n\nsection Combinators\nML \\\n \\ \\\n Manually passing around these proof state thms, and fetching the first lazy\n result from a tactic, is very annoying. However, there are utilities for\n composing tactics.\n\n We're going to construct a subgoal tactic that deals with the subgoal\n @{term \"A \\ B \\ B \\ A\"}.\n \\\n\n \\ \\\n Here's one way to get a fact by name without using an antiquotation.\n \\\n fun get_thm name =\n Facts.named name |> Proof_Context.get_fact @{context} |> hd;\n\n val [iffI, conjI, conjunct1, conjunct2] =\n [\"iffI\", \"conjI\", \"conjunct1\", \"conjunct2\"] |> map get_thm;\n\n fun resolve thm = resolve_tac @{context} [thm];\n fun eresolve thm = eresolve_tac @{context} [thm];\n\n val solve_commute_conjunct_goal_tac =\n resolve conjI\n THEN' eresolve conjunct2\n THEN' eresolve conjunct1;\n\n \\ \\\n After applying our tactic, we can confirm that the proof state is the same\n as it was after the manual application of these steps (back at\n @{ML after_conjunct1}).\n \\\n val result =\n Goal.init goal_cterm\n |> (HEADGOAL (resolve iffI)\n THEN HEADGOAL (solve_commute_conjunct_goal_tac)) |> Seq.hd;\n\n \\ \\\n If we want to apply our subgoal tactic to both subgoals at once, we can\n replace `HEADGOAL` with `ALLGOALS`. As expected, this will solve both\n subgoals.\n \\\n val result =\n Goal.init goal_cterm\n |> (HEADGOAL (resolve iffI)\n THEN ALLGOALS (solve_commute_conjunct_goal_tac)) |> Seq.hd;\n\\\n\nsection \"Tracing tactics\"\nML \\\n \\ \\\n The tactic @{ML print_tac} prints all the subgoals when it's invoked, then\n passes the proof state through unchanged. Let's use it to follow what our\n @{ML solve_commute_conjunct_goal_tac} is doing.\n \\\n\n \\ \\\n `trace` wraps a subgoal-tactic with messages showing the state before and\n after the tactic was applied (and also indicating which subgoal it's\n applied to). Note that the indicated subgoal might be *removed* in the\n \"after\" state.\n \\\n fun trace msg tac =\n let\n fun msg_before i =\n print_tac @{context} (\"(subgoal \" ^ Int.toString i ^ \") before \" ^ msg);\n val msg_after = K (print_tac @{context} (\"after \" ^ msg));\n in\n msg_before THEN' tac THEN' msg_after\n end\n val tracing_tac =\n (trace \"conjI\" (resolve conjI))\n THEN' (trace \"conjunct2\" (eresolve conjunct2))\n THEN' (trace \"conjunct1\" (eresolve conjunct1));\n\n \\ \\\n The result is very verbose, but also very explicit about what changes and\n when.\n \\\n val result =\n Goal.init goal_cterm\n |> (HEADGOAL (resolve iffI)\n THEN ALLGOALS (tracing_tac)) |> Seq.hd;\n\\\n\nsection \"Proof States\"\nML \\\n \\ \\\n How is @{ML \"Goal.init goal_cterm\"} different to\n @{ML \"Thm.trivial goal_cterm\"}?\n \n `Goal.init` \"protects\" the goal, which prevents most standard tactics from\n changing it (this is good, because otherwise a tactic might suddenly change\n *what you'll finally prove*).\n\n In this tutorial, the section \"Subgoal Restriction\" goes through an example\n of using this \"protection\" feature in a tactic.\n\n This topic is covered in the Isabelle implementation manual, section 4.1\n (\"Goals\").\n \\\n\n val bigger_cterm = @{cterm \"A \\ B \\ B \\ A\"};\n val bigger_goal_thm = Goal.init bigger_cterm;\n val trivial_thm = Thm.trivial bigger_cterm;\n\n \\ \\\n `bigger_goal_thm` has one premise (a subgoal) and one conclusion (the\n goal):\n\n Subgoal Goal (protected)\n vvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvv\n (A /\\ B ==> B /\\ A) ==> (A /\\ B ==> B /\\ A)\n\n Whereas `trivial_thm` has two premises (and hence two \"subgoals\"):\n\n Subgoal 1 Subgoal 2 Goal (unprotected)\n vvvvvvvvvvvvvvvvvvv vvvvvv vvvvvv\n (A /\\ B ==> B /\\ A) ==> A /\\ B ==> B /\\ A\n\n This means that tactics which specify what subgoal they're going to modify\n can modify a part of the proof state that \"should represent\" the goal that\n we want to prove.\n \\\n\\\n\nsection \"Methods and tactics\"\nML \\\n \\ \\\n Dummy ML declarations to make the examples in the table work.\n \\\n val some_ctxt = @{context};\n val some_thms = [];\n\\\n\\ \\\n Here is a rough correspondence between methods and their tactic equivalents.\n The first four \"basic\" tactics are documented in the Isabelle implementation\n manual, section 4.2.1 (\"Resolution and assumption tactics\").\n\n Method | Tactic\n ----------------+-------\n @{method rule} | @{ML resolve_tac}\n @{method erule} | @{ML eresolve_tac}\n @{method frule} | @{ML forward_tac}\n @{method drule} | @{ML dresolve_tac}\n ----------------+-----------------------------------\n @{method subst} | \"subst\" ~ @{ML EqSubst.eqsubst_tac}\n | \"subst (asm)\" ~ @{ML EqSubst.eqsubst_asm_tac}\n ----------------+--------------------------------------------------------------\n @{method simp} | \"simp\" ~ @{ML simp_tac} (only modifies conclusion of subgoal)\n | ~ @{ML asm_simp_tac} (can use assumptions of subgoal, e.g. to do\n | proof by contradiction)\n | \"simp only: some_thms\" ~\n | @{ML \"simp_tac (clear_simpset some_ctxt addsimps some_thms)\"}\n\\\n\nsection \"Method combinators and tactic combinators\"\n\\ \\\n These are documented in the Isabelle implementation manual, section 4.3.1\n (\"Combining tactics\").\n\n Method combinator | Tactic combinator | Subgoal tactic combinator\n ------------------+-------------------+--------------------------\n (a , b) | @{ML THEN} | @{ML THEN'}\n (a | b) | @{ML ORELSE} | @{ML ORELSE'}\n (a ; b) | (none) | @{ML THEN_ALL_NEW}\n a + | @{ML REPEAT1} | (none)\n a ? | @{ML TRY} | (none)\n ------------------+-------------------+--------------------\n a [n] | (see the section on \"Subgoal restriction\")\n\\\n\nsection \"Subgoal restriction\"\nML \\\n \\ \\\n How do we stop a method or tactic from modifying certain subgoals?\n\n The method combinator `[n]` restricts the given method to only modifying\n the first n subgoals. This works by using the same modification protection\n that @{ML \"Goal.init\"} uses.\n\n We usually see `[n]` used with methods that heavily modify proof state in\n ways that are unsafe or hard to predict, such as @{method auto}.\n\n The tactic combinator @{ML Goal.SELECT_GOAL} turns a general tactic into a\n subgoal-targeted tactic, by restricting which subgoals the tactic can\n modify (side note: there's also a combinator @{ML Goal.PREFER_GOAL} which\n merely moves a specific subgoal to the \"front\").\n\n We're going to write a subgoal-targeting version of `auto` *without* using\n `SELECT_GOAL`, to learn how it works. To start, we're going to need to\n understand how to \"protect\" subgoals. We'll begin with a proof state with\n lots of subgoals for us to play with.\n \\\n val cterm = @{cterm \"A \\ B \\ C \\ D \\ E \\ X\"};\n val goal =\n Goal.init cterm\n |> HEADGOAL (REPEAT_ALL_NEW (eresolve_tac @{context} @{thms disjE}))\n |> Seq.hd;\n\n \\ \\\n Our proof state has five subgoals:\n\n Subgoal 1 Subgoal 5\n vvvvvvvvv vvvvvvvvv\n (A ==> X) ==> (B ==> X) ==> (C ==> X) ==> (D ==> X) ==> (E ==> X) ==>\n\n Goal\n vvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n (A \\/ B \\/ C \\/ D \\/ E ==> X)\n\n In the same way that @{ML Goal.init} \"protected\" the final goal to prevent\n us messing with it, we can use @{ML Goal.restrict} to \"protect\" some\n subgoals so we can only modify the rest (hence \"restricting\" us).\n\n In the abstract, `Goal.restrict i n thm` restricts the proof state to only\n be able to modify subgoals i, i + 1, ..., i + (n - 1) (the n subgoals\n starting at subgoal i). In detail, it accomplishes this by rotating the\n first (i - 1) subgoals to the back of the subgoals list, then \"protecting\"\n all but the first n subgoals.\n \\\n val restricted = goal |> Goal.restrict 2 2;\n \\ \\\n This proof state only has two subgoals; the others are \"protected\", and\n can't be modified by most tactics.\n\n Subgoal 2 Subgoal 3\n vvvvvvvvv vvvvvvvvv\n (B ==> X) ==> (C ==> X) ==>\n\n Protected \"goal\"\n vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n Protected Protected Protected Doubly-protected\n subgoal 4 subgoal 5 subgoal 1 actual goal\n vvvvvvvvv vvvvvvvvv vvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n ((D ==> X) ==> (E ==> X) ==> (A ==> X) ==> (A \\/ B \\/ C \\/ D \\/ E ==> X))\n \\\n\n \\ \\\n To restore the previous state, we use @{ML Goal.unrestrict}. In the\n abstract, `Goal.unrestrict i` \"undoes\" `Goal.restrict i n`. In detail, it\n accomplishes this by first removing a layer of protection from the goal,\n then rotating the last (i - 1) subgoals to the front.\n \\\n val unrestricted = restricted |> Goal.unrestrict 2;\n\n \\ \\\n Here, we check that the unrestricted restricted goal is the same as the\n original goal.\n\n This checks that the statements of the two thms are alpha-equivalent.\n \\\n @{assert} ((Thm.full_prop_of unrestricted) aconv (Thm.full_prop_of goal));\n\n \\ \\\n We're now ready to make a subgoal-targeting version of `auto_tac`.\n\n This isn't equivalent to the `[n]` notation (if we wanted to apply auto to\n the first i subgoals, instead of the ith subgoal, we'd replace\n `Goal.restrict i 1` with `Goal.restrict 1 i`), but it's arguably more\n useful.\n \\\n fun subgoal_auto_tac ctxt i =\n PRIMITIVE (Goal.restrict i 1)\n THEN (auto_tac ctxt)\n THEN PRIMITIVE (Goal.unrestrict i);\n\\\n\\ \\\n Let's check that it works.\n\\\nlemma \"A = B \\ B = C \\ C = D \\ D = E \\ E = X \\ A \\ B \\ C \\ D \\ E \\ X\"\n apply (tactic \\HEADGOAL (REPEAT_ALL_NEW (eresolve_tac @{context} @{thms disjE}))\\)\n apply (tactic \\subgoal_auto_tac @{context} 3\\) (* Only removes \"C ==> X\" case. *)\n apply (tactic \\subgoal_auto_tac @{context} 4\\) (* Only removes \"E ==> X\" case. *)\n oops\nML \\\n \\ \\\n For reference, here's the version that uses SELECT_GOAL (the main\n difference is that SELECT_GOAL handles the case where there's only one\n subgoal).\n \\\n fun better_subgoal_auto_tac ctxt = Goal.SELECT_GOAL (auto_tac ctxt);\n\\\nlemma \"A = B \\ B = C \\ C = D \\ D = E \\ E = X \\ A \\ B \\ C \\ D \\ E \\ X\"\n apply (tactic \\HEADGOAL (REPEAT_ALL_NEW (eresolve_tac @{context} @{thms disjE}))\\)\n apply (tactic \\better_subgoal_auto_tac @{context} 3\\) (* Only removes \"C ==> X\" case. *)\n apply (tactic \\better_subgoal_auto_tac @{context} 4\\) (* Only removes \"E ==> X\" case. *)\n oops\n\nend\n", "meta": {"author": "seL4", "repo": "l4v", "sha": "9ba34e269008732d4f89fb7a7e32337ffdd09ff9", "save_path": "github-repos/isabelle/seL4-l4v", "path": "github-repos/isabelle/seL4-l4v/l4v-9ba34e269008732d4f89fb7a7e32337ffdd09ff9/lib/ML_Utils/TacticTutorial.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.15817435671676675, "lm_q1q2_score": 0.07723391194639738}} {"text": "(*\n * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *)\n\n(*<*)\ntheory Chapter1_MinMax\nimports \"AutoCorres.AutoCorres\"\nbegin\n\nexternal_file \"minmax.c\"\n(*>*)\n\nsection \\Introduction\\\n\ntext \\\n\n AutoCorres is a tool that attempts to simplify the formal verification of C\n programs in the Isabelle/HOL theorem prover. It allows C code\n to be automatically abstracted to produce a higher-level functional\n specification.\n\n AutoCorres relies on the C-Parser~\\cite{CParser_download} developed by Michael Norrish\n at NICTA. This tool takes raw C code as input and produces a translation in\n SIMPL~\\cite{Simpl-AFP}, an imperative language written by Norbert Schirmer on top\n of Isabelle. AutoCorres takes this SIMPL code to produce a \"monadic\"\n specification, which is intended to be simpler to reason about in Isabelle.\n The composition of these two tools (AutoCorres applied after the C-Parser) can\n then be used to reason about C programs.\n\n This guide is written for users of Isabelle/HOL, with some knowledge of C, to\n get started proving properties of C programs. Using AutoCorres in conjunction\n with the verification condition generator (VCG) \\texttt{wp}, one\n should be able to do this without an understanding of SIMPL nor of the monadic\n representation produced by AutoCorres. We will see how this is possible in the\n next chapter.\n\n\\\n\nsection \\A First Proof with AutoCorres\\\n\ntext \\\n\n We will now show how to use these tools to prove correctness of some very\n simple C functions.\n\n\\\n\nsubsection \\Two simple functions: \\texttt{min} and \\texttt{max}\\\n\ntext \\\n\n Consider the following two functions, defined in a file \\texttt{minmax.c},\n which (we expect) return the minimum and maximum respectively of two unsigned\n integers.\n\n \\lstinputlisting[language=C, firstline=17]{../../minmax.c}\n\n It is easy to see that \\texttt{min} is correct, but perhaps less obvious why\n \\texttt{max} is correct. AutoCorres will hopefully allow us to prove these\n claims without too much effort.\n\n\\\n\nsubsection \\Invoking the C-parser\\\n\ntext \\\n\n As mentioned earlier, AutoCorres does not handle C code directly. The first\n step is to apply the\n C-Parser\\footnote{\\url{https://ts.data61.csiro.au/software/TS/c-parser}} to\n obtain a SIMPL translation. We do this using the \\texttt{install-C-file}\n command in Isabelle, as shown.\n\n\\\n\ninstall_C_file \"minmax.c\"\n\n(* FIXME: Be consistent with \\texttt and \\emph *)\ntext \\\n\n For every function in the C source file, the C-Parser generates a\n corresponding Isabelle definition. These definitions are placed in an Isabelle\n \"locale\", whose name matches the input filename. For our file \\emph{minmax.c},\n the C-Parser will place definitions in the locale \\emph{minmax}.\\footnote{The\n C-parser uses locales to avoid having to make certain assumptions about the\n behaviour of the linker, such as the concrete addresses of symbols in your\n program.}\n\n For our purposes, we just have to remember to enter the appropriate locale\n before writing our proofs. This is done using the \\texttt{context} keyword in\n Isabelle.\n\n Let's look at the C-Parser's outputs for \\texttt{min} and \\texttt{max}, which\n are contained in the theorems \\texttt{min\\_body\\_def} and \\texttt{max\\_body\\_def}.\n These are simply definitions of the generated names \\emph{min\\_body} and\n \\emph{max\\_body}. We can also see here how our work is wrapped within the\n \\emph{minmax} context.\n\n\\\n\ncontext minmax begin\n\n thm min_body_def\n text \\@{thm [display] min_body_def}\\\n thm max_body_def\n text \\@{thm [display] max_body_def}\\\n\nend\n\ntext \\\n\n The definitions above show us the SIMPL generated for each of the\n functions; we can see that C-parser has translated \\texttt{min} and\n \\texttt{max} very literally and no detail of the C language has been\n omitted. For example:\n\n \\begin{itemize}\n \\item C \\texttt{return} statements have been translated into\n exceptions which are caught at the outside of the\n function's body;\n\n \\item \\emph{Guard} statements are used to ensure that behaviour\n deemed `undefined' by the C standard does not occur. In the\n above functions, we see that a guard statement is emitted\n that ensures that program execution does not hit the end\n of the function, ensuring that we always return a value\n (as is required by all non-\\texttt{void} functions).\n\n \\item Function parameters are modelled as local variables, which\n are setup prior to a function being called. Return variables\n are also modelled as local variables, which are then\n read by the caller.\n \\end{itemize}\n\n While a literal translation of C helps to improve confidence that the\n translation is sound, it does tend to make formal reasoning an arduous\n task.\n\n\\\n\nsubsection \\Invoking AutoCorres\\\n\ntext \\\n\n Now let's use AutoCorres to simplify our functions. This is done using\n the \\texttt{autocorres} command, in a similar manner to the\n \\texttt{install\\_C\\_file} command:\n\n\\\n\nautocorres \"minmax.c\"\n\ntext \\\n\n AutoCorres produces a definition in the \\texttt{minmax} locale\n for each function body produced by the C parser. For example,\n our \\texttt{min} function is defined as follows:\n\n\\\ncontext minmax begin\nthm min'_def\ntext \\@{thm [display] min'_def}\\\n\ntext \\\n\n Each function's definition is named identically to its name in\n C, but with a prime mark (\\texttt{'}) appended. For example,\n our functions \\texttt{min} above was named @{term min'}, while\n the function \\texttt{foo\\_Bar} would be named @{term foo_Bar'}.\n\n AutoCorres does not require you to trust its translation is sound,\n but also emits a \\emph{correspondence} or \\emph{refinement} proof,\n as follows:\n\n\\\n\n(* FIXME *)\n(* thm min_autocorres *)\n\ntext \\\n\n Informally, this theorem states that, assuming the abstract function\n @{term min'} can be proven to not fail for a partciular input, then\n for the associated input, the concrete C SIMPL program also will not\n fault, will always terminate, and will have a corresponding end state\n to the generated abstract program.\n\n For more technical details, see~\\cite{Greenaway_AK_12} and~\\cite{Greenaway_LAK_14}.\n\n\\\n\nsubsection \\Verifying \\texttt{min}\\\n\ntext \\\n\n In the abstracted version of @{term min'}, we can see that AutoCorres\n has simplified away the local variable reads and writes in the\n C-parser translation of \\texttt{min}, simplified away the exception\n throwing and handling code, and also simplified away the unreachable\n guard statement at the end of the function. In fact, @{term min'} has\n been simplified to the point that it exactly matches Isabelle's\n built-in function @{term min}:\n\n\\\nthm min_def\ntext \\@{thm [display] min_def}\\\n\ntext \\\n So, verifying @{term min'} (and by extension, the C function\n \\texttt{min}) should be easy:\n\\\nlemma min'_is_min: \"min' a b = min a b\"\n unfolding min_def min'_def\n by (rule refl)\n\nsubsection \\Verifying \\texttt{max}\\\n\ntext \\\n\n Now we also wish to verify that @{term max'} implements the built-in\n function @{term max}. @{term min'} was nearly too simple to bother\n verifying, but @{term max'} is a bit more complicated. Let's look at\n AutoCorres' output for \\texttt{max}:\n\n\\\nthm max'_def\ntext \\@{thm [display] max'_def}\\\n\ntext \\\n\n At this point, you might still doubt that @{term max'} is indeed\n correct, so perhaps a proof is in order. The basic idea is that\n subtracting from \\texttt{UINT\\_MAX} flips the ordering of unsigned\n ints. We can then use @{term min'} on the flipped numbers to compute\n the maximum.\n\n The next lemma proves that subtracting from \\texttt{UINT\\_MAX} flips\n the ordering. To prove it, we convert all words to @{typ int}'s, which\n does not change the meaning of the statement.\n\n\\\n\n lemma n1_minus_flips_ord:\n \"((a :: word32) \\ b) = ((-1 - a) \\ (-1 - b))\"\n apply (subst word_le_def)+\n apply (subst word_n1_ge [simplified uint_minus_simple_alt])+\n txt \\Now that our statement uses @{typ int}, we can apply Isabelle's built-in \\texttt{arith} method.\\\n apply arith\n done\n\ntext \\\n And now for the main proof:\n\\\n lemma max'_is_max: \"max' a b = max a b\"\n unfolding max'_def min'_def max_def\n using n1_minus_flips_ord\n by force\n\nend\n\ntext \\\n In the next section, we will see how to use AutoCorres to simplify\n larger, more realistic C programs.\n\\\n\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "NICTA", "repo": "l4v", "sha": "3c3514fe99082f7b6a6fb8445b8dfc592ff7f02b", "save_path": "github-repos/isabelle/NICTA-l4v", "path": "github-repos/isabelle/NICTA-l4v/l4v-3c3514fe99082f7b6a6fb8445b8dfc592ff7f02b/tools/autocorres/doc/quickstart/Chapter1_MinMax.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.21469142413688416, "lm_q1q2_score": 0.07715240010815624}} {"text": "(* Title: Containers/Containers_Userguide.thy\n Author: Andreas Lochbihler, ETH Zurich *)\n(*<*)\ntheory Containers_Userguide imports\n Card_Datatype\n List_Proper_Interval\n Containers\nbegin\n(*>*)\nchapter {* User guide *}\ntext_raw {* \\label{chapter:Userguide} *}\n\ntext {*\n This user guide shows how to use and extend the lightweight containers framework (LC).\n For a more theoretical discussion, see \\cite{Lochbihler2013ITP}.\n This user guide assumes that you are familiar with refinement in the code generator \\cite{HaftmannBulwahn2013codetut,HaftmannKrausKuncarNipkow2013ITP}.\n The theory @{theory Containers_Userguide} generates it; so if you want to experiment with the examples, you can find their source code there.\n*}\n\nsection {* Characteristics *}\n\ntext_raw {*\n \\isastyletext\n \\begin{itemize}\n*}\ntext_raw {*\n \\isastyletext\n \\item \\textbf{Separate type classes for code generation}\n \\\\\n LC follows the ideal that type classes for code generation should be separate from the standard type classes in Isabelle.\n LC's type classes are designed such that every type can become an instance, so well-sortedness errors during code generation can always be remedied.\n*}\ntext_raw {*\n \\isastyletext\n \\item \\textbf{Multiple implementations}\n \\\\\n LC supports multiple simultaneous implementations of the same container type.\n For example, the following implements at the same time\n (i)~the set of @{typ bool} as a distinct list of the elements,\n (ii)~@{typ \"int set\"} as a RBT of the elements or as the RBT of the complement, and\n (iii)~sets of functions as monad-style lists:\n \\par\n*}\nvalue \"({True}, {1 :: int}, - {2 :: int, 3}, {\\x :: int. x * x, \\y. y + 1})\"\ntext_raw {*\n \\isastyletext\n \\par\n The LC type classes are the key to simultaneously supporting different implementations.\n\n \\item \\textbf{Extensibility}\n \\\\\n The LC framework is designed for being extensible.\n You can add new containers, implementations and element types any time.\n \\end{itemize}\n*}\n\nsection {* Getting started *}\ntext_raw {* \\label{section:getting:started} *}\n\ntext {*\n Add the entry theory @{theory Containers} for LC to the end of your imports.\n This will reconfigure the code generator such that it implements the types @{typ \"'a set\"} for sets and @{typ \"('a, 'b) mapping\"} for maps with one of the data structures supported.\n As with all the theories that adapt the code generator setup, it is important that @{theory Containers} comes at the end of the imports.\n\n Run the following command, e.g., to check that LC works correctly and implements sets of @{typ int}s as red-black trees (RBT):\n*}\n\nvalue \"{1 :: int}\"\n\ntext {*\n This should produce @{value [names_short] \"{1 :: int}\"}.\n Without LC, sets are represented as (complements of) a list of elements, i.e., @{term \"set [1 :: int]\"} in the example.\n*}\n\ntext {*\n If your exported code does not use your own types as elements of sets or maps and you have not declared any code equation for these containers, then your \\isacommand{export{\\isacharunderscore}code} command will use LC to implement @{typ \"'a set\"} and @{typ \"('a, 'b) mapping\"}.\n \n Our running example will be arithmetic expressions.\n The function @{term \"vars e\"} computes the variables that occur in the expression @{term e}\n*}\n\ntype_synonym vname = string\ndatatype expr = Var vname | Lit int | Add expr expr\nfun vars :: \"expr \\ vname set\" where\n \"vars (Var v) = {v}\"\n| \"vars (Lit i) = {}\"\n| \"vars (Add e\\<^sub>1 e\\<^sub>2) = vars e\\<^sub>1 \\ vars e\\<^sub>2\"\n\nvalue \"vars (Var ''x'')\"\n\ntext {*\n To illustrate how to deal with type variables, we will use the following variant where variable names are polymorphic:\n*}\n\ndatatype 'a expr' = Var' 'a | Lit' int | Add' \"'a expr'\" \"'a expr'\"\nfun vars' :: \"'a expr' \\ 'a set\" where\n \"vars' (Var' v) = {v}\"\n| \"vars' (Lit' i) = {}\"\n| \"vars' (Add' e\\<^sub>1 e\\<^sub>2) = vars' e\\<^sub>1 \\ vars' e\\<^sub>2\"\n\nvalue \"vars' (Var' (1 :: int))\"\n\nsection {* New types as elements *}\n\ntext {*\n This section explains LC's type classes and shows how to instantiate them.\n If you want to use your own types as the elements of sets or the keys of maps, you must instantiate up to eight type classes: @{class ceq} (\\S\\ref{subsection:ceq}), @{class corder} (\\S\\ref{subsection:corder}), @{class set_impl} (\\S\\ref{subsection:set_impl}), @{class mapping_impl} (\\S\\ref{subsection:mapping_impl}), @{class cenum} (\\S\\ref{subsection:cenum}), @{class finite_UNIV} (\\S\\ref{subsection:finite_UNIV}), @{class card_UNIV} (\\S\\ref{subsection:card_UNIV}), and @{class cproper_interval} (\\S\\ref{subsection:cproper_interval}).\n Otherwise, well-sortedness errors like the following will occur:\n\\begin{verbatim}\n*** Wellsortedness error:\n*** Type expr not of sort {ceq,corder}\n*** No type arity expr :: ceq\n*** At command \"value\"\n\\end{verbatim}\n\n In detail, the sort requirements on the element type @{typ \"'a\"} are:\n \\begin{itemize}\n \\item @{class ceq} (\\S\\ref{subsection:ceq}), @{class corder} (\\S\\ref{subsection:corder}), and @{class set_impl} (\\S\\ref{subsection:set_impl}) for @{typ \"'a set\"} in general\n \\item @{class cenum} (\\S\\ref{subsection:cenum}) for set comprehensions @{term \"{x. P x}\"},\n \\item @{class card_UNIV}, @{class cproper_interval} for @{typ \"'a set set\"} and any deeper nesting of sets (\\S\\ref{subsection:card_UNIV}),%\n \\footnote{%\n These type classes are only required for set complements (see \\S\\ref{subsection:well:sortedness}).\n }\n and\n \\item @{class equal},%\n \\footnote{%\n We deviate here from the strict separation of type classes, because it does not make sense to store types in a map on which we do not have equality, because the most basic operation @{term \"Mapping.lookup\"} inherently requires equality.\n }\n @{class corder} (\\S\\ref{subsection:corder}) and @{class mapping_impl} (\\S\\ref{subsection:mapping_impl}) for @{typ \"('a, 'b) mapping\"}.\n \\end{itemize}\n*}\n\nsubsection {* Equality testing *}\ntext_raw {* \\label{subsection:ceq} *}\n\n(*<*)context fixes dummy :: \"'a :: {cenum, ceq, corder, set_impl, mapping_impl}\" begin(*>*)\ntext {*\n The type class @{class ceq} defines the operation @{term [source] \"CEQ('a) :: ('a \\ 'a \\ bool) option\" } for testing whether two elements are equal.%\n \\footnote{%\n Technically, the type class @{class ceq} defines the operation @{term [source] ceq}.\n As usage often does not fully determine @{term [source] ceq}'s type, we use the notation @{term \"CEQ('a)\"} that explicitly mentions the type.\n In detail, @{term \"CEQ('a)\"} is translated to @{term [source] \"CEQ('a) :: ('a \\ 'a \\ bool) option\" } including the type constraint.\n We do the same for the other type class operators:\n @{term \"CORDER('a)\"} constrains the operation @{term [source] corder} (\\S\\ref{subsection:corder}), \n @{term [source] \"SET_IMPL('a)\"} constrains the operation @{term [source] set_impl}, (\\S\\ref{subsection:set_impl}),\n @{term [source] \"MAPPING_IMPL('a)\"} (constrains the operation @{term [source] mapping_impl}, (\\S\\ref{subsection:mapping_impl}), and\n @{term \"CENUM('a)\"} constrains the operation @{term [source] cenum}, \\S\\ref{subsection:cenum}.\n }\n The test is embedded in an @{text option} value to allow for types that do not support executable equality test such as @{typ \"'a \\ 'b\"}.\n Whenever possible, @{term \"CEQ('a)\"} should provide an executable equality operator.\n Otherwise, membership tests on such sets will raise an exception at run-time.\n\n For data types, the @{text derive} command can automatically instantiates of @{class ceq},\n we only have to tell it whether an equality operation should be provided or not (parameter @{text no}).\n*}\n(*<*)end(*>*)\n\nderive (eq) ceq expr\n\ndatatype example = Example\nderive (no) ceq example\n\ntext {*\n In the remainder of this subsection, we look at how to manually instantiate a type for @{class ceq}.\n First, the simple case of a type constructor @{text simple_tycon} without parameters that already is an instance of @{class equal}:\n*}\ntypedecl simple_tycon\naxiomatization where simple_tycon_equal: \"OFCLASS(simple_tycon, equal_class)\"\ninstance simple_tycon :: equal by (rule simple_tycon_equal)\n\ninstantiation simple_tycon :: ceq begin\ndefinition \"CEQ(simple_tycon) = Some op =\"\ninstance by(intro_classes)(simp add: ceq_simple_tycon_def)\nend\n\ntext {*\n For polymorphic types, this is a bit more involved, as the next example with @{typ \"'a expr'\"} illustrates (note that we could have delegated all this to @{text derive}). \n First, we need an operation that implements equality tests with respect to a given equality operation on the polymorphic type.\n For data types, we can use the relator which the transfer package (method @{text transfer}) requires and the BNF package generates automatically.\n As we have used the old datatype package for @{typ \"'a expr'\"}, we must define it manually:\n*}\n\ncontext fixes R :: \"'a \\ 'b \\ bool\" begin\nfun expr'_rel :: \"'a expr' \\ 'b expr' \\ bool\"\nwhere\n \"expr'_rel (Var' v) (Var' v') \\ R v v'\"\n| \"expr'_rel (Lit' i) (Lit' i') \\ i = i'\"\n| \"expr'_rel (Add' e\\<^sub>1 e\\<^sub>2) (Add' e\\<^sub>1' e\\<^sub>2') \\ expr'_rel e\\<^sub>1 e\\<^sub>1' \\ expr'_rel e\\<^sub>2 e\\<^sub>2'\"\n| \"expr'_rel _ _ \\ False\"\nend\n\ntext {* If we give HOL equality as parameter, the relator is equality: *}\n\nlemma expr'_rel_eq: \"expr'_rel op = e\\<^sub>1 e\\<^sub>2 \\ e\\<^sub>1 = e\\<^sub>2\"\nby(induct e\\<^sub>1 e\\<^sub>2 rule: expr'_rel.induct) simp_all\ntext {*\n Then, the instantiation is again canonical:\n*}\ninstantiation expr' :: (ceq) ceq begin\ndefinition\n \"CEQ('a expr') =\n (case ID CEQ('a) of None \\ None | Some eq \\ Some (expr'_rel eq))\"\ninstance\n by(intro_classes)\n (auto simp add: ceq_expr'_def expr'_rel_eq[abs_def] \n dest: Collection_Eq.ID_ceq \n split: option.split_asm)\nend\n(*<*)context fixes dummy :: \"'a :: ceq\" begin(*>*)\ntext {*\n Note the following two points:\n First, the instantiation should avoid to use @{term \"op =\"} on terms of the polymorphic type.\n This keeps the LC framework separate from the type class @{class equal}, i.e., every choice of @{typ \"'a\"}\n in @{typ \"'a expr'\"} can be of sort @{class \"ceq\"}.\n The easiest way to achieve this is to obtain the equality test from @{term \"CEQ('a)\"}.\n Second, we use @{term \"ID CEQ('a)\"} instead of @{term \"CEQ('a)\"}.\n In proofs, we want that the simplifier uses assumptions like @{text \"CEQ('a) = Some \\\"} for rewriting.\n However, @{term \"CEQ('a)\"} is a nullary constant, so the simplifier reverses such an equation, i.e., it only rewrites @{text \"Some \\\"} to @{term \"CEQ('a :: ceq)\"}.\n Applying the identity function @{term \"ID\"} to @{term \"CEQ('a :: ceq)\"} avoids this, and the code generator eliminates all occurrences of @{term \"ID\"}.\n Although @{thm ID_def} by definition, do not use the conventional @{term \"id\"} instead of @{term ID}, because @{term \"id CEQ('a :: ceq)\"} immediately simplifies to @{term \"CEQ('a :: ceq)\"}.\n*}\n(*<*)end(*>*)\n\nsubsection {* Ordering *}\ntext_raw {* \\label{subsection:corder} *}\n\n(*<*)context fixes dummy :: \"'a :: {corder, ceq}\" begin(*>*)\ntext {* \n LC takes the order for storing elements in search trees from the type class @{class corder} rather than @{class linorder}, because we cannot instantiate @{class linorder} for some types (e.g., @{typ \"'a set\"} as @{term \"op \\\"} is not linear).\n Similar to @{term \"CEQ('a)\"} in class @{term ceq}, the class @{class corder} specifies an optional linear order @{term [source] \"CORDER('a) :: (('a \\ 'a \\ bool) \\ ('a \\ 'a \\ bool)) option\" }.\n If you cannot or do not want to implement a linear order on your type, you can default to @{term \"None\"}.\n In that case, you will not be able to use your type as elements of sets or as keys in maps implemented by search trees.\n\n If the type is already instantiates @{class linorder} and we wish to use that order also for the search tree, instantiation is again canonical:\n For our data type @{typ expr}, derive does everything!\n*}\n(*<*)end(*>*)\n(*<*);(*>*)\nderive linorder expr\nderive (linorder) corder expr\n(*<*);(*>*)\n\ntext {*\n In general, the pattern for type constructors without parameters looks as follows:\n*}\naxiomatization where simple_tycon_linorder: \"OFCLASS(simple_tycon, linorder_class)\"\ninstance simple_tycon :: linorder by (rule simple_tycon_linorder)\n\ninstantiation simple_tycon :: corder begin\ndefinition \"CORDER(simple_tycon) = Some (op \\, op <)\"\ninstance by(intro_classes)(simp add: corder_simple_tycon_def, unfold_locales)\nend\n\n(*<*)\nlemma less_expr_iff:\n \"e < Var y \\ (\\x. e = Var x \\ x < y)\"\n \"Var x < e \\ (\\y. e = Var y \\ x < y)\"\n \"e < Lit j \\ (\\x. e = Var x) \\ (\\i. e = Lit i \\ i < j)\"\n \"Lit i < e \\ (\\j. e = Lit j \\ i < j) \\ (\\e1 e2. e = Add e1 e2)\"\n \"e < Add e1' e2' \\ (\\e1 e2. e = Add e1 e2 \\ e1 < e1' \\ e1 = e1' \\ e2 < e2')\"\n \"Add e1 e2 < e \\ (\\e1' e2'. e = Add e1' e2' \\ (e1 < e1' \\ e1 = e1' \\ e2 < e2'))\"\nby(case_tac [!] e)(simp_all add: less_expr_def)\n(*>*)\ntext {* \n For polymorphic types like @{typ \"'a expr'\"}, we should not do everything manually:\n Frist, we must define an order that takes the order on the type variable @{typ \"'a\"} as a parameter.\n This is necessary to maintain the separation between Isabelle/HOL's type classes (like @{class linorder}) and LC's.\n (Alternatively, you can also use the order generator and the same pattern as for @{typ expr}, but you will then never be able to use unorderable variable names in generated code for sets of expressions, e.g., @{typ \"int set expr' set\"} -- if you stick to the separation, such things will still be possible.)\n*}\n\ncontext fixes le_a lt_a :: \"'a \\ 'a \\ bool\" begin\n\nfunction (sequential) less_expr' :: \"'a expr' \\ 'a expr' \\ bool\" (infix \"\\\" 50)\nwhere\n \"Var' x \\ Var' x' \\ lt_a x x'\"\n| \"Var' x \\ _ \\ True\"\n| \"Lit' i \\ Lit' i' \\ i < i'\"\n| \"Lit' _ \\ Add' _ _ \\ True\"\n| \"Add' e\\<^sub>1 e\\<^sub>2 \\ Add' e\\<^sub>1' e\\<^sub>2' \\ \n e\\<^sub>1 \\ e\\<^sub>1' \\ \\ e\\<^sub>1' \\ e\\<^sub>1 \\ e\\<^sub>2 \\ e\\<^sub>2'\"\n -- {* Note that we avoid an explicit equality test here by using @{text \"\\ e\\<^sub>1' \\ e\\<^sub>1\"} *}\n| \"_ \\ _ \\ False\"\nby pat_completeness simp_all\ntermination by size_change\n\ndefinition less_eq_expr' :: \"'a expr' \\ 'a expr' \\ bool\" (infix \"\\\" 50)\nwhere \"e\\<^sub>1 \\ e\\<^sub>2 \\ \\ e\\<^sub>2 \\ e\\<^sub>1\"\n\nlemma expr'_linorder:\n assumes linorder: \"class.linorder le_a lt_a\"\n shows \"class.linorder op \\ op \\\"\nproof -\n interpret linorder le_a lt_a by(rule assms)\n { fix e\\<^sub>1 e\\<^sub>2\n have \"\\ e\\<^sub>1 \\ e\\<^sub>2; e\\<^sub>2 \\ e\\<^sub>1 \\ \\ False\"\n by(induct e\\<^sub>1 e\\<^sub>2 rule: less_expr'.induct) auto }\n hence lt_eq: \"\\e\\<^sub>1 e\\<^sub>2. e\\<^sub>1 \\ e\\<^sub>2 \\ e\\<^sub>1 \\ e\\<^sub>2 \\ \\ e\\<^sub>2\\ e\\<^sub>1\" \n and \"\\e. e \\ e\" unfolding less_eq_expr'_def by auto\n moreover\n { fix e\\<^sub>1 e\\<^sub>2\n have \"\\ e\\<^sub>1 \\ e\\<^sub>2; e\\<^sub>2 \\ e\\<^sub>1 \\ \\ e\\<^sub>1 = e\\<^sub>2\"\n unfolding less_eq_expr'_def \n by(induct e\\<^sub>1 e\\<^sub>2 rule: less_expr'.induct) auto }\n note antisym = this\n moreover\n { fix e\\<^sub>1 e\\<^sub>2\n have \"e\\<^sub>1 \\ e\\<^sub>2 \\ e\\<^sub>2 \\ e\\<^sub>1\" unfolding less_eq_expr'_def\n by(induct e\\<^sub>1 e\\<^sub>2 rule: less_expr'.induct) auto }\n moreover\n { fix e\\<^sub>1 e\\<^sub>2 e\\<^sub>3\n have \"\\ e\\<^sub>1 \\ e\\<^sub>2; e\\<^sub>2 \\ e\\<^sub>3 \\ \\ e\\<^sub>1 \\ e\\<^sub>3\"\n apply(induct e\\<^sub>1 e\\<^sub>2 arbitrary: e\\<^sub>3 rule: less_expr'.induct)\n apply(case_tac [!] e\\<^sub>3)\n apply(simp_all add: less_eq_expr'_def)\n apply(fold less_eq_expr'_def lt_eq[symmetric])\n using antisym by(auto 6 2) }\n ultimately show ?thesis by(unfold_locales)\nqed\n\nend\n\ntext {* \n Now, we are ready to instantiate @{class corder}.\n The instantiation follows the same pattern as for @{class ceq}.\n*}\n\ninstantiation expr' :: (corder) corder begin\ndefinition\n \"CORDER('a expr') =\n (case ID CORDER('a) of None \\ None\n | Some (le_a, lt_a) \\ Some (less_eq_expr' lt_a, less_expr' lt_a))\"\ninstance\n by(intro_classes)\n (auto simp add: corder_expr'_def\n split: option.split_asm prod.split_asm \n intro: expr'_linorder ID_corder)\nend\n\nsubsection {* Heuristics for picking an implementation *}\ntext_raw {* \\label{subsection:set_impl} \\label{subsection:mapping_impl} *}\n(*<*)context fixes dummy :: \"'a :: {ceq, corder, set_impl, mapping_impl}\" begin(*>*)\ntext {*\n Now, we have defined the necessary operations on @{typ expr} and @{typ \"'a expr'\"} to store them in a set \n or use them as the keys in a map.\n But before we can actually do so, we also have to say which data structure to use.\n The type classes @{class set_impl} and @{class mapping_impl} are used for this.\n\n They define the overloaded operations @{term [source] \"SET_IMPL('a) :: ('a, set_impl) phantom\" } and @{term [source] \"MAPPING_IMPL('a) :: ('a, mapping_impl) phantom\"}, respectively.\n The phantom type @{typ \"('a, 'b) phantom\"} from theory @{theory \"Phantom_Type\"} is isomorphic to @{typ \"'b\"}, but formally depends on @{typ \"'a\"}.\n This way, the type class operations meet the requirement that their type contains exactly one type variable.\n The Haskell and ML compiler will get rid of the extra type constructor again.\n\n For sets, you can choose between @{term set_Collect} (characteristic function @{term P} like in @{term \"{x. P x}\"}), @{term set_DList} (distinct list), @{term set_RBT} (red-black tree), and @{term set_Monad} (list with duplicates).\n Additionally, you can define @{term \"set_impl\"} as @{term \"set_Choose\"} which picks the implementation based on the available operations (RBT if @{term \"CORDER('a)\"} provides a linear order, else distinct lists if @{term \"CEQ('a)\"} provides equality testing, and lists with duplicates otherwise).\n @{term \"set_Choose\"} is the safest choice because it picks only a data structure when the required operations are actually available.\n If @{term set_impl} picks a specific implementation, Isabelle does not ensure that all required operations are indeed available.\n\n For maps, the choices are @{term \"mapping_Assoc_List\"} (associative list without duplicates), @{term \"mapping_RBT\"} (red-black tree), and @{term \"mapping_Mapping\"} (closures with function update).\n Again, there is also the @{term \"mapping_Choose\"} heuristics.\n \n For simple cases, @{text derive} can be used again (even if the type is not a data type).\n Consider, e.g., the following instantiations:\n @{typ \"expr set\"} uses RBTs, @{typ \"(expr, _) mapping\"} and @{typ \"'a expr' set\"} use the heuristics, and @{typ \"('a expr', _) mapping\"} uses the same implementation as @{typ \"('a, _) mapping\"}.\n*}\n(*<*)end(*>*)\n\nderive (rbt) set_impl expr\nderive (choose) mapping_impl expr\nderive (choose) set_impl expr'\n\ntext {*\n More complex cases such as taking the implementation preference of a type parameter must be done manually.\n*}\n\ninstantiation expr' :: (mapping_impl) mapping_impl begin\ndefinition\n \"MAPPING_IMPL('a expr') = \n Phantom('a expr') (of_phantom MAPPING_IMPL('a))\"\ninstance ..\nend\n\n(*<*)\nlocale mynamespace begin\ndefinition empty where \"empty = Mapping.empty\" \ndeclare (in -) mynamespace.empty_def [code]\n(*>*)\ntext {* \n To see the effect of the different configurations, consider the following examples where @{term [names_short] \"empty\"} refers to @{term \"Mapping.empty\"}.\n For that, we must disable pretty printing for sets as follows:\n*}\ndeclare (*<*)(in -) (*>*)pretty_sets[code_post del]\ntext {*\n \\begin{center}\n \\small\n \\begin{tabular}{ll}\n \\toprule\n \\isamarkuptrue\\isacommand{value}\\isamarkupfalse\\ {\\isacharbrackleft}code{\\isacharbrackright}\n &\n \\textbf{result}\n \\\\\n \\midrule\n @{term [source] \"{} :: expr set\"}\n &\n @{value [names_short] \"{} :: expr set\"}\n \\\\\n @{term [source] \"empty :: (expr, unit) mapping\"}\n &\n @{value [names_short] \"empty :: (expr, unit) mapping\"}\n \\\\\n \\midrule\n @{term [source] \"{} :: string expr' set\"}\n &\n @{value [names_short] \"{} :: string expr' set\"}\n \\\\\n @{term [source] \"{} :: (nat \\ nat) expr' set\"}\n &\n @{value [names_short] \"{} :: (nat \\ nat) expr' set\"}\n \\\\\n @{term [source] \"{} :: bool expr' set\"}\n &\n @{value [names_short] \"{} :: bool expr' set\"}\n \\\\\n @{term [source] \"empty :: (bool expr', unit) mapping\"}\n &\n @{value [names_short] \"empty :: (bool expr', unit) mapping\"}\n \\\\\n \\bottomrule\n \\end{tabular}\n \\end{center}\n \n For @{typ expr}, @{term mapping_Choose} picks RBTs, because @{term \"CORDER(expr)\"} provides a comparison operation for @{typ \"expr\"}.\n For @{typ \"'a expr'\"}, the effect of @{term set_Choose} is more pronounced:\n @{term \"CORDER(string)\"} is not @{term \"None\"}, so neither is @{term \"CORDER(string expr')\"}, and @{term set_Choose} picks RBTs.\n As @{typ \"nat \\ nat\"} neither provides equality tests (@{class ceq}) nor comparisons (@{class corder}), neither does @{typ \"(nat \\ nat) expr'\"}, so we use lists with duplicates.\n The last two examples show the difference between inheriting a choice and choosing freshly:\n By default, @{typ bool} prefers distinct (associative) lists over RBTs, because there are just two elements.\n As @{typ \"bool expr'\"} enherits the choice for maps from @{typ bool}, an associative list implements @{term [source] \"empty :: (bool expr', unit) mapping\"}.\n For sets, in contrast, @{term \"SET_IMPL('a expr')\"} discards @{typ 'a}'s preferences and picks RBTs, because there is a comparison operation.\n\n Finally, let's enable pretty-printing for sets again:\n*}\ndeclare (*<*)(in -) (*>*)pretty_sets [code_post]\n(*<*)\n (* The following value commands ensure that the code generator executes @{value ...} above,\n I could not find a way to specify [code] to @{value}. *)\n value \"{} :: expr set\"\n value \"empty :: (expr, unit) mapping\"\n value \"{} :: string expr' set\"\n value \"{} :: (nat \\ nat) expr' set\"\n value \"{} :: bool expr' set\"\n value \"empty :: (bool expr', unit) mapping\"\n(*>*)\n(*<*)end(*>*)\n\nsubsection {* Set comprehensions *}\ntext_raw {* \\label{subsection:cenum} *}\n\n(*<*)context fixes dummy :: \"'a :: cenum\" begin(*>*)\ntext {*\n If you use the default code generator setup that comes with Isabelle, set comprehensions @{term [source] \"{x. P x} :: 'a set\"} are only executable if the type @{typ 'a} has sort @{class enum}.\n Internally, Isabelle's code generator transforms set comprehensions into an explicit list of elements which it obtains from the list @{term enum} of all of @{typ \"'a\"}'s elements.\n Thus, the type must be an instance of @{class enum}, i.e., finite in particular.\n For example, @{term \"{c. CHR ''A'' \\ c \\ c \\ CHR ''D''}\"} evaluates to @{term \"set ''ABCD''\"}, the set of the characters A, B, C, and D.\n\n For compatibility, LC also implements such an enumeration strategy, but avoids the finiteness restriction.\n The type class @{class cenum} mimicks @{class enum}, but its single parameter @{term [source] \"cEnum :: ('a list \\ (('a \\ bool) \\ bool) \\ (('a \\ bool) \\ bool)) option\"} combines all of @{class enum}'s parameters, namely a list of all elements, a universal and an existential quantifier.\n @{text \"option\"} ensures that every type can be an instance as @{term \"CENUM('a)\"} can always default to @{term None}.\n \n For types that define @{term \"CENUM('a)\"}, set comprehensions evaluate to a list of their elements.\n Otherwise, set comprehensions are represented as a closure.\n This means that if the generated code contains at least one set comprehension, all element types of a set must instantiate @{class cenum}.\n Infinite types default to @{term None}, and enumerations for finite types are canoncial, see @{theory Collection_Enum} for examples.\n*}\n(*<*)end(*>*)\n\ninstantiation expr :: cenum begin\ndefinition \"CENUM(expr) = None\"\ninstance by(intro_classes)(simp_all add: cEnum_expr_def)\nend\n\nderive (no) cenum expr'\n\ntext_raw {* \\par\\medskip \\isastyletext For example, *}\nvalue \"({b. b = True}, {x. x > Lit 0})\"\ntext_raw {*\n \\isastyletext{}\n yields @{value \"({b. b = True}, {x. x > Lit 0})\"}\n*}\n\ntext {*\n LC keeps complements of such enumerated set comprehensions, i.e., @{term \"- {b. b = True}\"} evaluates to @{value \"- {b. b = True}\"}.\n If you want that the complement operation actually computes the elements of the complements, you have to replace the code equations for @{term uminus} as follows:\n*}\ndeclare Set_uminus_code[code del] Set_uminus_cenum[code]\n(*<*)value \"- {b. b = True}\"(*>*)\ntext {*\n Then, @{term \"- {b. b = True}\"} becomes @{value \"- {b. b = True}\"}, but this applies to all complement invocations.\n For example, @{term [source] \"UNIV :: bool set\"} becomes @{value \"UNIV :: bool set\"}.\n*}\n(*<*)declare Set_uminus_cenum[code del] Set_uminus_code[code](*>*)\n\nsubsection {* Nested sets *}\ntext_raw {* \\label{subsection:finite_UNIV} \\label{subsection:card_UNIV} \\label{subsection:cproper_interval} *}\n\n(*<*)context fixes dummy :: \"'a :: {card_UNIV, cproper_interval}\" begin(*>*)\ntext {*\n To deal with nested sets such as @{typ \"expr set set\"}, the element type must provide three operations from three type classes:\n \\begin{itemize}\n \\item @{class finite_UNIV} from theory @{theory Cardinality} defines the constant @{term [source] \"finite_UNIV :: ('a, bool) phantom\"} which designates whether the type is finite.\n \\item @{class card_UNIV} from theory @{theory Cardinality} defines the constant @{term [source] \"card_UNIV :: ('a, nat) phantom\"} which returns @{term \"CARD('a)\"}, i.e., the number of values in @{typ 'a}.\n If @{typ \"'a\"} is infinite, @{term \"CARD('a) = 0\"}.\n \\item @{class cproper_interval} from theory @{theory Collection_Order} defines the function @{term [source] \"cproper_interval :: 'a option \\ 'a option \\ bool\"}.\n If the type @{typ \"'a\"} is finite and @{term \"CORDER('a)\"} yields a linear order on @{typ \"'a\"}, then @{term \"cproper_interval x y\"} returns whether the open interval between @{term \"x\"} and @{term \"y\"} is non-empty.\n The bound @{term \"None\"} denotes unboundedness.\n \\end{itemize}\n\n Note that the type class @{class finite_UNIV} must not be confused with the type class @{class finite}.\n @{class finite_UNIV} allows the generated code to examine whether a type is finite whereas @{class finite} requires that the type in fact is finite.\n*}\n(*<*)end(*>*)\n\ntext {* \n For datatypes, the theory @{theory Card_Datatype} defines some machinery to assist in proving that the type is (in)finite and has a given number of elements -- see @{file \"Card_Datatype_Ex.thy\"} for examples.\n With this, it is easy to instantiate @{class card_UNIV} for our running examples:\n*}\n\nlemma inj_expr [simp]: \"inj Lit\" \"inj Var\" \"inj Add\" \"inj (Add e)\"\nby(simp_all add: fun_eq_iff inj_on_def)\n\nlemma infinite_UNIV_expr: \"\\ finite (UNIV :: expr set)\"\n including card_datatype\nproof -\n have \"rangeIt (Lit 0) (Add (Lit 0)) \\ UNIV\" by simp\n from finite_subset[OF this] show ?thesis by auto\nqed\n\ninstantiation expr :: card_UNIV begin\ndefinition \"finite_UNIV = Phantom(expr) False\"\ndefinition \"card_UNIV = Phantom(expr) 0\"\ninstance\n by intro_classes\n (simp_all add: finite_UNIV_expr_def card_UNIV_expr_def infinite_UNIV_expr)\nend\n\nlemma inj_expr' [simp]: \"inj Lit'\" \"inj Var'\" \"inj Add'\" \"inj (Add' e)\"\nby(simp_all add: fun_eq_iff inj_on_def)\n\nlemma infinite_UNIV_expr': \"\\ finite (UNIV :: 'a expr' set)\"\n including card_datatype\nproof -\n have \"rangeIt (Lit' 0) (Add' (Lit' 0)) \\ UNIV\" by simp\n from finite_subset[OF this] show ?thesis by auto\nqed\n\ninstantiation expr' :: (type) card_UNIV begin\ndefinition \"finite_UNIV = Phantom('a expr') False\"\ndefinition \"card_UNIV = Phantom('a expr') 0\"\ninstance\n by intro_classes\n (simp_all add: finite_UNIV_expr'_def card_UNIV_expr'_def infinite_UNIV_expr')\nend\n\ntext {*\n As @{typ expr} and @{typ \"'a expr'\"} are infinite, instantiating @{class cproper_interval} is trivial,\n because @{class cproper_interval} only makes assumptions about its parameters for finite types.\n Nevertheless, it is important to actually define @{term cproper_interval}, because the\n code generator requires a code equation.\n*}\n\ninstantiation expr :: cproper_interval begin\ndefinition cproper_interval_expr :: \"expr proper_interval\" \n where \"cproper_interval_expr _ _ = undefined\"\ninstance by(intro_classes)(simp add: infinite_UNIV_expr)\nend\n\ninstantiation expr' :: (corder) cproper_interval begin\ndefinition cproper_interval_expr' :: \"'a expr' proper_interval\" \n where \"cproper_interval_expr' _ _ = undefined\"\ninstance by(intro_classes)(simp add: infinite_UNIV_expr')\nend\n\nsubsubsection {* Instantiation of @{class proper_interval} *}\n\ntext {*\n To illustrate what to do with finite types, we instantiate @{class proper_interval} for @{typ expr}.\n Like @{class corder} relates to @{class linorder}, the class @{class cproper_interval} has a counterpart @{class proper_interval} without the finiteness assumption.\n*}\ninstantiation expr :: proper_interval begin\n\nfun proper_interval_expr :: \"expr option \\ expr option \\ bool\"\nwhere\n \"proper_interval_expr None (Some (Var x)) \\ proper_interval None (Some x)\"\n| \"proper_interval_expr (Some (Var x)) (Some (Var y)) \\ proper_interval (Some x) (Some y)\"\n| \"proper_interval_expr (Some (Lit i)) (Some (Lit j)) \\ proper_interval (Some i) (Some j)\"\n| \"proper_interval_expr (Some (Lit i)) (Some (Var x)) \\ False\"\n| \"proper_interval_expr (Some (Add e1 e2)) (Some (Lit i)) \\ False\"\n| \"proper_interval_expr (Some (Add e1 e2)) (Some (Var x)) \\ False\"\n| \"proper_interval_expr (Some (Add e1 e2)) (Some (Add e1' e2')) \\ \n e1 < e1' \\\n e1 \\ e1' \\ proper_interval_expr (Some e2) (Some e2')\"\n| \"proper_interval_expr _ _ \\ True\"\n\ninstance\nproof(intro_classes)\n fix x y :: expr\n show \"proper_interval None (Some y) = (\\z. z < y)\"\n by(cases y)(auto simp add: less_expr_iff Nil_less_conv_neq_Nil intro: exI[where x=\"''''\"])\n\n { fix x y have \"x < Add x y\" \n by(induct x arbitrary: y)(simp_all add: less_expr_def) }\n note le_Add = this\n thus \"proper_interval (Some x) None = (\\z. x < z)\"\n by(simp add: less_expr_def exI[where x=\"Add x y\"])\n\n note [simp] = less_expr_iff\n\n show \"proper_interval (Some x) (Some y) = (\\z. x < z \\ z < y)\"\n proof(induct \"Some x\" \"Some y\" arbitrary: x y rule: proper_interval_expr.induct)\n case 2\n show ?case by(auto simp add: proper_interval_list_aux_correct)\n next\n case (3 i j)\n show ?case by(auto intro: exI[where x=\"Lit (i + 1)\"])\n next\n case (7 e1 e2 e1' e2')\n thus ?case by(auto intro: le_Add simp add: le_less)\n next\n case (\"8_2\" i e1 e2)\n show ?case by(auto intro: exI[where x=\"Lit (i + 1)\"])\n next\n case (\"8_5\" x i) show ?case\n by(auto intro: exI[where x=\"Var (x @ [undefined])\"] simp add: less_append_same_iff)\n next\n case (\"8_6\" x e1 e2) show ?case\n by(auto intro: exI[where x=\"Lit 0\"])\n next\n case (\"8_7\" i e1 e2) show ?case\n by(auto intro: exI[where x=\"Lit (i + 1)\"])\n next\n case (\"8_10\" x i) show ?case\n by(auto intro: exI[where x=\"Lit (i - 1)\"])\n next\n case (\"8_12\" x e1 e2) show ?case\n by(auto intro: exI[where x=\"Lit 0\"])\n next\n case (\"8_13\" i e1 e2) show ?case\n by(auto intro: exI[where x=\"Lit (i + 1)\"])\n qed auto\nqed simp\nend\n\n(*<*)\nvalue \"{{Lit 1}}\"\nvalue \"{{{Lit 1}}}\"\nvalue \"{{{{Lit 1}}}}\"\n(*>*)\n\nsection {* New implementations for containers *}\ntext_raw {* \\label{section:new:implementation} *}\n\n(*<*)\ntypedecl 'v trie_raw\n(*>*)\n\ntext {*\n This section explains how to add a new implementation for a container type.\n If you do so, please consider to add your implementation to this AFP entry.\n*}\n\nsubsection {* Model and verify the data structure *}\ntext_raw {* \\label{subsection:implement:data:structure} *}\ntext {*\n First, you of course have to define the data structure and verify that it has the required properties.\n As our running example, we use a trie to implement @{typ \"('a, 'b) mapping\"}.\n A trie is a binary tree whose the nodes store the values, the keys are the paths from the root to the given node.\n We use lists of @{typ bool}ans for the keys where the @{typ bool}ean indicates whether we should go to the left or right child.\n\n For brevity, we skip this step and rather assume that the type @{typ \"'v trie_raw\"} of tries has following operations and properties:\n*}\ntype_synonym trie_key = \"bool list\"\naxiomatization\n trie_empty :: \"'v trie_raw\" and\n trie_update :: \"trie_key \\ 'v \\ 'v trie_raw \\ 'v trie_raw\" and\n trie_lookup :: \"'v trie_raw \\ trie_key \\ 'v option\" and\n trie_keys :: \"'v trie_raw \\ trie_key set\"\nwhere trie_lookup_empty: \"trie_lookup trie_empty = Map.empty\"\n and trie_lookup_update: \n \"trie_lookup (trie_update k v t) = (trie_lookup t)(k \\ v)\"\n and trie_keys_dom_lookup: \"trie_keys t = dom (trie_lookup t)\"\n\ntext {*\n This is only a minimal example.\n A full-fledged implementation has to provide more operations and -- for efficiency -- should use more than just @{typ bool}eans for the keys.\n*}\n\n(*<*) (* Implement trie by free term algebra *)\ncode_datatype trie_empty trie_update\nlemmas [code] = trie_lookup_empty trie_lookup_update\n\nlemma trie_keys_empty [code]: \"trie_keys trie_empty = {}\"\nby(simp add: trie_keys_dom_lookup trie_lookup_empty)\n\nlemma trie_keys_update [code]:\n \"trie_keys (trie_update k v t) = insert k (trie_keys t)\"\nby(simp add: trie_keys_dom_lookup trie_lookup_update)\n(*>*)\n\nsubsection {* Generalise the data structure *}\ntext_raw {* \\label{subsection:introduce:type:class} *}\ntext {*\n As @{typ \"('k, 'v) mapping\"} store keys of arbitrary type @{typ \"'k\"}, not just @{typ \"trie_key\"}, we cannot use @{typ \"'v trie_raw\"} directly.\n Instead, we must first convert arbitrary types @{typ \"'k\"} into @{typ \"trie_key\"}.\n Of course, this is not always possbile, but we only have to make sure that we pick tries as implementation only if the types do.\n This is similar to red-black trees which require an order.\n Hence, we introduce a type class to convert arbitrary keys into trie keys.\n We make the conversions optional such that every type can instantiate the type class, just as LC does for @{class ceq} and @{class corder}.\n*}\ntype_synonym 'a cbl = \"(('a \\ bool list) \\ (bool list \\ 'a)) option\"\nclass cbl =\n fixes cbl :: \"'a cbl\"\n assumes inj_to_bl: \"ID cbl = Some (to_bl, from_bl) \\ inj to_bl\"\n and to_bl_inverse: \"ID cbl = Some (to_bl, from_bl) \\ from_bl (to_bl a) = a\"\nbegin\nabbreviation from_bl where \"from_bl \\ snd (the (ID cbl))\"\nabbreviation to_bl where \"to_bl \\ fst (the (ID cbl))\"\nend\n\ntext {*\n It is best to immediately provide the instances for as many types as possible.\n Here, we only present two examples: @{typ unit} provides conversion functions, @{typ \"'a \\ 'b\"} does not.\n*}\ninstantiation unit :: cbl begin\ndefinition \"cbl = Some (\\_. [], \\_. ())\"\ninstance by(intro_classes)(auto simp add: cbl_unit_def ID_Some intro: injI)\nend\n\ninstantiation \"fun\" :: (type, type) cbl begin\ndefinition \"cbl = (None :: ('a \\ 'b) cbl)\"\ninstance by intro_classes(simp_all add: cbl_fun_def ID_None)\nend\n\nsubsection {* Hide the invariants of the data structure *}\ntext_raw {* \\label{subsection:hide:invariants} *}\ntext {*\n Many data structures have invariants on which the operations rely.\n You must hide such invariants in a \\isamarkuptrue\\isacommand{typedef}\\isamarkupfalse{} before connecting to the container, because the code generator cannot handle explicit invariants.\n The type must be inhabited even if the types of the elements do not provide the required operations.\n The easiest way is often to ignore all invariants in that case.\n\n In our example, we require that all keys in the trie represent encoded values.\n*}\ntypedef ('k :: cbl, 'v) trie = \n \"{t :: 'v trie_raw. \n trie_keys t \\ range (to_bl :: 'k \\ trie_key) \\ ID (cbl :: 'k cbl) = None}\"\nproof\n show \"trie_empty \\ ?trie\"\n by(simp add: trie_keys_dom_lookup trie_lookup_empty)\nqed\n\ntext {*\n Next, transfer the operations to the new type.\n The transfer package does a good job here.\n*}\n\nsetup_lifting type_definition_trie -- {* also sets up code generation *}\n\nlift_definition empty :: \"('k :: cbl, 'v) trie\" \n is trie_empty\n by(simp add: trie_keys_empty)\n\nlift_definition lookup :: \"('k :: cbl, 'v) trie \\ 'k \\ 'v option\"\n is \"\\t. trie_lookup t \\ to_bl\" .\n\nlift_definition update :: \"'k \\ 'v \\ ('k :: cbl, 'v) trie \\ ('k, 'v) trie\"\n is \"trie_update \\ to_bl\"\n by(auto simp add: trie_keys_dom_lookup trie_lookup_update)\n\nlift_definition keys :: \"('k :: cbl, 'v) trie \\ 'k set\"\n is \"\\t. from_bl ` trie_keys t\" .\n\ntext {*\n And now we go for the properties.\n Note that some properties hold only if the type class operations are actually provided, i.e., @{term \"cbl \\ None\"} in our example.\n*}\n\nlemma lookup_empty: \"lookup empty = Map.empty\"\nby transfer(simp add: trie_lookup_empty fun_eq_iff)\n\ncontext\n fixes t :: \"('k :: cbl, 'v) trie\"\n assumes ID_cbl: \"ID (cbl :: 'k cbl) \\ None\"\nbegin\n\nlemma lookup_update: \"lookup (update k v t) = (lookup t)(k \\ v)\"\nusing ID_cbl\nby transfer(auto simp add: trie_lookup_update fun_eq_iff dest: inj_to_bl[THEN injD])\n\nlemma keys_conv_dom_lookup: \"keys t = dom (lookup t)\"\nusing ID_cbl\nby transfer(force simp add: trie_keys_dom_lookup to_bl_inverse intro: rev_image_eqI)\n\nend\n\nsubsection {* Connecting to the container *}\ntext_raw {* \\label{subsection:connect:container} *}\ntext {*\n Connecting to the container (@{typ \"('a, 'b) mapping\"} in our example) takes three steps:\n \\begin{enumerate}\n \\item Define a new pseudo-constructor\n \\item Implement the container operations for the new type\n \\item Configure the heuristics to automatically pick an implementation\n \\item Test thoroughly\n \\end{enumerate}\n Thorough testing is particularly important, because Isabelle does not check whether you have implemented all your operations, whether you have configured your heuristics sensibly, nor whether your implementation always terminates.\n*}\n\nsubsubsection {* Define a new pseudo-constructor *}\n\ntext {*\n Define a function that returns the abstract container view for a data structure value, and declare it as a datatype constructor for code generation with \\isamarkuptrue\\isacommand{code{\\isacharunderscore}datatype}\\isamarkupfalse.\n Unfortunately, you have to repeat all existing pseudo-constructors, because there is no way to extract the current set of pseudo-constructors from the code generator.\n We call them pseudo-constructors, because they do not behave like datatype constructors in the logic.\n For example, ours are neither injective nor disjoint.\n*}\n\ndefinition Trie_Mapping :: \"('k :: cbl, 'v) trie \\ ('k, 'v) mapping\" \nwhere [simp, code del]: \"Trie_Mapping t = Mapping.Mapping (lookup t)\"\n\ncode_datatype Assoc_List_Mapping RBT_Mapping Mapping Trie_Mapping\n\nsubsubsection {* Implement the operations *}\n\ntext {*\n Next, you have to prove and declare code equations that implement the container operations for the new implementation.\n Typically, these just dispatch to the operations on the type from \\S\\ref{subsection:hide:invariants}.\n Some operations depend on the type class operations from \\S\\ref{subsection:introduce:type:class} being defined; then, the code equation must check that the operations are indeed defined.\n If not, there is usually no way to implement the operation, so the code should raise an exception.\n Logically, we use the function @{term \"Code.abort\"} of type @{typ \"String.literal \\ (unit \\ 'a) \\ 'a\"} with definition @{term \"\\_ f. f ()\"}, but the generated code raises an exception \\texttt{Fail} with the given message (the unit closure avoids non-termination in strict languages).\n This function gets the exception message and the unit-closure of the equation's left-hand side as argument, because it is then trivial to prove equality.\n\n Again, we only show a small set of operations; a realistic implementation should cover as many as possible.\n*}\ncontext fixes t :: \"('k :: cbl, 'v) trie\" begin\n\nlemma lookup_Trie_Mapping [code]:\n \"Mapping.lookup (Trie_Mapping t) = lookup t\"\n -- {* Lookup does not need the check on @{term cbl},\n because we have defined the pseudo-constructor @{term Trie_Mapping} in terms of @{term \"lookup\"} *}\nby simp(transfer, simp)\n\nlemma update_Trie_Mapping [code]:\n \"Mapping.update k v (Trie_Mapping t) = \n (case ID cbl :: 'k cbl of\n None \\ Code.abort (STR ''update Trie_Mapping: cbl = None'') (\\_. Mapping.update k v (Trie_Mapping t))\n | Some _ \\ Trie_Mapping (update k v t))\"\nby(simp split: option.split add: lookup_update Mapping.update.abs_eq)\n\nlemma keys_Trie_Mapping [code]:\n \"Mapping.keys (Trie_Mapping t) =\n (case ID cbl :: 'k cbl of\n None \\ Code.abort (STR ''keys Trie_Mapping: cbl = None'') (\\_. Mapping.keys (Trie_Mapping t))\n | Some _ \\ keys t)\"\nby(simp add: Mapping.keys.abs_eq keys_conv_dom_lookup split: option.split)\n\nend\n\ntext {*\n These equations do not replace the existing equations for the other constructors, but they do take precedence over them.\n If there is already a generic implementation for an operation @{term \"foo\"}, say @{term \"foo A = gen_foo A\"}, and you prove a specialised equation @{term \"foo (Trie_Mapping t) = trie_foo t\"}, then when you call @{term \"foo\"} on some @{term \"Trie_Mapping t\"}, your equation will kick in.\n LC exploits this sequentiality especially for binary operators on sets like @{term \"op \\\"}, where there are generic implementations and faster specialised ones.\n*}\n\nsubsubsection {* Configure the heuristics *}\n\ntext {*\n Finally, you should setup the heuristics that automatically picks a container implementation based on the types of the elements (\\S\\ref{subsection:set_impl}).\n\n The heuristics uses a type with a single value, e.g., @{typ mapping_impl} with value @{term Mapping_IMPL}, but there is one pseudo-constructor for each container implementation in the generated code.\n All these pseudo-constructors are the same in the logic, but they are different in the generated code.\n Hence, the generated code can distinguish them, but we do not have to commit to anything in the logic.\n This allows to reconfigure and extend the heuristic at any time.\n\n First, define and declare a new pseudo-constructor for the heuristics.\n Again, be sure to redeclare all previous pseudo-constructors.\n*}\ndefinition mapping_Trie :: mapping_impl \nwhere [simp]: \"mapping_Trie = Mapping_IMPL\"\n\ncode_datatype \n mapping_Choose mapping_Assoc_List mapping_RBT mapping_Mapping mapping_Trie\n\ntext {*\n Then, adjust the implementation of the automatic choice.\n For every initial value of the container (such as the empty map or the empty set), there is one new constant (e.g., @{term mapping_empty_choose} and @{term set_empty_choose}) equivalent to it.\n Its code equation, however, checks the available operations from the type classes and picks an appropriate implementation.\n \n For example, the following prefers red-black trees over tries, but tries over associative lists:\n*}\n\nlemma mapping_empty_choose_code [code]:\n \"(mapping_empty_choose :: ('a :: {corder, cbl}, 'b) mapping) =\n (case ID CORDER('a) of Some _ \\ RBT_Mapping RBT_Mapping2.empty\n | None \\\n case ID (cbl :: 'a cbl) of Some _ \\ Trie_Mapping empty \n | None \\ Assoc_List_Mapping DAList.empty)\"\nby(auto split: option.split simp add: DAList.lookup_empty[abs_def] Mapping.empty_def lookup_empty)\n\ntext {*\n There is also a second function for every such initial value that dispatches on the pseudo-constructors for @{typ mapping_impl}.\n This function is used to pick the right implementation for types that specify a preference.\n*}\nlemma mapping_empty_code [code]:\n \"mapping_empty mapping_Trie = Trie_Mapping empty\"\nby(simp add: lookup_empty Mapping.empty_def)\n\ntext {*\n For @{typ \"('k, 'v) mapping\"}, LC also has a function @{term \"mapping_impl_choose2\"} which is given two preferences and returns one (for @{typ \"'a set\"}, it is called @{term \"set_impl_choose2\"}).\n Polymorphic type constructors like @{typ \"'a + 'b\"} use it to pick an implementation based on the preferences of @{typ \"'a\"} and @{typ \"'b\"}.\n By default, it returns @{term mapping_Choose}, i.e., ignore the preferences.\n You should add a code equation like the following that overrides this choice if both preferences are your new data structure:\n*}\n\nlemma mapping_impl_choose2_Trie [code]:\n \"mapping_impl_choose2 mapping_Trie mapping_Trie = mapping_Trie\"\nby(simp add: mapping_Trie_def)\n\ntext {*\n If your new data structure is better than the existing ones for some element type, you should reconfigure the type's preferene.\n As all preferences are logically equal, you can prove (and declare) the appropriate code equation.\n For example, the following prefers tries for keys of type @{typ \"unit\"}:\n*}\n\nlemma mapping_impl_unit_Trie [code]:\n \"MAPPING_IMPL(unit) = Phantom(unit) mapping_Trie\"\nby(simp add: mapping_impl_unit_def)\n\nvalue \"Mapping.empty :: (unit, int) mapping\"\n\ntext {*\n You can also use your new pseudo-constructor with @{text derive} in instantiations, just give its name as option:\n*}\nderive (mapping_Trie) mapping_impl simple_tycon\n\nsection {* Changing the configuration *}\n\ntext {*\n As containers are connected to data structures only by refinement in the code generator, this can always be adapted later on.\n You can add new data structures as explained in \\S\\ref{section:new:implementation}.\n If you want to drop one, you redeclare the remaining pseudo-constructors with \\isamarkuptrue\\isacommand{code{\\isacharunderscore}datatype}\\isamarkupfalse{} and delete all code equations that pattern-match on the obsolete pseudo-constructors.\n The command \\isamarkuptrue\\isacommand{code{\\isacharunderscore}thms}\\isamarkupfalse{} will tell you which constants have such code equations.\n You can also freely adapt the heuristics for picking implementations as described in \\S\\ref{subsection:connect:container}.\n\n One thing, however, you cannot change afterwards, namely the decision whether an element type supports an operation and if so how it does, because this decision is visible in the logic.\n*}\n\nsection {* New containers types *}\n\ntext {*\n We hope that the above explanations and the examples with sets and maps suffice to show what you need to do if you add a new container type, e.g., priority queues.\n There are three steps:\n \\begin{enumerate}\n \\item \\textbf{Introduce a type constructor for the container.}\n \\\\\n Your new container type must not be a composite type, like @{typ \"'a \\ 'b option\"} for maps, because refinement for code generation only works with a single type constructor.\n Neither should you reuse a type constructor that is used already in other contexts, e.g., do not use @{typ \"'a list\"} to model queues.\n\n Introduce a new type constructor if necessary (e.g., @{typ \"('a, 'b) mapping\"} for maps) -- if your container type already has its own type constructor, everything is fine.\n\n \\item \\textbf{Implement the data structures} \n \\\\\n and connect them to the container type as described in \\S\\ref{section:new:implementation}.\n\n \\item \\textbf{Define a heuristics for picking an implementation.}\n \\\\\n See \\cite{Lochbihler2013ITP} for an explanation.\n \\end{enumerate}\n*}\n\nsection {* Troubleshooting *}\n\ntext {*\n This section describes some difficulties in using LC that we have come across, provides some background for them, and discusses how to overcome them.\n If you experience other difficulties, please contact the author.\n*}\n\nsubsection {* Nesting of mappings *}\n\ntext {*\n Mappings can be arbitrarily nested on the value side, e.g., @{typ \"('a, ('b, 'c) mapping) mapping\"}.\n However, @{typ \"('a, 'b) mapping\"} cannot currently be the key of a mapping, i.e., code generation fails for @{typ \"(('a, 'b) mapping, 'c) mapping\"}.\n Simiarly, you cannot have a set of mappings like @{typ \"('a, 'b) mapping set\"} at the moment.\n There are no issues to make this work, we have just not seen the need for it.\n If you need to generate code for such types, please get in touch with the author.\n*}\n\nsubsection {* Wellsortedness errors *}\ntext_raw {* \\label{subsection:well:sortedness} *}\n\ntext {*\n LC uses its own hierarchy of type classes which is distinct from Isabelle/HOL's.\n This ensures that every type can be made an instance of LC's type classes.\n Consequently, you must instantiate these classes for your own types.\n The following lists where you can find information about the classes and examples how to instantiate them:\n \\begin{center}\n \\begin{tabular}{lll}\n \\textbf{type class} & \\textbf{user guide} & \\textbf{theory}\n \\\\\n @{class card_UNIV} & \\S\\ref{subsection:card_UNIV} & @{theory Cardinality} \n %@{term \"Cardinality.card_UNIV_class\"}\n \\\\\n @{class cenum} & \\S\\ref{subsection:cenum} & @{theory Collection_Enum}\n %@{term \"Collection_Enum.cenum_class\"}\n \\\\\n @{class ceq} & \\S\\ref{subsection:ceq} & @{theory Collection_Eq}\n %@{term \"Collection_Eq.ceq_class\"}\n \\\\\n @{class corder} & \\S\\ref{subsection:corder} & @{theory Collection_Order}\n %@{term \"Collection_Order.corder_class\"}\n \\\\\n @{class cproper_interval} & \\S\\ref{subsection:cproper_interval} & @{theory Collection_Order}\n %@{term \"Collection_Order.cproper_interval_class\"}\n \\\\\n @{class finite_UNIV} & \\S\\ref{subsection:finite_UNIV} & @{theory Cardinality}\n %@{term \"Cardinality.finite_UNIV_class\"}\n \\\\\n @{class mapping_impl} & \\S\\ref{subsection:mapping_impl} & @{theory Mapping_Impl}\n %@{term \"Mapping_Impl.mapping_impl_class\"}\n \\\\\n @{class set_impl} & \\S\\ref{subsection:set_impl} & @{theory Set_Impl}\n %@{term \"Set_Impl.set_impl_class\"}\n \\\\\n \\end{tabular}\n \\end{center}\n\n The type classes @{class card_UNIV} and @{class cproper_interval} are only required to implement the operations on set complements.\n If your code does not need complements, you can manually delete the code equations involving @{const \"Complement\"}, the theorem list @{thm [source] set_complement_code} collects them.\n It is also recommended that you remove the pseudo-constructor @{const Complement} from the code generator.\n Note that some set operations like @{term \"A - B\"} and @{const UNIV} have no code equations any more.\n*}\ndeclare set_complement_code[code del]\ncode_datatype Collect_set DList_set RBT_set Set_Monad\n(*<*)\ndatatype minimal_sorts = Minimal_Sorts bool\nderive (eq) ceq minimal_sorts\nderive (no) corder minimal_sorts\nderive (monad) set_impl minimal_sorts\nderive (no) cenum minimal_sorts\nvalue \"{Minimal_Sorts True} \\ {} \\ Minimal_Sorts ` {True, False}\"\n(*>*)\n\nsubsection {* Exception raised at run-time *}\ntext_raw {* \\label{subsection:set_impl_unsupported_operation} *}\n\ntext {*\n Not all combinations of data and container implementation are possible.\n For example, you cannot implement a set of functions with a RBT, because there is no order on @{typ \"'a \\ 'b\"}.\n If you try, the code will raise an exception \\texttt{Fail} (with an exception message) or \\texttt{Match}.\n They can occur in three cases:\n\n \\begin{enumerate}\n \\item\n You have misconfigured the heuristics that picks implementations (\\S\\ref{subsection:set_impl}), or you have manually picked an implementation that requires an operation that the element type does not provide.\n Printing a stack trace for the exception may help you in locating the error.\n\n \\item You are trying to invoke an operation on a set complement which cannot be implemented on a complement representation, e.g., @{term \"op `\"}.\n If the element type is enumerable, provide an instance of @{class cenum} and choose to represent complements of sets of enumerable types by the elements rather than the elements of the complement (see \\S\\ref{subsection:cenum} for how to do this).\n\n \\item You use set comprehensions on types which do not provide an enumeration (i.e., they are represented as closures) or you chose to represent a map as a closure.\n\n A lot of operations are not implementable for closures, in particular those that return some element of the container\n\n Inspect the code equations with \\isacommand{code{\\isacharunderscore}thms} and look for calls to @{term \"Collect_set\"} and @{term \"Mapping\"} which are LC's constructor for sets and maps as closures.\n\n Note that the code generator preprocesses set comprehensions like @{term \"{i < 4|i :: int. i > 2}\"} to @{term \"(\\i :: int. i < 4) ` {i. i > 2}\"}, so this is a set comprehension over @{typ int} rather than @{typ bool}.\n \\end{enumerate}\n*}\n\n(*<*)\ndefinition test_set_impl_unsupported_operation1 :: \"unit \\ (int \\ int) set\"\nwhere \"test_set_impl_unsupported_operation1 _ = RBT_set RBT_Set2.empty \\ {}\"\n\ndefinition test_set_impl_unsupported_operation2 :: \"unit \\ bool set\"\nwhere \"test_set_impl_unsupported_operation2 _ = {i < 4 | i :: int. i > 2}\"\n\ndefinition test_mapping_impl_unsupported_operation :: \"unit \\ bool\"\nwhere \n \"test_mapping_impl_unsupported_operation _ = \n Mapping.is_empty (RBT_Mapping (RBT_Mapping2.empty) :: (Enum.finite_4, unit) mapping)\"\n\nML_val {*\nfun test_fail s f =\n let\n fun error s' = Fail (\"exception Fail \\\"\" ^ s ^ \"\\\" expected, but got \" ^ s')\n in\n (f (); raise (error \"no exception\") )\n handle\n Fail s' => if s = s' then () else raise (error s')\n end;\n\ntest_fail \"union RBT_set Set_Monad: corder = None\" @{code test_set_impl_unsupported_operation1};\ntest_fail \"image Collect_set\" @{code test_set_impl_unsupported_operation2};\ntest_fail \"is_empty RBT_Mapping: corder = None\" @{code test_mapping_impl_unsupported_operation};\n*}\n(*>*)\n\nsubsection {* LC slows down my code *}\n\ntext {*\n Normally, this will not happen, because LC's data structures are more efficient than Isabelle's list-based implementations.\n However, in some rare cases, you can experience a slowdown:\n*}\n(*<*)\ndefinition tiny_set :: \"nat set\"\nwhere tiny_set_code: \"tiny_set = {1, 2}\"\n(*>*)\ntext_raw {*\n \\isastyletext\n \\begin{enumerate}\n \\item \\textbf{Your containers contain just a few elements.}\n \\\\\n In that case, the overhead of the heuristics to pick an implementation outweighs the benefits of efficient implementations.\n You should identify the tiny containers and disable the heuristics locally.\n You do so by replacing the initial value like @{term \"{}\"} and @{term \"Mapping.empty\"} with low-overhead constructors like @{term \"Set_Monad\"} and @{term \"Mapping\"}.\n For example, if @{thm [source] tiny_set_code}: @{thm tiny_set_code} is your code equation with a tiny set,\n the following changes the code equation to directly use the list-based representation, i.e., disables the heuristics:\n \\par\n*}\nlemma empty_Set_Monad: \"{} = Set_Monad []\" by simp\ndeclare tiny_set_code[code del, unfolded empty_Set_Monad, code]\ntext_raw {*\n \\isastyletext\n \\par\n If you want to globally disable the heuristics, you can also declare an equation like @{thm [source] empty_Set_Monad} as [code].\n\n \\item \\textbf{The element type contains many type constructors and some type variables.}\n \\\\\n LC heavily relies on type classes, and type classes are implemented as dictionaries if the compiler cannot statically resolve them, i.e., if there are type variables.\n For type constructors with type variables (like @{typ \"'a * 'b\"}), LC's definitions of the type class parameters recursively calls itself on the type variables, i.e., @{typ \"'a\"} and @{typ \"'b\"}.\n If the element type is polymorphic, the compiler cannot precompute these recursive calls and therefore they have to be constructed repeatedly at run time.\n If you wrap your complicated type in a new type constructor, you can define optimised equations for the type class parameters.\n \\end{enumerate}\n*}\n\n(*<*)\nend\n(*>*)", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Containers/Containers_Userguide.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.18242553047372242, "lm_q1q2_score": 0.07707563213358466}} {"text": "(*\n * Copyright 2014, NICTA\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * @TAG(NICTA_BSD)\n *)\n\ntheory WhileLoopRules\nimports \"NonDetMonadVCG\"\nbegin\n\nsection \"Well-ordered measures\"\n\n(* A version of \"measure\" that takes any wellorder, instead of\n * being fixed to \"nat\". *)\ndefinition measure' :: \"('a \\ 'b::wellorder) => ('a \\ 'a) set\"\nwhere \"measure' = (\\f. {(a, b). f a < f b})\"\n\nlemma in_measure'[simp, code_unfold]:\n \"((x,y) : measure' f) = (f x < f y)\"\n by (simp add:measure'_def)\n\nlemma wf_measure' [iff]: \"wf (measure' f)\"\n apply (clarsimp simp: measure'_def)\n apply (insert wf_inv_image [OF wellorder_class.wf, where f=f])\n apply (clarsimp simp: inv_image_def)\n done\n\nlemma wf_wellorder_measure: \"wf {(a, b). (M a :: 'a :: wellorder) < M b}\"\n apply (subgoal_tac \"wf (inv_image ({(a, b). a < b}) M)\")\n apply (clarsimp simp: inv_image_def)\n apply (rule wf_inv_image)\n apply (rule wellorder_class.wf)\n done\n\n\nsection \"whileLoop lemmas\"\n\ntext {*\n The following @{const whileLoop} definitions with additional\n invariant/variant annotations allow the user to annotate\n @{const whileLoop} terms with information that can be used\n by automated tools.\n*}\ndefinition\n \"whileLoop_inv (C :: 'a \\ 'b \\ bool) B x (I :: 'a \\ 'b \\ bool) (R :: (('a \\ 'b) \\ ('a \\ 'b)) set) \\ whileLoop C B x\"\n\ndefinition\n \"whileLoopE_inv (C :: 'a \\ 'b \\ bool) B x (I :: 'a \\ 'b \\ bool) (R :: (('a \\ 'b) \\ ('a \\ 'b)) set) \\ whileLoopE C B x\"\n\nlemma whileLoop_add_inv: \"whileLoop B C = (\\x. whileLoop_inv B C x I (measure' M))\"\n by (clarsimp simp: whileLoop_inv_def)\n\nlemma whileLoopE_add_inv: \"whileLoopE B C = (\\x. whileLoopE_inv B C x I (measure' M))\"\n by (clarsimp simp: whileLoopE_inv_def)\n\nsubsection \"Simple base rules\"\n\nlemma whileLoop_terminates_unfold:\n \"\\ whileLoop_terminates C B r s; (r', s') \\ fst (B r s); C r s \\\n \\ whileLoop_terminates C B r' s'\"\n apply (erule whileLoop_terminates.cases)\n apply simp\n apply force\n done\n\nlemma snd_whileLoop_first_step: \"\\ \\ snd (whileLoop C B r s); C r s \\ \\ \\ snd (B r s)\"\n apply (subst (asm) whileLoop_unroll)\n apply (clarsimp simp: bind_def condition_def)\n done\n\nlemma snd_whileLoopE_first_step: \"\\ \\ snd (whileLoopE C B r s); C r s \\ \\ \\ snd (B r s)\"\n apply (subgoal_tac \"\\ \\ snd (whileLoopE C B r s); C r s \\ \\ \\ snd ((lift B (Inr r)) s)\")\n apply (clarsimp simp: lift_def)\n apply (unfold whileLoopE_def)\n apply (erule snd_whileLoop_first_step)\n apply clarsimp\n done\n\nlemma snd_whileLoop_unfold:\n \"\\ \\ snd (whileLoop C B r s); C r s; (r', s') \\ fst (B r s) \\ \\ \\ snd (whileLoop C B r' s')\"\n apply (clarsimp simp: whileLoop_def)\n apply (auto simp: elim: whileLoop_results.cases whileLoop_terminates.cases\n intro: whileLoop_results.intros whileLoop_terminates.intros)\n done\n\nlemma snd_whileLoopE_unfold:\n \"\\ \\ snd (whileLoopE C B r s); (Inr r', s') \\ fst (B r s); C r s \\ \\ \\ snd (whileLoopE C B r' s')\"\n apply (clarsimp simp: whileLoopE_def)\n apply (drule snd_whileLoop_unfold)\n apply clarsimp\n apply (clarsimp simp: lift_def)\n apply assumption\n apply (clarsimp simp: lift_def)\n done\n\nlemma whileLoop_results_cong [cong]:\n assumes C: \"\\r s. C r s = C' r s\"\n and B:\"\\(r :: 'r) (s :: 's). C' r s \\ B r s = B' r s\"\n shows \"whileLoop_results C B = whileLoop_results C' B'\"\nproof -\n {\n fix x y C B C' B'\n have \"\\ (x, y) \\ whileLoop_results C B;\n \\(r :: 'r) (s :: 's). C r s = C' r s;\n \\r s. C' r s \\ B r s = B' r s \\\n \\ (x, y) \\ whileLoop_results C' B'\"\n apply (induct rule: whileLoop_results.induct)\n apply clarsimp\n apply clarsimp\n apply (rule whileLoop_results.intros, auto)[1]\n apply clarsimp\n apply (rule whileLoop_results.intros, auto)[1]\n done\n }\n\n thus ?thesis\n apply -\n apply (rule set_eqI, rule iffI)\n apply (clarsimp split: prod.splits)\n apply (clarsimp simp: C B split: prod.splits)\n apply (clarsimp split: prod.splits)\n apply (clarsimp simp: C [symmetric] B [symmetric] split: prod.splits)\n done\nqed\n\nlemma whileLoop_terminates_cong [cong]:\n assumes r: \"r = r'\"\n and s: \"s = s'\"\n and C: \"\\r s. C r s = C' r s\"\n and B: \"\\r s. C' r s \\ B r s = B' r s\"\n shows \"whileLoop_terminates C B r s = whileLoop_terminates C' B' r' s'\"\nproof (rule iffI)\n assume T: \"whileLoop_terminates C B r s\"\n show \"whileLoop_terminates C' B' r' s'\"\n apply (insert T r s)\n apply (induct arbitrary: r' s' rule: whileLoop_terminates.induct)\n apply (clarsimp simp: C)\n apply (erule whileLoop_terminates.intros)\n apply (clarsimp simp: C B split: prod.splits)\n apply (rule whileLoop_terminates.intros, assumption)\n apply (clarsimp simp: C B split: prod.splits)\n done\nnext\n assume T: \"whileLoop_terminates C' B' r' s'\"\n show \"whileLoop_terminates C B r s\"\n apply (insert T r s)\n apply (induct arbitrary: r s rule: whileLoop_terminates.induct)\n apply (rule whileLoop_terminates.intros)\n apply (clarsimp simp: C)\n apply (rule whileLoop_terminates.intros, fastforce simp: C)\n apply (clarsimp simp: C B split: prod.splits)\n done\nqed\n\nlemma whileLoop_cong [cong]:\n \"\\ \\r s. C r s = C' r s; \\r s. C r s \\ B r s = B' r s \\ \\ whileLoop C B = whileLoop C' B'\"\n apply (rule ext, clarsimp simp: whileLoop_def)\n done\n\nlemma whileLoopE_cong [cong]:\n \"\\ \\r s. C r s = C' r s ; \\r s. C r s \\ B r s = B' r s \\\n \\ whileLoopE C B = whileLoopE C' B'\"\n apply (clarsimp simp: whileLoopE_def)\n apply (rule whileLoop_cong [THEN arg_cong])\n apply (clarsimp split: sum.splits)\n apply (clarsimp split: sum.splits)\n apply (clarsimp simp: lift_def throwError_def split: sum.splits)\n done\n\nlemma whileLoop_terminates_wf:\n \"wf {(x, y). C (fst y) (snd y) \\ x \\ fst (B (fst y) (snd y)) \\ whileLoop_terminates C B (fst y) (snd y)}\"\n apply (rule wfI [where A=\"UNIV\" and B=\"{(r, s). whileLoop_terminates C B r s}\"])\n apply clarsimp\n apply clarsimp\n apply (erule whileLoop_terminates.induct)\n apply blast\n apply blast\n done\n\nsubsection \"Basic induction helper lemmas\"\n\nlemma whileLoop_results_induct_lemma1:\n \"\\ (a, b) \\ whileLoop_results C B; b = Some (x, y) \\ \\ \\ C x y\"\n apply (induct rule: whileLoop_results.induct, auto)\n done\n\nlemma whileLoop_results_induct_lemma1':\n \"\\ (a, b) \\ whileLoop_results C B; a \\ b \\ \\ \\x. a = Some x \\ C (fst x) (snd x)\"\n apply (induct rule: whileLoop_results.induct, auto)\n done\n\nlemma whileLoop_results_induct_lemma2 [consumes 1]:\n \"\\ (a, b) \\ whileLoop_results C B;\n a = Some (x :: 'a \\ 'b); b = Some y;\n P x; \\s t. \\ P s; t \\ fst (B (fst s) (snd s)); C (fst s) (snd s) \\ \\ P t \\ \\ P y\"\n apply (induct arbitrary: x y rule: whileLoop_results.induct)\n apply simp\n apply simp\n apply atomize\n apply fastforce\n done\n\nlemma whileLoop_results_induct_lemma3 [consumes 1]:\n assumes result: \"(Some (r, s), Some (r', s')) \\ whileLoop_results C B\"\n and inv_start: \"I r s\"\n and inv_step: \"\\r s r' s'. \\ I r s; C r s; (r', s') \\ fst (B r s) \\ \\ I r' s'\"\n shows \"I r' s'\"\n apply (rule whileLoop_results_induct_lemma2 [where P=\"case_prod I\" and y=\"(r', s')\" and x=\"(r, s)\",\n simplified case_prod_unfold, simplified])\n apply (rule result)\n apply simp\n apply simp\n apply fact\n apply (erule (1) inv_step)\n apply clarsimp\n done\n\nsubsection \"Inductive reasoning about whileLoop results\"\n\nlemma in_whileLoop_induct [consumes 1]:\n assumes in_whileLoop: \"(r', s') \\ fst (whileLoop C B r s)\"\n and init_I: \"\\ r s. \\ C r s \\ I r s r s\"\n and step:\n \"\\r s r' s' r'' s''.\n \\ C r s; (r', s') \\ fst (B r s);\n (r'', s'') \\ fst (whileLoop C B r' s');\n I r' s' r'' s'' \\ \\ I r s r'' s''\"\n shows \"I r s r' s'\"\nproof cases\n assume \"C r s\"\n\n {\n obtain a where a_def: \"a = Some (r, s)\"\n by blast\n obtain b where b_def: \"b = Some (r', s')\"\n by blast\n\n have \"\\ (a, b) \\ whileLoop_results C B; \\x. a = Some x; \\x. b = Some x \\\n \\ I (fst (the a)) (snd (the a)) (fst (the b)) (snd (the b))\"\n apply (induct rule: whileLoop_results.induct)\n apply (auto simp: init_I whileLoop_def intro: step)\n done\n\n hence \"(Some (r, s), Some (r', s')) \\ whileLoop_results C B\n \\ I r s r' s'\"\n by (clarsimp simp: a_def b_def)\n }\n\n thus ?thesis\n using in_whileLoop\n by (clarsimp simp: whileLoop_def)\nnext\n assume \"\\ C r s\"\n\n hence \"r' = r \\ s' = s\"\n using in_whileLoop\n by (subst (asm) whileLoop_unroll,\n clarsimp simp: condition_def return_def)\n\n thus ?thesis\n by (metis init_I `\\ C r s`)\nqed\n\nlemma snd_whileLoop_induct [consumes 1]:\n assumes induct: \"snd (whileLoop C B r s)\"\n and terminates: \"\\ whileLoop_terminates C B r s \\ I r s\"\n and init: \"\\ r s. \\ snd (B r s); C r s \\ \\ I r s\"\n and step: \"\\r s r' s' r'' s''.\n \\ C r s; (r', s') \\ fst (B r s);\n snd (whileLoop C B r' s');\n I r' s' \\ \\ I r s\"\n shows \"I r s\"\n apply (insert init induct)\n apply atomize\n apply (unfold whileLoop_def)\n apply clarsimp\n apply (erule disjE)\n apply (erule rev_mp)\n apply (induct \"Some (r, s)\" \"None :: ('a \\ 'b) option\"\n arbitrary: r s rule: whileLoop_results.induct)\n apply clarsimp\n apply clarsimp\n apply (erule (1) step)\n apply (clarsimp simp: whileLoop_def)\n apply clarsimp\n apply (metis terminates)\n done\n\nlemma whileLoop_terminatesE_induct [consumes 1]:\n assumes induct: \"whileLoop_terminatesE C B r s\"\n and init: \"\\r s. \\ C r s \\ I r s\"\n and step: \"\\r s r' s'. \\ C r s; \\(v', s') \\ fst (B r s). case v' of Inl _ \\ True | Inr r' \\ I r' s' \\ \\ I r s\"\n shows \"I r s\"\n apply (insert induct)\n apply (clarsimp simp: whileLoop_terminatesE_def)\n apply (subgoal_tac \"(\\r s. case (Inr r) of Inl x \\ True | Inr x \\ I x s) r s\")\n apply simp\n apply (induction rule: whileLoop_terminates.induct)\n apply (case_tac r)\n apply simp\n apply clarsimp\n apply (erule init)\n apply (clarsimp split: sum.splits)\n apply (rule step)\n apply simp\n apply (clarsimp simp: lift_def split: sum.splits)\n apply force\n done\n\nsubsection \"Direct reasoning about whileLoop components\"\n\nlemma fst_whileLoop_cond_false:\n assumes loop_result: \"(r', s') \\ fst (whileLoop C B r s)\"\n shows \"\\ C r' s'\"\n using loop_result\n by (rule in_whileLoop_induct, auto)\n\nlemma snd_whileLoop:\n assumes init_I: \"I r s\"\n and cond_I: \"C r s\"\n and non_term: \"\\r. \\ \\s. I r s \\ C r s \\ \\ snd (B r s) \\\n B r \\\\ \\r' s'. C r' s' \\ I r' s' \\\"\n shows \"snd (whileLoop C B r s)\"\n apply (clarsimp simp: whileLoop_def)\n apply (rotate_tac)\n apply (insert init_I cond_I)\n apply (induct rule: whileLoop_terminates.induct)\n apply clarsimp\n apply (cut_tac r=r in non_term)\n apply (clarsimp simp: exs_valid_def)\n apply (subst (asm) (2) whileLoop_results.simps)\n apply clarsimp\n apply (insert whileLoop_results.simps)\n apply fast\n done\n\nlemma whileLoop_terminates_inv:\n assumes init_I: \"I r s\"\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\\"\n assumes wf_R: \"wf R\"\n shows \"whileLoop_terminates C B r s\"\n apply (insert init_I)\n using wf_R\n apply (induction \"(r, s)\" arbitrary: r s)\n apply atomize\n apply (subst whileLoop_terminates_simps)\n apply clarsimp\n apply (erule use_valid)\n apply (rule hoare_strengthen_post, rule inv)\n apply force\n apply force\n done\n\nlemma not_snd_whileLoop:\n assumes init_I: \"I r s\"\n and inv_holds: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\!\"\n and wf_R: \"wf R\"\n shows \"\\ snd (whileLoop C B r s)\"\nproof -\n {\n fix x y\n have \"\\ (x, y) \\ whileLoop_results C B; x = Some (r, s); y = None \\ \\ False\"\n apply (insert init_I)\n apply (induct arbitrary: r s rule: whileLoop_results.inducts)\n apply simp\n apply simp\n apply (insert snd_validNF [OF inv_holds])[1]\n apply blast\n apply (drule use_validNF [OF _ inv_holds])\n apply simp\n apply clarsimp\n apply blast\n done\n }\n\n also have \"whileLoop_terminates C B r s\"\n apply (rule whileLoop_terminates_inv [where I=I, OF init_I _ wf_R])\n apply (insert inv_holds)\n apply (clarsimp simp: validNF_def)\n done\n\n ultimately show ?thesis\n by (clarsimp simp: whileLoop_def, blast)\nqed\n\nlemma valid_whileLoop:\n assumes first_step: \"\\s. P r s \\ I r s\"\n and inv_step: \"\\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\\"\n and final_step: \"\\r s. \\ I r s; \\ C r s \\ \\ Q r s\"\n shows \"\\ P r \\ whileLoop C B r \\ Q \\\"\nproof -\n {\n fix r' s' s\n assume inv: \"I r s\"\n assume step: \"(r', s') \\ fst (whileLoop C B r s)\"\n\n have \"I r' s'\"\n using step inv\n apply (induct rule: in_whileLoop_induct)\n apply simp\n apply (drule use_valid, rule inv_step, auto)\n done\n }\n\n thus ?thesis\n apply (clarsimp simp: valid_def)\n apply (drule first_step)\n apply (rule final_step, simp)\n apply (metis fst_whileLoop_cond_false)\n done\nqed\n\nlemma whileLoop_wp:\n \"\\ \\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\;\n \\r s. \\ I r s; \\ C r s \\ \\ Q r s \\ \\\n \\ I r \\ whileLoop C B r \\ Q \\\"\n by (rule valid_whileLoop)\n\nlemma whileLoop_wp_inv [wp]:\n \"\\ \\r. \\\\s. I r s \\ C r s\\ B r \\I\\; \\r s. \\I r s; \\ C r s\\ \\ Q r s \\\n \\ \\ I r \\ whileLoop_inv C B r I M \\ Q \\\"\n apply (clarsimp simp: whileLoop_inv_def)\n apply (rule valid_whileLoop [where P=I and I=I], auto)\n done\n\nlemma validE_whileLoopE:\n \"\\\\s. P r s \\ I r s; \n \\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\,\\ A \\;\n \\r s. \\ I r s; \\ C r s \\ \\ Q r s\n \\ \\ \\ P r \\ whileLoopE C B r \\ Q \\,\\ A \\\"\n apply (clarsimp simp: whileLoopE_def validE_def)\n apply (rule valid_whileLoop [where I=\"\\r s. (case r of Inl x \\ A x s | Inr x \\ I x s)\"\n and Q=\"\\r s. (case r of Inl x \\ A x s | Inr x \\ Q x s)\"])\n apply atomize\n apply (clarsimp simp: valid_def lift_def split: sum.splits)\n apply (clarsimp simp: valid_def lift_def split: sum.splits)\n apply (clarsimp split: sum.splits)\n done\n\nlemma whileLoopE_wp:\n \"\\ \\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\, \\ A \\;\n \\r s. \\ I r s; \\ C r s \\ \\ Q r s \\ \\\n \\ I r \\ whileLoopE C B r \\ Q \\, \\ A \\\"\n by (rule validE_whileLoopE)\n\nlemma exs_valid_whileLoop:\n assumes init_T: \"\\s. P s \\ T r s\"\n and iter_I: \"\\ r s0.\n \\ \\s. T r s \\ C r s \\ s = s0 \\\n B r \\\\\\r' s'. T r' s' \\ ((r', s'),(r, s0)) \\ R\\\"\n and wf_R: \"wf R\"\n and final_I: \"\\r s. \\ T r s; \\ C r s \\ \\ Q r s\"\n shows \"\\ P \\ whileLoop C B r \\\\ Q \\\"\nproof (clarsimp simp: exs_valid_def Bex_def)\n fix s\n assume \"P s\"\n\n {\n fix x\n have \"T (fst x) (snd x) \\\n \\r' s'. (r', s') \\ fst (whileLoop C B (fst x) (snd x)) \\ T r' s'\"\n using wf_R\n apply induction\n apply atomize\n apply (case_tac \"C (fst x) (snd x)\")\n apply (subst whileLoop_unroll)\n apply (clarsimp simp: condition_def bind_def' split: prod.splits)\n apply (cut_tac ?s0.0=b and r=a in iter_I)\n apply (clarsimp simp: exs_valid_def)\n apply blast\n apply (subst whileLoop_unroll)\n apply (clarsimp simp: condition_def bind_def' return_def)\n done\n }\n\n thus \"\\r' s'. (r', s') \\ fst (whileLoop C B r s) \\ Q r' s'\"\n by (metis `P s` fst_conv init_T snd_conv\n final_I fst_whileLoop_cond_false)\nqed\n\nlemma empty_fail_whileLoop:\n assumes body_empty_fail: \"\\r. empty_fail (B r)\"\n shows \"empty_fail (whileLoop C B r)\"\nproof -\n {\n fix s A\n assume empty: \"fst (whileLoop C B r s) = {}\"\n\n have cond_true: \"\\x s. fst (whileLoop C B x s) = {} \\ C x s\"\n apply (subst (asm) whileLoop_unroll)\n apply (clarsimp simp: condition_def return_def split: if_split_asm)\n done\n\n have \"snd (whileLoop C B r s)\"\n apply (rule snd_whileLoop [where I=\"\\x s. fst (whileLoop C B x s) = {}\"])\n apply fact\n apply (rule cond_true, fact)\n apply (clarsimp simp: exs_valid_def)\n apply (case_tac \"fst (B r s) = {}\")\n apply (metis empty_failD [OF body_empty_fail])\n apply (subst (asm) whileLoop_unroll)\n apply (fastforce simp: condition_def bind_def split_def cond_true)\n done\n }\n\n thus ?thesis\n by (clarsimp simp: empty_fail_def)\nqed\n\nlemma empty_fail_whileLoopE:\n assumes body_empty_fail: \"\\r. empty_fail (B r)\"\n shows \"empty_fail (whileLoopE C B r)\"\n apply (clarsimp simp: whileLoopE_def)\n apply (rule empty_fail_whileLoop)\n apply (insert body_empty_fail)\n apply (clarsimp simp: empty_fail_def lift_def throwError_def return_def split: sum.splits)\n done\n\nlemma whileLoop_results_bisim:\n assumes base: \"(a, b) \\ whileLoop_results C B\"\n and vars1: \"Q = (case a of Some (r, s) \\ Some (rt r, st s) | _ \\ None)\"\n and vars2: \"R = (case b of Some (r, s) \\ Some (rt r, st s) | _ \\ None)\"\n and inv_init: \"case a of Some (r, s) \\ I r s | _ \\ True\"\n and inv_step: \"\\r s r' s'. \\ I r s; C r s; (r', s') \\ fst (B r s) \\ \\ I r' s'\"\n and cond_match: \"\\r s. I r s \\ C r s = C' (rt r) (st s)\"\n and fail_step: \"\\r s. \\C r s; snd (B r s); I r s\\\n \\ (Some (rt r, st s), None) \\ whileLoop_results C' B'\"\n and refine: \"\\r s r' s'. \\ I r s; C r s; (r', s') \\ fst (B r s) \\\n \\ (rt r', st s') \\ fst (B' (rt r) (st s))\"\n shows \"(Q, R) \\ whileLoop_results C' B'\"\n apply (subst vars1)\n apply (subst vars2)\n apply (insert base inv_init)\n apply (induct rule: whileLoop_results.induct)\n apply clarsimp\n apply (subst (asm) cond_match)\n apply (clarsimp simp: option.splits)\n apply (clarsimp simp: option.splits)\n apply (clarsimp simp: option.splits)\n apply (metis fail_step)\n apply (case_tac z)\n apply (clarsimp simp: option.splits)\n apply (metis cond_match inv_step refine whileLoop_results.intros(3))\n apply (clarsimp simp: option.splits)\n apply (metis cond_match inv_step refine whileLoop_results.intros(3))\n done\n\nlemma whileLoop_terminates_liftE:\n \"whileLoop_terminatesE C (\\r. liftE (B r)) r s = whileLoop_terminates C B r s\"\n apply (subst eq_sym_conv)\n apply (clarsimp simp: whileLoop_terminatesE_def)\n apply (rule iffI)\n apply (erule whileLoop_terminates.induct)\n apply (rule whileLoop_terminates.intros)\n apply clarsimp\n apply (clarsimp simp: split_def)\n apply (rule whileLoop_terminates.intros(2))\n apply clarsimp\n apply (clarsimp simp: liftE_def in_bind return_def lift_def [abs_def]\n bind_def lift_def throwError_def o_def split: sum.splits\n cong: sum.case_cong)\n apply (drule (1) bspec)\n apply clarsimp\n apply (subgoal_tac \"case (Inr r) of Inl _ \\ True | Inr r \\\n whileLoop_terminates (\\r s. (\\r s. case r of Inl _ \\ False | Inr v \\ C v s) (Inr r) s)\n (\\r. (lift (\\r. liftE (B r)) (Inr r)) >>= (\\x. return (theRight x))) r s\")\n apply (clarsimp simp: liftE_def lift_def)\n apply (erule whileLoop_terminates.induct)\n apply (clarsimp simp: liftE_def lift_def split: sum.splits)\n apply (erule whileLoop_terminates.intros)\n apply (clarsimp simp: liftE_def split: sum.splits)\n apply (clarsimp simp: bind_def return_def split_def lift_def)\n apply (erule whileLoop_terminates.intros)\n apply force\n done\n\nlemma snd_X_return [simp]:\n \"\\A X s. snd ((A >>= (\\a. return (X a))) s) = snd (A s)\"\n by (clarsimp simp: return_def bind_def split_def)\n\nlemma whileLoopE_liftE:\n \"whileLoopE C (\\r. liftE (B r)) r = liftE (whileLoop C B r)\"\n apply (rule ext)\n apply (clarsimp simp: whileLoopE_def)\n apply (rule prod_eqI)\n apply (rule set_eqI, rule iffI)\n apply clarsimp\n apply (clarsimp simp: in_bind whileLoop_def liftE_def)\n apply (rule_tac x=\"b\" in exI)\n apply (rule_tac x=\"theRight a\" in exI)\n apply (rule conjI)\n apply (erule whileLoop_results_bisim [where rt=theRight and st=\"\\x. x\" and I=\"\\r s. case r of Inr x \\ True | _ \\ False\"],\n auto intro: whileLoop_results.intros simp: bind_def return_def lift_def split: sum.splits)[1]\n apply (drule whileLoop_results_induct_lemma2 [where P=\"\\(r, s). case r of Inr x \\ True | _ \\ False\"] )\n apply (rule refl)\n apply (rule refl)\n apply clarsimp\n apply (clarsimp simp: return_def bind_def lift_def split: sum.splits)\n apply (clarsimp simp: return_def bind_def lift_def split: sum.splits)\n apply (clarsimp simp: in_bind whileLoop_def liftE_def)\n apply (erule whileLoop_results_bisim [where rt=Inr and st=\"\\x. x\" and I=\"\\r s. True\"],\n auto intro: whileLoop_results.intros intro!: bexI simp: bind_def return_def lift_def split: sum.splits)[1]\n apply (rule iffI)\n apply (clarsimp simp: whileLoop_def liftE_def del: notI)\n apply (erule disjE)\n apply (erule whileLoop_results_bisim [where rt=theRight and st=\"\\x. x\" and I=\"\\r s. case r of Inr x \\ True | _ \\ False\"],\n auto intro: whileLoop_results.intros simp: bind_def return_def lift_def split: sum.splits)[1]\n apply (subst (asm) whileLoop_terminates_liftE [symmetric])\n apply (fastforce simp: whileLoop_def liftE_def whileLoop_terminatesE_def)\n apply (clarsimp simp: whileLoop_def liftE_def del: notI)\n apply (subst (asm) whileLoop_terminates_liftE [symmetric])\n apply (clarsimp simp: whileLoop_def liftE_def whileLoop_terminatesE_def)\n apply (erule disjE)\n apply (erule whileLoop_results_bisim [where rt=Inr and st=\"\\x. x\" and I=\"\\r s. True\"])\n apply (clarsimp split: option.splits)\n apply (clarsimp split: option.splits)\n apply (clarsimp split: option.splits)\n apply (auto intro: whileLoop_results.intros intro!: bexI simp: bind_def return_def lift_def split: sum.splits)\n done\n\nlemma validNF_whileLoop:\n assumes pre: \"\\s. P r s \\ I r s\"\n and inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\!\"\n and wf: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\P r\\ whileLoop C B r \\Q\\!\"\n apply rule\n apply (rule valid_whileLoop)\n apply fact\n apply (insert inv, clarsimp simp: validNF_def\n valid_def split: prod.splits, force)[1]\n apply (metis post_cond)\n apply (unfold no_fail_def)\n apply (intro allI impI)\n apply (rule not_snd_whileLoop [where I=I and R=R])\n apply (auto intro: assms)\n done\n\nlemma validNF_whileLoop_inv [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\!\"\n and wf: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoop_inv C B r I R \\Q\\!\"\n apply (clarsimp simp: whileLoop_inv_def)\n apply (rule validNF_whileLoop [where I=I and R=R])\n apply simp\n apply (rule inv)\n apply (rule wf)\n apply (metis post_cond)\n done\n\nlemma validNF_whileLoop_inv_measure [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ M r' s' < M r s \\!\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoop_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\!\"\n apply (clarsimp simp: whileLoop_inv_def)\n apply (rule validNF_whileLoop [where R=\"measure' (\\(r, s). M r s)\" and I=I])\n apply simp\n apply clarsimp\n apply (rule inv)\n apply simp\n apply (metis post_cond)\n done\n\nlemma validNF_whileLoop_inv_measure_twosteps:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ B r \\ \\r' s'. I r' s' \\!\"\n assumes measure: \"\\r m. \\\\s. I r s \\ C r s \\ M r s = m \\ B r \\ \\r' s'. M r' s' < m \\\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoop_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\!\"\n apply (rule validNF_whileLoop_inv_measure)\n apply (rule validNF_weaken_pre)\n apply (rule validNF_post_comb_conj_L)\n apply (rule inv)\n apply (rule measure)\n apply fast\n apply (metis post_cond)\n done\n\nlemma wf_custom_measure:\n \"\\ \\a b. (a, b) \\ R \\ f a < (f :: 'a \\ nat) b \\ \\ wf R\"\n by (metis in_measure wf_def wf_measure)\n\nlemma validNF_whileLoopE:\n assumes pre: \"\\s. P r s \\ I r s\"\n and inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\,\\ E \\!\"\n and wf: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\ P r \\ whileLoopE C B r \\ Q \\,\\ E \\!\"\n apply (unfold validE_NF_alt_def whileLoopE_def)\n apply (rule validNF_whileLoop [\n where I=\"\\r s. case r of Inl x \\ E x s | Inr x \\ I x s\"\n and R=\"{((r', s'), (r, s)). \\x x'. r' = Inl x' \\ r = Inr x}\n \\ {((r', s'), (r, s)). \\x x'. r' = Inr x' \\ r = Inr x \\ ((x', s'),(x, s)) \\ R}\"])\n apply (simp add: pre)\n apply (insert inv)[1]\n apply (fastforce simp: lift_def validNF_def valid_def\n validE_NF_def throwError_def no_fail_def return_def\n validE_def split: sum.splits prod.splits)\n apply (rule wf_Un)\n apply (rule wf_custom_measure [where f=\"\\(r, s). case r of Inl _ \\ 0 | _ \\ 1\"])\n apply clarsimp\n apply (insert wf_inv_image [OF wf, where f=\"\\(r, s). (theRight r, s)\"])\n apply (drule wf_Int1 [where r'=\"{((r', s'),(r, s)). (\\x. r = Inr x) \\ (\\x. r' = Inr x)}\"])\n apply (erule wf_subset)\n apply rule\n apply (clarsimp simp: inv_image_def split: prod.splits sum.splits)\n apply clarsimp\n apply rule\n apply rule\n apply clarsimp\n apply clarsimp\n apply (clarsimp split: sum.splits)\n apply (blast intro: post_cond)\n done\n\nlemma validNF_whileLoopE_inv [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\,\\ E \\!\"\n and wf_R: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoopE_inv C B r I R \\Q\\,\\E\\!\"\n apply (clarsimp simp: whileLoopE_inv_def)\n apply (metis validNF_whileLoopE [OF _ inv] post_cond wf_R)\n done\n\nlemma validNF_whileLoopE_inv_measure [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ M r' s' < M r s \\, \\ E \\!\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoopE_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\,\\E\\!\"\n apply (rule validNF_whileLoopE_inv)\n apply clarsimp\n apply (rule inv)\n apply clarsimp\n apply (metis post_cond)\n done\n\nlemma validNF_whileLoopE_inv_measure_twosteps:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ B r \\ \\r' s'. I r' s' \\, \\ E \\!\"\n assumes measure: \"\\r m. \\\\s. I r s \\ C r s \\ M r s = m \\ B r \\ \\r' s'. M r' s' < m \\, \\ \\_ _. True \\\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoopE_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\, \\E\\!\"\n apply (rule validNF_whileLoopE_inv_measure)\n apply (rule validE_NF_weaken_pre)\n apply (rule validE_NF_post_comb_conj_L)\n apply (rule inv)\n apply (rule measure)\n apply fast\n apply (metis post_cond)\n done\n\nlemma whileLoopE_wp_inv [wp]:\n \"\\ \\r. \\\\s. I r s \\ C r s\\ B r \\I\\,\\E\\; \\r s. \\I r s; \\ C r s\\ \\ Q r s \\\n \\ \\ I r \\ whileLoopE_inv C B r I M \\ Q \\,\\ E \\\"\n apply (clarsimp simp: whileLoopE_inv_def)\n apply (rule validE_whileLoopE [where I=I], auto)\n done\n\nsubsection \"Stronger whileLoop rules\"\n\nlemma whileLoop_rule_strong:\n assumes init_U: \"\\ \\s'. s' = s \\ whileLoop C B r \\ \\r s. (r, s) \\ fst Q \\\"\n and path_exists: \"\\r'' s''. \\ (r'', s'') \\ fst Q \\ \\ \\ \\s'. s' = s \\ whileLoop C B r \\\\ \\r s. r = r'' \\ s = s'' \\\"\n and loop_fail: \"snd Q \\ snd (whileLoop C B r s)\"\n and loop_nofail: \"\\ snd Q \\ \\ \\s'. s' = s \\ whileLoop C B r \\ \\_ _. True \\!\"\n shows \"whileLoop C B r s = Q\"\n using assms\n apply atomize\n apply (clarsimp simp: valid_def exs_valid_def validNF_def no_fail_def)\n apply rule\n apply blast\n apply blast\n apply blast\n done\n\nlemma whileLoop_rule_strong_no_fail:\n assumes init_U: \"\\ \\s'. s' = s \\ whileLoop C B r \\ \\r s. (r, s) \\ fst Q \\!\"\n and path_exists: \"\\r'' s''. \\ (r'', s'') \\ fst Q \\ \\ \\ \\s'. s' = s \\ whileLoop C B r \\\\ \\r s. r = r'' \\ s = s'' \\\"\n and loop_no_fail: \"\\ snd Q\"\n shows \"whileLoop C B r s = Q\"\n apply (rule whileLoop_rule_strong)\n apply (metis init_U validNF_valid)\n apply (metis path_exists)\n apply (metis loop_no_fail)\n apply (metis (lifting, no_types) init_U validNF_chain)\n done\n\nsubsection \"Miscellaneous rules\"\n\n(* Failure of one whileLoop implies the failure of another whileloop\n * which will only ever fail more. *)\nlemma snd_whileLoop_subset:\n assumes a_fails: \"snd (whileLoop C A r s)\"\n and b_success_step:\n \"\\r s r' s'. \\ C r s; (r', s') \\ fst (A r s); \\ snd (B r s) \\\n \\ (r', s') \\ fst (B r s)\"\n and b_fail_step: \"\\r s. \\ C r s; snd (A r s) \\ \\ snd (B r s) \"\n shows \"snd (whileLoop C B r s)\"\n apply (insert a_fails)\n apply (induct rule: snd_whileLoop_induct)\n apply (unfold whileLoop_def snd_conv)[1]\n apply (rule disjCI, simp)\n apply rotate_tac\n apply (induct rule: whileLoop_terminates.induct)\n apply (subst (asm) whileLoop_terminates.simps)\n apply simp\n apply (subst (asm) (3) whileLoop_terminates.simps, clarsimp)\n apply (subst whileLoop_results.simps, clarsimp)\n apply (rule classical)\n apply (frule b_success_step, assumption, simp)\n apply (drule (1) bspec)\n apply clarsimp\n apply (frule (1) b_fail_step)\n apply (metis snd_whileLoop_first_step)\n apply (metis b_success_step snd_whileLoop_first_step snd_whileLoop_unfold)\n done\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/l4v/lib/Monad_WP/WhileLoopRules.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4610167645017354, "lm_q2_score": 0.16238004274695514, "lm_q1q2_score": 0.07485992192685474}} {"text": "theory Chapter8\nimports \"HOL-IMP.Compiler\" \"Short_Theory\"\nbegin\n\ntext{*\n\\section*{Chapter 8}\n\nFor the following exercises copy and adjust theory @{short_theory \"Compiler\"}.\nIntrepid readers only should attempt to adjust theory @{text Compiler2} too.\n\n\\begin{exercise}\nA common programming idiom is @{text \"IF b THEN c\"}, i.e.,\nthe @{text ELSE}-branch is a @{term SKIP} command.\nLook at how, for example, the command @{term \"IF Less (V ''x'') (N 5) THEN ''y'' ::= N 3 ELSE SKIP\"}\nis compiled by @{const ccomp} and identify a possible compiler optimization.\nModify the definition of @{const ccomp} such that it generates fewer instructions\nfor commands of the form @{term \"IF b THEN c ELSE SKIP\"}.\nIdeally the proof of theorem @{thm[source] ccomp_bigstep} should still work;\notherwise adapt it.\n\\end{exercise}\n\n\\begin{exercise}\nBuilding on Exercise~\\ref{exe:IMP:REPEAT}, extend the compiler @{const ccomp}\nand its correctness theorem @{thm[source] ccomp_bigstep} to @{text REPEAT}\nloops. Hint: the recursion pattern of the big-step semantics\nand the compiler for @{text REPEAT} should match.\n\\end{exercise}\n\n\\begin{exercise}\\label{exe:COMP:addresses}\nModify the machine language such that instead of variable names to values,\nthe machine state maps addresses (integers) to values. Adjust the compiler\nand its proof accordingly.\n\nIn the simple version of this exercise, assume the existence of a globally\nbijective function @{term \"addr_of :: vname => int\"} with @{term \"bij addr_of\"}\nto adjust the compiler. Use the @{text find_theorems} search to find applicable\ntheorems for bijectivte functions.\n\nFor the more advanced version and a slightly larger project, only assume that\nthe function works on a finite set of variables: those that occur in the\nprogram. For the other, unused variables, it should return a suitable default\naddress. In this version, you may want to split the work into two parts:\nfirst, update the compiler and machine language, assuming the existence of\nsuch a function and the (partial) inverse it provides. Second, separately\nconstruct this function from the input program, having extracted the\nproperties needed for it in the first part. In the end, rearrange you theory\nfile to combine both into a final theorem.\n\\end{exercise}\n\n\\begin{exercise}\nThis is a slightly more challenging project. Based on\n\\autoref{exe:COMP:addresses}, and similarly to \\autoref{exe:register-machine}\nand \\autoref{exe:accumulator}, define a second machine language that does not\npossess a built-in stack, but instead, in addition to the program counter, a\nstack pointer register. Operations that previously worked on the stack now\nwork on memory, accessing locations based on the stack pointer.\n\nFor instance, let @{term \"(pc, s, sp)\"} be a configuration of this new machine consisting of\nprogram counter, store, and stack pointer. Then the configuration after an @{const ADD} instruction\nis \\mbox{@{term \"(pc + 1::int, s(sp + 1 := s (sp + 1::int) + s sp), sp + 1)\"}}, that is, @{const ADD} dereferences\nthe memory at @{term \"sp + 1::int\"} and @{term sp}, adds these two values and stores them at\n@{term \"sp + 1::int\"}, updating the values on the stack. It also increases the stack pointer by one\nto pop one value from the stack and leave the result at the top of the stack. This means the stack grows downwards.\n\nModify the compiler from \\autoref{exe:COMP:addresses} to work on this new machine language. Reformulate and reprove the easy direction of compiler correctness.\n\n\\emph{Hint:} Let the stack start below @{text 0}, growing downwards, and use type @{typ nat} for addressing variable in @{const LOAD} and @{const STORE} instructions, so that it is clear by type that these instructions do not interfere with the stack.\n\n\\emph{Hint:} When the new machine pops a value from the stack, this now unused value is left behind in the store. This means, even after executing a purely arithmetic expression, the values in initial and final stores are not all equal. But: they are equal above a given address. Define an abbreviation for this concept and use it to express the intermediate correctness statements.\n\n\\end{exercise}\n\n*}\nend\n\n", "meta": {"author": "brando90", "repo": "isabelle-gym", "sha": "f4d231cb9f625422e873aa2c9c2c6f22b7da4b27", "save_path": "github-repos/isabelle/brando90-isabelle-gym", "path": "github-repos/isabelle/brando90-isabelle-gym/isabelle-gym-f4d231cb9f625422e873aa2c9c2c6f22b7da4b27/isar_brandos_resources/templates/Chapter8.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.1540575665754383, "lm_q1q2_score": 0.07462241708131793}} {"text": "(*\n * Copyright 2014, NICTA\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * @TAG(NICTA_BSD)\n *)\n\ntheory WPTutorial\nimports \"../proof/refine/$L4V_ARCH/Bits_R\"\nbegin\n\ntext {*\nThis is a tutorial on the use of the various Hoare mechanisms developed\nfor the L4.verified project. We import Bits_R above, which is a compromise\nbetween the twin goals of getting the Hoare setup from L4.verified and not\nimporting existing properties. It's probably best to work from a prebuilt\nREFINE_S or REFINE Isabelle image which includes Bits_R.\n*}\n\ntext {* The point of our apparatus is to prove Hoare triples. These are a\ntriple of a precondition, function and postcondition. In our state-monadic\nworld, the precondition is a function of the state, and the postcondition\nis a function of the return value and the state. In example 1 below,\nthe precondition doesn't impose any restriction on the state, and the\npostcondition only requires that the return value be the obvious one. *}\n\ntext {* The weakest precondition tool, wp, attempts to construct the\nweakest precondition for a given postcondition. Use wp (with the command\n\"apply wp\") to solve example 1 *}\n\nlemma example_1:\n \"\\\\s. True\\ return 1 \\\\rv s. rv = 1\\\"\n apply wp\n apply simp\n done\n\ntext {* The wp tool works in reverse order (from postcondition to weakest\nprecondition, rather than from precondition to strongest postcondition).\nIt stops when it encounters a postcondition/function pair it doesn't\nknow any rules for. Try example 2 below, noting where wp gets stuck.\n\nThe wp method already knows how to handle most monadic operations\n(liftE, catch, assert, when, if-then-else, etc) but there are some\nexceptions. One is the split operator, which hides behind Isabelle syntax\nthat looks like (\\(x, y). blah), {(x, y). blah}, (\\(x, y) \\ S. blah).\nSolve the problem by unfolding it with (simp add: split_def).\n\nThe intermediate precondition seen when wp stops is a schematic variable.\nThe wp tool uses Isabelle's underlying unification mechanism to set the\nprecondition as it goes. This usually works well, but there are some\nproblems, especially with tuples. Note the strange behaviour if we use\nclarsimp instead of (simp add: split_def) to deal with the split constant.\nThe root cause of this strange behaviour is that the unification mechanism\ndoes not know how to construct a ?P such that \"?P (a, b) = a\". This is\nannoying, since it means that clarsimp/clarify/safe must frequently be\navoided.\n*}\n\nlemma example_2:\n \"\\\\s. s = [(True, False), (False, True)]\\ do\n v \\ gets length;\n (x, y) \\ gets hd;\n return x\n od \\\\rv s. rv\\\"\n apply wp\n apply (simp add: split_def)\n apply wp\n apply simp\n done\n\ntext {*\nAn additional annoyance to the clarsimp/tuple issue described above is\nthe splitter. The wp tool is designed to work on a hoare triple with a\nschematic precondition. Note how the simplifier splits the problem\nin two because it contains an if constant. Delete the split\nrule from the simpset with (simp split del: if_split) to avoid this\nissue and see where wp gets stuck.\n\nWe still need to deal with the if constant. In this (somewhat contrived)\nexample we can give the simplifier the rule if_apply_def2 to make\nprogress.\n\nNote that wp can deal with a function it knows nothing about if\nthe postcondition is constant in the return value and state.\n*}\n\nlemma example_3:\n \"\\\\s. s = [False, True]\\ do\n x \\ gets hd;\n possible_state_change_that_isnt_defined;\n y \\ gets (if x then \\ else \\);\n return $ y \\ \\ x\n od \\\\rv s. rv\\\"\n apply wp\n apply (simp add: if_apply_def2 split del: if_split)\n apply wp\n apply simp\n done\n\ntext {* Let's make this more interesting by introducing some functions\nfrom the abstract specification. The set_endpoint function is used to\nset the contents of an endpoint object somewhere in the kernel object\nheap (kheap). The cap derivation tree (cdt) lives in an entirely\ndifferent field of the state to the kheap, so this fact about it should\nbe unchanged by the endpoint update. Solve example 4 - you'll have to\nunfold enough definitions that wp knows what to do. *}\n\nlemma example_4:\n \"\\\\s. cdt s (42, [True, False]) = None\\\n set_endpoint ptr Structures_A.IdleEP\n \\\\rv s. cdt s (42, [True, False]) = None\\\"\n apply (simp add: set_endpoint_def set_object_def get_object_def)\n apply wp\n apply clarsimp\n done\n\ntext {*\nExample 4 proved that a property about the cdt was preserved from\nbefore set_endpoint to after. This preservation property is true for\nany property that just talks about the cdt. Example 5 rephrases\nexample 4 in this style. Get used to this style of Hoare triple,\nit is very common in our proofs.\n*}\n\nlemma example_5:\n \"\\\\s. P (cdt s)\\\n set_endpoint ptr Structures_A.IdleEP\n \\\\rv s. P (cdt s)\\\"\n apply (simp add: set_endpoint_def set_object_def get_object_def)\n apply wp\n apply clarsimp\n done\n\ntext {*\nThe set_cap function from the abstract specification is not much different\nto set_endpoint. However, caps can live within CSpace objects or within\nTCBs, and the set_cap function handles this issue with a case division.\n\nThe wp tool doesn't know anything about how to deal with case statements.\nIn addition to the tricks we've learned already, use the wpc tool to break\nup the case statement into components so that wp can deal with it to solve\nexample 6.\n*}\n\nlemma example_6:\n \"\\\\s. P (cdt s)\\\n set_cap cap ptr\n \\\\rv s. P (cdt s)\\\"\n apply (simp add: set_cap_def split_def set_object_def\n get_object_def)\n apply (wp | wpc)+\n apply simp\n done\n\ntext {*\nThe wp method can be given additional arguments which are theorems to use\nas summaries. Solve example 7 by supplying example 6 as a rule to\nuse with (wp example_6).\n*}\n\nlemma example_7:\n \"\\\\s. cdt s ptr' = None\\ do\n set_cap cap.NullCap ptr;\n v \\ gets (\\s. cdt s ptr);\n assert (v = None);\n set_cap cap.NullCap ptr';\n set_cap cap.IRQControlCap ptr';\n return True\n od \\\\rv s. cdt s ptr = None \\ cdt s ptr' = None\\\"\n apply (wp example_6)\n apply simp\n done\n\ntext {*\nThere isn't a good reason not to use example_6 whenever possible, so we can\ndeclare example_6 a member of the wp rule set by changing its proof site to\n\"lemma example_6[wp]:\", by doing \"declare example_6[wp]\", or by putting it\nin a group of lemmas declared wp with \"lemmas foo[wp] = example_6\".\nPick one of those options and remove the manual reference to example_6 from\nthe proof of example_7.\n*}\n\ntext {*\nThese preservation Hoare triples are often easy to prove and apply, so much\nof the effort is in typing them all out. To speed this up we have the crunch\ntool. Let's prove that setup_reply_master and set_endpoint don't change\nanother field of the state, machine_state. I've typed out the required\ncrunch command below. Let's explain the bits. The naming scheme\n\"machine_state_preserved:\" sets a common suffix for all the lemmas\nproved. Just like with lemma names, we could add the theorems to the wp set\nwith \"machine_state_preserved[wp]:\". What follows is a list of functions.\nThe crunch tool also descends through the call graph of functions, so it\nproves a rule about set_cap because setup_reply_master calls it. The last\nargument is the term to appear in the precondition and postcondition.\n\nThe final, optional bit of the crunch syntax is a group of modifiers, which\ngo between the parentheses inserted below. The crunch command doesn't\ncurrently work. We need to provide some additional simp and wp rules\nwith syntax like (simp: some rules wp: some rules). If you look at the way\ncrunch failed, you'll spot which simp rule we need to add to make some\nprogress.\n\nBut not much more progress. To get through set_endpoint, we need to deal\nwith a slightly complex postcondition to get_object, one which incorporates\nan assertion about its return value. We can solve this problem by simply\nthrowing the extra assumption away - supplying the wp rule hoare_drop_imps\ndoes this. There are standard sets of simp and wp rules which are frequently\nhelpful to crunch, crunch_simps and crunch_wps, which contain the rules we\nadded here.\n*}\n\ncrunch machine_state_preserved:\n setup_reply_master, set_endpoint\n \"\\s. P (machine_state s)\"\n (simp: split_def wp: crunch_wps)\n\ntext {*\nWe're making progress in solving simple problems here. It's time to\nintroduce some more complicated predicates, and explain the remaining\nfeatures of wp.\n*}\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/l4v/lib/WPTutorial.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.14608725448372273, "lm_q1q2_score": 0.07133198062875878}} {"text": "section \\Introduction to IMP2-VCG, based on IMP\\\ntheory IMP2_from_IMP\nimports \"../IMP2\"\nbegin\n\n text \\This document briefly introduces the extensions of IMP2 over IMP.\\\n\n subsection \\Fancy Syntax\\\n \n text \\Standard Syntax\\\n definition \"exp_count_up1 \\ \n ''a'' ::= N 1;;\n ''c'' ::= N 0;;\n WHILE Cmpop (<) (V ''c'') (V ''n'') DO (\n ''a'' ::= Binop (*) (N 2) (V ''a'');; \n ''c'' ::= Binop (+) (V ''c'') (N 1))\"\n\n (* Type \\ < ^ imp > \\open \\close , without the spaces.\n \n for \\\\\\, there is an autocompletion if you type a quote (\")\n \n for \\ \\\\, type \\comment and use autocompletion\n \n *)\n text \\Fancy Syntax\\\n definition \"exp_count_up2 \\ \\<^imp>\\\n \\ \\Initialization\\\n a = 1;\n c = 0;\n while (c \\Iterate until \\c\\ has reached \\n\\\\\n a=2*a; \\ \\Double \\a\\\\\n c=c+1 \\ \\Increment \\c\\\\\n }\n \\\" \n \n lemma \"exp_count_up1 = exp_count_up2\"\n unfolding exp_count_up1_def exp_count_up2_def ..\n \n \n\n subsection \\Operators and Arrays\\\n\n text \\We reflect arbitrary Isabelle functions into the syntax: \\\n value \"bval (Cmpop (\\) (Binop (+) (Unop uminus (V ''x'')) (N 42)) (N 50)) <''x'':=(\\_. -5)> \"\n \n thm aval.simps bval.simps\n\n text \\Every variable is an array, indexed by integers, no bounds.\n Syntax shortcuts to access index 0.\n \\ \n\n term \\Vidx ''a'' (i::aexp)\\ \\ \\Array access at index \\i\\\\\n lemma \"V ''x'' = Vidx ''x'' (N 0)\" .. \\ \\Shortcut for access at index \\0\\\\\n \n text \\New commands:\\\n term \\AssignIdx ''a'' (i::aexp) (v::aexp)\\ \\ \\Assign at index. Replaces assign.\\\n term \\''a''[i] ::= v\\ \\ \\Standard syntax\\\n term \\\\<^imp>\\ a[i] = v \\\\ \\ \\Fancy syntax\\\n \n lemma \\Assign ''x'' v = AssignIdx ''x'' (N 0) v\\ .. \\ \\Shortcut for assignment to index \\0\\\\\n term \\''x'' ::= v\\ term \\\\<^imp>\\x = v+1\\\\\n \n text \\Note: In fancy syntax, assignment between variables is always parsed as array copy.\n This is no problem unless a variable is used as both, array and plain value, \n which should be avoided anyway.\n \\\n \n term \\ArrayCpy ''d'' ''s''\\ \\ \\Copy whole array. Both operands are variable names.\\\n term \\''d''[] ::= ''s''\\ term \\\\<^imp>\\d = s\\\\\n \n term \\ArrayClear ''a''\\ \\ \\Initialize array to all zeroes.\\\n term \\CLEAR ''a''[]\\ term \\\\<^imp>\\clear a[]\\\\\n\n text \\Semantics of these is straightforward\\\n thm big_step.AssignIdx big_step.ArrayCpy big_step.ArrayClear\n \n subsection \\Local and Global Variables\\\n term \\is_global\\ term \\is_local\\ \\ \\Partitions variable names\\\n term \\1|s\\<^sub>2>\\ \\ \\State with locals from \\s\\<^sub>1\\ and globals from \\s\\<^sub>2\\\\\n \n term \\SCOPE c\\ term \\\\<^imp>\\scope { skip }\\\\ \\ \\Execute \\c\\ with fresh set of local variables\\\n thm big_step.Scope\n \n subsubsection \\Parameter Passing\\\n text \\Parameters and return values by global variables: This is syntactic sugar only:\\\n context fixes f :: com begin\n term \\\\<^imp>\\ (r1,r2) = f(x1,x2,x3)\\\\\n end\n \n \n subsection \\Recursive procedures\\\n term \\PCall ''name''\\ \n thm big_step.PCall\n \n subsubsection \\Procedure Scope\\\n text \\Execute command with local set of procedures\\\n term \\PScope \\ c\\\n thm big_step.PScope\n \n subsubsection \\Syntactic sugar for procedure call with parameters\\\n term \\\\<^imp>\\(r1,r2) = rec name(x1,x2,x3)\\\\\n \n subsection \\More Readable VCs\\\n lemmas nat_distribs = nat_add_distrib nat_diff_distrib Suc_diff_le nat_mult_distrib nat_div_distrib\n \n lemma \"s\\<^sub>0 ''n'' 0 \\ 0 \\ wlp \\ exp_count_up1 (\\s. s ''a'' 0 = 2^nat (s\\<^sub>0 ''n'' 0)) s\\<^sub>0\"\n unfolding exp_count_up1_def\n apply (subst annotate_whileI[where \n I=\"\\s. s ''n'' 0 = s\\<^sub>0 ''n'' 0 \\ s ''a'' 0 = 2 ^ nat (s ''c'' 0) \\ 0 \\ s ''c'' 0 \\ s ''c'' 0 \\ s\\<^sub>0 ''n'' 0\" \n ])\n apply (i_vcg_preprocess; i_vcg_gen; clarsimp)\n text \\The postprocessor converts from states applied to string names to actual variables\\\n apply i_vcg_postprocess\n by (auto simp: algebra_simps nat_distribs)\n \n lemma \"s\\<^sub>0 ''n'' 0 \\ 0 \\ wlp \\ exp_count_up1 (\\s. s ''a'' 0 = 2^nat (s\\<^sub>0 ''n'' 0)) s\\<^sub>0\"\n unfolding exp_count_up1_def\n apply (subst annotate_whileI[where \n I=\"\\s. s ''n'' 0 = s\\<^sub>0 ''n'' 0 \\ s ''a'' 0 = 2 ^ nat (s ''c'' 0) \\ 0 \\ s ''c'' 0 \\ s ''c'' 0 \\ s\\<^sub>0 ''n'' 0\" \n ])\n text \\The postprocessor is invoked by default\\ \n apply vcg\n oops\n \n \n subsection \\Specification Commands\\ \n \n text \\IMP2 provides a set of commands to simplify specification and annotation of programs.\\\n\n text \\Old way of proving a specification: \\ \n lemma \"let n = s\\<^sub>0 ''n'' 0 in n \\ 0 \n \\ wlp \\ exp_count_up1 (\\s. let a = s ''a'' 0; n\\<^sub>0 = s\\<^sub>0 ''n'' 0 in a = 2^nat (n\\<^sub>0)) s\\<^sub>0\"\n unfolding exp_count_up1_def\n apply (subst annotate_whileI[where \n I=\"\\s. s ''n'' 0 = s\\<^sub>0 ''n'' 0 \\ s ''a'' 0 = 2 ^ nat (s ''c'' 0) \\ 0 \\ s ''c'' 0 \\ s ''c'' 0 \\ s\\<^sub>0 ''n'' 0\" \n (* Similar for invar! *)\n ])\n apply vcg\n apply (auto simp: algebra_simps nat_distribs)\n done\n \n lemma \"VAR (s x) P = (let v=s x in P v)\" unfolding VAR_def by simp \n\n text \\IMP2 specification commands\\\n program_spec (partial) exp_count_up\n assumes \"0\\n\" \\ \\Precondition. Use variable names of program.\\\n ensures \"a = 2^nat n\\<^sub>0\" \\ \\Postcondition. Use variable names of programs. \n Suffix with \\\\\\<^sub>0\\ to refer to initial state\\\n defines \\ \\Program\\\n \\\n a = 1;\n c = 0;\n while (cn=n\\<^sub>0 \\ a=2^nat c \\ 0\\c \\ c\\n\\ \\ \\\n Invar annotation. Variable names and suffix \\\\\\<^sub>0\\ for variables from initial state.\\\n {\n a=2*a;\n c=c+1\n }\n \\\n apply vcg\n by (auto simp: algebra_simps nat_distribs)\n\n thm exp_count_up_spec \n thm exp_count_up_def\n \n (* \n We can also annotate \n @variant \\measure-expression\\ \n (interpreted over variables (v) and variables at program start (v\\<^sub>0) \n \n or, both @variant \\\\\\ and @relation \\R\\:\n R :: 'a rel, and variant produces an 'a\n \n *)\n \n \n procedure_spec exp_count_up_proc(n) returns a\n assumes \"0\\n\" \n ensures \"a = 2^nat n\\<^sub>0\" \n defines \n \\\n a = 1;\n c = 0;\n while (cn=n\\<^sub>0 \\ a=2^nat c \\ 0\\c \\ c\\n\\ \n @variant \\n-c\\\n {\n a=2*a;\n c=c+1\n }\n \\\n apply vcg\n by (auto simp: algebra_simps nat_distribs)\n \n text \\Simple Recursion\\\n recursive_spec \n exp_rec(n) returns a assumes \"0\\n\" ensures \"a=2^nat n\\<^sub>0\" variant \"n\"\n defines \\if (n==0) a=1 else {t=rec exp_rec(n-1); a=2*t}\\\n apply vcg\n apply (auto simp: algebra_simps nat_distribs)\n by (metis Suc_le_D diff_Suc_Suc dvd_1_left dvd_imp_le minus_nat.diff_0 nat_0_iff nat_int neq0_conv of_nat_0 order_class.order.antisym pos_int_cases power_Suc zless_nat_eq_int_zless)\n \n text \\Mutual Recursion: See Examples\\\n \n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/IMP2/doc/IMP2_from_IMP.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.1520322377801054, "lm_q1q2_score": 0.0712712880163257}} {"text": "(* header\\ Teorema de existencia de models proposicionales \\ *)\n\n(*<*)\ntheory T5CCerradaIngles\nimports T1SintaxisSemanticaIngles T2NotacionUniformeIngles\nbegin\n(*>*)\n\ntext \\ \n \\label{cap6}\n\\\n\nsection\\ Teorema de Existencia de Modelos \\\ntext \\\n \\label{consistcerradoP}\n Un método de\n demostración, utilizado por el lógico Leon Henkin, para demostrar la completitud\n de un sistema de deducción es considerar la\n afirmación contrarrecíproca, es decir, si una fórmula $F$ no es\n deducible entonces no es tautología. La prueba utiliza el siguiente\n teorema que hace referencia a la noción de {\\em consistencia}. Una\n fórmula $F$ es consistente, con respecto al cálculo de prueba\n $\\vdash$, si $\\nvdash \\neg F$; es decir, si $\\neg F$ no es deducible\n en el sistema.\n\n \\begin{teorema}[Henkin]\\label{Henkin}\n Para cualquier fórmula $F$, Si $F$ es consistente entonces $F$ tiene\n un model. \n \\end{teorema}\n\n Como una consecuencia del teorema anterior podemos demostrar que\n el sistema deductivo es completo. Consideremos una fórmu\\-la $F$\n que no es deducible, $\\nvdash F$. Además supongamos que\n $\\vdash \\neg \\neg F \\rightarrow F$. Entonces, de la\n hipótesis $\\nvdash F$ y por la regla MP tene\\-mos que $\\nvdash \\neg \\neg F$,\n es decir, $\\nvdash \\neg (\\neg F)$. De esta forma, $\\neg F$ es\n consistente. Luego, por el teorema \\ref{Henkin}, $\\neg F$ tiene un\n model. Por lo tanto, $F$ no es tautología.\n\n Para demostrar el teorema \\ref{Henkin}, se extiende la noción de\n consistencia de una fórmu\\-la a un conjunto de fórmulas. Un conjunto\n finito de fórmulas $S = \\{F_1, F_2,\\dots , F_n\\}$ es consistente si la\n fórmula $F_1\\wedge F_2\\wedge \\dots \\wedge F_n$ es consistente, es\n decir $\\nvdash \\neg(F_1\\wedge F_2\\wedge \\dots \\wedge F_n)$. Un\n conjunto arbitrario de fórmulas $S$ es consistente si cada subconjunto\n finito de $S$ es consistente.\n\n Un conjunto consistente de fórmulas $S$ es un {\\em conjunto\n consistente maximal} si para toda fórmula $F\\notin S$, $S\\cup\\{F\\}$ no\n es consistente. Un resultado importante sobre estos conjuntos es el\n teorema de Lindenbaum:\n\n \\begin{teorema}[Lindenbaum]\\label{Lindenbaum} \n Todo conjunto consistente $S$ puede ser extendido a un conjunto\n consistente maximal $M$. \n \\end{teorema}\n\n El conjunto $M$ se define, a partir de $S$ y de una @{text\n \"enumeración\"} $\\phi_0$, $\\phi_1$, $\\phi_2$, $\\ldots$ del conjunto de\n fórmulas del lenguaje proposicional, como la unión $\\bigcup_i S_i$ de\n la siguiente sucesión $S_i$ de conjuntos consistentes:\n \\[\n \\begin{array}{l}\n S_0 = S \\\\\n S_{i+1} = \n \\left\\{\n \\begin{array}{ll}\n S_i \\cup \\{\\phi_i\\} & \n \\hbox{si } S_i \\cup \\{\\phi_i\\} \\hbox{ es consistente} \\\\\n S_i & \n \\hbox{en otro caso.}\n \\end{array}\n \\right.\n \\end{array}\n \\]\n\n Sea $M$ un conjunto consistente maximal. Para establecer la conexión\n entre conjuntos consistentes e interpretaciones, definimos la\n siguiente interpretación $I_M$. Sea $P$ un símbolo proposicional,\n entonces\n \\newline \\hspace*{1cm}\n \\[ I_M(P) = \n \\begin{cases}\n \\V, & \\text{si $P\\in M$} \\\\\n \\F, & \\text{en otro caso.}\n \\end{cases} \\]\n\n Se tiene el siguiente resultado.\n\n \\begin{teorema}\\label{preHintikka} \n Si $M$ es un conjunto consistente maximal, entonces para toda fórmula\n $F$, $I'_M(F)=\\V$ si y solamente si $F\\in M$.\n \\end{teorema}\n\n Como una consecuencia del teorema anterior se tiene la demostración\n del teorema \\ref{Henkin}: \n\n \\begin{demostracion}\n Sea $F$ una fórmula consistente. Por el teorema \\ref{Lindenbaum},\n $\\{F\\}$ puede extenderse a un conjunto consistente maximal $M$. Por el\n teorema \\ref{preHintikka}, $I'_M(F)=\\V$ puesto que $F\\in M$. Es decir,\n $F$ tiene un model. \n \\end{demostracion}\n\n Utilizando el concepto abstracto de conjunto consiste y siguiendo \n las ideas anteriores, de extender un conjunto consistente de fórmulas\n $S$ a un conjunto consistente maximal $M$, \n el desarrollo central de la demostración que aparece en el texto de\n Fitting, (\\cite{Fitting} página 60), es el sigui\\-ente. \n \\begin{itemize}\n \\item Usando la noción de @{text \"clausura por subconjuntos\"} se\n prueba que $M$ es maximal. \n \\item Usando la noción de @{text \"carácter finito\"} se prueba que $M$\n es consistente. \n \\end{itemize}\n\n Además se demuestran los siguientes dos resultados.\n \\begin{itemize}\n \\item Al ser $M$ un conjunto maximal de carácter finito es de @{text \"Hintikka\"}.\n \\item Los conjuntos de Hintikka son satisfiables.\n \\end{itemize}\n\n Por tanto, se puede concluir que $M$ es satisfiable y, puesto que\n @{text \"S \\ M\"}, se tiene que $S$ también es satisfiable. \n\\\n\nsubsection \\ Conjuntos consistentes \\\n\ntext \\\n \\label{conjuntosconsistentesP}\n En esta sección formalizamos el criterio abstracto, propuesto en\n (\\cite{Fitting} página 59), para describir los conjuntos consistentes.\n\n \\begin{definicion}\\label{consistenciaP}\n Una colección de conjuntos de fórmulas $\\mathcal{C}$ es una\n {\\bf{propiedad de consistencia proposicional}}, si todo elemento \n $S$ de $\\mathcal{C}$ verifica las siguien\\-tes propiedades.\n \\begin{enumerate}\n \\item Para cualquier fórmula atómica $P$, $P\\notin S$ o $\\neg P \\notin S$.\n \\item $\\bot\\notin S$ y $\\neg \\top\\notin S$.\n \\item Si $\\neg \\neg F \\in S$ entonces $S\\cup \\{F\\}\\in \\mathcal{C}$.\n \\item Si $\\alpha \\in S$ entonces, $S\\cup\\{\\alpha_1,\\alpha_2\\}\\in \\mathcal{C}$.\n \\item Si $\\beta \\in S$ entonces, $S\\cup \\{\\beta_1\\}\\in \\mathcal{C}$ o\n $S\\cup \\{\\beta_2\\}\\in \\mathcal{C}$. \n \\end{enumerate}\n \\end{definicion}\n\n \\noindent Su formalización es:\n\\\n\ndefinition consistenceP :: \"'b formula set set \\ bool\" where\n \"consistenceP \\ = \n (\\S. S \\ \\ \\ (\\P. \\ (atom P \\ S \\ (\\.atom P) \\ S)) \\\n FF \\ S \\ (\\.TT) \\ S \\\n (\\F. (\\.\\.F) \\ S \\ S \\ {F} \\ \\) \\\n (\\F. ((FormulaAlfa F) \\ F\\S) \\ (S\\{Comp1 F, Comp2 F}) \\ \\) \\\n (\\F. ((FormulaBeta F) \\ F\\S) \\ (S\\{Comp1 F}\\\\) \\ (S\\{Comp2 F}\\\\)))\" \n\nsubsection \\ Conjuntos consistentes y clausura por subconjuntos \\\n\ntext \\\n \\label{cerraduraP}\n \\begin{definicion}\\label{subcerrada}\n Una colección de conjuntos $\\mathcal{C}$ es {\\bf{cerrada por\n subconjuntos}} si para cada $S\\in\\mathcal{C}$ los subconjuntos de $S$\n también son elementos de $\\mathcal{C}$. \n \\end{definicion}\n\n \\noindent Su formalización es:\n\\\n\ndefinition subconj_cerrada :: \"'a set set \\ bool\" where\n \"subconj_cerrada \\ = (\\S \\ \\. \\S'. S' \\ S \\ S' \\ \\)\"\n\ntext \\\n En esta sección demostraremos que toda propiedad de consistencia\n proposicional $\\mathcal{C}$ puede extenderse a una propiedad de\n consistencia $\\mathcal{C^{+}}$ que es cerrada por subconjuntos. Para\n la demostración basta con considerar $\\mathcal{C^{+}}$ igual a la\n colección de los subconjuntos de los elementos de $\\mathcal{C}$,\n \\[\\mathcal{C^{+}}=\\{S| \\exists S' \\in \\mathcal{C} (S \\subseteq\n S')\\}.\\] La definición en Isabelle de $\\mathcal{C^{+}}$ es,\n\\\n\ndefinition clausura_subconj :: \"'a set set \\ 'a set set\" (\"_⁺\"[1000] 1000) where\n \"\\⁺ = {S. \\S' \\ \\. S \\ S'}\"\n\ntext \\\n \\begin{teorema}\\label{CerraduraSubconjuntosP}\\mbox{}\n \\par\\noindent\n Sea $\\mathcal{C}$ una colección de conjuntos. entonces,\n \\begin{itemize}\n \\item[(a)] $\\mathcal{C} \\subseteq \\mathcal{C^{+}}$.\n \\item[(b)] $\\mathcal{C^{+}}$ es cerrada por subconjuntos.\n \\item[(c)] Si $\\mathcal{C}$ es una propiedad de consistencia\n proposicional entonces $\\mathcal{C^{+}}$ también es una propiedad de \n consistencia proposicional.\n \\end{itemize} \n \\end{teorema}\n\\\n\ntext \\\n \\begin{demostracion}\n \\begin{itemize}\n \\item[(a)] Sea $S \\in \\mathcal{C}$. Puesto que $S \\subseteq S$ se\n tiene que $S \\in \\mathcal{C^{+}}$ por la definición de\n $\\mathcal{C^{+}}$. Por tanto $\\mathcal{C}$ está contenido en\n $\\mathcal{C^{+}}$. \n\n \\item[(b)] Supongamos que $S \\in \\mathcal{C^{+}}$ y sea $T\\subseteq\n S$. Puesto que $S \\in \\mathcal{C^{+}}$, existe $S'\\in \\mathcal{C}$\n tal que $S \\subseteq S'$ por la definición de\n $\\mathcal{C^{+}}$. Luego existe $S'\\in \\mathcal{C}$ tal que\n $T\\subseteq S'$ y, por tanto, $T\\in \\mathcal{C^{+}}$. Así,\n $\\mathcal{C^{+}}$ es una colección cerrada por subconjuntos.\n \n \\item[(c)] Supongamos que $\\mathcal{C}$ es una propiedad de\n consistencia proposicional. Sea $S\\in \\mathcal{C^{+}}$, entonces\n existe $S'\\in \\mathcal{C}$ tal que $S\\subseteq S'$, de esto último\n mostramos que se cumplen las condiciones para que $\\mathcal{C^{+}}$\n sea una propiedad de consistencia.\n \\end{itemize}\n \\begin{enumerate}\n\n \\item Sea $P$ una fórmula atómica, entonces $P\\notin S'$ o $\\neg P\n \\notin S'$ ya que $S'\\in \\mathcal{C}$ y $\\mathcal{C}$ es una\n propiedad de consistencia. Luego, $P\\notin S$ o $\\neg P \\notin S$\n puesto que $S\\subseteq S'$.\n\n \\item $\\bot\\notin S'$ y $\\neg \\top \\notin S'$ puesto que $S'\\in\n \\mathcal{C}$ y $\\mathcal{C}$ es una propiedad de consistencia.\n Luego, $\\bot\\notin S$ y $\\neg \\top \\notin S$ puesto que $S\\subseteq\n S'$.\n\n \\item Supongamos que $\\neg \\neg F \\in S$, entonces $\\neg \\neg F \\in\n S'$ ya que $S\\subseteq S'$. Luego $S'\\cup \\{F\\}\\in \\mathcal{C}$, ya\n que $S'\\in \\mathcal{C}$ y $\\mathcal{C}$ es una propiedad de\n consistencia; además $S\\cup \\{F\\}\\subseteq S'\\cup \\{F\\}$ puesto que\n $S\\subseteq S'$. Por lo tanto, por definición de $\\mathcal{C^{+}}$,\n se tiene que $S\\cup \\{F\\}\\in \\mathcal{C^{+}}$.\n\n \\item Supongamos que $\\alpha \\in S$, entonces $\\alpha \\in S'$ ya que\n $S\\subseteq S'$. Luego $S'\\cup \\{\\alpha_1,\\alpha_2\\} \\in\n \\mathcal{C}$, ya que $S'\\in \\mathcal{C}$ y $\\mathcal{C}$ es una\n propiedad de consistencia.\n\n Por otro lado $S\\cup \\{\\alpha_1, \\alpha_2\\}\\subseteq S'\\cup\n \\{\\alpha_1,\\alpha_2\\}$ ya que, $S\\subseteq S'$. Por lo tanto, por\n definición de $\\mathcal{C^{+}}$, se tiene que $S\\cup \\{\\alpha_1,\n \\alpha_2\\}\\in \\mathcal{C^{+}}$. \\item Supongamos que $\\beta \\in S$,\n entonces $\\beta\\in S'$ puesto que que $S\\subseteq S'$.\n\n Luego, $S'\\cup \\{\\beta_1\\}\\in \\mathcal{C}$ o $S'\\cup \\{\\beta_2\\}\\in\n \\mathcal{C}$ por ser $\\mathcal{C}$ una propiedad de consistencia;\n además $S\\cup \\{\\beta_1\\} \\subseteq S'\\cup \\{\\beta_1\\}$ y $S\\cup\n \\{\\beta_2\\} \\subseteq S'\\cup \\{\\beta_2\\}$ ya que $S\\subseteq S'$. Por\n lo tanto, por definición de $\\mathcal{C^{+}}$, se tiene que $S\\cup\n \\{\\beta_1\\}\\in \\mathcal{C^{+}}$ o $S\\cup \\{\\beta_2\\}\\in\n \\mathcal{C^{+}}$.\n \\end{enumerate}\n \\mbox{}\n \\end{demostracion}\n\n A continuación formalizamos cada parte del teorema anterior. La\n formali\\-zación de la parte (a) es la siguiente:\n\\\n\nlemma cerrado_subset: \"\\ \\ \\⁺\"\nproof -\n { fix S\n assume \"S \\ \\\" \n moreover \n have \"S \\ S\" by simp\n ultimately\n have \"S \\ \\⁺\"\n by (unfold clausura_subconj_def, auto) }\n thus ?thesis by auto\nqed \n\ntext \\ \n El siguiente lema formaliza la parte (b).\n\\\n\nlemma cerrado_cerrado: \"subconj_cerrada (\\⁺)\"\nproof -\n { fix S T\n assume \"S \\ \\⁺\" and \"T \\ S\"\n obtain S1 where \"S1 \\ \\\" and \"S \\ S1\" using `S \\ \\⁺` \n by (unfold clausura_subconj_def, auto)\n have \"T \\ S1\" using `T \\ S` and `S \\ S1` by simp\n hence \"T \\ \\⁺\" using `S1 \\ \\` \n by (unfold clausura_subconj_def, auto)}\n thus ?thesis by (unfold subconj_cerrada_def, auto) \nqed \n\ntext \\ \n Los siguientes lemas corresponden a la formalización de los 5 casos de\n la parte (c) del teorema anterior. \n\\\n\nlemma condiconsisP1:\n assumes \"consistenceP \\\" and \"T \\ \\\" and \"S \\ T\" \n shows \"(\\P. \\(atom P \\ S \\ (\\.atom P) \\ S))\"\n(*<*) \nproof (rule allI)+ \n fix P \n show \"\\(atom P \\ S \\ (\\.atom P) \\ S)\"\n proof -\n have \"\\(atom P \\ T \\ (\\.atom P) \\ T)\" \n using `consistenceP \\` and `T \\ \\`\n by(simp add: consistenceP_def)\n thus \"\\(atom P \\ S \\ (\\.atom P) \\ S)\" using `S \\ T` by auto\n qed\nqed \n(*>*)\ntext\\ \\\nlemma condiconsisP2:\n assumes \"consistenceP \\\" and \"T \\ \\\" and \"S \\ T\" \n shows \"FF \\ S \\ (\\.TT)\\ S\"\n(*<*)\nproof -\n have \"FF \\ T \\ (\\.TT)\\ T\" \n using `consistenceP \\` and `T \\ \\` \n by(simp add: consistenceP_def)\n thus \"FF \\ S \\ (\\.TT)\\ S\" using `S \\ T` by auto\nqed\n(*>*)\ntext\\ \\\nlemma condiconsisP3:\n assumes \"consistenceP \\\" and \"T \\ \\\" and \"S \\ T\" \n shows \"\\F. (\\.\\.F) \\ S \\ S \\ {F} \\ \\⁺\"\nproof(rule allI) \n(*<*) \n fix F\n show \"(\\.\\.F) \\ S \\ S \\ {F} \\ \\⁺\"\n proof (rule impI)\n assume \"(\\.\\.F) \\ S\"\n hence \"(\\.\\.F) \\ T\" using `S \\ T` by auto \n hence \"T \\ {F} \\ \\\" using `consistenceP \\` and `T \\ \\` \n by(simp add: consistenceP_def)\n moreover \n have \"S \\ {F} \\ T \\ {F}\" using `S \\ T` by auto\n ultimately \n show \"S \\ {F} \\ \\⁺\"\n by (auto simp add: clausura_subconj_def)\n qed\nqed\n(*>*)\ntext\\ \\\nlemma condiconsisP4:\n assumes \"consistenceP \\\" and \"T \\ \\\" and \"S \\ T\" \n shows \"\\F. ((FormulaAlfa F) \\ F \\ S) \\ (S \\ {Comp1 F, Comp2 F}) \\ \\⁺\"\n(*<*)\nproof (rule allI) \n fix F \n show \"((FormulaAlfa F) \\ F \\ S) \\ S \\ {Comp1 F, Comp2 F} \\ \\⁺\"\n proof (rule impI)\n assume \"((FormulaAlfa F) \\ F \\ S)\"\n hence \"FormulaAlfa F\" and \"F \\ T\" using `S \\ T` by auto \n hence \"T \\ {Comp1 F, Comp2 F} \\ \\\" \n using `consistenceP \\` and `FormulaAlfa F` and `T \\ \\` \n by (auto simp add: consistenceP_def)\n moreover\n have \"S \\ {Comp1 F, Comp2 F} \\ T \\ {Comp1 F, Comp2 F}\" \n using `S \\ T` by auto\n ultimately\n show \"S \\ {Comp1 F, Comp2 F} \\ \\⁺\" \n by (auto simp add: clausura_subconj_def)\n qed\nqed\n(*>*)\ntext\\ \\\nlemma condiconsisP5:\n assumes \"consistenceP \\\" and \"T \\ \\\" and \"S \\ T\" \n shows \"(\\F. ((FormulaBeta F) \\ F \\ S) \\ \n (S \\ {Comp1 F} \\ \\⁺) \\ (S \\ {Comp2 F} \\ \\⁺))\" \n(*<*)\nproof (rule allI) \n fix F \n show \"((FormulaBeta F) \\ F \\ S) \\ S \\ {Comp1 F} \\ \\⁺ \\ S \\ {Comp2 F} \\ \\⁺\" \n proof (rule impI)\n assume \"(FormulaBeta F) \\ F \\ S\"\n hence \"FormulaBeta F\" and \"F \\ T\" using `S \\ T` by auto \n hence \"T \\ {Comp1 F} \\ \\ \\ T \\ {Comp2 F} \\ \\\" \n using `consistenceP \\` and `FormulaBeta F` and `T \\ \\` \n by(simp add: consistenceP_def)\n moreover\n have \"S \\ {Comp1 F} \\ T \\ {Comp1 F}\" and \"S \\ {Comp2 F} \\ T \\ {Comp2 F}\" \n using `S \\ T` by auto\n ultimately\n show \"S \\ {Comp1 F} \\ \\⁺ \\ S \\ {Comp2 F} \\ \\⁺\"\n by(auto simp add: clausura_subconj_def)\n qed\nqed\n(*>*)\ntext \\ \n Por último, la formalización de la parte (c) del teorema\n \\ref{CerraduraSubconjuntosP} es la siguiente: \n\\ \n\ntheorem cerrado_consistenceP:\n assumes hip1: \"consistenceP \\\"\n shows \"consistenceP (\\⁺)\"\nproof -\n { fix S\n assume \"S \\ \\⁺\" \n hence \"\\T\\\\. S \\ T\" by(simp add: clausura_subconj_def)\n then obtain T where hip2: \"T \\ \\\" and hip3: \"S \\ T\" by auto\n have \"(\\P. \\ (atom P \\ S \\ (\\.atom P) \\ S)) \\\n FF \\ S \\ (\\.TT) \\ S \\\n (\\F. (\\.\\.F) \\ S \\ S \\ {F} \\ \\⁺) \\\n (\\F. ((FormulaAlfa F) \\ F \\ S) \\ \n (S \\ {Comp1 F, Comp2 F}) \\ \\⁺) \\\n (\\F. ((FormulaBeta F) \\ F \\ S) \\ \n (S \\ {Comp1 F} \\ \\⁺) \\ (S \\ {Comp2 F} \\ \\⁺))\"\n using \n condiconsisP1[OF hip1 hip2 hip3] condiconsisP2[OF hip1 hip2 hip3]\n condiconsisP3[OF hip1 hip2 hip3] condiconsisP4[OF hip1 hip2 hip3]\n condiconsisP5[OF hip1 hip2 hip3] \n by blast}\n thus ?thesis by (simp add: consistenceP_def)\nqed\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "mayalarincon", "repo": "halltheorem", "sha": "6c694d6b154df4576b648810a5ec2f1814a0c99b", "save_path": "github-repos/isabelle/mayalarincon-halltheorem", "path": "github-repos/isabelle/mayalarincon-halltheorem/halltheorem-6c694d6b154df4576b648810a5ec2f1814a0c99b/ExistenciaModelosIngles/T5CCerradaIngles.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.17553806715374198, "lm_q1q2_score": 0.0701821651517276}} {"text": "(*\n * Copyright 2019, Data61\n * Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n * ABN 41 687 119 230.\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * @TAG(DATA61_BSD)\n *)\n\ntheory FP_Eval\nimports\n HOL.HOL\n \"ml-helpers/TermPatternAntiquote\"\nbegin\n\ntext \\\n FP_Eval: efficient evaluator for functional programs.\n\n The algorithm is similar to @{method simp}, but streamlined somewhat.\n Poorly-scaling simplifier features are omitted, e.g.:\n conditional rules, eta normalisation, rewriting under lambdas, etc.\n\n See FP_Eval_Tests for examples and tests. Currently, only\n ML conversions and tactics are provided.\n\n Features:\n \\ Low overhead (usually lower than @{method simp})\n \\ Applicative-order evaluation to WHNF (doesn't rewrite under lambdas)\n \\ Manual specification of rewrite rules, no global context\n \\ Cong rules supported for controlling evaluation (if, let, case, etc.)\n \\ Finer control than simp: explicit skeletons, debugging callbacks,\n perf counters (see signature for FP_Eval.eval')\n\n Major TODOs:\n \\ Preprocess rewrite rules for speed\n \\ Optimize eval_rec more\n \\ Support for simprocs (ideally with static checks)\n \\ Simple tactical and Isar method wrappers\n \\ Automatic ruleset builders\n \\ Static analysis for rules:\n \\ Confluence, termination\n \\ Completeness\n \\ Running time?\n \\ Dynamic analysis e.g. unused rules\n\n Work in progress.\n\\\n\nlocale FP_Eval begin\nlemma bool_prop_eq_True:\n \"Trueprop P \\ (P \\ True)\"\n by (simp add: atomize_eq)\n\nlemma bool_prop_eq_False:\n \"Trueprop (\\P) \\ (P \\ False)\"\n by (simp add: atomize_eq)\nend\n\nML \\\nstructure FP_Eval = struct\n\n(*** Utils ***)\n\n(* O(1) version of thm RS @{thm eq_reflection} *)\nfun then_eq_reflection thm = let\n val (x, y) = Thm.dest_binop (Thm.dest_arg (Thm.cprop_of thm));\n val cT = Thm.ctyp_of_cterm x;\n val rule = @{thm eq_reflection} |> Thm.instantiate' [SOME cT] [SOME x, SOME y];\n in Thm.implies_elim rule thm end;\n\nfun bool_conv_True thm =\n Thm.instantiate ([], [(((\"P\", 0), @{typ bool}),\n Thm.dest_arg (Thm.cprop_of thm))])\n @{thm FP_Eval.bool_prop_eq_True}\n |> (fn conv => Thm.equal_elim conv thm);\n\nfun bool_conv_False thm =\n Thm.instantiate ([], [(((\"P\", 0), @{typ bool}),\n Thm.dest_arg (Thm.dest_arg (Thm.cprop_of thm)))])\n @{thm FP_Eval.bool_prop_eq_False}\n |> (fn conv => Thm.equal_elim conv thm);\n\n(* Emulate simp's conversion of non-equational rules to \"P \\ True\", etc. *)\nfun maybe_convert_eqn thm =\n (* HACK: special case to transform @{thm refl} to \"(HOL.eq ?t ?t) \\ True\",\n as the default result of \"?t \\ ?t\" isn't what we want *)\n if Thm.eq_thm_prop (thm, @{thm refl}) then SOME (bool_conv_True thm) else\n (case Thm.prop_of thm of\n @{term_pat \"Trueprop (_ = _)\"} =>\n SOME (then_eq_reflection thm)\n | @{term_pat \"Trueprop (\\ _)\"} =>\n SOME (bool_conv_False thm)\n | @{term_pat \"_ \\ _\"} => SOME thm\n | @{term_pat \"Trueprop _\"} =>\n SOME (bool_conv_True thm)\n | _ => NONE);\n\n(* FIXME: turn into Config.\n NB: low-level eval' ignores this global setting *)\n(* 0: none; 1: summary details; 2+: everything *)\nval trace = Unsynchronized.ref 0;\n\n\n(*** Data structures ***)\n\n(* TODOs:\n - cond rules?\n - simprocs?\n - skeleton optimisation?\n*)\ntype eqns_for_const =\n int * (* arity of const (we require it to be equal in all rules) *)\n (int list * thm) option * (* possible cong rule skeleton (list of which args to evaluate) *)\n thm Net.net; (* eval equations *)\n(* NB: the cong thm is never actually used; it only tells\n fp_eval how to perform the rewriting. *)\n\n(* Main fp_eval context *)\ntype rules = eqns_for_const Symtab.table;\n\n(* For completeness, though make_rules is preferred *)\nval empty_rules : rules = Symtab.empty;\n\n\n(*** Data structure operations ***)\n\n(* Must be simple Pure.eq equations *)\nval net_from_eqns : thm list -> thm Net.net = fn eqns =>\n let fun lift_eqn eqn = (case Thm.prop_of eqn of\n @{term_pat \"_ \\ _\"} => eqn\n | _ => raise THM (\"net_from_eqns: not a simple equation\", 0, [eqn]));\n val eqns' = map lift_eqn eqns;\n fun insert eqn = Net.insert_term (K false) (Thm.term_of (Thm.lhs_of eqn), eqn);\n in fold_rev insert eqns' Net.empty end;\n\n(* Must be a simple Pure.eq equation, or convertible to one *)\nfun add_eqn raw_eqn : rules -> rules =\n let val eqn = case maybe_convert_eqn raw_eqn of\n NONE => raise THM (\"add_eqn: can't use this as equation\", 0, [raw_eqn])\n | SOME eqn => eqn;\n val eqn_lhs = Thm.term_of (Thm.lhs_of eqn);\n val (cname, args) = case strip_comb eqn_lhs of\n (* This should be OK because Const names are qualified *)\n (Const (cname, _), args) => (cname, args)\n | (Free (cname, _), args) => (cname, args)\n | _ => raise THM (\"add_eqn: head of LHS is not a constant\", 0, [eqn]);\n val arity = length args;\n val empty_entry = (cname, (arity, NONE, Net.empty));\n fun update_entry (arity', cong, net) =\n if arity <> arity'\n then raise THM (\"add_eqn: arity mismatch for \" ^ cname ^\n \" (existing=\" ^ string_of_int arity' ^\n \", new=\" ^ string_of_int arity ^ \")\", 0, [raw_eqn])\n else (arity, cong, Net.insert_term (K false) (eqn_lhs, eqn) net);\n in Symtab.map_default empty_entry update_entry end\n\n(* Helper for add_cong. cong_thm must be a weak cong rule of the form\n\n \"\\ ?x_i = ?y_i;\n ?x_j = ?y_j \\ \\\n my_const ?x_1 ?x_2 ... ?x_i ... = my_const ?x_1 ... ?y_i ...\"\n\n Returns indices of ?x_i in the LHS of the conclusion.\n *)\nfun process_cong cong_thm : string * int * int list =\n let fun die msg terms = raise TERM (\"add_cong: \" ^ msg, terms @ [Thm.prop_of cong_thm]);\n (* LHS vars in premises tell us which order to use for rewriting *)\n fun dest_prem (Const (@{const_name Pure.eq}, _) $ Var (vl, _) $ Var (vr, _)) = (vl, vr)\n | dest_prem (@{const Trueprop} $\n (Const (@{const_name HOL.eq}, _) $ Var (vl, _) $ Var (vr, _))) = (vl, vr)\n | dest_prem t = die \"premise not a simple equality\" [t];\n val prem_pairs = Logic.strip_imp_prems (Thm.prop_of cong_thm)\n |> map dest_prem;\n (* check concl and get LHS argument list *)\n val (concl_lhs, concl_rhs) =\n case Logic.strip_imp_concl (Thm.prop_of cong_thm) of\n @{term_pat \"?lhs \\ ?rhs\"} => (lhs, rhs)\n | @{term_pat \"Trueprop (?lhs = ?rhs)\"} => (lhs, rhs)\n | concl => die \"concl not a simple equality\" [concl];\n val (cname, arg_pairs) = case apply2 strip_comb (concl_lhs, concl_rhs) of\n ((head as Const (cname, _), args1), (head' as Const (cname', _), args2)) =>\n if cname <> cname'\n then die \"different consts\" [head, head']\n else if length args1 <> length args2\n then die \"different arities\" [concl_lhs, concl_rhs]\n else if not (forall is_Var (args1 @ args2))\n then die \"args not schematic vars\" [concl_lhs, concl_rhs]\n else (cname, map (apply2 (dest_Var #> fst)) (args1 ~~ args2))\n | _ => die \"equation heads are not constants\" [concl_lhs, concl_rhs];\n (* for each prem LHS, find its argument position in the concl *)\n fun prem_index var = case find_index (fn v => v = var) (map fst arg_pairs) of\n ~1 => die \"var in prems but not conclusion\" [Var (var, dummyT)]\n | n => n;\n val prem_indices = map prem_index (map fst prem_pairs);\n (* ensure no duplicates, otherwise fp_eval would do multiple evaluations *)\n val _ = case duplicates (op=) prem_indices of\n [] => ()\n | (n::_) => die \"var appears twice in prems\" [Var (fst (nth prem_pairs n), dummyT)];\n (* TODO: we could do even more checking here, but most other errors would\n cause fp_eval to fail-fast *)\n val const_arity = length arg_pairs;\n in (cname, const_arity, prem_indices) end;\n\nfun add_cong cong_thm : rules -> rules =\n let val (cname, arity, cong_spec) = process_cong cong_thm;\n val empty_entry = (cname, (arity, NONE, Net.empty));\n fun update_entry (arity', opt_cong, net) =\n if arity <> arity'\n then raise THM (\"add_cong: arity mismatch for \" ^ cname ^\n \" (existing=\" ^ string_of_int arity' ^\n \", new=\" ^ string_of_int arity ^ \")\", 0, [cong_thm])\n else case opt_cong of\n NONE => (arity, SOME (cong_spec, cong_thm), net)\n | SOME (cong_spec', cong_thm') =>\n if cong_spec = cong_spec'\n then (warning (\"add_cong: adding duplicate for \" ^ cname);\n (arity, opt_cong, net))\n else raise THM (\"add_cong: different cong rule already exists for \" ^ cname,\n 0, [cong_thm', cong_thm]);\n in Symtab.map_default empty_entry update_entry end;\n\n(* Simple builder *)\nfun make_rules eqns congs = fold_rev add_eqn eqns (fold add_cong congs empty_rules);\n\nfun merge_rules (r1, r2) =\n let fun merge_const cname (r as (arity, cong, net), r' as (arity', cong', net')) =\n if pointer_eq (r, r') then r else\n let val _ = if arity = arity' then () else\n error (\"merge_rules: different arity for \" ^ cname ^ \": \" ^\n string_of_int arity ^ \", \" ^ string_of_int arity');\n val cong'' = case (cong, cong') of\n (NONE, NONE) => NONE\n | (SOME _, NONE) => cong\n | (NONE, SOME _) => cong'\n | (SOME (_, thm), SOME (_, thm')) =>\n if Thm.eq_thm_prop (thm, thm') then cong else\n raise THM (\"merge_rules: different cong rules for \" ^ cname, 0,\n [thm, thm']);\n in (arity, cong'', Net.merge Thm.eq_thm_prop (net, net')) end;\n in if pointer_eq (r1, r2) then r1 else\n Symtab.join merge_const (r1, r2)\n end;\n\nfun dest_rules rules =\n let val const_rules = Symtab.dest rules |> map snd;\n val eqnss = map (fn (_, _, net) => Net.content net) const_rules;\n val congs = map_filter (fn (_, cong, _) => Option.map snd cong) const_rules;\n in (List.concat eqnss, congs) end;\n\n\n(*** Evaluator ***)\n\n(* Skeleton terms track which subterms have already been fully\n evaluated and can be skipped. This follows the same method as\n Raw_Simplifier.bottomc. *)\nval skel0 = Bound 0; (* always descend and rewrite *)\nval skel_skip = Var ((\"\", 0), dummyT); (* always skip *)\n\n(* Full interface *)\nfun eval' (ctxt: Proof.context)\n (debug_trace: int -> (unit -> string) -> unit) (* debug callback: level, message *)\n (breakpoint: cterm -> bool) (* if true, stop rewriting and return *)\n (eval_under_var: bool) (* if true, expand partially applied funcs under Var skeletons *)\n (rules: rules)\n (ct0: cterm, ct0_skel: term)\n (* eqn, final skeleton, perf counters *)\n : (thm * term) * (string * int) list = let\n (* Performance counters *)\n val counter_eval_rec = Unsynchronized.ref 0;\n val counter_try_rewr = Unsynchronized.ref 0;\n val counter_rewrite1 = Unsynchronized.ref 0;\n val counter_rewrites = Unsynchronized.ref 0;\n val counter_rewr_skel = Unsynchronized.ref 0;\n val counter_beta_redc = Unsynchronized.ref 0;\n val counter_transitive = Unsynchronized.ref 0;\n val counter_combination = Unsynchronized.ref 0;\n val counter_dest_comb = Unsynchronized.ref 0;\n val counter_congs = Unsynchronized.ref 0;\n fun increment c = (c := !c + 1);\n\n (* Debug output *)\n val print_term = Syntax.string_of_term ctxt;\n val print_cterm = print_term o Thm.term_of;\n fun print_maybe_thm t = Option.getOpt (Option.map (print_term o Thm.prop_of) t, \"\");\n\n (* Utils *)\n fun my_transitive t1 t2 =\n (increment counter_transitive;\n Thm.transitive t1 t2);\n fun my_combination t1 t2 =\n (increment counter_combination;\n Thm.combination t1 t2);\n\n fun transitive1 NONE NONE = NONE\n | transitive1 (t1 as SOME _) NONE = t1\n | transitive1 NONE (t2 as SOME _) = t2\n | transitive1 (SOME t1) (SOME t2) = SOME (my_transitive t1 t2);\n\n fun maybe_rewr_result NONE ct = ct\n | maybe_rewr_result (SOME rewr) _ = Thm.rhs_of rewr;\n\n fun maybe_eqn (SOME eqn) _ = eqn\n | maybe_eqn _ ct = Thm.reflexive ct;\n\n fun combination1 _ NONE _ NONE = NONE\n | combination1 cf cf_rewr cx cx_rewr =\n SOME (my_combination (maybe_eqn cf_rewr cf) (maybe_eqn cx_rewr cx));\n\n (* strip_comb; invent skeleton to same depth if required *)\n val strip_comb_skel = let\n fun strip (f $ x, fK $ xK, ts) = strip (f, fK, (x, xK)::ts)\n | strip (f $ x, skel as Var _, ts) =\n (* if a sub-comb is normalized, expand it for matching purposes,\n but don't expand children *)\n if eval_under_var then strip (f, skel, (x, skel)::ts)\n else (f $ x, skel, ts)\n (* skeleton doesn't match; be conservative and expand all *)\n | strip (f $ x, _, ts) = strip (f, skel0, (x, skel0)::ts)\n | strip (f, fK, ts) = (f, fK, ts) (* finish *);\n in fn (t, skel) => strip (t, skel, []) end;\n\n (* strip_comb for cterms *)\n val strip_ccomb : cterm -> int -> cterm * cterm list = let\n fun strip ts t n = if n = 0 then (t, ts) else\n case Thm.term_of t of\n _ $ _ => let val (f, x) = Thm.dest_comb t;\n (* yes, even dest_comb is nontrivial *)\n val _ = increment counter_dest_comb;\n in strip (x::ts) f (n-1) end\n | _ => (t, ts);\n in strip [] end;\n\n (* find the first matching eqn and use it *)\n fun rewrite1 _ [] = NONE\n | rewrite1 ct (eqn::eqns) = let\n val _ = increment counter_rewrite1;\n in\n SOME (Thm.instantiate (Thm.first_order_match (Thm.lhs_of eqn, ct)) eqn, eqn)\n |> tap (fn _ => increment counter_rewrites)\n handle Pattern.MATCH => rewrite1 ct eqns\n end;\n\n (* Apply rewrite step to skeleton.\n FIXME: traverses whole RHS. If the RHS is large and the rest of the\n evaluation ignores most of it, then this is wasted work.\n Either preprocess eqn or somehow update skel lazily *)\n fun rewrite_skel eqn skel =\n let val _ = debug_trace 2 (fn () => \"rewrite_skel: \" ^ print_maybe_thm (SOME eqn) ^ \" on \" ^ print_term skel);\n (* FIXME: may be wrong wrt. first_order_match--eta conversions? *)\n fun match (Var (v, _)) t = Vartab.map_default (v, t) I\n | match (pf $ px) (f $ x) = match pf f #> match px x\n | match (pf $ px) (t as Var _) = match pf t #> match px t\n | match (Abs (_, _, pt)) (Abs (_, _, t)) = match pt t\n | match (Abs (_, _, pt)) (t as Var _) = match pt t\n | match _ _ = I;\n val inst = match (Thm.term_of (Thm.lhs_of eqn)) skel Vartab.empty;\n fun subst (t as Var (v, _)) = Option.getOpt (Vartab.lookup inst v, t)\n | subst t = t;\n (* Consts in the RHS that don't appear in our rewrite rules, are also normalised *)\n fun norm_consts (t as Var _) = t\n | norm_consts (t as Bound _) = t\n | norm_consts (Abs (v, T, t)) = Abs (v, T, norm_consts t)\n | norm_consts (t as Const (cname, _)) =\n if Symtab.defined rules cname then t else Var ((cname, 0), dummyT)\n | norm_consts (t as Free (cname, _)) =\n if Symtab.defined rules cname then t else Var ((cname, 0), dummyT)\n | norm_consts (f $ x) =\n let val f' = norm_consts f;\n val x' = norm_consts x;\n in case (f', x') of\n (Var _, Var _) => f'\n | _ => f' $ x'\n end;\n in map_aterms subst (Thm.term_of (Thm.rhs_of eqn))\n |> tap (fn t' => counter_rewr_skel := !counter_rewr_skel + size_of_term t')\n |> norm_consts\n |> tap (fn t' => debug_trace 2 (fn () => \"rewrite_skel: ==> \" ^ print_term t')) end;\n\n fun apply_skel (f as Var _) (Var _) = f\n | apply_skel (f as Abs _) x = betapply (f, x)\n | apply_skel f x = f $ x;\n\n (* Main structure.\n We just rewrite all combinations inside-out, and ignore everything else.\n Special cases:\n - Combinations may have no arguments; this expands a single Const or Free.\n - A combination may have more args than the arity of its head, e.g.\n \"If c t f x y z ...\". In this case, we rewrite \"If c t f\" only,\n then recurse on the new combination.\n - If the head is a lambda abs, its arity is considered to be the number of\n bound vars; they are evaluated first and then beta redc is performed.\n *)\n val reached_breakpoint = Unsynchronized.ref false;\n fun eval_rec (ct, skel) =\n ((if !reached_breakpoint then () else reached_breakpoint := breakpoint ct);\n if !reached_breakpoint\n then (debug_trace 1 (fn () => \"eval_rec: triggered breakpoint on: \" ^ print_cterm ct);\n (NONE, skel))\n else\n (increment counter_eval_rec;\n debug_trace 2 (fn () => \"eval_rec: \" ^ print_cterm ct ^ \" (skel: \" ^ print_term skel ^ \")\");\n case skel of\n Var _ => (NONE, skel)\n | Abs _ => (NONE, skel)\n | _ => let\n val (head, head_skel, args) = strip_comb_skel (Thm.term_of ct, skel);\n val (chead, cargs) = strip_ccomb ct (length args);\n (* rules for head, if any *)\n val maybe_head_rules =\n case head of\n Const (cname, _) => Symtab.lookup rules cname\n | Free (cname, _) => Symtab.lookup rules cname\n | _ => NONE;\n\n val beta_depth = let\n fun f (Abs (_, _, t)) = 1 + f t\n | f _ = 0;\n in Int.min (length args, f head) end;\n\n (* Emulating call by value. First, we find the equation arity of the head.\n We evaluate a number of args up to the arity, except if the head has a\n cong specification, we follow the cong spec. *)\n val (eval_args, effective_arity) =\n case maybe_head_rules of\n SOME (arity, maybe_cong, _) =>\n if length args < arity\n then (List.tabulate (length args, I), length args)\n else (case maybe_cong of\n NONE => (List.tabulate (arity, I), arity)\n | SOME (indices, cong_thm) =>\n (increment counter_congs;\n debug_trace 2 (fn () => \"eval_rec: will use cong skeleton: \" ^ print_maybe_thm (SOME cong_thm));\n (indices, arity)))\n (* If head has no equations, just evaluate all arguments. *)\n | NONE => let val d = if beta_depth = 0 then length args else beta_depth;\n in (List.tabulate (d, I), d) end;\n val skip_args = subtract op= eval_args (List.tabulate (length args, I));\n\n (* evaluate args *)\n fun eval_arg i = (i, (nth cargs i, eval_rec (nth cargs i, snd (nth args i))));\n fun skip_arg i = (i, (nth cargs i, (NONE, snd (nth args i))));\n val arg_convs = map eval_arg eval_args @ map skip_arg skip_args\n |> sort (int_ord o apply2 fst) |> map snd;\n\n (* substitute results up to arity of head *)\n (* TODO: avoid unnecessary cterm ops? *)\n fun recombine beta_redc =\n fold (fn (arg, (arg_conv, arg_skel)) => fn (f, (f_conv, f_skel)) =>\n let val comb_thm = combination1 f f_conv arg arg_conv;\n val result = maybe_rewr_result comb_thm (Thm.apply f arg);\n (* respect breakpoint, if set *)\n in case (if not beta_redc orelse !reached_breakpoint then Bound 0\n else Thm.term_of f) of\n Abs _ => let\n val _ = debug_trace 2 (fn () =>\n \"eval_rec: beta redc: \" ^ print_cterm result);\n val _ = increment counter_beta_redc;\n val beta_thm = Thm.beta_conversion false result;\n (* f_skel must be Abs, for apply_skel to do what we want *)\n val f_skel' = case f_skel of Abs _ => f_skel\n | _ => Thm.term_of f;\n in (Thm.rhs_of beta_thm,\n (transitive1 comb_thm (SOME beta_thm),\n apply_skel f_skel' arg_skel)) end\n | _ => (result, (comb_thm, apply_skel f_skel arg_skel))\n end);\n\n val (ct', (arg_conv, skel')) =\n recombine true\n (take effective_arity arg_convs)\n (chead, (NONE, head_skel));\n\n (* Now rewrite the application of head to args *)\n val _ = debug_trace 2 (fn () => \"eval_rec: head is \" ^ print_term head ^\n \", (effective) arity \" ^ string_of_int effective_arity);\n in case maybe_head_rules of (* TODO: refactor the following *)\n NONE =>\n if beta_depth = 0\n then let (* No equation and not Abs head, so mark as normalised.\n We also know effective_arity = length args, so arg_convs\n is complete *)\n val _ = @{assert} (effective_arity = length args);\n val skel'' = case head of Abs _ => skel' | _ =>\n fold (fn x => fn f => apply_skel f x)\n (map (snd o snd) arg_convs) skel_skip;\n in (arg_conv, skel'') end\n else let (* Add remaining args and continue rewriting *)\n val (ct'', (conv'', skel'')) =\n recombine false\n (drop effective_arity arg_convs)\n (maybe_rewr_result arg_conv ct', (arg_conv, skel'));\n val (final_conv, final_skel) = eval_rec (ct'', skel'');\n in (transitive1 conv'' final_conv, final_skel) end\n | SOME (arity, _, net) =>\n if effective_arity < arity then (arg_conv, skel') else\n let val rewr_result =\n if !reached_breakpoint then NONE else\n (debug_trace 2 (fn () => \"eval_rec: now rewrite head from: \" ^ print_cterm ct');\n rewrite1 ct' (Net.match_term net (Thm.term_of ct')));\n in case rewr_result of\n NONE =>\n (* No equations; add remaining args and mark head as normalised *)\n let val (_, (conv'', _)) =\n recombine false\n (drop effective_arity arg_convs)\n (ct', (arg_conv, skel'));\n val skel'' = fold (fn x => fn f => apply_skel f x)\n (map (snd o snd) arg_convs) skel_skip;\n in (conv'', skel'') end\n | SOME (conv, rule) =>\n let val _ = debug_trace 2 (fn () => \"eval: \"\n ^ print_maybe_thm (SOME conv) ^ \"\\n using: \"\n ^ print_maybe_thm (SOME rule));\n val _ = increment counter_try_rewr;\n val rhs_skel = rewrite_skel rule skel';\n val conv' = case arg_conv of NONE => conv\n | SOME t => my_transitive t conv;\n val _ = debug_trace 2 (fn () =>\n \"eval_rec: after rewrite: \" ^ print_maybe_thm (SOME conv'));\n (* Add remaining args and continue rewriting *)\n val (ct'', (conv'', skel'')) =\n recombine false\n (drop effective_arity arg_convs)\n (Thm.rhs_of conv', (SOME conv', rhs_skel));\n val (final_conv, final_skel) = eval_rec (ct'', skel'');\n in (transitive1 conv'' final_conv, final_skel) end\n end\n end\n |> tap (fn (conv, skel) => debug_trace 2 (fn () =>\n \"result: \" ^ print_maybe_thm (SOME (maybe_eqn conv ct)) ^ \"\\n skel: \" ^ print_term skel))\n ));\n\n (* Final result *)\n val (ct_rewr, final_skel) = eval_rec (ct0, ct0_skel);\n val counters = [\n (\"eval_rec\", !counter_eval_rec),\n (\"try_rewr\", !counter_try_rewr),\n (\"rewrite1\", !counter_rewrite1),\n (\"rewrites\", !counter_rewrites),\n (\"rewr_skel\", !counter_rewr_skel),\n (\"beta_redc\", !counter_beta_redc),\n (\"transitive\", !counter_transitive),\n (\"combination\", !counter_combination),\n (\"dest_comb\", !counter_dest_comb),\n (\"congs\", !counter_congs)\n ];\n in ((maybe_eqn ct_rewr ct0, final_skel), counters) end;\n\n\n(* Simplified interface with common defaults *)\nfun eval (ctxt: Proof.context)\n (rules: rules)\n : (cterm * term) -> ((thm * term) * (string * int) list) =\n let fun debug_trace level msg = if level <= !trace then tracing (msg ()) else ();\n fun breakpoint _ = false;\n val eval_under_var = false;\n in eval' ctxt debug_trace breakpoint eval_under_var rules end;\n\n(* Even simpler interface; uses default skel *)\nfun eval_conv ctxt rules: conv =\n rpair skel0 #> eval ctxt rules #> fst #> fst;\n\n(* FIXME: eval doesn't rewrite under binders, we should add some forall_conv here *)\nfun eval_tac ctxt rules n: tactic =\n Conv.gconv_rule (eval_conv ctxt rules) n\n #> Seq.succeed;\n\nend;\n\\\n\ntext \\See FP_Eval_Tests for explanation\\\nlemma (in FP_Eval) let_weak_cong':\n \"a = b \\ Let a t = Let b t\"\n by simp\n\nend", "meta": {"author": "amblafont", "repo": "AutoCorres", "sha": "a8e96bff9fb22d633ff473401947ca84235d3b73", "save_path": "github-repos/isabelle/amblafont-AutoCorres", "path": "github-repos/isabelle/amblafont-AutoCorres/AutoCorres-a8e96bff9fb22d633ff473401947ca84235d3b73/lib/FP_Eval.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.14414885303274058, "lm_q1q2_score": 0.06813678100236364}} {"text": "(*<*)\ntheory Resumen\nimports Main \"HOL-Library.LaTeXsugar\" \"HOL-Library.OptionalSugar\" \nbegin\n(*>*)\n\ntext \\\nEl objetivo de la Lógica es la formalización del conocimiento y su\nrazonamiento. En este trabajo, estudiaremos elementos de la lógica\nproposicional desde la perspectiva teórica de \\First−Order Logic and \nAutomated Theorem Proving\\ \\[4]\\ de Melvin Fitting. En particular, nos \ncentraremos en la sintaxis y la semántica, concluyendo con la versión \nproposicional del lema de Hintikka sobre la satisfacibilidad de una \nclase determinada de conjuntos de fórmulas. Siguiendo la inspiración de \n\\Propositional Proof Systems\\ \\[10]\\ por Julius Michaelis y Tobias \nNipkow, los resultados expuestos serán formalizados mediante Isabelle: \nun demostrador interactivo que incluye herramientas de razonamiento \nautomático para guiar al usuario en el proceso de formalización, \nverificación y automatización de resultados. Concretamente, Isabelle/HOL \nes una especialización de Isabelle para la lógica de orden superior. \nLas demostraciones de los resultados en Isabelle/HOL se elaborarán \nsiguiendo dos tácticas distintas a lo largo del trabajo. En primer \nlugar, cada lema será probado de manera detallada prescindiendo de toda \nherramienta de razonamiento automático, como resultado de una búsqueda \ninversa en cada paso de la prueba. En contraposición, elaboraremos una \ndemostración automática alternativa de cada resultado que utilice todas \nlas herramientas de razonamiento automático que proporciona el \ndemostrador. De este modo, se evidenciará la capacidad de razonamiento \nautomático de Isabelle. \n \\\n\n(*section \\Abstract \\*)\n\ntext\\Logic’s purpose is about knowledge’s formalisation and its \nreasoning. In this project, we will approach Propositional Logic’s \nelements from the theoretical perspective of \\First−Order Logic and \nAutomated Theorem Proving\\ \\[4]\\ by Melvin Fitting. We will focus on the \nstudy of Syntax and Semantics to reach propositional version of \nHintikka’s lemma, which determinate the satisfiability of a concrete \ntype of formula set. Inspired by \\Propositional Proof Systems\\ \\[10]\\ by \nJulius Michaelis and Tobias Nipkow, these results will be formalised \nusing Isabelle: a proof assistant including automatic reasoning tools \nto guide the user on formalising, verifying and automating results. In \nparticular, Isabelle/HOL is the specialization of Isabelle for \nHigh-Order Logic. The processing of the results formalised in \nIsabelle/HOL follows two directions. In the first place, each lemma \nwill be proved on detail without any automation, as the result of an \ninverse research on every step of the demonstration until it is only \ncompleted with deductions based on elementary rules and definitions. \nConversely, we will alternatively prove the results using all the \nautomatic reasoning tools that are provide by the proof assistant. In \nthis way,\\\\ Isabelle’s power of automatic reasoning will be shown as the \ncontrast between these two different proving tactics. \n\\\n\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "sofsanfer", "repo": "TFG", "sha": "6030097eccb70ea2c2d1ef84183ee5c867bfb4df", "save_path": "github-repos/isabelle/sofsanfer-TFG", "path": "github-repos/isabelle/sofsanfer-TFG/TFG-6030097eccb70ea2c2d1ef84183ee5c867bfb4df/Logica_Proposicional/Resumen.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.13660838475359832, "lm_q1q2_score": 0.06777057673024936}} {"text": "section \\Implementation of Flow Networks\\\ntheory Network_Impl\nimports \n \"Lib/Refine_Add_Fofu\"\n Ford_Fulkerson \nbegin\n\nsubsection \\Type Constraints\\ \ntext \\We constrain the types that we use for implementation.\\ \n \ntext \\We define capacities to be integer values.\\ \ntype_synonym capacity_impl = int\ntype_synonym flow_impl = \"capacity_impl flow\" \n \ntext \\We define a locale that assumes that the nodes are natural numbers in the \n range @{term \"{0.. \n\nlocale Network_Impl = Network c s t for c :: \"capacity_impl graph\" and s t +\n fixes N :: nat\n assumes V_ss: \"V\\{0.. {0..{0.. \\Network Implementation Locale\\\n\nsubsection \\Basic Operations\\\n \ncontext Network_Impl\nbegin\n subsubsection \\Residual Graph\\\n text \\Get the residual capacity of an edge.\\ \n definition cf_get :: \"flow_impl \\ edge \\ capacity_impl nres\" \n where \"cf_get cf e \\ do {\n assert (e\\E \\ E\\);\n return (cf e)\n }\" \n \n text \\Update the residual capacity of an edge.\\ \n definition cf_set :: \"flow_impl \\ edge \\ capacity_impl \\ flow_impl nres\" \n where \"cf_set cf e x \\ do {\n assert (e\\E \\ E\\);\n return (cf (e:=x))\n }\" \n \n text \\Obtain the initial residual graph.\\ \n definition cf_init :: \"flow_impl nres\" \n where \"cf_init \\ return (op_mtx_new c)\"\n \n subsubsection \\Adjacency Map\\\n text \\Obtain the list of adjacent nodes for a specified node.\\ \n definition am_get :: \"(node \\ node list) \\ node \\ node list nres\" \n where \"am_get am u \\ do {\n assert (u\\V);\n return (am u)\n }\"\n \n text \\Test whether a node identifier is actually a node. \n As not all numbers in the range @{term \\{0..} must identify nodes, \n this function uses the adjacency map to check whether there are adjacent\n edges. Due to the network constraints, all nodes have adjacent edges.\n \\ \n definition am_is_in_V :: \"(node \\ node list) \\ node \\ bool nres\"\n where \"am_is_in_V am u \\ do {\n return (am u \\ [])\n }\"\n \n lemma am_is_in_V_correct[THEN order_trans, refine_vcg]: \n assumes \"(am,adjacent_nodes) \\ nat_rel \\ \\nat_rel\\list_set_rel\"\n shows \"am_is_in_V am u \\ (spec x. x \\ u\\V)\"\n proof -\n have \"u\\V \\ adjacent_nodes u \\ {}\" \n unfolding V_def adjacent_nodes_def by auto\n also have \"\\ \\ am u \\ []\" \n using fun_relD[OF assms IdI[of u]] \n by (auto simp: list_set_rel_def in_br_conv)\n finally show ?thesis unfolding am_is_in_V_def by refine_vcg auto\n qed \n \nend \\ \\Network Implementation Locale\\\n \nsubsubsection \\Registration of Basic Operations to Sepref\\ \n\ntext \\Bundles the setup for registration of abstract operations.\\ \nbundle Network_Impl_Sepref_Register begin\n text \\Automatically rewrite to \\i_mtx\\ interface type\\ \n lemmas [map_type_eqs] = \n map_type_eqI[of \"TYPE(capacity_impl flow)\" \"TYPE(capacity_impl i_mtx)\"]\n \nend \\ \\Bundle\\\n \n \ncontext Network_Impl\nbegin\n\nsubsubsection \\Registration of Abstract Operations\\ \n \ncontext\n includes Network_Impl_Sepref_Register\nbegin\n\nsepref_register N s t\nsepref_register c :: \"capacity_impl graph\"\n\nsepref_register cf_get cf_set cf_init\n \nsepref_register am_get am_is_in_V \n \nend \\ \\Anonymous Context\\ \n\nend \\ \\Network Implementation Locale\\\n \nsubsection \\Refinement To Efficient Data Structures\\ \n\nsubsubsection \\Functions from Nodes by Arrays\\ \n(*\n TODO: Move to own file in IICF\n \n This has more general uses than implementing nodes!\n It can implement functions from any objects represented by an initial\n segment of the natural numbers, a very often recurring pattern.\n*) \ntext \\\n We provide a template for implementing functions from nodes by arrays.\n Outside the node range, the abstract functions have a default value.\n\n This template is then used for refinement of various data structures.\n\\ \ndefinition \"is_nf N dflt f a \n \\ \\\\<^sub>Al. a\\\\<^sub>al * \\(length l = N \\ (\\i (\\i\\N. f i = dflt))\"\n \nlemma nf_init_rule: \n \" Array.new N dflt _. dflt)>\"\n unfolding is_nf_def by sep_auto\n\nlemma nf_copy_rule[sep_heap_rules]: \n \" array_copy a <\\r. is_nf N dflt f a * is_nf N dflt f r>\"\n unfolding is_nf_def by sep_auto\n \nlemma nf_lookup_rule[sep_heap_rules]: \n \"v Array.nth a v <\\r. is_nf N dflt f a *\\(r = f v)>\"\n unfolding is_nf_def by sep_auto\n \nlemma nf_update_rule[sep_heap_rules]: \n \"v Array.upd v x a \" \n unfolding is_nf_def by sep_auto\n \n \n \nsubsubsection \\Automation Setup for Side-Condition Discharging\\ \n \ncontext Network_Impl\nbegin\n \n\nlemma mtx_nonzero_iff[simp]: \"mtx_nonzero c = E\" \n unfolding E_def by (auto simp: mtx_nonzero_def)\n\nlemma mtx_nonzeroN: \"mtx_nonzero c \\ {0..{0.. mtx_nonzero c \\ u vV \\ vE \\ e\\E\\ \\ case e of (u,v) \\ u vNetwork Parameters by Identity\\ \nabbreviation (in -) cap_assn :: \"capacity_impl \\ _\" where \"cap_assn \\ id_assn\" \nabbreviation (in -) \"edge_assn \\ nat_assn \\\\<^sub>a nat_assn\" \nabbreviation (in -) (input) \"node_assn \\ nat_assn\" \n\ntext \\Refine number of nodes, and source and sink node by themselves\\\nlemmas [sepref_import_param] = \n IdI[of N]\n IdI[of s]\n IdI[of t]\n\nlemma c_hnr[sepref_fr_rules]: \n \"(uncurry0 (return c),uncurry0 (RETURN c))\n \\unit_assn\\<^sup>k \\\\<^sub>a pure (nat_rel \\\\<^sub>r nat_rel \\ Id)\"\n by (sepref_to_hoare) sep_auto \n \n \nsubsubsection \\Residual Graph by Adjacency Matrix\\ \n \ndefinition (in -) \"cf_assn N \\ asmtx_assn N cap_assn\"\nabbreviation cf_assn where \"cf_assn \\ Network_Impl.cf_assn N\"\nlemma [intf_of_assn]: \"intf_of_assn (cf_assn) TYPE(capacity_impl i_mtx)\"\n by simp\n \nsepref_thm cf_get_impl is \"uncurry (PR_CONST cf_get)\" \n :: \"cf_assn\\<^sup>k *\\<^sub>a edge_assn\\<^sup>k \\\\<^sub>a cap_assn\" \n unfolding cf_get_def cf_assn_def PR_CONST_def\n by sepref\nconcrete_definition (in -) cf_get_impl \n uses Network_Impl.cf_get_impl.refine_raw is \"(uncurry ?f,_)\\_\"\n \nsepref_thm cf_set_impl is \"uncurry2 (PR_CONST cf_set)\" \n :: \"cf_assn\\<^sup>d *\\<^sub>a edge_assn\\<^sup>k *\\<^sub>a cap_assn\\<^sup>k \\\\<^sub>a cf_assn\" \n unfolding cf_set_def cf_assn_def PR_CONST_def by sepref\nconcrete_definition (in -) cf_set_impl \n uses Network_Impl.cf_set_impl.refine_raw is \"(uncurry2 ?f,_)\\_\"\n\nsepref_thm cf_init_impl is \"uncurry0 (PR_CONST cf_init)\" \n :: \"unit_assn\\<^sup>k \\\\<^sub>a cf_assn\" \n unfolding PR_CONST_def cf_assn_def cf_init_def \n apply (rewrite amtx_fold_custom_new[of N N])\n by sepref \nconcrete_definition (in -) cf_init_impl \n uses Network_Impl.cf_init_impl.refine_raw is \"(uncurry0 ?f,_)\\_\"\nlemmas [sepref_fr_rules] = \n cf_get_impl.refine[OF Network_Impl_axioms] \n cf_set_impl.refine[OF Network_Impl_axioms] \n cf_init_impl.refine[OF Network_Impl_axioms]\n \n \n \nsubsubsection \\Adjacency Map by Array\\ \ndefinition (in -) \"am_assn N \\ is_nf N ([]::nat list)\" \nabbreviation am_assn where \"am_assn \\ Network_Impl.am_assn N\"\n\nlemma am_get_hnr[sepref_fr_rules]: \n \"(uncurry Array.nth, uncurry (PR_CONST am_get)) \n \\ am_assn\\<^sup>k *\\<^sub>a node_assn\\<^sup>k \\\\<^sub>a list_assn id_assn\" \n unfolding am_assn_def am_get_def list_assn_pure_conv\n by sepref_to_hoare (sep_auto simp: refine_pw_simps)\n\n \ndefinition (in -) \"am_is_in_V_impl am u \\ do {\n amu \\ Array.nth am u;\n return (\\is_Nil amu)\n}\" \nlemma am_is_in_V_hnr[sepref_fr_rules]: \"(uncurry am_is_in_V_impl, uncurry (am_is_in_V)) \n \\ [\\(_,v). va am_assn\\<^sup>k *\\<^sub>a node_assn\\<^sup>k \\ bool_assn\" \n unfolding am_assn_def am_is_in_V_def am_is_in_V_impl_def\n apply sepref_to_hoare \n apply (sep_auto simp: refine_pw_simps split: list.split)\n done\n \nend \\ \\Network Implementation Locale\\\n \nsubsection \\Computing the Flow Value\\\ntext \\We define an algorithm to compute the value of a flow from \n the residual graph\n\\ \n \nlocale RGraph_Impl = RGraph c s t cf + Network_Impl c s t N\n for c :: \"capacity_impl flow\" and s t N cf\n \nlemma rgraph_and_network_impl_imp_rgraph_impl:\n assumes \"RGraph c s t cf\"\n assumes \"Network_Impl c s t N\"\n shows \"RGraph_Impl c s t N cf\" \n using assms by (rule Network_Impl.RGraph_Impl.intro) \n \n \nlemma (in RGraph) val_by_adj_map: \n assumes AM: \"is_adj_map am\"\n shows \"f.val = (\\v\\set (am s). cf (v,s))\"\nproof -\n have [simp]: \"set (am s) = E``{s}\"\n using AM unfolding is_adj_map_def\n by auto\n \n note f.val_by_cf\n also note rg_is_cf\n also have \"(\\(u, v)\\outgoing s. cf (v, u)) \n = ((\\v\\set (am s). cf (v,s)))\" \n by (simp add: sum_outgoing_pointwise)\n finally show ?thesis . \nqed \n \ncontext Network_Impl \nbegin\n \ndefinition \"compute_flow_val_aux am cf \\ do {\n succs \\ am_get am s;\n sum_impl (\\v. cf_get cf (v,s)) (set succs)\n }\"\n\nlemma (in RGraph_Impl) compute_flow_val_aux_correct:\n assumes \"is_adj_map am\"\n shows \"compute_flow_val_aux am cf \\ (spec v. v = f.val)\"\n unfolding val_by_adj_map[OF assms]\n unfolding compute_flow_val_aux_def cf_get_def am_get_def\n apply (refine_vcg sum_impl_correct)\n apply (vc_solve simp: s_node)\n subgoal using assms unfolding is_adj_map_def by auto \n done\n \ntext \\For technical reasons (poor foreach-support of Sepref tool), \n we have to add another refinement step: \\ \ndefinition \"compute_flow_val am cf \\ (do {\n succs \\ am_get am s;\n nfoldli succs (\\_. True) (\\x a. do {\n b \\ cf_get cf (x, s); \n return (a + b)\n }) 0\n})\" \n\nlemma (in RGraph_Impl) compute_flow_val_correct[THEN order_trans, refine_vcg]:\n assumes \"is_adj_map am\"\n shows \"compute_flow_val am cf \\ (spec v. v = f.val)\"\nproof -\n have [refine_dref_RELATES]: \"RELATES (\\Id\\list_set_rel)\" \n by (simp add: RELATES_def)\n show ?thesis\n apply (rule order_trans[OF _ compute_flow_val_aux_correct[OF assms]])\n unfolding compute_flow_val_def compute_flow_val_aux_def sum_impl_def\n apply (rule refine_IdD)\n apply (refine_rcg LFO_refine bind_refine')\n apply refine_dref_type\n apply vc_solve\n using assms\n by (auto \n simp: list_set_rel_def br_def am_get_def is_adj_map_def \n simp: refine_pw_simps)\nqed \n \ncontext \n includes Network_Impl_Sepref_Register\nbegin \n sepref_register compute_flow_val\nend \n \nsepref_thm compute_flow_val_impl\n is \"uncurry (PR_CONST compute_flow_val)\" \n :: \"am_assn\\<^sup>k *\\<^sub>a cf_assn\\<^sup>k \\\\<^sub>a cap_assn\" \n unfolding compute_flow_val_def PR_CONST_def\n by sepref \nconcrete_definition (in -) compute_flow_val_impl \n uses Network_Impl.compute_flow_val_impl.refine_raw is \"(uncurry ?f,_)\\_\"\nlemmas compute_flow_val_impl_hnr[sepref_fr_rules] \n = compute_flow_val_impl.refine[OF Network_Impl_axioms]\n \nend \\ \\Network Implementation Locale\\\n \ntext \\We also export a correctness theorem on the separation logic level\\ \n\nlemma compute_flow_val_impl_correct[sep_heap_rules]:\n assumes \"RGraph_Impl c s t N cf\"\n assumes AM: \"Graph.is_adj_map c am\" \n shows \" \n compute_flow_val_impl s N ami cfi \n <\\v. cf_assn N cf cfi * am_assn N am ami \n * \\( v = Flow.val c s (RPreGraph.f c cf) )>\\<^sub>t\"\nproof -\n interpret RGraph_Impl c s t N cf by fact\n\n \n from hn_refine_ref[OF \n compute_flow_val_correct[OF AM order_refl] \n compute_flow_val_impl_hnr[to_hnr, unfolded autoref_tag_defs]] \n show ?thesis \n apply (simp add: hn_ctxt_def pure_def hn_refine_def f_def)\n apply (rule cons_post_rule)\n apply assumption \n apply sep_auto\n done \nqed \n \nsubsubsection \\Computing the Exact Number of Nodes\\ \n \ncontext Network_Impl\nbegin\n \nlemma am_to_adj_nodes_refine:\n assumes AM: \"is_adj_map am\" \n shows \"(am u, adjacent_nodes u) \\ \\nat_rel\\list_set_rel\" \n using AM \n unfolding adjacent_nodes_def is_adj_map_def \n by (auto simp: list_set_rel_def in_br_conv) \n\n \n \n \ndefinition \"init_C am \\ do {\n let cardV=0;\n nfoldli [0.._. True) (\\v cardV. do {\n assert (v am_is_in_V am v;\n if inV then do {\n return (cardV + 1)\n } else\n return cardV\n }) cardV\n}\" \n\nlemma init_C_correct:\n assumes AM: \"is_adj_map am\" \n shows \"init_C am \\ SPEC (\\C. C = card V)\"\n unfolding init_C_def \n apply (refine_vcg \n nfoldli_rule[where I=\"\\l1 _ C. C = card (V\\set l1)\"]\n ) \n apply clarsimp_all \n using V_ss \n apply (auto simp: upt_eq_lel_conv Int_absorb2 am_to_adj_nodes_refine[OF AM]) \n done \n\ncontext \n includes Network_Impl_Sepref_Register\nbegin \n sepref_register init_C \nend \n \nsepref_thm fifo_init_C_impl is \"(PR_CONST init_C)\" \n :: \"am_assn\\<^sup>k \\\\<^sub>a nat_assn\" \n unfolding init_C_def PR_CONST_def\n by sepref\nconcrete_definition (in -) fifo_init_C_impl \n uses Network_Impl.fifo_init_C_impl.refine_raw is \"(?f,_)\\_\"\nlemmas [sepref_fr_rules] = fifo_init_C_impl.refine[OF Network_Impl_axioms]\n \nend \\ \\Network Implementation Locale\\\n \nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Flow_Networks/Network_Impl.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.13846179234652575, "lm_q1q2_score": 0.06760859408570842}} {"text": "(*\n * Copyright 2014, NICTA\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * @TAG(NICTA_BSD)\n *)\n\ntheory WhileLoopRules\nimports \"NonDetMonadVCG\"\nbegin\n\nsection \"Well-ordered measures\"\n\n(* A version of \"measure\" that takes any wellorder, instead of\n * being fixed to \"nat\". *)\ndefinition measure' :: \"('a \\ 'b::wellorder) => ('a \\ 'a) set\"\nwhere \"measure' = (\\f. {(a, b). f a < f b})\"\n\nlemma in_measure'[simp, code_unfold]:\n \"((x,y) : measure' f) = (f x < f y)\"\n by (simp add:measure'_def)\n\nlemma wf_measure' [iff]: \"wf (measure' f)\"\n apply (clarsimp simp: measure'_def)\n apply (insert wf_inv_image [OF wellorder_class.wf, where f=f])\n apply (clarsimp simp: inv_image_def)\n done\n\nlemma wf_wellorder_measure: \"wf {(a, b). (M a :: 'a :: wellorder) < M b}\"\n apply (subgoal_tac \"wf (inv_image ({(a, b). a < b}) M)\")\n apply (clarsimp simp: inv_image_def)\n apply (rule wf_inv_image)\n apply (rule wellorder_class.wf)\n done\n\n\nsection \"whileLoop lemmas\"\n\ntext \\\n The following @{const whileLoop} definitions with additional\n invariant/variant annotations allow the user to annotate\n @{const whileLoop} terms with information that can be used\n by automated tools.\n\\\ndefinition\n \"whileLoop_inv (C :: 'a \\ 'b \\ bool) B x (I :: 'a \\ 'b \\ bool) (R :: (('a \\ 'b) \\ ('a \\ 'b)) set) \\ whileLoop C B x\"\n\ndefinition\n \"whileLoopE_inv (C :: 'a \\ 'b \\ bool) B x (I :: 'a \\ 'b \\ bool) (R :: (('a \\ 'b) \\ ('a \\ 'b)) set) \\ whileLoopE C B x\"\n\nlemma whileLoop_add_inv: \"whileLoop B C = (\\x. whileLoop_inv B C x I (measure' M))\"\n by (clarsimp simp: whileLoop_inv_def)\n\nlemma whileLoopE_add_inv: \"whileLoopE B C = (\\x. whileLoopE_inv B C x I (measure' M))\"\n by (clarsimp simp: whileLoopE_inv_def)\n\nsubsection \"Simple base rules\"\n\nlemma whileLoop_terminates_unfold:\n \"\\ whileLoop_terminates C B r s; (r', s') \\ fst (B r s); C r s \\\n \\ whileLoop_terminates C B r' s'\"\n apply (erule whileLoop_terminates.cases)\n apply simp\n apply force\n done\n\nlemma snd_whileLoop_first_step: \"\\ \\ snd (whileLoop C B r s); C r s \\ \\ \\ snd (B r s)\"\n apply (subst (asm) whileLoop_unroll)\n apply (clarsimp simp: bind_def condition_def)\n done\n\nlemma snd_whileLoopE_first_step: \"\\ \\ snd (whileLoopE C B r s); C r s \\ \\ \\ snd (B r s)\"\n apply (subgoal_tac \"\\ \\ snd (whileLoopE C B r s); C r s \\ \\ \\ snd ((lift B (Inr r)) s)\")\n apply (clarsimp simp: lift_def)\n apply (unfold whileLoopE_def)\n apply (erule snd_whileLoop_first_step)\n apply clarsimp\n done\n\nlemma snd_whileLoop_unfold:\n \"\\ \\ snd (whileLoop C B r s); C r s; (r', s') \\ fst (B r s) \\ \\ \\ snd (whileLoop C B r' s')\"\n apply (clarsimp simp: whileLoop_def)\n apply (auto simp: elim: whileLoop_results.cases whileLoop_terminates.cases\n intro: whileLoop_results.intros whileLoop_terminates.intros)\n done\n\nlemma snd_whileLoopE_unfold:\n \"\\ \\ snd (whileLoopE C B r s); (Inr r', s') \\ fst (B r s); C r s \\ \\ \\ snd (whileLoopE C B r' s')\"\n apply (clarsimp simp: whileLoopE_def)\n apply (drule snd_whileLoop_unfold)\n apply clarsimp\n apply (clarsimp simp: lift_def)\n apply assumption\n apply (clarsimp simp: lift_def)\n done\n\nlemma whileLoop_results_cong [cong]:\n assumes C: \"\\r s. C r s = C' r s\"\n and B:\"\\(r :: 'r) (s :: 's). C' r s \\ B r s = B' r s\"\n shows \"whileLoop_results C B = whileLoop_results C' B'\"\nproof -\n {\n fix x y C B C' B'\n have \"\\ (x, y) \\ whileLoop_results C B;\n \\(r :: 'r) (s :: 's). C r s = C' r s;\n \\r s. C' r s \\ B r s = B' r s \\\n \\ (x, y) \\ whileLoop_results C' B'\"\n apply (induct rule: whileLoop_results.induct)\n apply clarsimp\n apply clarsimp\n apply (rule whileLoop_results.intros, auto)[1]\n apply clarsimp\n apply (rule whileLoop_results.intros, auto)[1]\n done\n }\n\n thus ?thesis\n apply -\n apply (rule set_eqI, rule iffI)\n apply (clarsimp split: prod.splits)\n apply (clarsimp simp: C B split: prod.splits)\n apply (clarsimp split: prod.splits)\n apply (clarsimp simp: C [symmetric] B [symmetric] split: prod.splits)\n done\nqed\n\nlemma whileLoop_terminates_cong [cong]:\n assumes r: \"r = r'\"\n and s: \"s = s'\"\n and C: \"\\r s. C r s = C' r s\"\n and B: \"\\r s. C' r s \\ B r s = B' r s\"\n shows \"whileLoop_terminates C B r s = whileLoop_terminates C' B' r' s'\"\nproof (rule iffI)\n assume T: \"whileLoop_terminates C B r s\"\n show \"whileLoop_terminates C' B' r' s'\"\n apply (insert T r s)\n apply (induct arbitrary: r' s' rule: whileLoop_terminates.induct)\n apply (clarsimp simp: C)\n apply (erule whileLoop_terminates.intros)\n apply (clarsimp simp: C B split: prod.splits)\n apply (rule whileLoop_terminates.intros, assumption)\n apply (clarsimp simp: C B split: prod.splits)\n done\nnext\n assume T: \"whileLoop_terminates C' B' r' s'\"\n show \"whileLoop_terminates C B r s\"\n apply (insert T r s)\n apply (induct arbitrary: r s rule: whileLoop_terminates.induct)\n apply (rule whileLoop_terminates.intros)\n apply (clarsimp simp: C)\n apply (rule whileLoop_terminates.intros, fastforce simp: C)\n apply (clarsimp simp: C B split: prod.splits)\n done\nqed\n\nlemma whileLoop_cong [cong]:\n \"\\ \\r s. C r s = C' r s; \\r s. C r s \\ B r s = B' r s \\ \\ whileLoop C B = whileLoop C' B'\"\n apply (rule ext, clarsimp simp: whileLoop_def)\n done\n\nlemma whileLoopE_cong [cong]:\n \"\\ \\r s. C r s = C' r s ; \\r s. C r s \\ B r s = B' r s \\\n \\ whileLoopE C B = whileLoopE C' B'\"\n apply (clarsimp simp: whileLoopE_def)\n apply (rule whileLoop_cong [THEN arg_cong])\n apply (clarsimp split: sum.splits)\n apply (clarsimp split: sum.splits)\n apply (clarsimp simp: lift_def throwError_def split: sum.splits)\n done\n\nlemma whileLoop_terminates_wf:\n \"wf {(x, y). C (fst y) (snd y) \\ x \\ fst (B (fst y) (snd y)) \\ whileLoop_terminates C B (fst y) (snd y)}\"\n apply (rule wfI [where A=\"UNIV\" and B=\"{(r, s). whileLoop_terminates C B r s}\"])\n apply clarsimp\n apply clarsimp\n apply (erule whileLoop_terminates.induct)\n apply blast\n apply blast\n done\n\nsubsection \"Basic induction helper lemmas\"\n\nlemma whileLoop_results_induct_lemma1:\n \"\\ (a, b) \\ whileLoop_results C B; b = Some (x, y) \\ \\ \\ C x y\"\n apply (induct rule: whileLoop_results.induct, auto)\n done\n\nlemma whileLoop_results_induct_lemma1':\n \"\\ (a, b) \\ whileLoop_results C B; a \\ b \\ \\ \\x. a = Some x \\ C (fst x) (snd x)\"\n apply (induct rule: whileLoop_results.induct, auto)\n done\n\nlemma whileLoop_results_induct_lemma2 [consumes 1]:\n \"\\ (a, b) \\ whileLoop_results C B;\n a = Some (x :: 'a \\ 'b); b = Some y;\n P x; \\s t. \\ P s; t \\ fst (B (fst s) (snd s)); C (fst s) (snd s) \\ \\ P t \\ \\ P y\"\n apply (induct arbitrary: x y rule: whileLoop_results.induct)\n apply simp\n apply simp\n apply atomize\n apply fastforce\n done\n\nlemma whileLoop_results_induct_lemma3 [consumes 1]:\n assumes result: \"(Some (r, s), Some (r', s')) \\ whileLoop_results C B\"\n and inv_start: \"I r s\"\n and inv_step: \"\\r s r' s'. \\ I r s; C r s; (r', s') \\ fst (B r s) \\ \\ I r' s'\"\n shows \"I r' s'\"\n apply (rule whileLoop_results_induct_lemma2 [where P=\"case_prod I\" and y=\"(r', s')\" and x=\"(r, s)\",\n simplified case_prod_unfold, simplified])\n apply (rule result)\n apply simp\n apply simp\n apply fact\n apply (erule (1) inv_step)\n apply clarsimp\n done\n\nsubsection \"Inductive reasoning about whileLoop results\"\n\nlemma in_whileLoop_induct [consumes 1]:\n assumes in_whileLoop: \"(r', s') \\ fst (whileLoop C B r s)\"\n and init_I: \"\\ r s. \\ C r s \\ I r s r s\"\n and step:\n \"\\r s r' s' r'' s''.\n \\ C r s; (r', s') \\ fst (B r s);\n (r'', s'') \\ fst (whileLoop C B r' s');\n I r' s' r'' s'' \\ \\ I r s r'' s''\"\n shows \"I r s r' s'\"\nproof cases\n assume \"C r s\"\n\n {\n obtain a where a_def: \"a = Some (r, s)\"\n by blast\n obtain b where b_def: \"b = Some (r', s')\"\n by blast\n\n have \"\\ (a, b) \\ whileLoop_results C B; \\x. a = Some x; \\x. b = Some x \\\n \\ I (fst (the a)) (snd (the a)) (fst (the b)) (snd (the b))\"\n apply (induct rule: whileLoop_results.induct)\n apply (auto simp: init_I whileLoop_def intro: step)\n done\n\n hence \"(Some (r, s), Some (r', s')) \\ whileLoop_results C B\n \\ I r s r' s'\"\n by (clarsimp simp: a_def b_def)\n }\n\n thus ?thesis\n using in_whileLoop\n by (clarsimp simp: whileLoop_def)\nnext\n assume \"\\ C r s\"\n\n hence \"r' = r \\ s' = s\"\n using in_whileLoop\n by (subst (asm) whileLoop_unroll,\n clarsimp simp: condition_def return_def)\n\n thus ?thesis\n by (metis init_I \\\\ C r s\\)\nqed\n\nlemma snd_whileLoop_induct [consumes 1]:\n assumes induct: \"snd (whileLoop C B r s)\"\n and terminates: \"\\ whileLoop_terminates C B r s \\ I r s\"\n and init: \"\\ r s. \\ snd (B r s); C r s \\ \\ I r s\"\n and step: \"\\r s r' s' r'' s''.\n \\ C r s; (r', s') \\ fst (B r s);\n snd (whileLoop C B r' s');\n I r' s' \\ \\ I r s\"\n shows \"I r s\"\n apply (insert init induct)\n apply atomize\n apply (unfold whileLoop_def)\n apply clarsimp\n apply (erule disjE)\n apply (erule rev_mp)\n apply (induct \"Some (r, s)\" \"None :: ('a \\ 'b) option\"\n arbitrary: r s rule: whileLoop_results.induct)\n apply clarsimp\n apply clarsimp\n apply (erule (1) step)\n apply (clarsimp simp: whileLoop_def)\n apply clarsimp\n apply (metis terminates)\n done\n\nlemma whileLoop_terminatesE_induct [consumes 1]:\n assumes induct: \"whileLoop_terminatesE C B r s\"\n and init: \"\\r s. \\ C r s \\ I r s\"\n and step: \"\\r s r' s'. \\ C r s; \\(v', s') \\ fst (B r s). case v' of Inl _ \\ True | Inr r' \\ I r' s' \\ \\ I r s\"\n shows \"I r s\"\n apply (insert induct)\n apply (clarsimp simp: whileLoop_terminatesE_def)\n apply (subgoal_tac \"(\\r s. case (Inr r) of Inl x \\ True | Inr x \\ I x s) r s\")\n apply simp\n apply (induction rule: whileLoop_terminates.induct)\n apply (case_tac r)\n apply simp\n apply clarsimp\n apply (erule init)\n apply (clarsimp split: sum.splits)\n apply (rule step)\n apply simp\n apply (clarsimp simp: lift_def split: sum.splits)\n apply force\n done\n\nsubsection \"Direct reasoning about whileLoop components\"\n\nlemma fst_whileLoop_cond_false:\n assumes loop_result: \"(r', s') \\ fst (whileLoop C B r s)\"\n shows \"\\ C r' s'\"\n using loop_result\n by (rule in_whileLoop_induct, auto)\n\nlemma snd_whileLoop:\n assumes init_I: \"I r s\"\n and cond_I: \"C r s\"\n and non_term: \"\\r. \\ \\s. I r s \\ C r s \\ \\ snd (B r s) \\\n B r \\\\ \\r' s'. C r' s' \\ I r' s' \\\"\n shows \"snd (whileLoop C B r s)\"\n apply (clarsimp simp: whileLoop_def)\n apply (rotate_tac)\n apply (insert init_I cond_I)\n apply (induct rule: whileLoop_terminates.induct)\n apply clarsimp\n apply (cut_tac r=r in non_term)\n apply (clarsimp simp: exs_valid_def)\n apply (subst (asm) (2) whileLoop_results.simps)\n apply clarsimp\n apply (insert whileLoop_results.simps)\n apply fast\n done\n\nlemma whileLoop_terminates_inv:\n assumes init_I: \"I r s\"\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\\"\n assumes wf_R: \"wf R\"\n shows \"whileLoop_terminates C B r s\"\n apply (insert init_I)\n using wf_R\n apply (induction \"(r, s)\" arbitrary: r s)\n apply atomize\n apply (subst whileLoop_terminates_simps)\n apply clarsimp\n apply (erule use_valid)\n apply (rule hoare_strengthen_post, rule inv)\n apply force\n apply force\n done\n\nlemma not_snd_whileLoop:\n assumes init_I: \"I r s\"\n and inv_holds: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\!\"\n and wf_R: \"wf R\"\n shows \"\\ snd (whileLoop C B r s)\"\nproof -\n {\n fix x y\n have \"\\ (x, y) \\ whileLoop_results C B; x = Some (r, s); y = None \\ \\ False\"\n apply (insert init_I)\n apply (induct arbitrary: r s rule: whileLoop_results.inducts)\n apply simp\n apply simp\n apply (insert snd_validNF [OF inv_holds])[1]\n apply blast\n apply (drule use_validNF [OF _ inv_holds])\n apply simp\n apply clarsimp\n apply blast\n done\n }\n\n also have \"whileLoop_terminates C B r s\"\n apply (rule whileLoop_terminates_inv [where I=I, OF init_I _ wf_R])\n apply (insert inv_holds)\n apply (clarsimp simp: validNF_def)\n done\n\n ultimately show ?thesis\n by (clarsimp simp: whileLoop_def, blast)\nqed\n\nlemma valid_whileLoop:\n assumes first_step: \"\\s. P r s \\ I r s\"\n and inv_step: \"\\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\\"\n and final_step: \"\\r s. \\ I r s; \\ C r s \\ \\ Q r s\"\n shows \"\\ P r \\ whileLoop C B r \\ Q \\\"\nproof -\n {\n fix r' s' s\n assume inv: \"I r s\"\n assume step: \"(r', s') \\ fst (whileLoop C B r s)\"\n\n have \"I r' s'\"\n using step inv\n apply (induct rule: in_whileLoop_induct)\n apply simp\n apply (drule use_valid, rule inv_step, auto)\n done\n }\n\n thus ?thesis\n apply (clarsimp simp: valid_def)\n apply (drule first_step)\n apply (rule final_step, simp)\n apply (metis fst_whileLoop_cond_false)\n done\nqed\n\nlemma whileLoop_wp:\n \"\\ \\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\;\n \\r s. \\ I r s; \\ C r s \\ \\ Q r s \\ \\\n \\ I r \\ whileLoop C B r \\ Q \\\"\n by (rule valid_whileLoop)\n\nlemma whileLoop_wp_inv [wp]:\n \"\\ \\r. \\\\s. I r s \\ C r s\\ B r \\I\\; \\r s. \\I r s; \\ C r s\\ \\ Q r s \\\n \\ \\ I r \\ whileLoop_inv C B r I M \\ Q \\\"\n apply (clarsimp simp: whileLoop_inv_def)\n apply (rule valid_whileLoop [where P=I and I=I], auto)\n done\n\nlemma validE_whileLoopE:\n \"\\\\s. P r s \\ I r s;\n \\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\,\\ A \\;\n \\r s. \\ I r s; \\ C r s \\ \\ Q r s\n \\ \\ \\ P r \\ whileLoopE C B r \\ Q \\,\\ A \\\"\n apply (clarsimp simp: whileLoopE_def validE_def)\n apply (rule valid_whileLoop [where I=\"\\r s. (case r of Inl x \\ A x s | Inr x \\ I x s)\"\n and Q=\"\\r s. (case r of Inl x \\ A x s | Inr x \\ Q x s)\"])\n apply atomize\n apply (clarsimp simp: valid_def lift_def split: sum.splits)\n apply (clarsimp simp: valid_def lift_def split: sum.splits)\n apply (clarsimp split: sum.splits)\n done\n\nlemma whileLoopE_wp:\n \"\\ \\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\, \\ A \\;\n \\r s. \\ I r s; \\ C r s \\ \\ Q r s \\ \\\n \\ I r \\ whileLoopE C B r \\ Q \\, \\ A \\\"\n by (rule validE_whileLoopE)\n\nlemma exs_valid_whileLoop:\n assumes init_T: \"\\s. P s \\ T r s\"\n and iter_I: \"\\ r s0.\n \\ \\s. T r s \\ C r s \\ s = s0 \\\n B r \\\\\\r' s'. T r' s' \\ ((r', s'),(r, s0)) \\ R\\\"\n and wf_R: \"wf R\"\n and final_I: \"\\r s. \\ T r s; \\ C r s \\ \\ Q r s\"\n shows \"\\ P \\ whileLoop C B r \\\\ Q \\\"\nproof (clarsimp simp: exs_valid_def Bex_def)\n fix s\n assume \"P s\"\n\n {\n fix x\n have \"T (fst x) (snd x) \\\n \\r' s'. (r', s') \\ fst (whileLoop C B (fst x) (snd x)) \\ T r' s'\"\n using wf_R\n apply induction\n apply atomize\n apply (case_tac \"C (fst x) (snd x)\")\n apply (subst whileLoop_unroll)\n apply (clarsimp simp: condition_def bind_def' split: prod.splits)\n apply (cut_tac ?s0.0=b and r=a in iter_I)\n apply (clarsimp simp: exs_valid_def)\n apply blast\n apply (subst whileLoop_unroll)\n apply (clarsimp simp: condition_def bind_def' return_def)\n done\n }\n\n thus \"\\r' s'. (r', s') \\ fst (whileLoop C B r s) \\ Q r' s'\"\n by (metis \\P s\\ fst_conv init_T snd_conv\n final_I fst_whileLoop_cond_false)\nqed\n\nlemma empty_fail_whileLoop:\n assumes body_empty_fail: \"\\r. empty_fail (B r)\"\n shows \"empty_fail (whileLoop C B r)\"\nproof -\n {\n fix s A\n assume empty: \"fst (whileLoop C B r s) = {}\"\n\n have cond_true: \"\\x s. fst (whileLoop C B x s) = {} \\ C x s\"\n apply (subst (asm) whileLoop_unroll)\n apply (clarsimp simp: condition_def return_def split: if_split_asm)\n done\n\n have \"snd (whileLoop C B r s)\"\n apply (rule snd_whileLoop [where I=\"\\x s. fst (whileLoop C B x s) = {}\"])\n apply fact\n apply (rule cond_true, fact)\n apply (clarsimp simp: exs_valid_def)\n apply (case_tac \"fst (B r s) = {}\")\n apply (metis empty_failD [OF body_empty_fail])\n apply (subst (asm) whileLoop_unroll)\n apply (fastforce simp: condition_def bind_def split_def cond_true)\n done\n }\n\n thus ?thesis\n by (clarsimp simp: empty_fail_def)\nqed\n\nlemma empty_fail_whileLoopE:\n assumes body_empty_fail: \"\\r. empty_fail (B r)\"\n shows \"empty_fail (whileLoopE C B r)\"\n apply (clarsimp simp: whileLoopE_def)\n apply (rule empty_fail_whileLoop)\n apply (insert body_empty_fail)\n apply (clarsimp simp: empty_fail_def lift_def throwError_def return_def split: sum.splits)\n done\n\nlemma whileLoop_results_bisim:\n assumes base: \"(a, b) \\ whileLoop_results C B\"\n and vars1: \"Q = (case a of Some (r, s) \\ Some (rt r, st s) | _ \\ None)\"\n and vars2: \"R = (case b of Some (r, s) \\ Some (rt r, st s) | _ \\ None)\"\n and inv_init: \"case a of Some (r, s) \\ I r s | _ \\ True\"\n and inv_step: \"\\r s r' s'. \\ I r s; C r s; (r', s') \\ fst (B r s) \\ \\ I r' s'\"\n and cond_match: \"\\r s. I r s \\ C r s = C' (rt r) (st s)\"\n and fail_step: \"\\r s. \\C r s; snd (B r s); I r s\\\n \\ (Some (rt r, st s), None) \\ whileLoop_results C' B'\"\n and refine: \"\\r s r' s'. \\ I r s; C r s; (r', s') \\ fst (B r s) \\\n \\ (rt r', st s') \\ fst (B' (rt r) (st s))\"\n shows \"(Q, R) \\ whileLoop_results C' B'\"\n apply (subst vars1)\n apply (subst vars2)\n apply (insert base inv_init)\n apply (induct rule: whileLoop_results.induct)\n apply clarsimp\n apply (subst (asm) cond_match)\n apply (clarsimp simp: option.splits)\n apply (clarsimp simp: option.splits)\n apply (clarsimp simp: option.splits)\n apply (metis fail_step)\n apply (case_tac z)\n apply (clarsimp simp: option.splits)\n apply (metis cond_match inv_step refine whileLoop_results.intros(3))\n apply (clarsimp simp: option.splits)\n apply (metis cond_match inv_step refine whileLoop_results.intros(3))\n done\n\nlemma whileLoop_terminates_liftE:\n \"whileLoop_terminatesE C (\\r. liftE (B r)) r s = whileLoop_terminates C B r s\"\n apply (subst eq_sym_conv)\n apply (clarsimp simp: whileLoop_terminatesE_def)\n apply (rule iffI)\n apply (erule whileLoop_terminates.induct)\n apply (rule whileLoop_terminates.intros)\n apply clarsimp\n apply (clarsimp simp: split_def)\n apply (rule whileLoop_terminates.intros(2))\n apply clarsimp\n apply (clarsimp simp: liftE_def in_bind return_def lift_def [abs_def]\n bind_def lift_def throwError_def o_def split: sum.splits\n cong: sum.case_cong)\n apply (drule (1) bspec)\n apply clarsimp\n apply (subgoal_tac \"case (Inr r) of Inl _ \\ True | Inr r \\\n whileLoop_terminates (\\r s. (\\r s. case r of Inl _ \\ False | Inr v \\ C v s) (Inr r) s)\n (\\r. (lift (\\r. liftE (B r)) (Inr r)) >>= (\\x. return (theRight x))) r s\")\n apply (clarsimp simp: liftE_def lift_def)\n apply (erule whileLoop_terminates.induct)\n apply (clarsimp simp: liftE_def lift_def split: sum.splits)\n apply (erule whileLoop_terminates.intros)\n apply (clarsimp simp: liftE_def split: sum.splits)\n apply (clarsimp simp: bind_def return_def split_def lift_def)\n apply (erule whileLoop_terminates.intros)\n apply force\n done\n\nlemma snd_X_return [simp]:\n \"\\A X s. snd ((A >>= (\\a. return (X a))) s) = snd (A s)\"\n by (clarsimp simp: return_def bind_def split_def)\n\nlemma whileLoopE_liftE:\n \"whileLoopE C (\\r. liftE (B r)) r = liftE (whileLoop C B r)\"\n apply (rule ext)\n apply (clarsimp simp: whileLoopE_def)\n apply (rule prod_eqI)\n apply (rule set_eqI, rule iffI)\n apply clarsimp\n apply (clarsimp simp: in_bind whileLoop_def liftE_def)\n apply (rule_tac x=\"b\" in exI)\n apply (rule_tac x=\"theRight a\" in exI)\n apply (rule conjI)\n apply (erule whileLoop_results_bisim [where rt=theRight and st=\"\\x. x\" and I=\"\\r s. case r of Inr x \\ True | _ \\ False\"],\n auto intro: whileLoop_results.intros simp: bind_def return_def lift_def split: sum.splits)[1]\n apply (drule whileLoop_results_induct_lemma2 [where P=\"\\(r, s). case r of Inr x \\ True | _ \\ False\"] )\n apply (rule refl)\n apply (rule refl)\n apply clarsimp\n apply (clarsimp simp: return_def bind_def lift_def split: sum.splits)\n apply (clarsimp simp: return_def bind_def lift_def split: sum.splits)\n apply (clarsimp simp: in_bind whileLoop_def liftE_def)\n apply (erule whileLoop_results_bisim [where rt=Inr and st=\"\\x. x\" and I=\"\\r s. True\"],\n auto intro: whileLoop_results.intros intro!: bexI simp: bind_def return_def lift_def split: sum.splits)[1]\n apply (rule iffI)\n apply (clarsimp simp: whileLoop_def liftE_def del: notI)\n apply (erule disjE)\n apply (erule whileLoop_results_bisim [where rt=theRight and st=\"\\x. x\" and I=\"\\r s. case r of Inr x \\ True | _ \\ False\"],\n auto intro: whileLoop_results.intros simp: bind_def return_def lift_def split: sum.splits)[1]\n apply (subst (asm) whileLoop_terminates_liftE [symmetric])\n apply (fastforce simp: whileLoop_def liftE_def whileLoop_terminatesE_def)\n apply (clarsimp simp: whileLoop_def liftE_def del: notI)\n apply (subst (asm) whileLoop_terminates_liftE [symmetric])\n apply (clarsimp simp: whileLoop_def liftE_def whileLoop_terminatesE_def)\n apply (erule disjE)\n apply (erule whileLoop_results_bisim [where rt=Inr and st=\"\\x. x\" and I=\"\\r s. True\"])\n apply (clarsimp split: option.splits)\n apply (clarsimp split: option.splits)\n apply (clarsimp split: option.splits)\n apply (auto intro: whileLoop_results.intros intro!: bexI simp: bind_def return_def lift_def split: sum.splits)\n done\n\nlemma validNF_whileLoop:\n assumes pre: \"\\s. P r s \\ I r s\"\n and inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\!\"\n and wf: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\P r\\ whileLoop C B r \\Q\\!\"\n apply rule\n apply (rule valid_whileLoop)\n apply fact\n apply (insert inv, clarsimp simp: validNF_def\n valid_def split: prod.splits, force)[1]\n apply (metis post_cond)\n apply (unfold no_fail_def)\n apply (intro allI impI)\n apply (rule not_snd_whileLoop [where I=I and R=R])\n apply (auto intro: assms)\n done\n\nlemma validNF_whileLoop_inv [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\!\"\n and wf: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoop_inv C B r I R \\Q\\!\"\n apply (clarsimp simp: whileLoop_inv_def)\n apply (rule validNF_whileLoop [where I=I and R=R])\n apply simp\n apply (rule inv)\n apply (rule wf)\n apply (metis post_cond)\n done\n\nlemma validNF_whileLoop_inv_measure [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ M r' s' < M r s \\!\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoop_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\!\"\n apply (clarsimp simp: whileLoop_inv_def)\n apply (rule validNF_whileLoop [where R=\"measure' (\\(r, s). M r s)\" and I=I])\n apply simp\n apply clarsimp\n apply (rule inv)\n apply simp\n apply (metis post_cond)\n done\n\nlemma validNF_whileLoop_inv_measure_twosteps:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ B r \\ \\r' s'. I r' s' \\!\"\n assumes measure: \"\\r m. \\\\s. I r s \\ C r s \\ M r s = m \\ B r \\ \\r' s'. M r' s' < m \\\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoop_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\!\"\n apply (rule validNF_whileLoop_inv_measure)\n apply (rule validNF_weaken_pre)\n apply (rule validNF_post_comb_conj_L)\n apply (rule inv)\n apply (rule measure)\n apply fast\n apply (metis post_cond)\n done\n\nlemma wf_custom_measure:\n \"\\ \\a b. (a, b) \\ R \\ f a < (f :: 'a \\ nat) b \\ \\ wf R\"\n by (metis in_measure wf_def wf_measure)\n\nlemma validNF_whileLoopE:\n assumes pre: \"\\s. P r s \\ I r s\"\n and inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\,\\ E \\!\"\n and wf: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\ P r \\ whileLoopE C B r \\ Q \\,\\ E \\!\"\n apply (unfold validE_NF_alt_def whileLoopE_def)\n apply (rule validNF_whileLoop [\n where I=\"\\r s. case r of Inl x \\ E x s | Inr x \\ I x s\"\n and R=\"{((r', s'), (r, s)). \\x x'. r' = Inl x' \\ r = Inr x}\n \\ {((r', s'), (r, s)). \\x x'. r' = Inr x' \\ r = Inr x \\ ((x', s'),(x, s)) \\ R}\"])\n apply (simp add: pre)\n apply (insert inv)[1]\n apply (fastforce simp: lift_def validNF_def valid_def\n validE_NF_def throwError_def no_fail_def return_def\n validE_def split: sum.splits prod.splits)\n apply (rule wf_Un)\n apply (rule wf_custom_measure [where f=\"\\(r, s). case r of Inl _ \\ 0 | _ \\ 1\"])\n apply clarsimp\n apply (insert wf_inv_image [OF wf, where f=\"\\(r, s). (theRight r, s)\"])\n apply (drule wf_Int1 [where r'=\"{((r', s'),(r, s)). (\\x. r = Inr x) \\ (\\x. r' = Inr x)}\"])\n apply (erule wf_subset)\n apply rule\n apply (clarsimp simp: inv_image_def split: prod.splits sum.splits)\n apply clarsimp\n apply rule\n apply rule\n apply clarsimp\n apply clarsimp\n apply (clarsimp split: sum.splits)\n apply (blast intro: post_cond)\n done\n\nlemma validNF_whileLoopE_inv [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\,\\ E \\!\"\n and wf_R: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoopE_inv C B r I R \\Q\\,\\E\\!\"\n apply (clarsimp simp: whileLoopE_inv_def)\n apply (metis validNF_whileLoopE [OF _ inv] post_cond wf_R)\n done\n\nlemma validNF_whileLoopE_inv_measure [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ M r' s' < M r s \\, \\ E \\!\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoopE_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\,\\E\\!\"\n apply (rule validNF_whileLoopE_inv)\n apply clarsimp\n apply (rule inv)\n apply clarsimp\n apply (metis post_cond)\n done\n\nlemma validNF_whileLoopE_inv_measure_twosteps:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ B r \\ \\r' s'. I r' s' \\, \\ E \\!\"\n assumes measure: \"\\r m. \\\\s. I r s \\ C r s \\ M r s = m \\ B r \\ \\r' s'. M r' s' < m \\, \\ \\_ _. True \\\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoopE_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\, \\E\\!\"\n apply (rule validNF_whileLoopE_inv_measure)\n apply (rule validE_NF_weaken_pre)\n apply (rule validE_NF_post_comb_conj_L)\n apply (rule inv)\n apply (rule measure)\n apply fast\n apply (metis post_cond)\n done\n\nlemma whileLoopE_wp_inv [wp]:\n \"\\ \\r. \\\\s. I r s \\ C r s\\ B r \\I\\,\\E\\; \\r s. \\I r s; \\ C r s\\ \\ Q r s \\\n \\ \\ I r \\ whileLoopE_inv C B r I M \\ Q \\,\\ E \\\"\n apply (clarsimp simp: whileLoopE_inv_def)\n apply (rule validE_whileLoopE [where I=I], auto)\n done\n\nsubsection \"Stronger whileLoop rules\"\n\nlemma whileLoop_rule_strong:\n assumes init_U: \"\\ \\s'. s' = s \\ whileLoop C B r \\ \\r s. (r, s) \\ fst Q \\\"\n and path_exists: \"\\r'' s''. \\ (r'', s'') \\ fst Q \\ \\ \\ \\s'. s' = s \\ whileLoop C B r \\\\ \\r s. r = r'' \\ s = s'' \\\"\n and loop_fail: \"snd Q \\ snd (whileLoop C B r s)\"\n and loop_nofail: \"\\ snd Q \\ \\ \\s'. s' = s \\ whileLoop C B r \\ \\_ _. True \\!\"\n shows \"whileLoop C B r s = Q\"\n using assms\n apply atomize\n apply (clarsimp simp: valid_def exs_valid_def validNF_def no_fail_def)\n apply rule\n apply blast\n apply blast\n apply blast\n done\n\nlemma whileLoop_rule_strong_no_fail:\n assumes init_U: \"\\ \\s'. s' = s \\ whileLoop C B r \\ \\r s. (r, s) \\ fst Q \\!\"\n and path_exists: \"\\r'' s''. \\ (r'', s'') \\ fst Q \\ \\ \\ \\s'. s' = s \\ whileLoop C B r \\\\ \\r s. r = r'' \\ s = s'' \\\"\n and loop_no_fail: \"\\ snd Q\"\n shows \"whileLoop C B r s = Q\"\n apply (rule whileLoop_rule_strong)\n apply (metis init_U validNF_valid)\n apply (metis path_exists)\n apply (metis loop_no_fail)\n apply (metis (lifting, no_types) init_U validNF_chain)\n done\n\nsubsection \"Miscellaneous rules\"\n\n(* Failure of one whileLoop implies the failure of another whileloop\n * which will only ever fail more. *)\nlemma snd_whileLoop_subset:\n assumes a_fails: \"snd (whileLoop C A r s)\"\n and b_success_step:\n \"\\r s r' s'. \\ C r s; (r', s') \\ fst (A r s); \\ snd (B r s) \\\n \\ (r', s') \\ fst (B r s)\"\n and b_fail_step: \"\\r s. \\ C r s; snd (A r s) \\ \\ snd (B r s) \"\n shows \"snd (whileLoop C B r s)\"\n apply (insert a_fails)\n apply (induct rule: snd_whileLoop_induct)\n apply (unfold whileLoop_def snd_conv)[1]\n apply (rule disjCI, simp)\n apply rotate_tac\n apply (induct rule: whileLoop_terminates.induct)\n apply (subst (asm) whileLoop_terminates.simps)\n apply simp\n apply (subst (asm) (3) whileLoop_terminates.simps, clarsimp)\n apply (subst whileLoop_results.simps, clarsimp)\n apply (rule classical)\n apply (frule b_success_step, assumption, simp)\n apply (drule (1) bspec)\n apply clarsimp\n apply (frule (1) b_fail_step)\n apply (metis snd_whileLoop_first_step)\n apply (metis b_success_step snd_whileLoop_first_step snd_whileLoop_unfold)\n done\n\nend\n", "meta": {"author": "amblafont", "repo": "AutoCorres", "sha": "a8e96bff9fb22d633ff473401947ca84235d3b73", "save_path": "github-repos/isabelle/amblafont-AutoCorres", "path": "github-repos/isabelle/amblafont-AutoCorres/AutoCorres-a8e96bff9fb22d633ff473401947ca84235d3b73/lib/Monad_WP/WhileLoopRules.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.15405756269148543, "lm_q1q2_score": 0.06745002116259168}} {"text": "(* Title: HOL/Proofs/Lambda/WeakNorm.thy\n Author: Stefan Berghofer\n Copyright 2003 TU Muenchen\n*)\n\nsection {* Weak normalization for simply-typed lambda calculus *}\n\ntheory WeakNorm\nimports LambdaType NormalForm \"~~/src/HOL/Library/Old_Datatype\"\n \"~~/src/HOL/Library/Code_Target_Int\"\nbegin\n\ntext {*\nFormalization by Stefan Berghofer. Partly based on a paper proof by\nFelix Joachimski and Ralph Matthes @{cite \"Matthes-Joachimski-AML\"}.\n*}\n\n\nsubsection {* Main theorems *}\n\nlemma norm_list:\n assumes f_compat: \"\\t t'. t \\\\<^sub>\\\\<^sup>* t' \\ f t \\\\<^sub>\\\\<^sup>* f t'\"\n and f_NF: \"\\t. NF t \\ NF (f t)\"\n and uNF: \"NF u\" and uT: \"e \\ u : T\"\n shows \"\\Us. e\\i:T\\ \\ as : Us \\\n listall (\\t. \\e T' u i. e\\i:T\\ \\ t : T' \\\n NF u \\ e \\ u : T \\ (\\t'. t[u/i] \\\\<^sub>\\\\<^sup>* t' \\ NF t')) as \\\n \\as'. \\j. Var j \\\\ map (\\t. f (t[u/i])) as \\\\<^sub>\\\\<^sup>*\n Var j \\\\ map f as' \\ NF (Var j \\\\ map f as')\"\n (is \"\\Us. _ \\ listall ?R as \\ \\as'. ?ex Us as as'\")\nproof (induct as rule: rev_induct)\n case (Nil Us)\n with Var_NF have \"?ex Us [] []\" by simp\n thus ?case ..\nnext\n case (snoc b bs Us)\n have \"e\\i:T\\ \\ bs @ [b] : Us\" by fact\n then obtain Vs W where Us: \"Us = Vs @ [W]\"\n and bs: \"e\\i:T\\ \\ bs : Vs\" and bT: \"e\\i:T\\ \\ b : W\"\n by (rule types_snocE)\n from snoc have \"listall ?R bs\" by simp\n with bs have \"\\bs'. ?ex Vs bs bs'\" by (rule snoc)\n then obtain bs' where\n bsred: \"\\j. Var j \\\\ map (\\t. f (t[u/i])) bs \\\\<^sub>\\\\<^sup>* Var j \\\\ map f bs'\"\n and bsNF: \"\\j. NF (Var j \\\\ map f bs')\" by iprover\n from snoc have \"?R b\" by simp\n with bT and uNF and uT have \"\\b'. b[u/i] \\\\<^sub>\\\\<^sup>* b' \\ NF b'\"\n by iprover\n then obtain b' where bred: \"b[u/i] \\\\<^sub>\\\\<^sup>* b'\" and bNF: \"NF b'\"\n by iprover\n from bsNF [of 0] have \"listall NF (map f bs')\"\n by (rule App_NF_D)\n moreover have \"NF (f b')\" using bNF by (rule f_NF)\n ultimately have \"listall NF (map f (bs' @ [b']))\"\n by simp\n hence \"\\j. NF (Var j \\\\ map f (bs' @ [b']))\" by (rule NF.App)\n moreover from bred have \"f (b[u/i]) \\\\<^sub>\\\\<^sup>* f b'\"\n by (rule f_compat)\n with bsred have\n \"\\j. (Var j \\\\ map (\\t. f (t[u/i])) bs) \\ f (b[u/i]) \\\\<^sub>\\\\<^sup>*\n (Var j \\\\ map f bs') \\ f b'\" by (rule rtrancl_beta_App)\n ultimately have \"?ex Us (bs @ [b]) (bs' @ [b'])\" by simp\n thus ?case ..\nqed\n\nlemma subst_type_NF:\n \"\\t e T u i. NF t \\ e\\i:U\\ \\ t : T \\ NF u \\ e \\ u : U \\ \\t'. t[u/i] \\\\<^sub>\\\\<^sup>* t' \\ NF t'\"\n (is \"PROP ?P U\" is \"\\t e T u i. _ \\ PROP ?Q t e T u i U\")\nproof (induct U)\n fix T t\n let ?R = \"\\t. \\e T' u i.\n e\\i:T\\ \\ t : T' \\ NF u \\ e \\ u : T \\ (\\t'. t[u/i] \\\\<^sub>\\\\<^sup>* t' \\ NF t')\"\n assume MI1: \"\\T1 T2. T = T1 \\ T2 \\ PROP ?P T1\"\n assume MI2: \"\\T1 T2. T = T1 \\ T2 \\ PROP ?P T2\"\n assume \"NF t\"\n thus \"\\e T' u i. PROP ?Q t e T' u i T\"\n proof induct\n fix e T' u i assume uNF: \"NF u\" and uT: \"e \\ u : T\"\n {\n case (App ts x e1 T'1 u1 i1)\n assume \"e\\i:T\\ \\ Var x \\\\ ts : T'\"\n then obtain Us\n where varT: \"e\\i:T\\ \\ Var x : Us \\ T'\"\n and argsT: \"e\\i:T\\ \\ ts : Us\"\n by (rule var_app_typesE)\n from nat_eq_dec show \"\\t'. (Var x \\\\ ts)[u/i] \\\\<^sub>\\\\<^sup>* t' \\ NF t'\"\n proof\n assume eq: \"x = i\"\n show ?thesis\n proof (cases ts)\n case Nil\n with eq have \"(Var x \\\\ [])[u/i] \\\\<^sub>\\\\<^sup>* u\" by simp\n with Nil and uNF show ?thesis by simp iprover\n next\n case (Cons a as)\n with argsT obtain T'' Ts where Us: \"Us = T'' # Ts\"\n by (cases Us) (rule FalseE, simp)\n from varT and Us have varT: \"e\\i:T\\ \\ Var x : T'' \\ Ts \\ T'\"\n by simp\n from varT eq have T: \"T = T'' \\ Ts \\ T'\" by cases auto\n with uT have uT': \"e \\ u : T'' \\ Ts \\ T'\" by simp\n from argsT Us Cons have argsT': \"e\\i:T\\ \\ as : Ts\" by simp\n from argsT Us Cons have argT: \"e\\i:T\\ \\ a : T''\" by simp\n from argT uT refl have aT: \"e \\ a[u/i] : T''\" by (rule subst_lemma)\n from App and Cons have \"listall ?R as\" by simp (iprover dest: listall_conj2)\n with lift_preserves_beta' lift_NF uNF uT argsT'\n have \"\\as'. \\j. Var j \\\\ map (\\t. lift (t[u/i]) 0) as \\\\<^sub>\\\\<^sup>*\n Var j \\\\ map (\\t. lift t 0) as' \\\n NF (Var j \\\\ map (\\t. lift t 0) as')\" by (rule norm_list)\n then obtain as' where\n asred: \"Var 0 \\\\ map (\\t. lift (t[u/i]) 0) as \\\\<^sub>\\\\<^sup>*\n Var 0 \\\\ map (\\t. lift t 0) as'\"\n and asNF: \"NF (Var 0 \\\\ map (\\t. lift t 0) as')\" by iprover\n from App and Cons have \"?R a\" by simp\n with argT and uNF and uT have \"\\a'. a[u/i] \\\\<^sub>\\\\<^sup>* a' \\ NF a'\"\n by iprover\n then obtain a' where ared: \"a[u/i] \\\\<^sub>\\\\<^sup>* a'\" and aNF: \"NF a'\" by iprover\n from uNF have \"NF (lift u 0)\" by (rule lift_NF)\n hence \"\\u'. lift u 0 \\ Var 0 \\\\<^sub>\\\\<^sup>* u' \\ NF u'\" by (rule app_Var_NF)\n then obtain u' where ured: \"lift u 0 \\ Var 0 \\\\<^sub>\\\\<^sup>* u'\" and u'NF: \"NF u'\"\n by iprover\n from T and u'NF have \"\\ua. u'[a'/0] \\\\<^sub>\\\\<^sup>* ua \\ NF ua\"\n proof (rule MI1)\n have \"e\\0:T''\\ \\ lift u 0 \\ Var 0 : Ts \\ T'\"\n proof (rule typing.App)\n from uT' show \"e\\0:T''\\ \\ lift u 0 : T'' \\ Ts \\ T'\" by (rule lift_type)\n show \"e\\0:T''\\ \\ Var 0 : T''\" by (rule typing.Var) simp\n qed\n with ured show \"e\\0:T''\\ \\ u' : Ts \\ T'\" by (rule subject_reduction')\n from ared aT show \"e \\ a' : T''\" by (rule subject_reduction')\n show \"NF a'\" by fact\n qed\n then obtain ua where uared: \"u'[a'/0] \\\\<^sub>\\\\<^sup>* ua\" and uaNF: \"NF ua\"\n by iprover\n from ared have \"(lift u 0 \\ Var 0)[a[u/i]/0] \\\\<^sub>\\\\<^sup>* (lift u 0 \\ Var 0)[a'/0]\"\n by (rule subst_preserves_beta2')\n also from ured have \"(lift u 0 \\ Var 0)[a'/0] \\\\<^sub>\\\\<^sup>* u'[a'/0]\"\n by (rule subst_preserves_beta')\n also note uared\n finally have \"(lift u 0 \\ Var 0)[a[u/i]/0] \\\\<^sub>\\\\<^sup>* ua\" .\n hence uared': \"u \\ a[u/i] \\\\<^sub>\\\\<^sup>* ua\" by simp\n from T asNF _ uaNF have \"\\r. (Var 0 \\\\ map (\\t. lift t 0) as')[ua/0] \\\\<^sub>\\\\<^sup>* r \\ NF r\"\n proof (rule MI2)\n have \"e\\0:Ts \\ T'\\ \\ Var 0 \\\\ map (\\t. lift (t[u/i]) 0) as : T'\"\n proof (rule list_app_typeI)\n show \"e\\0:Ts \\ T'\\ \\ Var 0 : Ts \\ T'\" by (rule typing.Var) simp\n from uT argsT' have \"e \\ map (\\t. t[u/i]) as : Ts\"\n by (rule substs_lemma)\n hence \"e\\0:Ts \\ T'\\ \\ map (\\t. lift t 0) (map (\\t. t[u/i]) as) : Ts\"\n by (rule lift_types)\n thus \"e\\0:Ts \\ T'\\ \\ map (\\t. lift (t[u/i]) 0) as : Ts\"\n by (simp_all add: o_def)\n qed\n with asred show \"e\\0:Ts \\ T'\\ \\ Var 0 \\\\ map (\\t. lift t 0) as' : T'\"\n by (rule subject_reduction')\n from argT uT refl have \"e \\ a[u/i] : T''\" by (rule subst_lemma)\n with uT' have \"e \\ u \\ a[u/i] : Ts \\ T'\" by (rule typing.App)\n with uared' show \"e \\ ua : Ts \\ T'\" by (rule subject_reduction')\n qed\n then obtain r where rred: \"(Var 0 \\\\ map (\\t. lift t 0) as')[ua/0] \\\\<^sub>\\\\<^sup>* r\"\n and rnf: \"NF r\" by iprover\n from asred have\n \"(Var 0 \\\\ map (\\t. lift (t[u/i]) 0) as)[u \\ a[u/i]/0] \\\\<^sub>\\\\<^sup>*\n (Var 0 \\\\ map (\\t. lift t 0) as')[u \\ a[u/i]/0]\"\n by (rule subst_preserves_beta')\n also from uared' have \"(Var 0 \\\\ map (\\t. lift t 0) as')[u \\ a[u/i]/0] \\\\<^sub>\\\\<^sup>*\n (Var 0 \\\\ map (\\t. lift t 0) as')[ua/0]\" by (rule subst_preserves_beta2')\n also note rred\n finally have \"(Var 0 \\\\ map (\\t. lift (t[u/i]) 0) as)[u \\ a[u/i]/0] \\\\<^sub>\\\\<^sup>* r\" .\n with rnf Cons eq show ?thesis\n by (simp add: o_def) iprover\n qed\n next\n assume neq: \"x \\ i\"\n from App have \"listall ?R ts\" by (iprover dest: listall_conj2)\n with TrueI TrueI uNF uT argsT\n have \"\\ts'. \\j. Var j \\\\ map (\\t. t[u/i]) ts \\\\<^sub>\\\\<^sup>* Var j \\\\ ts' \\\n NF (Var j \\\\ ts')\" (is \"\\ts'. ?ex ts'\")\n by (rule norm_list [of \"\\t. t\", simplified])\n then obtain ts' where NF: \"?ex ts'\" ..\n from nat_le_dec show ?thesis\n proof\n assume \"i < x\"\n with NF show ?thesis by simp iprover\n next\n assume \"\\ (i < x)\"\n with NF neq show ?thesis by (simp add: subst_Var) iprover\n qed\n qed\n next\n case (Abs r e1 T'1 u1 i1)\n assume absT: \"e\\i:T\\ \\ Abs r : T'\"\n then obtain R S where \"e\\0:R\\\\Suc i:T\\ \\ r : S\" by (rule abs_typeE) simp\n moreover have \"NF (lift u 0)\" using `NF u` by (rule lift_NF)\n moreover have \"e\\0:R\\ \\ lift u 0 : T\" using uT by (rule lift_type)\n ultimately have \"\\t'. r[lift u 0/Suc i] \\\\<^sub>\\\\<^sup>* t' \\ NF t'\" by (rule Abs)\n thus \"\\t'. Abs r[u/i] \\\\<^sub>\\\\<^sup>* t' \\ NF t'\"\n by simp (iprover intro: rtrancl_beta_Abs NF.Abs)\n }\n qed\nqed\n\n\n-- {* A computationally relevant copy of @{term \"e \\ t : T\"} *}\ninductive rtyping :: \"(nat \\ type) \\ dB \\ type \\ bool\" (\"_ \\\\<^sub>R _ : _\" [50, 50, 50] 50)\n where\n Var: \"e x = T \\ e \\\\<^sub>R Var x : T\"\n | Abs: \"e\\0:T\\ \\\\<^sub>R t : U \\ e \\\\<^sub>R Abs t : (T \\ U)\"\n | App: \"e \\\\<^sub>R s : T \\ U \\ e \\\\<^sub>R t : T \\ e \\\\<^sub>R (s \\ t) : U\"\n\nlemma rtyping_imp_typing: \"e \\\\<^sub>R t : T \\ e \\ t : T\"\n apply (induct set: rtyping)\n apply (erule typing.Var)\n apply (erule typing.Abs)\n apply (erule typing.App)\n apply assumption\n done\n\n\ntheorem type_NF:\n assumes \"e \\\\<^sub>R t : T\"\n shows \"\\t'. t \\\\<^sub>\\\\<^sup>* t' \\ NF t'\" using assms\nproof induct\n case Var\n show ?case by (iprover intro: Var_NF)\nnext\n case Abs\n thus ?case by (iprover intro: rtrancl_beta_Abs NF.Abs)\nnext\n case (App e s T U t)\n from App obtain s' t' where\n sred: \"s \\\\<^sub>\\\\<^sup>* s'\" and \"NF s'\"\n and tred: \"t \\\\<^sub>\\\\<^sup>* t'\" and tNF: \"NF t'\" by iprover\n have \"\\u. (Var 0 \\ lift t' 0)[s'/0] \\\\<^sub>\\\\<^sup>* u \\ NF u\"\n proof (rule subst_type_NF)\n have \"NF (lift t' 0)\" using tNF by (rule lift_NF)\n hence \"listall NF [lift t' 0]\" by (rule listall_cons) (rule listall_nil)\n hence \"NF (Var 0 \\\\ [lift t' 0])\" by (rule NF.App)\n thus \"NF (Var 0 \\ lift t' 0)\" by simp\n show \"e\\0:T \\ U\\ \\ Var 0 \\ lift t' 0 : U\"\n proof (rule typing.App)\n show \"e\\0:T \\ U\\ \\ Var 0 : T \\ U\"\n by (rule typing.Var) simp\n from tred have \"e \\ t' : T\"\n by (rule subject_reduction') (rule rtyping_imp_typing, rule App.hyps)\n thus \"e\\0:T \\ U\\ \\ lift t' 0 : T\"\n by (rule lift_type)\n qed\n from sred show \"e \\ s' : T \\ U\"\n by (rule subject_reduction') (rule rtyping_imp_typing, rule App.hyps)\n show \"NF s'\" by fact\n qed\n then obtain u where ured: \"s' \\ t' \\\\<^sub>\\\\<^sup>* u\" and unf: \"NF u\" by simp iprover\n from sred tred have \"s \\ t \\\\<^sub>\\\\<^sup>* s' \\ t'\" by (rule rtrancl_beta_App)\n hence \"s \\ t \\\\<^sub>\\\\<^sup>* u\" using ured by (rule rtranclp_trans)\n with unf show ?case by iprover\nqed\n\n\nsubsection {* Extracting the program *}\n\ndeclare NF.induct [ind_realizer]\ndeclare rtranclp.induct [ind_realizer irrelevant]\ndeclare rtyping.induct [ind_realizer]\nlemmas [extraction_expand] = conj_assoc listall_cons_eq\n\nextract type_NF\n\nlemma rtranclR_rtrancl_eq: \"rtranclpR r a b = r\\<^sup>*\\<^sup>* a b\"\n apply (rule iffI)\n apply (erule rtranclpR.induct)\n apply (rule rtranclp.rtrancl_refl)\n apply (erule rtranclp.rtrancl_into_rtrancl)\n apply assumption\n apply (erule rtranclp.induct)\n apply (rule rtranclpR.rtrancl_refl)\n apply (erule rtranclpR.rtrancl_into_rtrancl)\n apply assumption\n done\n\nlemma NFR_imp_NF: \"NFR nf t \\ NF t\"\n apply (erule NFR.induct)\n apply (rule NF.intros)\n apply (simp add: listall_def)\n apply (erule NF.intros)\n done\n\ntext_raw {*\n\\begin{figure}\n\\renewcommand{\\isastyle}{\\scriptsize\\it}%\n@{thm [display,eta_contract=false,margin=100] subst_type_NF_def}\n\\renewcommand{\\isastyle}{\\small\\it}%\n\\caption{Program extracted from @{text subst_type_NF}}\n\\label{fig:extr-subst-type-nf}\n\\end{figure}\n\n\\begin{figure}\n\\renewcommand{\\isastyle}{\\scriptsize\\it}%\n@{thm [display,margin=100] subst_Var_NF_def}\n@{thm [display,margin=100] app_Var_NF_def}\n@{thm [display,margin=100] lift_NF_def}\n@{thm [display,eta_contract=false,margin=100] type_NF_def}\n\\renewcommand{\\isastyle}{\\small\\it}%\n\\caption{Program extracted from lemmas and main theorem}\n\\label{fig:extr-type-nf}\n\\end{figure}\n*}\n\ntext {*\nThe program corresponding to the proof of the central lemma, which\nperforms substitution and normalization, is shown in Figure\n\\ref{fig:extr-subst-type-nf}. The correctness\ntheorem corresponding to the program @{text \"subst_type_NF\"} is\n@{thm [display,margin=100] subst_type_NF_correctness\n [simplified rtranclR_rtrancl_eq Collect_mem_eq, no_vars]}\nwhere @{text NFR} is the realizability predicate corresponding to\nthe datatype @{text NFT}, which is inductively defined by the rules\n\\pagebreak\n@{thm [display,margin=90] NFR.App [of ts nfs x] NFR.Abs [of nf t]}\n\nThe programs corresponding to the main theorem @{text \"type_NF\"}, as\nwell as to some lemmas, are shown in Figure \\ref{fig:extr-type-nf}.\nThe correctness statement for the main function @{text \"type_NF\"} is\n@{thm [display,margin=100] type_NF_correctness\n [simplified rtranclR_rtrancl_eq Collect_mem_eq, no_vars]}\nwhere the realizability predicate @{text \"rtypingR\"} corresponding to the\ncomputationally relevant version of the typing judgement is inductively\ndefined by the rules\n@{thm [display,margin=100] rtypingR.Var [no_vars]\n rtypingR.Abs [of ty, no_vars] rtypingR.App [of ty e s T U ty' t]}\n*}\n\nsubsection {* Generating executable code *}\n\ninstantiation NFT :: default\nbegin\n\ndefinition \"default = Dummy ()\"\n\ninstance ..\n\nend\n\ninstantiation dB :: default\nbegin\n\ndefinition \"default = dB.Var 0\"\n\ninstance ..\n\nend\n\ninstantiation prod :: (default, default) default\nbegin\n\ndefinition \"default = (default, default)\"\n\ninstance ..\n\nend\n\ninstantiation list :: (type) default\nbegin\n\ndefinition \"default = []\"\n\ninstance ..\n\nend\n\ninstantiation \"fun\" :: (type, default) default\nbegin\n\ndefinition \"default = (\\x. default)\"\n\ninstance ..\n\nend\n\ndefinition int_of_nat :: \"nat \\ int\" where\n \"int_of_nat = of_nat\"\n\ntext {*\n The following functions convert between Isabelle's built-in {\\tt term}\n datatype and the generated {\\tt dB} datatype. This allows to\n generate example terms using Isabelle's parser and inspect\n normalized terms using Isabelle's pretty printer.\n*}\n\nML {*\nval nat_of_integer = @{code nat} o @{code int_of_integer};\n\nfun dBtype_of_typ (Type (\"fun\", [T, U])) =\n @{code Fun} (dBtype_of_typ T, dBtype_of_typ U)\n | dBtype_of_typ (TFree (s, _)) = (case raw_explode s of\n [\"'\", a] => @{code Atom} (nat_of_integer (ord a - 97))\n | _ => error \"dBtype_of_typ: variable name\")\n | dBtype_of_typ _ = error \"dBtype_of_typ: bad type\";\n\nfun dB_of_term (Bound i) = @{code dB.Var} (nat_of_integer i)\n | dB_of_term (t $ u) = @{code dB.App} (dB_of_term t, dB_of_term u)\n | dB_of_term (Abs (_, _, t)) = @{code dB.Abs} (dB_of_term t)\n | dB_of_term _ = error \"dB_of_term: bad term\";\n\nfun term_of_dB Ts (Type (\"fun\", [T, U])) (@{code dB.Abs} dBt) =\n Abs (\"x\", T, term_of_dB (T :: Ts) U dBt)\n | term_of_dB Ts _ dBt = term_of_dB' Ts dBt\nand term_of_dB' Ts (@{code dB.Var} n) = Bound (@{code integer_of_nat} n)\n | term_of_dB' Ts (@{code dB.App} (dBt, dBu)) =\n let val t = term_of_dB' Ts dBt\n in case fastype_of1 (Ts, t) of\n Type (\"fun\", [T, _]) => t $ term_of_dB Ts T dBu\n | _ => error \"term_of_dB: function type expected\"\n end\n | term_of_dB' _ _ = error \"term_of_dB: term not in normal form\";\n\nfun typing_of_term Ts e (Bound i) =\n @{code Var} (e, nat_of_integer i, dBtype_of_typ (nth Ts i))\n | typing_of_term Ts e (t $ u) = (case fastype_of1 (Ts, t) of\n Type (\"fun\", [T, U]) => @{code App} (e, dB_of_term t,\n dBtype_of_typ T, dBtype_of_typ U, dB_of_term u,\n typing_of_term Ts e t, typing_of_term Ts e u)\n | _ => error \"typing_of_term: function type expected\")\n | typing_of_term Ts e (Abs (_, T, t)) =\n let val dBT = dBtype_of_typ T\n in @{code Abs} (e, dBT, dB_of_term t,\n dBtype_of_typ (fastype_of1 (T :: Ts, t)),\n typing_of_term (T :: Ts) (@{code shift} e @{code \"0::nat\"} dBT) t)\n end\n | typing_of_term _ _ _ = error \"typing_of_term: bad term\";\n\nfun dummyf _ = error \"dummy\";\n\nval ct1 = @{cterm \"%f. ((%f x. f (f (f x))) ((%f x. f (f (f (f x)))) f))\"};\nval (dB1, _) = @{code type_NF} (typing_of_term [] dummyf (term_of ct1));\nval ct1' = cterm_of @{theory} (term_of_dB [] (#T (rep_cterm ct1)) dB1);\n\nval ct2 = @{cterm \"%f x. (%x. f x x) ((%x. f x x) ((%x. f x x) ((%x. f x x) ((%x. f x x) ((%x. f x x) x)))))\"};\nval (dB2, _) = @{code type_NF} (typing_of_term [] dummyf (term_of ct2));\nval ct2' = cterm_of @{theory} (term_of_dB [] (#T (rep_cterm ct2)) dB2);\n*}\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Proofs/Lambda/WeakNorm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.1403362422992606, "lm_q1q2_score": 0.06469736244559791}} {"text": "(*************************************************************************\n * Copyright (C) \n * 2019-2022 The University of Exeter \n * 2018-2022 The University of Paris-Saclay\n * 2018 The University of Sheffield\n *\n * License:\n * This program can be redistributed and/or modified under the terms\n * of the 2-clause BSD-style license.\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *************************************************************************)\n\n(*<*)\ntheory TR_MyCommentedIsabelle\n imports \"Isabelle_DOF.technical_report\" \nbegin\n\nuse_template \"scrreprt\"\nuse_ontology \"technical_report\"\n\ndefine_shortcut* isabelle \\ \\Isabelle/HOL\\\n\nopen_monitor*[this::report] \n(*>*)\n\ntitle*[tit::title]\\My Personal, Eclectic Isabelle Programming Manual\\ \nsubtitle*[stit::subtitle]\\Version : Isabelle 2022\\\ntext*[bu::author, \n email = \"''wolff@lri.fr''\",\n affiliation = \"\\Université Paris-Saclay, LRI, France\\\"]\\Burkhart Wolff\\\n \n\ntext*[abs::abstract,\n keywordlist=\"[''LCF-Architecture'',''Isabelle'',''SML'',''PIDE'',''Programming Guide'',\n ''Tactic Programming'']\"]\\\n While Isabelle is mostly known as \"logical framework\" underlying \\<^isabelle> and thus commonly\n understood as an interactive theorem prover, it actually provides a system framework for \n developing a wide spectrum of applications. A particular strength of the Isabelle framework is \n the combination of document editing, formal verification, and code generation. \n \n This is a programming-tutorial of \\<^isabelle>, conceived as a complementary\n text to the unfortunately somewhat outdated \"The Isabelle Cookbook\" in\n \\<^url>\\https://nms.kcl.ac.uk/christian.urban/Cookbook/\\. The reader is encouraged\n not only to consider the generated .pdf, but also consult the loadable version in Isabelle/jEdit\n @{cite \"DBLP:journals/corr/Wenzel14\"} in order to make experiments on the running code.\n \n This text is written itself in Isabelle/Isar using a specific document ontology\n for technical reports. It is intended to be a \"living document\", i.e. it is not only\n used for generating a static, conventional .pdf, but also for direct interactive \n exploration in Isabelle/jEdit. This way, types, intermediate results of computations and\n checks can be repeated by the reader who is invited to interact with this document.\n Moreover, the textual parts have been enriched with a maximum of formal content\n which makes this text re-checkable at each load and easier maintainable.\n\\\n\nchapter*[intro::introduction]\\ Introduction \\ \n\ntext\\ \\<^vs>\\-0.5cm\\ \n While Isabelle @{cite \"DBLP:books/sp/NipkowPW02\"} is mostly known as part of Isabelle/HOL \n (an interactive theorem prover), it actually provides a system framework for developing a wide \n spectrum of applications. A particular strength of the Isabelle framework is the combination \n of text editing, formal verification, and code generation. This is a programming-tutorial of \n Isabelle and Isabelle/HOL, a complementary text to the unfortunately somewhat outdated \n \"The Isabelle Cookbook\" in \\<^url>\\https://nms.kcl.ac.uk/christian.urban/Cookbook/\\. \n The present text is also complementary to the current version of \n \\<^url>\\https://isabelle.in.tum.de/doc/isar-ref.pdf\\\n \"The Isabelle/Isar Implementation\" by Makarius Wenzel in that it focusses on subjects\n not covered there, or presents alternative explanations for which I believe, based on my \n experiences with students and Phds, that they are helpful.\n For the present programming manual, the reader is encouraged not only to consider the generated \n .pdf, but also consult the loadable version \n in Isabelle/jedit in order to make experiments on the running code. This text is written \n itself in Isabelle/Isar using a specific document ontology for technical reports. It is \n intended to be a \"living document\", i.e. it is not only used for generating a static, \n conventional .pdf, but also for direct interactive exploration in Isabelle/jEdit. This way, \n types, intermediate results of computations and checks can be repeated by the reader who is \n invited to interact with this document. Moreover, the textual parts have been enriched with a \n maximum of formal content which makes this text re-checkable at each load and easier \n maintainable. \\\n\nfigure*[architecture::figure,relative_width=\"70\",src=\"''figures/isabelle-architecture''\"]\\ \n The system architecture of Isabelle (left-hand side) and the asynchronous communication \n between the Isabelle system and the IDE (right-hand side). \\\n\ntext\\This programming tutorial roughly follows the Isabelle system architecture shown in \n \\<^figure>\\architecture\\, and, to be more precise, more or less in the bottom-up order.\n\n We start from the basic underlying SML platform over the Kernels to the tactical layer \n and end with a discussion over the front-end technologies. \\<^vs>\\-1.0cm\\\n\\\n\nchapter*[t1::technical]\\ SML and Fundamental SML libraries \\ \n\nsection*[t11::technical] \"ML, Text and Antiquotations\"\n\ntext\\Isabelle is written in SML, the \"Standard Meta-Language\", which is an impure functional \n programming language allowing, in principle, mutable variables and side effects. \n The following Isabelle/Isar commands allow for accessing the underlying SML interpreter\n of Isabelle directly. In the example, a mutable variable X is declared, initialized to 0 and \n updated; and finally re-evaluated leading to output: \\\n\nML\\ \n val X = Unsynchronized.ref 0;\n X:= !X + 1;\n X\n \\\n\ntext\\However, since Isabelle is a platform involving parallel execution, concurrent computing, and,\n as an interactive environment, involves backtracking / re-evaluation as a consequence of user-\n interaction, imperative programming is discouraged and nearly never used in the entire Isabelle\n code-base @{cite \"DBLP:conf/mkm/BarrasGHRTWW13\"}.\n The preferred programming style is purely functional: \\\n\nML\\ \n fun fac x = if x = 0 then 1 else x * fac(x-1) ;\n fac 10;\n \\\ntext\\or:\\ \nML\\ \n type state = { a : int, b : string}\n fun incr_state ({a, b}:state) = {a=a+1, b=b}\n \\\n\ntext\\ The faculty function is defined and executed; the (sub)-interpreter in Isar\n works in the conventional read-execute-print loop for each statement separated by a \";\".\n Functions, types, data-types etc. can be grouped to modules (called \\<^emph>\\structures\\) which can\n be constrained to interfaces (called \\<^emph>\\signatures\\) and even be parametric structures\n (called \\<^emph>\\functors\\). \\\n\ntext\\ The Isabelle/Isar interpreter (called \\<^emph>\\toplevel\\ ) is extensible; by a mixture of SML\n and Isar-commands, domain-specific components can be developed and integrated into the system \n on the fly. Actually, the Isabelle system code-base consists mainly of SML and \\<^verbatim>\\.thy\\-files \n containing such mixtures of Isar commands and SML. \\\n\ntext\\ Besides the ML-command used in the above examples, there are a number of commands \n representing text-elements in Isabelle/Isar; text commands can be interleaved arbitrarily\n with other commands. Text in text-commands may use LaTeX and is used for type-setting \n documentations in a kind of literate programming style. \\\n\ntext\\So: the text command for:\\\n\ntext\\\\<^emph>\\This is a text.\\\\\n\ntext\\... is represented in the integrated source (the \\<^verbatim>\\.thy\\ file) by:\\\n\ntext\\ \\*\\This is a text.\\\\\\\n\ntext\\and displayed in the Isabelle/jEdit front-end at the sceen by:\\\n\nfigure*[fig2::figure, relative_width=\"60\", placement=\"pl_h\", src=\"''figures/text-element''\"]\n \\A text-element as presented in Isabelle/jEdit.\\\n\ntext\\The text-commands, ML-commands (and in principle any other command) can be seen as \n \\<^emph>\\quotations\\ over the underlying SML environment (similar to OCaml or Haskell).\n Linking these different sorts of quotations with each other and the underlying SML-environment\n is supported via \\<^emph>\\antiquotations\\'s. Generally speaking, antiquotations are a kind of semantic\n macro whose arguments were checked, interpreted and expanded using the underlying system\n state. This paves the way for a programming technique to specify expressions or patterns in an \n anti-quotation in various contexts, be it in an ML fragment or a documentation fragment.\n Anti-quotations as \"semantic macros\" can produce a value for the surrounding context\n (ML, text, HOL, whatever) depending on local arguments and the underlying logical context.\n \n The way an antiquotation is specified depends on the quotation expander: typically, this is a \n specific character and an identifier, or specific parentheses and a complete expression or \n pattern.\\\n\ntext\\ In Isabelle documentations, antiquotation's were heavily used to enrich literate explanations\n and documentations by \"formal content\", i.e. machine-checked, typed references\n to all sorts of entities in the context of the interpreting environment. \n Formal content allows for coping with sources that rapidly evolve and were developed by \n distributed teams as is typical in open-source developments. \n\n A paradigmatic example for antiquotation in documentation text snippets and program snippets is here:\n \\<^item> \\<^theory_text>\\text\\@{footnote \\sdf\\}, @{file \"$ISABELLE_HOME/src/Pure/ROOT.ML\"}\\\\\n \\<^item> @{theory_text [display]\n \\ val x = @{thm refl};\n val _ = @{term \"A \\ B\"}\n val y = @{typ \"'a list\"} \n \\\n }\n \\\n\n(*<*) (* example to execute: *)\ntext\\ @{footnote \\sdf\\}, @{file \"$ISABELLE_HOME/src/Pure/ROOT.ML\"}\\\nML\\ \n val x = @{thm refl};\n val _ = @{term \"A \\ B\"}\n val y = @{typ \"'a list\"}\n \\\n(*>*)\n\ntext\\\\<^vs>\\-1.0cm\\... which we will describe in more detail later. \\ \n\ntext\\In a way, anti-quotations implement a kind of \n literate specification style in text, models, code, proofs, etc., which become alltogether\n elements of one global \\<^emph>\\integrated document\\ in which mutual dependencies can be machine-checked\n (i.e. \\formal\\ in this sense).\n Attempting to maximize the \\formal content\\ is a way to ensure \"Agile Development\" (AD) of an \n integrated document development, in the sense that it allows to give immediate feedback\n with respect to changes which enable thus the popular AD-objective \\<^emph>\\embrace change\\.\n Note that while we adhere to this objective, we do not depend or encourage popular AD methods \n and processes such as SCRUM. \\\n\nparagraph\\\n A maximum of formal content inside text documentation also ensures the \n consistency of this present text with the underlying Isabelle version.\\\n\nsection\\The Isabelle/Pure bootstrap\\\n\ntext\\It is instructive to study the fundamental bootstrapping sequence of the Isabelle system;\n it is written in the Isar format and gives an idea of the global module dependencies: \n \\<^file>\\~~/src/Pure/ROOT.ML\\. Loading this file \n (for example by hovering over this hyperlink in the antiquotation holding control or\n command key in Isabelle/jEdit and activating it) allows the Isabelle IDE \n to support hyperlinking \\<^emph>\\inside\\ the Isabelle source.\\\n\ntext\\The bootstrapping sequence is also reflected in the following diagram @{figure \"architecture\"}.\\\n\n\nsection*[t12::technical] \"Elements of the SML library\" \ntext\\Elements of the \\<^file>\\~~/src/Pure/General/basics.ML\\ SML library\n are basic exceptions. Note that exceptions should be catched individually, uncatched exceptions \n except those generated by the specific \"error\" function are discouraged in Isabelle\n source programming since they might produce races in the internal Isabelle evaluation.\n % TODO:\n % The following exceptions are defined in $ML_SOURCES/basis/General.sml\n % and in $ISABELLE_HOME/src/Pure/general/scan.ml\n % ans not in \\<^file>\\~~/src/Pure/General/basics.ML\\\n \n\\<^item> \\<^ML>\\Bind : exn\\ \\<^vs>\\-0.3cm\\\n\\<^item> \\<^ML>\\Chr : exn\\ \\<^vs>\\-0.3cm\\\n\\<^item> \\<^ML>\\Div : exn\\ \\<^vs>\\-0.3cm\\\n\\<^item> \\<^ML>\\Domain : exn\\ \\<^vs>\\-0.3cm\\\n\\<^item> \\<^ML>\\Fail : string -> exn\\, \\<^vs>\\-0.3cm\\\n\\<^item> \\<^ML>\\Match : exn\\, relevant for pattern matching \\<^vs>\\-0.3cm\\\n\\<^item> \\<^ML>\\Overflow : exn\\ \\<^vs>\\-0.3cm\\\n\\<^item> \\<^ML>\\Size : exn\\ \\<^vs>\\-0.3cm\\\n\\<^item> \\<^ML>\\Span : exn\\ \\<^vs>\\-0.3cm\\\n\\<^item> \\<^ML>\\Subscript : exn\\ \\<^vs>\\-0.3cm\\\n\\<^item> \\<^ML>\\exnName : exn -> string\\, very interesting to query an unknown \\exception\\ \\<^vs>\\-0.3cm\\ \n\\<^item> \\<^ML>\\exnMessage: exn -> string\\ \\<^vs>\\-0.3 cm\\\n\\ (* typesetting as table ? *)\n\ntext*[squiggols::technical]\n\\\\<^noindent> Finally, a number of commonly used \"squigglish\" combinators is listed:\n\n\\<^item> @{ML \"op ! : 'a Unsynchronized.ref->'a\"}, access operation on a program variable \\<^vs>\\-0.3cm\\\n\\<^item> @{ML \"op := : ('a Unsynchronized.ref * 'a)->unit\"}, update operation on program variable\\<^vs>\\-0.3cm\\\n\\<^item> @{ML \"op #> : ('a->'b) * ('b->'c)->'a->'c\"}, a reversed function composition \\<^vs>\\-0.3cm\\\n\\<^item> @{ML \"I: 'a -> 'a\"}, the I combinator \\<^vs>\\-0.3cm\\\n\\<^item> @{ML \"K: 'a -> 'b -> 'a\"}, the K combinator \\<^vs>\\-0.3cm\\\n\\<^item> @{ML \"op o : (('b->'c) * ('a->'b))->'a->'c\"}, function composition \\<^vs>\\-0.3cm\\\n\\<^item> @{ML \"op || : ('a->'b) * ('a->'b) -> 'a -> 'b\"}, parse alternative \\<^vs>\\-0.3cm\\\n\\<^item> @{ML \"op -- : ('a->'b*'c) * ('c->'d*'e)->'a->('b*'d)*'e\"}, parse pair \\<^vs>\\-0.3cm\\\n\\<^item> @{ML \"op |-- : ('a->'b*'c) * ('c->'d*'e)->'a->'d*'e\"}, parse pair, forget right \\<^vs>\\-0.3cm\\\n\\<^item> @{ML \"op --| : ('a->'b*'c) * ('c->'d*'e)->'a->'b*'e\"}, parse pair, forget left \\<^vs>\\-0.3cm\\\n\\<^item> @{ML \"op ? : bool * ('a->'a)->'a->'a\"}, if then else \\<^vs>\\-0.3cm\\\n\\<^item> @{ML \"ignore : 'a->unit\"}, force execution, but ignore result \\<^vs>\\-0.3cm\\\n\\<^item> @{ML \"op before: ('a*unit) -> 'a\"} \\<^vs>\\-0.8cm\\\n% TODO:\n% Again the definitions of these operators span multiple files\n% and not just \\<^file>\\~~/src/Pure/General/basics.ML\\.\n\\\n\ntext\\\\<^noindent> Some basic examples for the programming style using these combinators can be found in the\n\"The Isabelle Cookbook\" section 2.3.\\\n\ntext\\An omnipresent data-structure in the Isabelle SML sources are tables\n implemented in @{file \"$ISABELLE_HOME/src/Pure/General/table.ML\"}. These \n generic tables are presented in an efficient purely functional implementation using\n balanced 2-3 trees. Key operations are:\\\nML\\\nsignature TABLE_reduced =\nsig\n type key\n type 'a table\n exception DUP of key\n exception SAME\n exception UNDEF of key\n val empty: 'a table\n val dest: 'a table -> (key * 'a) list\n val keys: 'a table -> key list\n val lookup_key: 'a table -> key -> (key * 'a) option\n val lookup: 'a table -> key -> 'a option\n val defined: 'a table -> key -> bool\n val update: key * 'a -> 'a table -> 'a table\n (* ... *)\nend\n\\\ntext\\... where \\<^verbatim>\\key\\ is usually just a synonym for string.\\\n\nchapter*[t2::technical] \\ Prover Architecture \\\n\nsection*[t21::technical] \\ The Nano-Kernel: Contexts, (Theory)-Contexts, (Proof)-Contexts \\\n\ntext\\ What I call the 'Nano-Kernel' in Isabelle can also be seen as an acyclic theory graph.\n The meat of it can be found in the file @{file \"$ISABELLE_HOME/src/Pure/context.ML\"}. \n My notion is a bit criticisable since this component, which provides the type of @{ML_type theory}\n and @{ML_type Proof.context}, is not that Nano after all.\n However, these type are pretty empty place-holders at that level and the content of\n @{file \"$ISABELLE_HOME/src/Pure/theory.ML\"} is registered much later.\n The sources themselves mention it as \"Fundamental Structure\".\n In principle, theories and proof contexts could be REGISTERED as user data inside contexts.\n The chosen specialization is therefore an acceptable meddling of the abstraction \"Nano-Kernel\"\n and its application context: Isabelle.\n \n Makarius himself says about this structure:\n \n \"Generic theory contexts with unique identity, arbitrarily typed data,\n monotonic development graph and history support. Generic proof\n contexts with arbitrarily typed data.\"\n % NOTE:\n % Add the reference.\n\n In my words: a context is essentially a container with\n \\<^item> an id\n \\<^item> a list of parents (so: the graph structure)\n \\<^item> a time stamp and\n \\<^item> a sub-context relation (which uses a combination of the id and the time-stamp to\n establish this relation very fast whenever needed; it plays a crucial role for the\n context transfer in the kernel.\n \n \n A context comes in form of three 'flavours':\n \\<^item> theories : \\<^ML_type>\\theory\\'s, containing a syntax and axioms, but also\n user-defined data and configuration information.\n \\<^item> Proof-Contexts: \\<^ML_type>\\Proof.context\\ \n containing theories but also additional information if Isar goes into prove-mode.\n In general a richer structure than theories coping also with fixes, facts, goals,\n in order to support the structured Isar proof-style.\n \\<^item> Generic: \\<^ML_type>\\Context.generic\\, i.e. the sum of both.\n \n All context have to be seen as mutable; so there are usually transformations defined on them\n which are possible as long as a particular protocol (\\<^verbatim>\\begin_thy\\ - \\<^verbatim>\\end_thy\\ etc) are respected.\n \n Contexts come with type user-defined data which is mutable through the entire lifetime of\n a context.\n\\ \n\nsubsection*[t212::technical]\\ Mechanism 1 : Core Interface. \\\ntext\\To be found in @{file \"$ISABELLE_HOME/src/Pure/context.ML\"}:\\\n\ntext\\\n\\<^item> \\<^ML>\\Context.parents_of: theory -> theory list\\ gets the (direct) parent theories\n\\<^item> \\<^ML>\\Context.ancestors_of: theory -> theory list\\ gets the imported theories\n\\<^item> \\<^ML>\\Context.proper_subthy : theory * theory -> bool\\ subcontext test\n\\<^item> \\<^ML>\\Context.Proof: Proof.context -> Context.generic \\ A constructor embedding local contexts\n\\<^item> \\<^ML>\\Context.proof_of : Context.generic -> Proof.context\\ the inverse\n\\<^item> \\<^ML>\\Context.theory_name : theory -> string\\\n\\<^item> \\<^ML>\\Context.map_theory: (theory -> theory) -> Context.generic -> Context.generic\\\n\\\n\ntext\\The structure \\<^ML_structure>\\Proof_Context\\ provides a key data-structures concerning contexts:\n\n\\<^item> \\<^ML>\\ Proof_Context.init_global: theory -> Proof.context\\\n embeds a global context into a local context\n\\<^item> \\<^ML>\\ Context.Proof: Proof.context -> Context.generic \\\n the path to a generic Context, i.e. a sum-type of global and local contexts\n in order to simplify system interfaces\n\\<^item> \\<^ML>\\ Proof_Context.get_global: theory -> string -> Proof.context\\\n\\\n\n\nsubsection*[t213::example]\\Mechanism 2 : Extending the Global Context \\\\\\ by User Data \\\n\ntext\\A central mechanism for constructing user-defined data is by the \\<^ML_functor>\\Generic_Data\\-functor.\n A plugin needing some data \\<^verbatim>\\T\\ and providing it with implementations for an \n \\<^verbatim>\\empty\\, and operation \\<^verbatim>\\merge\\, can construct a lense with operations\n \\<^verbatim>\\get\\ and \\<^verbatim>\\put\\ that attach this data into the generic system context. Rather than using\n unsynchronized SML mutable variables, this is the mechanism to introduce component local\n data in Isabelle, which allows to manage this data for the necessary backtrack and synchronization\n features in the pervasively parallel evaluation framework that Isabelle as a system represents.\\\n\nML \\\n datatype X = mt\n val init = mt;\n fun merge (X,Y) = mt\n \n structure Data = Generic_Data\n (\n type T = X\n val empty = init\n val merge = merge\n ); \n\\\ntext\\ This generates the result structure \\<^ML_structure>\\Data\\ by a functor instantiation \nwith the functions:\n\n\\<^item> \\<^ML>\\ Data.get : Context.generic -> Data.T\\\n\\<^item> \\<^ML>\\ Data.put : Data.T -> Context.generic -> Context.generic\\\n\\<^item> \\<^ML>\\ Data.map : (Data.T -> Data.T) -> Context.generic -> Context.generic\\\n\\<^item> ... and other variants to do this on theories ...\n\\\n\n\nsection*[lcfk::technical]\\The LCF-Kernel: \\<^ML_type>\\term\\s, \\<^ML_type>\\typ\\es, \\<^ML_type>\\theory\\s, \n \\<^ML_type>\\ Proof.context\\s, \\<^ML_type>\\thm\\s \\ \ntext\\The classical LCF-style \\<^emph>\\kernel\\ is about \n\\<^enum> Types and terms of a typed \\\\\\-Calculus including constant symbols,\n free variables, \\\\\\-binder and application,\n\\<^enum> An infrastructure to define types and terms, a \\<^emph>\\signature\\ in structure \\<^ML_structure>\\Sign\\\n that also assigns to constant symbols types and concrete syntax managed in structure\n \\<^ML_structure>\\Syntax\\\n\\<^enum> An abstract type \\<^ML_type>\\thm\\ for \\<^emph>\\theorem\\ and logical operations on them\n\\<^enum> (Isabelle specific): a notion of \\<^ML_type>\\theory\\, i.e. a container \n providing a signature and set (list) of theorems. \n\\\n\n\nsubsection*[termstypes::technical]\\ Terms and Types \\\ntext \\The basic data-structure \\<^ML_structure>\\Term\\ of the kernel is contained in file\n@{file \"$ISABELLE_HOME/src/Pure/term.ML\"}. At a glance, the highlights are summarized as follows: \\ \n(* Methodologically doubtful: nothing guarantees that TERM' corresponds to what is Isabelle reality*)\nML\\ \nsignature TERM' = sig\n (* ... *)\n type indexname = string * int\n type class = string\n type sort = class list\n type arity = string * sort list * sort\n datatype typ =\n Type of string * typ list |\n TFree of string * sort |\n TVar of indexname * sort\n datatype term =\n Const of string * typ |\n Free of string * typ |\n Var of indexname * typ |\n Bound of int |\n Abs of string * typ * term |\n $ of term * term (* the infix operator for the application *)\n exception TYPE of string * typ list * term list\n exception TERM of string * term list\n (* ... *)\nend\n\\\n\n(* methodologically better: *)\ntext\\\\<^noindent> Basic types introduced by structure \\<^ML_structure>\\Term\\ are:\n\n\\<^item> \\<^ML_type>\\Term.indexname\\ which is a synonym to \\<^ML_type>\\string * int\\\n\\<^item> \\<^ML_type>\\Term.class\\ which is a synonym to \\<^ML_type>\\string\\\n\\<^item> \\<^ML_type>\\Term.sort\\ which is a synonym to \\<^ML_type>\\class list\\\n\\<^item> \\<^ML_type>\\Term.arity\\ which is a synonym to \\<^ML_type>\\ string * sort list * sort\\\n\n\\<^item> \\<^ML_type>\\Term.typ\\ has the following constructors:\n \\<^enum> \\<^ML>\\Term.Type: string * typ list -> typ\\ : The universal type constructor. Note that \n \\Type(\"fun\", [A,B])\\ denotes the function space \\A \\ B\\ at the ML level.\n \\<^enum> \\<^ML>\\Term.TFree: string * sort -> typ\\ introduces free-type variables, pretty-printed\n by \\'a,'b,'c,...\\. In deduction, they are treated as constants.\n \\<^enum> \\<^ML>\\Term.TVar: indexname * sort -> typ\\ introduces schematic type variables, pretty-printed\n by \\?'a,?'b,?'c,...\\. In deduction, they were instantiated by the unification process.\n\n\\<^item> \\<^ML_type>\\Term.term\\ implements the heart of a Curry-style typed \\\\\\-calculus. \n It has the following constructors:\n \\<^enum> \\<^ML>\\Term.Const: string * typ -> term\\ for \\<^emph>\\constant symbols\\,\n \\<^enum> \\<^ML>\\Term.Free: string * typ -> term\\ for \\<^emph>\\free variable symbols\\,\n \\<^enum> \\<^ML>\\Term.Var: indexname * typ -> term\\ for \\<^emph>\\schematic variables\\, \\<^eg>, \\?X\\, \\?Y\\, \\?Z\\, ... \n \\<^enum> \\<^ML>\\Term.Bound: int -> term\\ for bound variables encoded as deBruin indices,\n \\<^enum> \\<^ML>\\Term.Abs: string * typ * term -> term\\ for the \\<^emph>\\abstraction\\\n \\<^enum> \\<^ML>\\op $ : term * term -> term\\ denotes the infix operator for the \\<^emph>\\application\\\n\n\\<^item> \\<^ML_structure>\\Term\\ provides also a number of core-exceptions relevant for type inference and\n term destruction: \\<^ML>\\Term.TYPE: string * typ list * term list -> exn\\ and\n \\<^ML>\\Term.TERM: string * term list -> exn\\.\n\\\n\ntext\\This core-data structure of the Isabelle Kernel is accessible in the Isabelle/ML environment\nand serves as basis for programmed extensions concerning syntax, type-checking, and advanced\ntactic programming over kernel primitives and higher API's. There are a number of anti-quotations\ngiving support for this task; since @{ML Const}-names are long-names revealing information\nof the potentially evolving library structure, the use of anti-quotations leads to a safer programming\nstyle of tactics and became therefore standard in the entire Isabelle code-base.\n\\\n\ntext\\The following examples show how term- and type-level antiquotations are used and that\n they can both be used for term-construction as well as term-destruction (pattern-matching):\\\n\nML\\ val Const (\"HOL.implies\", @{typ \"bool \\ bool \\ bool\"}) \n $ Free (\"A\", @{typ \"bool\"}) \n $ Free (\"B\", @{typ \"bool\"}) \n = @{term \"A \\ B\"};\n\n val \"HOL.bool\" = @{type_name \"bool\"};\n\n (* three ways to write type bool: *)\n val Type(\"fun\",[s,Type(\"fun\",[@{typ \"bool\"},Type(@{type_name \"bool\"},[])])]) = @{typ \"bool \\ bool \\ bool\"};\n \n\\\ntext\\\n% NOTE:\n% The quotes disappear in the pdf document output.\n\n\\\ntext\\Note that the SML interpreter is configured that he will actually print a type\n \\<^verbatim>\\Type(\"HOL.bool\",[])\\ just as \\<^verbatim>\\\"bool\": typ\\, so a compact notation looking\n pretty much like a string. This can be confusing at times.\\\n\ntext\\Note, furthermore, that there is a programming API for the HOL-instance of Isabelle:\n it is contained in @{file \"$ISABELLE_HOME/src/HOL/Tools/hologic.ML\"}. It offers many\n operators of the HOL logic specific constructors and destructors:\\\n\ntext*[T2::technical]\\\n\\<^enum> \\<^ML>\\HOLogic.boolT : typ\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.mk_Trueprop : term -> term\\, the embedder of bool to prop fundamental for HOL \\<^vs>\\-0.2cm\\ \n\\<^enum> \\<^ML>\\HOLogic.dest_Trueprop : term -> term\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.Trueprop_conv : conv -> conv\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.mk_setT : typ -> typ\\, the ML level type constructor set \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.dest_setT : typ -> typ\\, the ML level type destructor for set \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.Collect_const : typ -> term\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.mk_Collect : string * typ * term -> term\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.mk_mem : term * term -> term\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.dest_mem : term -> term * term\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.mk_set : typ -> term list -> term\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.conj_intr : Proof.context -> thm -> thm -> thm\\, some HOL-level derived-inferences \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.conj_elim : Proof.context -> thm -> thm * thm\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.conj_elims : Proof.context -> thm -> thm list\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.conj : term\\ , some ML level logical constructors \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.disj : term\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.imp : term\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.Not : term\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.mk_not : term -> term\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.mk_conj : term * term -> term\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.dest_conj : term -> term list\\ \\<^vs>\\-0.2cm\\\n\\<^enum> \\<^ML>\\HOLogic.conjuncts : term -> term list\\ \\<^vs>\\-0.2cm\\\n\\<^enum> ... \n\\\n\ntext*[T3::technical]\\In this style, extensions can be defined such as:\\\n\nML\\fun optionT t = Type(@{type_name \"Option.option\"},[t]); \\\n\nsubsection\\ Type-Certification (=checking that a type annotation is consistent) \\\n\ntext\\\n\\<^enum> \\<^ML>\\Type.typ_instance: Type.tsig -> typ * typ -> bool (* raises TYPE_MATCH *) \\\n\\<^enum> \\<^ML>\\ Term.dummyT : typ \\ is a joker type that can be added as place-holder during term \n construction. Jokers can be eliminated by the type inference. \\\n \n\ntext*[T4::technical]\\\n\\<^enum> \\<^ML>\\Sign.typ_instance: theory -> typ * typ -> bool\\\n\\<^enum> \\<^ML>\\Sign.typ_match: theory -> typ * typ -> Type.tyenv -> Type.tyenv\\\n\\<^enum> \\<^ML>\\Sign.typ_unify: theory -> typ * typ -> Type.tyenv * int -> Type.tyenv * int\\\n\\<^enum> \\<^ML>\\Sign.const_type: theory -> string -> typ option\\\n\\<^enum> \\<^ML>\\Sign.certify_term: theory -> term -> term * typ * int\\, the function for CERTIFICATION of types\n\\<^enum> \\<^ML>\\Sign.cert_term: theory -> term -> term\\, short-cut for the latter\n\\<^enum> \\<^ML>\\Sign.tsig_of: theory -> Type.tsig\\, projects from a theory the type signature \n\\\ntext\\ \n \\<^ML>\\Sign.typ_match\\ etc. is actually an abstract wrapper on the structure \n \\<^ML_structure>\\Type\\ which contains the heart of the type inference. \n It also contains the type substitution type \\<^ML_type>\\Type.tyenv\\ which is\n is actually a type synonym for \\<^ML_type>\\(sort * typ) Vartab.table\\ \n which in itself is a synonym for \\<^ML_type>\\'a Symtab.table\\, so \n possesses the usual \\<^ML>\\Symtab.empty\\ and \\<^ML>\\Symtab.dest\\ operations. \\ \n\ntext\\Note that \\<^emph>\\polymorphic variables\\ are treated like constant symbols \n in the type inference; thus, the following test, that one type is an instance of the\n other, yields false:\\\n\nsubsubsection*[exo4::example]\\ Example:\\ \n\nML\\\nval ty = @{typ \"'a option\"};\nval ty' = @{typ \"int option\"};\n\nval Type(\"List.list\",[S]) = @{typ \"('a) list\"}; (* decomposition example *)\n\nval false = Sign.typ_instance @{theory}(ty', ty);\n\\\ntext\\In order to make the type inference work, one has to consider \\<^emph>\\schematic\\ \n type variables, which are more and more hidden from the Isar interface. Consequently,\n the typ antiquotation above will not work for schematic type variables and we have\n to construct them by hand on the SML level: \\\n\nML\\ val t_schematic = Type(\"List.list\",[TVar((\"'a\",0),@{sort \"HOL.type\"})]); \\\n\ntext\\ MIND THE \"'\" !!! Ommitting it leads at times to VERY strange behaviour ...\\\n\ntext \\On this basis, the following \\<^ML_type>\\Type.tyenv\\ is constructed: \\\nML\\\nval tyenv = Sign.typ_match ( @{theory}) \n (t_schematic, @{typ \"int list\"})\n (Vartab.empty); \nval [((\"'a\", 0), ([\"HOL.type\"], @{typ \"int\"}))] = Vartab.dest tyenv;\n\\\n\ntext\\ Type generalization --- the conversion between free type variables and schematic \n type variables --- is apparently no longer part of the standard API (there is a slightly \n more general replacement in \\<^ML>\\Term_Subst.generalizeT_same\\, however). Here is a way to\n overcome this by a self-baked generalization function:\\ \n\nML\\\nval generalize_typ = Term.map_type_tfree (fn (str,sort)=> Term.TVar((str,0),sort));\nval generalize_term = Term.map_types generalize_typ;\nval true = Sign.typ_instance @{theory} (ty', generalize_typ ty)\n\\\ntext\\... or more general variants thereof that are parameterized by the indexes for schematic\n type variables instead of assuming just @{ML \"0\"}. \\\n\ntext\\ Example:\\ \nML\\val t = generalize_term @{term \"[]\"}\\\n\ntext\\Now we turn to the crucial issue of type-instantiation and with a given type environment\n \\<^ML>\\tyenv\\. For this purpose, one has to switch to the low-level interface \n \\<^ML_structure>\\Term_Subst\\. \\\n\nsubsection\\More operations on types\\\n\ntext\\\n\\<^item> \\<^ML>\\Term_Subst.map_types_same : (typ -> typ) -> term -> term\\\n\\<^item> \\<^ML>\\Term_Subst.map_aterms_same : (term -> term) -> term -> term\\\n\\<^item> \\<^ML>\\Term_Subst.instantiate: typ TVars.table * term Vars.table -> term -> term\\\n\\<^item> \\<^ML>\\Term_Subst.instantiateT: typ TVars.table -> typ -> typ\\\n\\<^item> \\<^ML>\\Term_Subst.generalizeT: Names.set -> int -> typ -> typ\\\n this is the standard type generalisation function !!!\n only type-frees in the string-list were taken into account. \n\\<^item> \\<^ML>\\Term_Subst.generalize: Names.set * Names.set -> int -> term -> term\\\n this is the standard term generalisation function !!!\n only type-frees and frees in the string-lists were taken \n into account. \n\\\n\n\n\ntext \\Apparently, a bizarre conversion between the old-style interface and \n the new-style \\<^ML>\\tyenv\\ is necessary. See the following example.\\\nML\\\nval S = Vartab.dest tyenv : (Vartab.key * (sort * typ)) list;\nval S' = (map (fn (s,(t,u)) => ((s,t),u)) S) : ((indexname * sort) * typ) list;\n (* it took me quite some time to find out that these two type representations,\n obscured by a number of type-synonyms, where actually identical. *)\nval S''= TVars.make S': typ TVars.table\nval ty = t_schematic;\nval ty' = Term_Subst.instantiateT S'' t_schematic;\n\n(* Don't know how to build a typ TVars.table *)\nval t = (generalize_term @{term \"[]\"});\n\nval t' = Term_Subst.map_types_same (Term_Subst.instantiateT (TVars.make S')) (t)\n(* or alternatively : *)\nval t'' = Term.map_types (Term_Subst.instantiateT S'') (t)\n\\\n\ntext\\A more abstract env for variable management in tactic proofs. A bit difficult to use\n outside the very closed-up tracks of conventional use...\\\n\nML\\ Consts.the_const; (* T is a kind of signature ... *)\n Variable.import_terms;\n Vartab.update;\\\n\nsubsection*[t232::technical]\\ Type-Inference (= inferring consistent type information if possible) \\\n\ntext\\ Type inference eliminates also joker-types such as @{ML dummyT} and produces\n instances for schematic type variables where necessary. In the case of success,\n it produces a certifiable term. \\ \nML\\ Type_Infer_Context.infer_types: Proof.context -> term list -> term list \\\n\nsubsection*[t237::technical]\\Constructing Terms without Type-Inference\\\ntext\\Using @{ML \"Type_Infer_Context.infer_types\"} is not quite unproblematic: since the type\ninference can construct types for largely underspecified terms, it may happen that under \nsome circumstances, tactics and proof-attempts fail since just some internal term representation\nwas too general. A more defensive strategy is already sketched --- but neither explicitely \nmentioned nor worked out in the interface in @{ML_structure HOLogic}. The idea is to have\nadvanced term constructors that construct the right term from the leaves, which were by convention\nfully type-annotated (so: this does not work for terms with dangling @(ML Bound)'s).\n\nOperations like @{ML \"HOLogic.mk_prod\"} or @{ML \"HOLogic.mk_fst\"} or @{ML \"HOLogic.mk_eq\"} do\nexactly this by using an internal pure bottom-up type-inference @{ML \"fastype_of\"}.\nThe following routines are written in the same style complement the existing API\n@{ML_structure HOLogic}.\n\\\n\nML\\\nfun mk_None ty = let val none = \\<^const_name>\\Option.option.None\\\n val none_ty = ty --> Type(\\<^type_name>\\option\\,[ty])\n in Const(none, none_ty)\n end;\nfun mk_Some t = let val some = \\<^const_name>\\Option.option.Some\\ \n val ty = fastype_of t\n val some_ty = ty --> Type(\\<^type_name>\\option\\,[ty])\n in Const(some, some_ty) $ t\n end;\n\nfun mk_undefined (@{typ \"unit\"}) = Const (\\<^const_name>\\Product_Type.Unity\\, \\<^typ>\\unit\\)\n |mk_undefined t = Const (\\<^const_name>\\HOL.undefined\\, t)\n\nfun meta_eq_const T = Const (\\<^const_name>\\Pure.eq\\, T --> T --> propT);\n\nfun mk_meta_eq (t, u) = meta_eq_const (fastype_of t) $ t $ u;\n\n\\\n\nsubsection\\Another Approach for Typed Parsing\\\n\ntext\\Another example for influencing @{ML \"Syntax.read_term\"} by modifying\nthe @{ML_type \"Proof.context\"}: \\\n\ndefinition \"zz = ()\" \nML\\@{term zz}\\ (* So : @(term \"zz\"} is now a constant*) \nML\\val Free (\"zz\", ty) = Proof_Context.add_fixes \n [(@{binding \"zz\"}, SOME @{typ nat}, NoSyn)] @{context}\n |> (fn (S, ctxt) => (writeln (String.concat S); \n Syntax.read_term ctxt \"zz\"));\n (* So : @(term \"zz\"} is here a free variable. *) \\\nML\\@{term zz}\\ (* So : @(term \"zz\"} is now a constant again.*) \nlocale Z =\n fixes zz :: nat\nbegin\n ML\\@{term \"(zz)\"}\\\nend\n\nlemma True\nproof - fix a :: nat\n show True\n ML_prf \\@{term a}\\\n term a\n oops\n\n\n\n\n\nsubsection*[t233::technical]\\ Theories and the Signature API\\ \ntext\\\n\\<^enum> \\<^ML>\\Sign.tsig_of : theory -> Type.tsig\\ extracts the type-signature of a theory\n\\<^enum> \\<^ML>\\Sign.syn_of : theory -> Syntax.syntax\\ extracts the constant-symbol signature \n\\<^enum> \\<^ML>\\Sign.of_sort : theory -> typ * sort -> bool\\ decides that a type belongs to a sort.\n\\\n\nsubsection*[t234::technical]\\\\<^ML_structure>\\Thm\\'s and the LCF-Style, \"Mikro\"-Kernel \\ \ntext\\ \n The basic constructors and operations on theorems \\<^file>\\$ISABELLE_HOME/src/Pure/thm.ML\\,\n a set of derived (Pure) inferences can be found in \\<^file>\\$ISABELLE_HOME/src/Pure/drule.ML\\.\n\n The main types provided by structure \\<^verbatim>\\thm\\ are certified types \\<^ML_type>\\Thm.ctyp\\, \n certified terms \\<^ML_type>\\Thm.cterm\\, \\<^ML_type>\\Thm.thm\\ as well as conversions \\<^ML_type>\\Thm.conv\\ \n \\<^ie>, transformation operations of \\<^ML_type>\\Thm.thm\\s to logically equivalent ones.\n\n Errors were reported with the \\<^ML>\\CTERM: string * cterm list -> exn\\-exceptions.\n\n Over this kernel, two infix main operations were provided:\n \\<^enum> \\<^ML>\\op RS: thm * thm -> thm\\ resolved the conclusion of left argument into the left-most\n assumption of the right arguement, while\n \\<^enum> \\<^ML>\\op RSN: thm * (int * thm) -> thm\\ resolves the conclusion of the left argument into\n the nth assumption of the right argument, so generalizes \\<^ML>\\op RS\\.\n\n Errors of the resolution operations were reported by \n \\<^ML>\\THM : string * int * thm list -> exn\\.\n\n At a glance, the very heart of the kernel is represented as follows (UNSAFE):\n\\\n\nML\\\nsignature BASIC_THM' =\nsig\n type ctyp\n type cterm\n exception CTERM of string * cterm list\n type thm\n type conv = cterm -> thm\n exception THM of string * int * thm list\n val RSN: thm * (int * thm) -> thm\n val RS: thm * thm -> thm\nend;\n\\\n\ntext\\Certification of types and terms on the kernel-level is done by the generators:\\\ntext\\\n\\<^item> \\<^ML>\\ Thm.global_ctyp_of: theory -> typ -> ctyp\\\n\\<^item> \\<^ML>\\ Thm.ctyp_of: Proof.context -> typ -> ctyp\\\n\\<^item> \\<^ML>\\ Thm.global_cterm_of: theory -> term -> cterm\\\n\\<^item> \\<^ML>\\ Thm.cterm_of: Proof.context -> term -> cterm\\\n\\\n\n\ntext\\... which perform type-checking in the given theory context in order to make a type\n or term \"admissible\" for the kernel.\\\n\ntext\\These operations were internally used in the ML-antiquotation:\\ML\\\\<^cterm>\\zero\\\\\\ yielding:\\\nML\\\\<^cterm>\\zero\\\\\n\ntext\\ We come now to the very heart of the LCF-Kernel of Isabelle, which \n provides the fundamental inference rules of Isabelle/Pure. \n\n Besides a number of destructors on \\<^ML_type>\\thm\\'s,\n the abstract data-type \\<^ML_type>\\thm\\ is used for logical objects of the form \n \\\\ \\\\<^sub>\\ \\\\, where \\\\\\ represents a set of local assumptions,\n \\\\\\ the global context or \\<^ML_type>\\theory\\ in which a formula \\\\\\ \n has been constructed just by applying the following operations representing \n the logical kernel inference rules:\n\n\\<^item> \\<^ML>\\ Thm.assume: cterm -> thm\\\n\\<^item> \\<^ML>\\ Thm.implies_intr: cterm -> thm -> thm\\\n\\<^item> \\<^ML>\\ Thm.implies_elim: thm -> thm -> thm\\\n\\<^item> \\<^ML>\\ Thm.forall_intr: cterm -> thm -> thm\\\n\\<^item> \\<^ML>\\ Thm.forall_elim: cterm -> thm -> thm\\\n\\<^item> \\<^ML>\\ Thm.transfer : theory -> thm -> thm\\\n\\<^item> \\<^ML>\\ Thm.generalize: Names.set * Names.set -> int -> thm -> thm\\\n\\<^item> \\<^ML>\\ Thm.instantiate: ctyp TVars.table * cterm Vars.table -> thm -> thm\\\n\\\n\ntext\\ They reflect the Pure logic depicted in a number of presentations such as\n M. Wenzel, \\<^emph>\\Parallel Proof Checking in Isabelle/Isar\\, PLMMS 2009, or simiular papers.\n Notated as logical inference rules, these operations were presented as follows:\n\\\n\nside_by_side_figure*[\"text-elements\"::side_by_side_figure,anchor=\"''fig-kernel1''\",\n caption=\"''Pure Kernel Inference Rules I ''\",relative_width=\"48\",\n src=\"''figures/pure-inferences-I''\",anchor2=\"''fig-kernel2''\",\n caption2=\"''Pure Kernel Inference Rules II''\",relative_width2=\"47\",\n src2=\"''figures/pure-inferences-II''\"]\\ \\\n\n(*\nfigure*[kir1::figure,relative_width=\"100\",src=\"''figures/pure-inferences-I''\"]\n \\ Pure Kernel Inference Rules I.\\\nfigure*[kir2::figure,relative_width=\"100\",src=\"''figures/pure-inferences-II''\"]\n \\ Pure Kernel Inference Rules II. \\\n *)\n\ntext\\Note that the transfer rule:\n\\[\n\\begin{prooftree}\n \\\\ \\\\<^sub>\\ \\\\ \\qquad \\qquad \\\\ \\ \\'\\ \n\\justifies\n \\\\ \\\\<^sub>\\\\<^sub>' \\\\ \\qquad \\qquad\n\\end{prooftree}\n\\]\n which is a consequence of explicit theories characteristic for Isabelle's LCF-kernel design\n and a remarkable difference to its sisters HOL-Light and HOL4; instead of transfer, these systems\n reconstruct proofs in an enlarged global context instead of taking the result and converting it.\\\n\ntext\\Besides the meta-logical (Pure) implication \\_ \\ _\\, the Kernel axiomatizes\n also a Pure-Equality \\_ \\ _\\ used for definitions of constant symbols: \n\\<^item> \\<^ML>\\ Thm.reflexive: cterm -> thm\\\n\\<^item> \\<^ML>\\ Thm.symmetric: thm -> thm\\\n\\<^item> \\<^ML>\\ Thm.transitive: thm -> thm -> thm\\\n\\\n\ntext\\The operation \\<^ML>\\ Thm.trivial: cterm -> thm \\\n ... produces the elementary tautologies of the form \\<^prop>\\A \\ A\\,\n an operation used to start a backward-style proof.\\\n\ntext\\The elementary conversions are:\n\n\\<^item> \\<^ML>\\Thm.beta_conversion: bool -> conv\\\n\\<^item> \\<^ML>\\Thm.eta_conversion: conv\\\n\\<^item> \\<^ML>\\Thm.eta_long_conversion: conv\\\n\\\n\ntext\\On the level of \\<^ML_structure>\\Drule\\, a number of higher-level operations is established, \n which is in part accessible by a number of forward-reasoning notations on Isar-level.\n\n\\<^item> \\<^ML>\\ op RLN: thm list * (int * thm list) -> thm list\\\n\\<^item> \\<^ML>\\ op RL: thm list * thm list -> thm list\\\n\\<^item> \\<^ML>\\ op MRS: thm list * thm -> thm\\\n\\<^item> \\<^ML>\\ op OF: thm * thm list -> thm\\\n\\<^item> \\<^ML>\\ op COMP: thm * thm -> thm\\\n\\\n\n\nsubsection*[t235::technical]\\ \\<^ML_structure>\\Theory\\'s \\\n\ntext \\ This structure yields the abstract datatype \\<^ML_structure>\\Theory\\ which becomes the content of \n \\<^ML_type>\\Context.theory\\. In a way, the LCF-Kernel registers itself into the Nano-Kernel,\n which inspired me (bu) to this naming. However, not that this is a mental model: the Nano-Kernel\n offers ab initio many operations directly linked to its main purpose: incommodating the \n micro-kernel and its management of local and global contexts.\n\\\n\ntext\\\n@{theory_text [display] \n\\\nintern Theory.Thy; \n\ndatatype thy = Thy of\n {pos: Position.T,\n id: serial,\n axioms: term Name_Space.table,\n defs: Defs.T,\n wrappers: wrapper list * wrapper list};\n\\}\n\n\\<^item> \\<^ML>\\Theory.check: {long: bool} -> Proof.context -> string * Position.T -> theory\\\n\\<^item> \\<^ML>\\Theory.local_setup: (Proof.context -> Proof.context) -> unit\\\n\\<^item> \\<^ML>\\Theory.setup: (theory -> theory) -> unit\\ (* The thing to extend the table of \"command\"s with parser - callbacks. *)\n\\<^item> \\<^ML>\\Theory.get_markup: theory -> Markup.T\\\n\\<^item> \\<^ML>\\Theory.axiom_table: theory -> term Name_Space.table\\\n\\<^item> \\<^ML>\\Theory.axiom_space: theory -> Name_Space.T\\\n\\<^item> \\<^ML>\\Theory.all_axioms_of: theory -> (string * term) list\\\n\\<^item> \\<^ML>\\Theory.defs_of: theory -> Defs.T\\\n\\<^item> \\<^ML>\\Theory.join_theory: theory list -> theory\\\n\\<^item> \\<^ML>\\Theory.at_begin: (theory -> theory option) -> theory -> theory\\\n\\<^item> \\<^ML>\\Theory.at_end: (theory -> theory option) -> theory -> theory\\\n\\<^item> \\<^ML>\\Theory.begin_theory: string * Position.T -> theory list -> theory\\\n\\<^item> \\<^ML>\\Theory.end_theory: theory -> theory\\\n\\\n\nsection*[t26::technical]\\Advanced Specification Constructs\\\ntext\\Isabelle is built around the idea that system components were built on top\nof the kernel in order to give the user high-level specification constructs \n--- rather than inside as in the Coq kernel that foresees, for example, data-types\nand primitive recursors already in the basic \\\\\\-term language.\nTherefore, records, definitions, type-definitions, recursive function definitions\nare supported by packages that belong to the \\<^emph>\\components\\ strata. \nWith the exception of the \\<^ML>\\Specification.axiomatization\\ construct, they\nare all-together built as composition of conservative extensions.\n\nThe components are a bit scattered in the architecture. A relatively recent and\nhigh-level component (more low-level components such as \\<^ML>\\Global_Theory.add_defs\\\nexist) for definitions and axiomatizations is here:\n\\\n\ntext\\\n\\<^item> \\<^ML>\\Specification.definition: (binding * typ option * mixfix) option ->\n (binding * typ option * mixfix) list -> term list -> Attrib.binding * term ->\n local_theory -> (term * (string * thm)) * local_theory\\\n\\<^item> \\<^ML>\\Specification.definition_cmd: (binding * string option * mixfix) option ->\n (binding * string option * mixfix) list -> string list -> Attrib.binding * string ->\n bool -> local_theory -> (term * (string * thm)) * local_theory\\\n\\<^item> \\<^ML>\\Specification.axiomatization: (binding * typ option * mixfix) list ->\n (binding * typ option * mixfix) list -> term list ->\n (Attrib.binding * term) list -> theory -> (term list * thm list) * theory\\\n\\<^item> \\<^ML>\\Specification.axiomatization_cmd: (binding * string option * mixfix) list ->\n (binding * string option * mixfix) list -> string list ->\n (Attrib.binding * string) list -> theory -> (term list * thm list) * theory\\\n\\<^item> \\<^ML>\\Specification.axiom: Attrib.binding * term -> theory -> thm * theory\\\n\\<^item> \\<^ML>\\Specification.abbreviation: Syntax.mode -> (binding * typ option * mixfix) option ->\n (binding * typ option * mixfix) list -> term -> bool -> local_theory -> local_theory\\\n\\<^item> \\<^ML>\\Specification.abbreviation_cmd: Syntax.mode -> (binding * string option * mixfix) option ->\n (binding * string option * mixfix) list -> string -> bool -> local_theory -> local_theory\\\n\\\n\n\ntext\\\nNote that the interface is mostly based on \\<^ML_type>\\local_theory\\, which is a synonym to\n\\<^ML_type>\\Proof.context\\. Need to lift this to a global system transition ?\nDon't worry, \\<^ML>\\Named_Target.theory_map: (local_theory -> local_theory) -> theory -> theory\\ \ndoes the trick.\n\\\n\nsubsection*[t261::example]\\Example\\\n\ntext\\Suppose that we want do \\<^theory_text>\\definition I :: \"'a \\ 'a\" where \"I x = x\"\\ at the ML-level.\nWe construct our defining equation and embed it as a \\<^typ>\\prop\\ into Pure.\n\\\nML\\ val ty = @{typ \"'a\"}\n val term = HOLogic.mk_eq (Free(\"I\",ty -->ty) $ Free(\"x\", ty), Free(\"x\", ty));\n val term_prop = HOLogic.mk_Trueprop term\\\ntext\\Recall the notes on defensive term construction wrt. typing in @{docitem \"t237\"}.\nThen the trick is done by:\\\n\nsetup\\\nlet\nfun mk_def name p = \n let val nameb = Binding.make(name,p)\n val ty_global = ty --> ty\n val args = (((SOME(nameb,SOME ty_global,NoSyn),(Binding.empty_atts,term_prop)),[]),[])\n val cmd = (fn (((decl, spec), prems), params) =>\n #2 o Specification.definition decl params prems spec)\n in cmd args\n end;\nin Named_Target.theory_map (mk_def \"I\" @{here} )\nend\\\n\nthm I_def\ntext\\Voilà.\\\n\nsection*[t24::technical]\\Backward Proofs: Tactics, Tacticals and Goal-States\\\n\ntext\\At this point, we leave the Pure-Kernel and start to describe the first layer on top\n of it, involving support for specific styles of reasoning and automation of reasoning.\\\n\ntext\\ \\<^ML_type>\\tactic\\'s are in principle \\<^emph>\\relations\\ on theorems \\<^ML_type>\\thm\\; the relation is\n lazy and encoded as function of type \\<^ML_type>\\thm -> thm Seq.seq\\.\n This gives a natural way to represent the fact that HO-Unification\n (and therefore the mechanism of rule-instantiation) are non-deterministic in principle.\n Heuristics may choose particular preferences between \n the theorems in the range of this relation, but the Isabelle Design accepts this fundamental \n fact reflected at this point in the prover architecture. \n This potentially infinite relation is implemented by a function of theorems to lazy lists \n over theorems, which gives both sufficient structure for heuristic\n considerations as well as a nice algebra, called \\<^ML_structure>\\Tactical\\'s, providing a bottom element\n \\<^ML>\\no_tac\\ (the function that always fails), the top-element \\<^ML>\\all_tac\\\n (the function that never fails), sequential composition \\<^ML>\\op THEN\\, (serialized) \n non-deterministic composition \\<^ML>\\op ORELSE\\, conditionals, repetitions over lists, etc.\n The following is an excerpt of \\<^file>\\~~/src/Pure/tactical.ML\\:\\\n\n\ntext\\ More specialized variants of \\<^ML_structure>\\Tactical\\'s are:\n\n\\<^item> \\<^ML>\\op THEN': ('a -> tactic) * ('a -> tactic) -> 'a -> tactic\\ -- lifted version \n\\<^item> \\<^ML>\\op ORELSE': ('a -> tactic) * ('a -> tactic) -> 'a -> tactic\\ -- lifted version \n\\<^item> \\<^ML>\\op TRY: tactic -> tactic\\ -- option\n\\<^item> \\<^ML>\\op EVERY: tactic list -> tactic\\ -- sequential enchainment\n\\<^item> \\<^ML>\\op EVERY': ('a -> tactic) list -> 'a -> tactic\\ -- lifted version\n\\<^item> \\<^ML>\\op FIRST: tactic list -> tactic\\ -- alternative enchainment\n\\<^item> etc.\n\n\\\n\n\ntext\\The next layer in the architecture describes \\<^ML_type>\\tactic\\'s, i.e. basic operations on \n theorems in a backward reasoning style (bottom up development of proof-trees). An initial \n goal-state for some property \\<^prop>\\A\\ --- the \\<^emph>\\goal\\ --- is constructed via the kernel \n \\<^ML>\\Thm.trivial\\-operation into \\<^prop>\\A \\ A\\, and tactics either refine the premises --- the \n \\<^emph>\\subgoals\\ of this meta-implication --- producing more and more of them or eliminate them \n in subsequent goal-states. Subgoals of the form \\<^prop>\\B\\<^sub>1 \\ B\\<^sub>2 \\ A \\ B\\<^sub>3 \\ B\\<^sub>4 \\ A\\ can be \n eliminated via the \\<^ML>\\Tactic.assume_tac\\-tactic, and a subgoal \\<^prop>\\C\\<^sub>m\\ can be refined via the \n theorem \\<^prop>\\E\\<^sub>1 \\ E\\<^sub>2 \\ E\\<^sub>3 \\ C\\<^sub>m\\ the \\<^ML>\\Tactic.resolve_tac\\ - tactic to new subgoals\n \\<^prop>\\E\\<^sub>1\\, \\<^prop>\\E\\<^sub>2\\, \\<^prop>\\E\\<^sub>3\\. In case that a theorem used for resolution has no premise \\<^prop>\\E\\<^sub>i\\, \n the subgoal \\<^prop>\\C\\<^sub>m\\ is also eliminated (\"closed\").\n \n The following abstract of the most commonly used \\<^ML_type>\\tactic\\'s drawn from\n \\<^file>\\~~/src/Pure/tactic.ML\\ are summarized as follows:\n\n\\<^item> \\<^ML>\\ assume_tac: Proof.context -> int -> tactic\\ \n\\<^item> \\<^ML>\\ compose_tac: Proof.context -> (bool * thm * int) -> int -> tactic\\\n\\<^item> \\<^ML>\\ resolve_tac: Proof.context -> thm list -> int -> tactic\\\n\\<^item> \\<^ML>\\ eresolve_tac: Proof.context -> thm list -> int -> tactic\\\n\\<^item> \\<^ML>\\ forward_tac: Proof.context -> thm list -> int -> tactic\\\n\\<^item> \\<^ML>\\ dresolve_tac: Proof.context -> thm list -> int -> tactic\\\n\\<^item> \\<^ML>\\ rotate_tac: int -> int -> tactic\\\n\\<^item> \\<^ML>\\ defer_tac: int -> tactic\\\n\\<^item> \\<^ML>\\ prefer_tac: int -> tactic\\\n\\<^item> ...\n\\\n\ntext\\Note that \"applying a rule\" is a fairly complex operation in the Extended Isabelle Kernel,\n i.e. the tactic layer. It involves at least four phases, interfacing a theorem \n coming from the global context $\\theta$ (=theory), be it axiom or derived, into a given goal-state.\n\\<^item> \\<^emph>\\generalization\\. All free variables in the theorem were replaced by schematic variables.\n For example, \\<^term>\\x + y = y + x\\ is converted into \n \\?x + ?y = ?y + ?x\\. \n By the way, type variables were treated equally.\n\\<^item> \\<^emph>\\lifting over assumptions\\. If a subgoal is of the form: \n \\<^prop>\\B\\<^sub>1 \\ B\\<^sub>2 \\ A\\ and we have a theorem \\<^prop>\\D\\<^sub>1 \\ D\\<^sub>2 \\ A\\, then before\n applying the theorem, the premisses were \\<^emph>\\lifted\\ resulting in the logical refinement:\n \\<^prop>\\(B\\<^sub>1 \\ B\\<^sub>2 \\ D\\<^sub>1) \\ (B\\<^sub>1 \\ B\\<^sub>2 \\ D\\<^sub>2) \\ A\\. Now, \\<^ML>\\resolve_tac\\, for example,\n will replace the subgoal \\<^prop>\\B\\<^sub>1 \\ B\\<^sub>2 \\ A\\ by the subgoals \n \\<^prop>\\B\\<^sub>1 \\ B\\<^sub>2 \\ D\\<^sub>1\\ and \\<^prop>\\B\\<^sub>1 \\ B\\<^sub>2 \\ D\\<^sub>2\\. Of course, if the theorem wouldn't\n have assumptions \\<^prop>\\D\\<^sub>1\\ and \\<^prop>\\D\\<^sub>2\\, the subgoal \\<^prop>\\A\\ would be replaced by \n \\<^bold>\\nothing\\, i.e. deleted.\n\\<^item> \\<^emph>\\lifting over parameters\\. If a subgoal is meta-quantified like in:\n \\<^prop>\\\\ x y z. A x y z\\, then a theorem like \\<^prop>\\D\\<^sub>1 \\ D\\<^sub>2 \\ A\\ is \\<^emph>\\lifted\\ \n to \\<^prop>\\\\ x y z. D\\<^sub>1' \\ D\\<^sub>2' \\ A'\\, too. Since free variables occurring in \\<^prop>\\D\\<^sub>1\\, \n \\<^prop>\\D\\<^sub>2\\ and \\<^prop>\\A\\ have been replaced by schematic variables (see phase one),\n they must be replaced by parameterized schematic variables, i. e. a kind of skolem function.\n For example, \\?x + ?y = ?y + ?x\\ would be lifted to \n \\\\ x y z. ?x x y z + ?y x y z = ?y x y z + ?x x y z\\. This way, the lifted theorem\n can be instantiated by the parameters \\x y z\\ representing \"fresh free variables\"\n used for this sub-proof. This mechanism implements their logically correct bookkeeping via\n kernel primitives.\n\\<^item> \\<^emph>\\Higher-order unification (of schematic type and term variables)\\.\n Finally, for all these schematic variables, a solution must be found.\n In the case of \\<^ML>\\resolve_tac\\, the conclusion of the (doubly lifted) theorem must\n be equal to the conclusion of the subgoal, so \\<^term>\\A\\ must be \\\\/\\\\-equivalent to\n \\<^term>\\A'\\ in the example above, which is established by a higher-order unification\n process. It is a bit unfortunate that for implementation efficiency reasons, a very substantial\n part of the code for HO-unification is in the kernel module \\<^ML_type>\\thm\\, which makes this\n critical component of the architecture larger than necessary. \n\\\n\ntext\\In a way, the two lifting processes represent an implementation of the conversion between\n Gentzen Natural Deduction (to which Isabelle/Pure is geared) reasoning and \n Gentzen Sequent Deduction.\\\n\n\nsection*[goalp::technical]\\The classical goal package\\\ntext\\The main mechanism in Isabelle as an LCF-style system is to produce \\<^ML_type>\\thm\\'s \n in backward-style via tactics as described in @{technical \"t24\"}. Given a context\n --- be it global as \\<^ML_type>\\theory\\ or be it inside a proof-context as \\<^ML_type>\\Proof.context\\,\n user-programmed verification of (type-checked) terms or just strings can be done via the \n operations:\n\n\\<^item> \\<^ML>\\Goal.prove_internal : Proof.context -> cterm list -> cterm -> (thm list -> tactic) -> thm\\\n\\<^item> \\<^ML>\\Goal.prove_global : theory -> string list -> term list -> term -> \n ({context: Proof.context, prems: thm list} -> tactic) -> thm\\\n\\<^item> ... and many more variants. \n\\\n\nsubsection*[ex211::example]\\Proof Example (Low-level)\\ \n\ntext\\Take this proof at Isar Level as example:\\\n\nlemma X : \"(10::int) + 2 = 12\" by simp\n\ndeclare X[simp]\n\ntext\\This represents itself at the SML interface as follows:\\\n\nML\\\nstructure SimpleSampleProof =\nstruct\n\nval tt = HOLogic.mk_Trueprop (Syntax.read_term @{context} \"(10::int) + 2 = 12\");\n (* read_term parses and type-checks its string argument;\n HOLogic.mk_Trueprop wraps the embedder from @{ML_type \"bool\"} to \n @{ML_type \"prop\"} from Pure. *)\n\nfun derive_thm name term lthy = \n Goal.prove lthy (* global context *)\n [name] (* name ? *)\n [] (* local assumption context *)\n (term) (* parsed goal *)\n (fn _ => simp_tac lthy 1) (* proof tactic *)\n |> Thm.close_derivation \\<^here> (* some cleanups *);\n\nval thm111_intern = derive_thm \"thm111\" tt @{context} (* just for fun at the ML level *)\n\nfun store_thm name thm lthy = \n lthy |> snd o Local_Theory.note ((Binding.name name, []), [thm]) \n\n\nval prove_n_store = (Named_Target.theory_map(fn lthy => \n let val thm = derive_thm \"thm111\" tt lthy\n in lthy |> store_thm \"thm111\" thm end));\n\nend\n\\\n\ntext\\Converting a local theory transformation into a global one:\\\nsetup\\SimpleSampleProof.prove_n_store\\\n\ntext\\... and there it is in the global (Isar) context:\\\nthm \"thm111\"\n\n\n\n\n\nsection\\Toplevel --- aka. ''The Isar Engine''\\\n\ntext\\ The main structure of the Isar-engine is \\<^ML_structure>\\Toplevel\\.\n The Isar Toplevel (aka \"the Isar engine\" or the \"Isar Interpreter\") is a transaction\n machine sitting over the Isabelle Kernel steering some asynchronous evaluation during the\n evaluation of Isabelle/Isar input, usually stemming from processing Isabelle \\<^verbatim>\\.thy\\-files. \\\n\nsubsection*[tplstate::technical] \\Toplevel Transaction Management in the Isar-Engine\\\ntext\\\n The structure \\<^ML_structure>\\Toplevel\\ provides an internal \\<^ML_type>\\state\\ with the \n necessary infrastructure --- i.e. the operations to pack and unpack theories and\n queries on it:\n\n\\<^item> \\<^ML>\\ Toplevel.theory_toplevel: theory -> Toplevel.state\\\n\\<^item> \\<^ML>\\ Toplevel.init_toplevel: unit -> Toplevel.state\\\n\\<^item> \\<^ML>\\ Toplevel.is_toplevel: Toplevel.state -> bool\\\n\\<^item> \\<^ML>\\ Toplevel.is_theory: Toplevel.state -> bool\\\n\\<^item> \\<^ML>\\ Toplevel.is_proof: Toplevel.state -> bool\\\n\\<^item> \\<^ML>\\ Toplevel.is_skipped_proof: Toplevel.state -> bool\\\n\\<^item> \\<^ML>\\ Toplevel.level: Toplevel.state -> int\\\n\\<^item> \\<^ML>\\ Toplevel.context_of: Toplevel.state -> Proof.context\\\n extracts the local context \n\\<^item> \\<^ML>\\ Toplevel.generic_theory_of: Toplevel.state -> generic_theory\\\n extracts the generic (local or global) context \n\\<^item> \\<^ML>\\ Toplevel.theory_of: Toplevel.state -> theory\\\n extracts the global context \n\\<^item> \\<^ML>\\ Toplevel.proof_of: Toplevel.state -> Proof.state\\\n\\<^item> \\<^ML>\\ Toplevel.presentation_context: Toplevel.state -> Proof.context\\\n\\<^item> ... \n\\\n\ntext\\ Type \\<^ML_type>\\Toplevel.state\\ represents Isar toplevel states, which are normally \n manipulated through the concept of toplevel transitions only.\n This type is constructed as the sum of \\<^emph>\\empty state\\, \\<^ML_type>\\Context.generic\\\n (synonym to \\<^ML_type>\\generic_theory\\) and enriched versions of proof states or\n abort proofs.\n\\\n\n\nsubsection*[transmgt::technical] \\Toplevel Transaction Management in the Isar-Engine\\\n\ntext\\ The extensibility of Isabelle as a system framework depends on a number of tables,\n into which various concepts commands, ML-antiquotations, text-antiquotations, cartouches, ...\n can be entered via a late-binding on the fly. \n \n The main operations to toplevel transitions are:\n\n \\<^item> \\<^ML>\\Toplevel.keep: (Toplevel.state -> unit) -> Toplevel.transition -> Toplevel.transition\\\n adjoins a diagnostic command\n \\<^item> \\<^ML>\\Toplevel.theory: (theory -> theory) -> Toplevel.transition -> Toplevel.transition\\\n adjoins a theory transformer.\n \\<^item> \\<^ML>\\Toplevel.generic_theory: (generic_theory -> generic_theory) -> Toplevel.transition -> Toplevel.transition\\\n \\<^item> \\<^ML>\\Toplevel.theory': (bool -> theory -> theory) -> Toplevel.presentation -> Toplevel.transition -> Toplevel.transition\\\n \\<^item> \\<^ML>\\Toplevel.exit: Toplevel.transition -> Toplevel.transition\\\n \\<^item> \\<^ML>\\Toplevel.ignored: Position.T -> Toplevel.transition\\\n \\<^item> \\<^ML>\\Toplevel.present_local_theory: (xstring * Position.T) option ->\n (Toplevel.state -> Latex.text) -> Toplevel.transition -> Toplevel.transition\\\n\n\\\nsubsection*[cmdbinding::technical] \\Toplevel Transaction Management in the Isar-Engine\\\ntext\\\n Toplevel transitions can finally be registered together with commandkeywords and \n IDE information into the toplevel.\n The global type of this key function for extending the Isar toplevel is, together\n with a few query operations on the state of the toplevel:\n \\<^item> \\<^ML>\\Outer_Syntax.command : Outer_Syntax.command_keyword -> string -> \n (Toplevel.transition -> Toplevel.transition) parser -> unit\\,\n \\<^item> \\<^ML>\\Document.state : unit -> Document.state\\, giving the state as a \"collection\" of named\n nodes, each consisting of an editable list of commands, associated with asynchronous \n execution process,\n \\<^item> \\<^ML>\\Session.get_keywords : unit -> Keyword.keywords\\, this looks to be session global,\n \\<^item> \\<^ML>\\Thy_Header.get_keywords : theory -> Keyword.keywords\\ this looks to be just theory global.\n\n\n A paradigmatic example is the \\<^ML>\\Outer_Syntax.command\\-operation, which ---\n representing itself as a toplevel system transition --- allows to define a new \n command section and bind its syntax and semantics at a specific keyword.\n Calling \\<^ML>\\Outer_Syntax.command\\ creates an implicit \\<^ML>\\Theory.setup\\ with an entry\n for a call-back function, which happens to be a parser that must have as side-effect \n a Toplevel-transition-transition. \n Registers \\<^ML_type>\\Toplevel.transition -> Toplevel.transition\\ parsers to the \n Isar interpreter.\\\n\ntext\\The file \\<^file>\\~~/src/HOL/Examples/Commands.thy\\ shows some example Isar command definitions, with the \n all-important theory header declarations for outer syntax keywords.\\\n \ntext\\@{ML_structure Pure_Syn}\\\n\nsubsubsection*[ex1137::example]\\Examples: \\<^theory_text>\\text\\\\\ntext\\ The integration of the \\<^theory_text>\\text\\-command is done as follows:\n\n @{ML [display]\\\n Outer_Syntax.command (\"text\", @{here}) \"formal comment (primary style)\"\n (Parse.opt_target -- Parse.document_source >> Document_Output.document_output \n {markdown = true, markup = I})\n \\}\n\n where \\<^ML>\\Document_Output.document_output\\ is the defining operation for the \n \"diagnostic\" (=side-effect-free) toplevel operation.\n \\<^ML>\\Document_Output.document_output\\ looks as follows:\n\n @{ML [display]\\let fun document_reports txt =\n let val pos = Input.pos_of txt in\n [(pos, Markup.language_document (Input.is_delimited txt)),\n (pos, Markup.plain_text)]\n end;\nfun document_output {markdown, markup} (loc, txt) =\n let\n fun output st =\n let\n val ctxt = Toplevel.presentation_context st;\n val _ = Context_Position.reports ctxt (document_reports txt);\n in txt |> Document_Output.output_document ctxt {markdown = markdown} |> markup end;\n in\n Toplevel.present (fn st =>\n (case loc of\n NONE => output st\n | SOME (_, pos) =>\n error (\"Illegal target specification -- not a theory context\" ^ Position.here pos))) o\n Toplevel.present_local_theory loc output\n end in () end\n\\}\n\\\n\nsubsubsection*[ex1138::example]\\Examples: \\<^theory_text>\\ML\\\\\n\ntext\\\n The integration of the \\<^theory_text>\\ML\\-command is done as follows:\n\n @{ML [display]\\\n Outer_Syntax.command (\"ML\", \\<^here>) \"ML text within theory or local theory\"\n (Parse.ML_source >> (fn source =>\n Toplevel.generic_theory\n (ML_Context.exec (fn () =>\n ML_Context.eval_source (ML_Compiler.verbose true ML_Compiler.flags) source) #>\n Local_Theory.propagate_ml_env)))\n \\}\n\\\n\n\nsubsection\\Miscellaneous\\\n\ntext\\Here are a few queries relevant for the global config of the isar engine:\\\nML\\ Document.state();\\\nML\\ Session.get_keywords(); (* this looks to be session global. *) \\\nML\\ Thy_Header.get_keywords @{theory};(* this looks to be really theory global. *) \\\n\n \nsubsection*[conf::technical]\\ Configuration Flags in the Isar-engine. \\\ntext\\The toplevel also provides an infrastructure for managing configuration options \n for system components. Based on a sum-type @{ML_type Config.value } \n with the alternatives \\<^verbatim>\\ Bool of bool | Int of int | Real of real | String of string\\\n and building the parametric configuration types @{ML_type \"'a Config.T\" } and the\n instance \\<^verbatim>\\type raw = value T\\, for all registered configurations the protocol:\n\n\n \\<^item> \\<^ML>\\Config.get : Proof.context -> 'a Config.T -> 'a\\\n \\<^item> \\<^ML>\\Config.map: 'a Config.T -> ('a -> 'a) -> Proof.context -> Proof.context\\ \n \\<^item> \\<^ML>\\Config.put: 'a Config.T -> 'a -> Proof.context -> Proof.context\\ \n \\<^item> \\<^ML>\\Config.get_global: theory -> 'a Config.T -> 'a\\ \n \\<^item> \\<^ML>\\Config.map_global: 'a Config.T -> ('a -> 'a) -> theory -> theory\\ \n \\<^item> \\<^ML>\\Config.put_global: 'a Config.T -> 'a -> theory -> theory\\ \n \\<^item> ... etc. is defined.\n\\\n\n\nsubsubsection*[ex::example]\\Example registration of a config attribute \\\ntext\\The attribute XS232 is initialized by false:\\\nML\\ \nval (XS232, XS232_setup)\n = Attrib.config_bool \\<^binding>\\XS232\\ (K false);\n\nval _ = Theory.setup XS232_setup;\\\n\ntext \\... which could also be achieved by \\setup\\XS232_setup\\\\. \\\n\nsubsubsection*[ex33333::example]\\Defining a high-level attribute:\\\nML\\ \nAttrib.setup \\<^binding>\\simp\\ (Attrib.add_del Simplifier.simp_add Simplifier.simp_del)\n \"declaration of Simplifier rewrite rule\"\n\\\n\n\nsubsection*[ex333::example]\\A Hack:\\\n\ntext\\Another mechanism are global synchronised variables:\\\nML\\\n \n val C = Synchronized.var \"Pretty.modes\" \"latEEex\"; \n (* Synchronized: a mechanism to bookkeep global\n variables with synchronization mechanism included *)\n Synchronized.value C;\\ \n\n\nsubsection*[ex213::example]\\A Definition Command (High-level)\\ \n\ntext\\A quite complex example is drawn from the Theory \\<^verbatim>\\Clean\\; it generates \\\n\nML\\Specification.definition\\\n\nML\\\nstructure HLDefinitionSample = \nstruct\nfun cmd (decl, spec, prems, params) = #2 o Specification.definition decl params prems spec\n\nfun MON_SE_T res state = state --> optionT(HOLogic.mk_prodT(res,state));\n\nfun push_eq binding name_op rty sty lthy = \n let val mty = MON_SE_T rty sty \n val thy = Proof_Context.theory_of lthy\n val term = Free(\"\\\",sty)\n in mk_meta_eq((Free(name_op, mty) $ Free(\"\\\",sty)), \n mk_Some ( HOLogic.mk_prod (mk_undefined rty,term)))\n \n end;\n\nfun mk_push_name binding = Binding.prefix_name \"push_\" binding\n\nfun mk_push_def binding sty lthy =\n let val name = mk_push_name binding\n val rty = \\<^typ>\\unit\\\n val eq = push_eq binding (Binding.name_of name) rty sty lthy\n val mty = MON_SE_T rty sty \n val args = (SOME(name, SOME mty, NoSyn), (Binding.empty_atts,eq),[],[])\n in cmd args lthy end;\n\nval define_test = Named_Target.theory_map (mk_push_def (Binding.name \"test\") @{typ \"'a\"})\n\nend\n\\\n\nsetup\\HLDefinitionSample.define_test\\\n\nsubsection*[ex212::example]\\Proof Example (High-level)\\ \n\ntext\\The Isar-toplevel refers to a level of \"specification constructs\"; i.e. to a level with\nmore high-level commands that represent internally quite complex theory transformations;\nwith the exception of the axiomatization constructs, they are alltogether logically conservative.\nThe proof command interface behind \\lemma\\ or \\theorem\\ uses a structure capturing the \nsyntactic @{ML_structure Element}'s of the \\fix\\, \\assume\\, \\shows\\ structuring.\n\\\n\ntext\\By the way, the Isar-language Element interface can by found under @{ML_structure Element}:\n\\<^enum> @{ML \"Element.Fixes : (binding * 'a option * mixfix) list -> ('a, 'b, 'c) Element.ctxt\"}\n\\<^enum> @{ML \"Element.Assumes: (Attrib.binding * ('a * 'a list) list) list -> ('b, 'a, 'c) Element.ctxt\"}\n\\<^enum> @{ML \"Element.Notes: string * (Attrib.binding * ('a * Token.src list) list) list \n -> ('b, 'c, 'a) Element.ctxt\"}\n\\<^enum> @{ML \"Element.Shows: (Attrib.binding * ('a * 'a list) list) list -> ('b, 'a) Element.stmt\"}\n\\\n\n(* UNCHECKED ! ! ! *)\n\nML\\\nfun lemma1 lemma_name goals_to_prove a lthy = \n let val lemma_name_bdg =(Binding.make (lemma_name, @{here}), []) \n val attrs' = [\"simp\"] (* ?????? *)\n in lthy |>\n Specification.theorem_cmd true \n Thm.theoremK NONE (K I)\n Binding.empty_atts [] [] \n (Element.Shows [(lemma_name_bdg,[(goals_to_prove, attrs')])])\n true (* disp ??? *)\n end\n\nfun lemma1' lemma_name goals_to_prove a b lthy =\n let fun gen_attribute_token simp lthy = \n List.map (fn s => Attrib.check_src lthy [Token.make_string (s, Position.none)])\n (if simp then [\"simp\", \"code_unfold\"] else [])\n val lemma_name_bdg =(Binding.make (lemma_name, @{here}), gen_attribute_token true lthy) \n in lthy |> #2 o Specification.theorems Thm.theoremK a b true end\n\\\n\n\nchapter*[frontend::technical]\\Front-End \\ \ntext\\In the following chapter, we turn to the right part of the system architecture \n shown in \\<^figure>\\architecture\\: \n The PIDE (\"Prover-IDE\") layer @{cite \"DBLP:conf/itp/Wenzel14\"}\n consisting of a part written in SML and another in SCALA.\n Roughly speaking, PIDE implements \"continuous build - continuous check\" - functionality\n over a textual, albeit generic document model. It transforms user modifications\n of text elements in an instance of this model into increments (edits) and communicates\n them to the Isabelle system. The latter reacts by the creation of a multitude of light-weight\n reevaluation threads resulting in an asynchronous stream of markup that is used to annotate text\n elements. Such markup is used to highlight, e.g., variables\n or keywords with specific colors, to hyper-linking bound variables to their defining occurrences,\n or to annotate type-information to terms which becomes displayed by specific\n user-gestures on demand (hovering), etc. \n Note that PIDE is not an editor, it is the framework that \n coordinates these asynchronous information streams and optimizes it to a certain\n extent (outdated markup referring to modified text is dropped, and \n corresponding re-calculations are oriented to the user focus, for example). \n Four concrete editors --- also called PIDE applications --- have been implemented:\n\n\\<^enum> an Eclipse plugin (developped by an Edinburg-group, based on an very old PIDE version),\n\\<^enum> a Visual-Studio Code plugin (developed by Makarius Wenzel), \n currently based on a fairly old PIDE version, \n\\<^enum> clide, a web-client supporting javascript and HTML5\n (developed by a group at University Bremen, based on a very old PIDE version), and \n\\<^enum> the most commonly used: the plugin in JEdit - Editor,\n (developed by Makarius Wenzel, current PIDE version.)\\\n\ntext\\The document model forsees a number of text files, which are organized in form of an \n acyclic graph. Such graphs can be grouped into \\<^emph>\\sessions\\ and \"frozen\" to binaries in order \n to avoid long compilation times. Text files have an abstract name serving as identity (the \n mapping to file-paths in an underlying file-system is done in an own build management).\n The primary format of the text files is \\<^verbatim>\\.thy\\ (historically for: theory),\n secondary formats can be \\<^verbatim>\\.sty\\,\\<^verbatim>\\.tex\\, \\<^verbatim>\\.png\\, \\<^verbatim>\\.pdf\\, or other files processed \n by Isabelle and listed in a configuration processed by the build system.\\\n\nfigure*[fig3::figure, relative_width=\"100\",src=\"''figures/document-model''\"]\n \\A Theory-Graph in the Document Model\\\n\ntext\\A \\<^verbatim>\\.thy\\ file consists of a \\<^emph>\\header\\, a \\<^emph>\\context-definition\\ and\n a \\<^emph>\\body\\ consisting of a sequence of \\<^emph>\\commands\\. Even the header consists of\n a sequence of commands used for introductory text elements not depending on any context\n information (so: practically excluding any form of text antiquotation (see above)).\n The context-definition contains an \\<^emph>\\import\\ and a \\<^emph>\\keyword\\ section; \n for example:\n @{theory_text [display] \\\n theory Isa_DOF (* Isabelle Document Ontology Framework *)\n imports Main \n RegExpInterface (* Interface to functional regular automata for monitoring *)\n Assert\n \n keywords \"+=\" \":=\" \"accepts\" \"rejects\"\n \\}\n where \\<^verbatim>\\Isa_DOF\\ is the abstract name of the text-file, \\<^verbatim>\\Main\\ etc. refer to imported\n text files (recall that the import relation must be acyclic). \\<^emph>\\keyword\\s are used to separate \n commands form each other;\n predefined commands allow for the dynamic creation of new commands similarly \n to the definition of new functions in an interpreter shell (or: toplevel, see above.).\n A command starts with a pre-declared keyword and specific syntax of this command;\n the declaration of a keyword is only allowed in the same \\<^verbatim>\\.thy\\-file where\n the corresponding new command is defined. The semantics of the command is expressed\n in ML and consists of a @{ML_type \"Toplevel.transition -> Toplevel.transition\"}\n function. Thus, the Isar-toplevel supports the generic document model \n and allows for user-programmed extensions.\\\n\ntext\\In the traditional literature, Isabelle \\<^verbatim>\\.thy\\-files \n were said to be processed by two types of parsers:\n\\<^enum> the \"outer-syntax\" (i.e. the syntax for commands) is processed \n by a lexer-library and parser combinators built on top, and\n\\<^enum> the \"inner-syntax\" (i.e. the syntax for @{term \\\\\\}-terms) \n with an evolved, eight-layer parsing and pretty-printing process\n based on an Earley-algorithm.\n\\\n\ntext\\This picture is less and less true for a number of reasons:\n\\<^enum> With the advent of \\\\ ... \\\\, a mechanism for\n \\<^emph>\\cascade-syntax\\ came to the Isabelle platform that introduces a flexible means\n to change parsing contexts \\<^emph>\\and\\ parsing technologies. \n\\<^enum> Inside the term-parser levels, the concept of \\<^emph>\\cartouche\\ can be used \n to escape the parser and its underlying parsing technology.\n\\<^enum> Outside, in the traditional toplevel-parsers, the \n \\\\ ... \\\\ is becoming more and more enforced\n (some years ago, syntax like \\term{* ... *}\\ was replaced by \n syntax \\term\\ ... \\\\. This makes technical support of cascade syntax\n more and more easy.\n\\<^enum> The Lexer infra-structure is already rather generic; nothing prevents to\n add beside the lexer - configurations for ML-Parsers, Toplevel Command Syntax \n parsers, mathematical notation parsers for $\\lambda$-terms new pillars\n of parsing technologies, say, for parsing C or Rust or JavaScript inside \n Isabelle.\n\\\n\n\nsection\\Basics: string, bstring and xstring\\\ntext\\\\<^ML_type>\\string\\ is the basic library type from the SML library\n in structure \\<^ML_structure>\\String\\. Many Isabelle operations produce\n or require formats thereof introduced as type synonyms \n \\<^ML_type>\\bstring\\ (defined in structure \\<^ML_structure>\\Binding\\)\n and \\<^ML_type>\\xstring\\ (defined in structure \\<^ML_structure>\\Name_Space\\).\n Unfortunately, the abstraction is not tight and combinations with \n elementary routines might produce quite crappy results.\\\n\nML\\val b = Binding.name_of @{binding \\here\\}\\\ntext\\... produces the system output \\<^verbatim>\\val it = \"here\": bstring\\,\n but note that it is misleading to believe it is just a string.\\\n\nML\\String.explode b\\ (* is harmless, but *)\nML\\String.explode(Binding.name_of\n (Binding.conglomerate[Binding.qualified_name \"X.x\", @{binding \"here\"}] ))\\\ntext\\... which leads to the output \\<^verbatim>\\val it = [#\"x\", #\"_\", #\"h\", #\"e\", #\"r\", #\"e\"]: char list\\\\\n\ntext\\ However, there is an own XML parser for this format. See Section Markup. \\\n\nML\\ fun dark_matter x = XML.content_of (YXML.parse_body x)\\\n\n(* MORE TO COME *)\n\nsection\\Positions\\\ntext\\A basic data-structure relevant for PIDE are \\<^emph>\\positions\\; beyond the usual line- and column\n information they can represent ranges, list of ranges, and the name of the atomic sub-document\n in which they are contained. In the command:\\\nML\\\nval pos = @{here};\nval markup = Position.here pos;\nwriteln (\"And a link to the declaration of 'here' is \"^markup)\\ \n\n(* \\<^here> *)\ntext\\ ... uses the antiquotation @{ML \"@{here}\"} to infer from the system lexer the actual position\n of itself in the global document, converts it to markup (a string-representation of it) and sends\n it via the usual @{ML \"writeln\"} to the interface. \\\n\nfigure*[hyplinkout::figure,relative_width=\"40\",src=\"''figures/markup-demo''\"]\n\\Output with hyperlinked position.\\\n\ntext\\@{figure \\hyplinkout\\} shows the produced output where the little house-like symbol in the \n display is hyperlinked to the position of @{ML \"@{here}\"} in the ML sample above.\\\n\nsection\\Markup and Low-level Markup Reporting\\\ntext\\The structures @{ML_structure Markup} and @{ML_structure Properties} represent the basic \n annotation data which is part of the protocol sent from Isabelle to the front-end.\n They are qualified as \"quasi-abstract\", which means they are intended to be an abstraction of \n the serialized, textual presentation of the protocol. Markups are structurally a pair of a key\n and properties; @{ML_structure Markup} provides a number of such \\<^emph>\\key\\s for annotation classes\n such as \"constant\", \"fixed\", \"cartouche\", some of them quite obscure. Here is a code sample\n from \\<^theory_text>\\Isabelle_DOF\\. A markup must be tagged with an id; this is done by the @{ML serial}-function\n discussed earlier. Markup operations were used for hyperlinking applications to binding\n occurrences, info for hovering, infos for type ... \\ \n\nML\\\n(* Position.report is also a type consisting of a pair of a position and markup. *)\n(* It would solve all my problems if I find a way to infer the defining Position.report\n from a type definition occurence ... *)\n\nPosition.report: Position.T -> Markup.T -> unit;\nPosition.reports: Position.report list -> unit; \n (* ? ? ? I think this is the magic thing that sends reports to the GUI. *)\nMarkup.entity : string -> string -> Markup.T;\nMarkup.properties : Properties.T -> Markup.T -> Markup.T ;\nProperties.get : Properties.T -> string -> string option;\nMarkup.enclose : Markup.T -> string -> string; \n \n(* example for setting a link, the def flag controls if it is a defining or a binding \noccurence of an item *)\nMarkup.theoryN : string;\n\nfun theory_markup refN (def:bool) (name:string) (id:serial) (pos:Position.T) =\n if id = 0 then Markup.empty\n else Position.make_entity_markup {def = def} id refN (name, pos);\n\nserial(); (* A global, lock-guarded serial counter used to produce unique identifiers,\n be it on the level of thy-internal states or as reference in markup in\n PIDE *)\n\\\n\n\nsubsection\\A simple Example\\\nML\\\nlocal \n \nval docclassN = \"doc_class\"; \n\n(* derived from: theory_markup; def for \"defining occurrence\" (true) in contrast to\n \"referring occurence\" (false). *) \nval docclass_markup = theory_markup docclassN \n\nin\n\nfun report_defining_occurrence pos cid =\n let val id = serial ()\n val markup_of_cid = docclass_markup true cid id pos\n in Position.report pos markup_of_cid end;\n\nend\n\\\n\ntext\\The @\\ML report_defining_occurrence\\-function above takes a position and a \"cid\" parsed\n in the Front-End, converts this into markup together with a unique number identifying this\n markup, and sends this as a report to the Front-End. \\\n\n\nsubsection\\A Slightly more Complex Example\\\ntext\\Note that this example is only animated in the integrated source of this document;\n it is essential that is executed inside Isabelle/jEdit. \\\nML \\\n\nfun markup_tvar def_name ps (name, id) =\n let \n fun markup_elem name = (name, (name, []): Markup.T);\n val (tvarN, tvar) = markup_elem ((case def_name of SOME name => name | _ => \"\") ^ \"'s nickname is\");\n val entity = Markup.entity tvarN name (* ??? *)\n val def = def_name = NONE\n in\n tvar ::\n (if def then I else cons (Markup.keyword_properties Markup.ML_keyword3))\n (map (fn pos => Position.make_entity_markup {def = def} id tvarN (name, pos) ) ps)\n end\n\n(* Position.make_entity_markup {def = def} id refN (name, pos) *)\n\nfun report [] _ _ = I\n | report ps markup x =\n let val ms = markup x\n in fold (fn p => fold (fn m => cons ((p, m), \"\")) ms) ps end\n\\\n\nML \\\nlocal\nval data = \\ \\Derived from Yakoub's example ;-)\\\n\n [ (\\Frédéric 1er\\, \\King of Naples\\)\n , (\\Frédéric II\\, \\King of Sicily\\)\n , (\\Frédéric III\\, \\the Handsome\\)\n , (\\Frédéric IV\\, \\of the Empty Pockets\\)\n , (\\Frédéric V\\, \\King of Denmark-Norway\\)\n , (\\Frédéric VI\\, \\the Knight\\)\n , (\\Frédéric VII\\, \\Count of Toggenburg\\)\n , (\\Frédéric VIII\\, \\Count of Zollern\\)\n , (\\Frédéric IX\\, \\the Old\\)\n , (\\Frédéric X\\, \\the Younger\\) ]\n\nval (tab0, markup) =\n fold_map (fn (name, msg) => fn reports =>\n let val id = serial ()\n val pos = [Input.pos_of name]\n in \n ( (fst(Input.source_content msg), (name, pos, id))\n , report pos (markup_tvar NONE pos) (fst(Input.source_content name), id) reports)\n end)\n data\n []\n\nval () = Position.reports_text markup\nin\nval tab = Symtab.make tab0\nend\n\\\n\nML \\\nval _ =\n fold (fn input =>\n let\n val pos1' = Input.pos_of input\n fun ctnt name0 = fst(Input.source_content name0)\n val pos1 = [pos1']\n val msg1 = fst(Input.source_content input)\n val msg2 = \"No persons were found to have such nickname\"\n in\n case Symtab.lookup tab (fst(Input.source_content input)) of\n NONE => tap (fn _ => Output.information (msg2 ^ Position.here_list pos1))\n (cons ((pos1', Markup.bad ()), \"\"))\n | SOME (name0, pos0, id) => report pos1 (markup_tvar (SOME (ctnt name0)) pos0) (msg1, id)\n end)\n [ \\the Knight\\ \\ \\Example of a correct retrieval (CTRL + Hovering shows what we are expecting)\\\n , \\the Handsome\\ \\ \\Example of a correct retrieval (CTRL + Hovering shows what we are expecting)\\\n , \\the Spy\\ \\ \\Example of a failure to retrieve the person in \\<^ML>\\tab\\\\\n ]\n []\n |> Position.reports_text\n\\\n\ntext\\The pudding comes with the eating: \\\n\nsubsection\\Environment Structured Reporting\\\n\ntext\\ The structure \\<^ML_structure>\\Name_Space\\ offers an own infra-structure for names and\n manages the markup accordingly. MORE TO COME\\\ntext\\ \\<^ML_type>\\'a Name_Space.table\\ \\\n\n\nsection\\The System Lexer and Token Issues\\\ntext\\Four syntactic contexts are predefined in Isabelle (others can be added): \n the ML context, the text context, the Isar-command context and the term-context, referring\n to different needs of the Isabelle Framework as an extensible framework supporting incremental,\n partially programmable extensions and as a Framework geared towards Formal Proofs and therefore\n mathematical notations. The basic data-structure for the lexical treatment of these elements\n are \\<^ML_structure>\\Token\\'s. \\\n\nsubsection\\Tokens\\\n\ntext\\The basic entity that lexers treat are \\<^emph>\\tokens\\. defined in \\<^ML_structure>\\Token\\\n It provides a classification infrastructure, the references to positions and Markup \n as well as way's to annotate tokens with (some) values they denote:\\\n\n\nML\\\nlocal\n open Token \n\n type dummy = Token.T\n type src = Token.T list\n type file = {src_path: Path.T, lines: string list, digest: SHA1.digest, pos: Position.T}\n\n type name_value = {name: string, kind: string, print: Proof.context -> Markup.T * xstring}\n\n\n val _ = Token.is_command : Token.T -> bool;\n val _ = Token.content_of : Token.T -> string; (* textueller kern eines Tokens. *)\n\n\n val _ = pos_of: T -> Position.T\n\n(*\ndatatype kind =\n (*immediate source*)\n Command | Keyword | Ident | Long_Ident | Sym_Ident | Var | Type_Ident | Type_Var | Nat |\n Float | Space |\n (*delimited content*)\n String | Alt_String | Verbatim | Cartouche | Comment of Comment.kind option |\n (*special content*)\n Error of string | EOF\n\n datatype value =\n Source of src |\n Literal of bool * Markup.T |\n Name of name_value * morphism |\n Typ of typ |\n Term of term |\n Fact of string option * thm list |\n Attribute of morphism -> attribute |\n Declaration of declaration |\n Files of file Exn.result list\n\n\n*)\nin val _ = ()\nend\n\\\n\n\n\nsubsection\\A Lexer Configuration Example\\\n\nML\\\n(* MORE TO COME *)\n\\\n\n\nsection\\ Combinator Parsing \\ \ntext\\Parsing Combinators go back to monadic programming as advocated by Wadler et. al, and has been \n worked out @{cite \"DBLP:journals/jfp/Hutton92\"}. Parsing combinators are one of the two\n major parsing technologies of the Isabelle front-end, in particular for the outer-syntax used\n for the parsing of toplevel-commands. The core of the combinator library is \n \\<^ML_structure>\\Scan\\ providing the \\<^ML_type>\\'a parser\\ which is a synonym for\n \\<^ML_type>\\Token.T list -> 'a * Token.T list\\. \n \n \"parsers\" are actually interpreters; an \\<^ML_type>\\'a parser\\ is a function that parses\n an input stream and computes (=evaluates) it into \\'a\\. \n\n \\<^item> \\<^theory_text>\\type 'a parser = Token.T list -> 'a * Token.T list\\\n \\<^item> \\<^theory_text>\\ type 'a context_parser = Context.generic * Token.T list -> \n 'a * (Context.generic * Token.T list)\\\n\n Since the semantics of an Isabelle command is a \\<^ML_type>\\Toplevel.transition -> Toplevel.transition \\\n or theory \\<^ML_type>\\theory -> theory\\ function, i.e. a global system transition,\n \"parsers\" of that type can be constructed and be bound as call-back functions\n to a table in the Toplevel-structure of Isar.\n \n The library also provides a bunch of infix parsing combinators, notably:\n\n\\<^item> \\<^ML>\\op !! : ('a * message option -> message) -> ('a -> 'b) -> 'a -> 'b\\ \n (*apply function*)\n\\<^item> \\<^ML>\\op >> : ('a -> 'b * 'c) * ('b -> 'd) -> 'a -> 'd * 'c\\ \n (*alternative*)\n\\<^item> \\<^ML>\\ op || : ('a -> 'b) * ('a -> 'b) -> 'a -> 'b\\\n (*sequential pairing*)\n\\<^item> \\<^ML>\\op -- : ('a -> 'b * 'c) * ('c -> 'd * 'e) -> 'a -> ('b * 'd) * 'e\\ \n (*dependent pairing*)\n\\<^item> \\<^ML>\\ op :-- : ('a -> 'b * 'c) * ('b -> 'c -> 'd * 'e) -> 'a -> ('b * 'd) * 'e\\\n (*projections*)\n\\<^item> \\<^ML>\\op :|-- : ('a -> 'b * 'c) * ('b -> 'c -> 'd * 'e) -> 'a -> 'd * 'e\\ \n\\<^item> \\<^ML>\\op |-- : ('a -> 'b * 'c) * ('c -> 'd * 'e) -> 'a -> 'd * 'e\\ \n concatenate and forget first parse result\n\\<^item> \\<^ML>\\op --| : ('a -> 'b * 'c) * ('c -> 'd * 'e) -> 'a -> 'b * 'e\\ \n concatenate and forget second parse result\n\\<^item> \\<^ML>\\op ^^ : ('a -> string * 'b) * ('b -> string * 'c) -> 'a -> string * 'c\\ \n\\<^item> \\<^ML>\\op ::: : ('a -> 'b * 'c) * ('c -> 'b list * 'd) -> 'a -> 'b list * 'd\\ \n\\<^item> \\<^ML>\\op @@@ : ('a -> 'b list * 'c) * ('c -> 'b list * 'd) -> 'a -> 'b list * 'd\\ \n parse one element literal\n\\<^item> \\<^ML>\\op $$ : string -> string list -> string * string list\\ \n\\<^item> \\<^ML>\\op ~$$ : string -> string list -> string * string list\\ \n\\\n\n\nsubsection\\Examples and Useful Glue\\\nML\\\n\n(* conversion between these two : *)\n\nfun parser2contextparser pars (ctxt, toks) = let val (a, toks') = pars toks\n in (a,(ctxt, toks')) end;\nval _ = parser2contextparser : 'a parser -> 'a context_parser;\n\n(* bah, it's the same as Scan.lift *)\nval _ = Scan.lift Args.cartouche_input : Input.source context_parser;\\\n\nsubsection\\Advanced Parser Library\\\n\ntext\\There are two parts. A general multi-purpose parsing combinator library is \n found under @{ML_structure \"Parse\"}, providing basic functionality for parsing strings\n or integers. There is also an important combinator that reads the current position information\n out of the input stream:\n\n\\<^item> \\<^ML>\\Parse.nat: int parser\\ \n\\<^item> \\<^ML>\\Parse.int: int parser\\\n\\<^item> \\<^ML>\\Parse.enum_positions: string -> 'a parser -> ('a list * Position.T list) parser\\\n\\<^item> \\<^ML>\\Parse.enum : string -> 'a parser -> 'a list parser\\\n\\<^item> \\<^ML>\\Parse.input: 'a parser -> Input.source parser\\\n\n\\<^item> \\<^ML>\\Parse.enum': string -> 'a context_parser -> 'a list context_parser\\\n\\<^item> \\<^ML>\\Parse.!!! : (Token.T list -> 'a) -> Token.T list -> 'a\\\n\\<^item> \\<^ML>\\Parse.position: 'a parser -> ('a * Position.T) parser\\\n\n\\<^item> \\<^ML>\\Parse.position Args.cartouche_input\\\n\\\n\ntext\\The second part is much more high-level, and can be found under \\<^ML_structure>\\Args\\.\n In parts, these combinators are again based on more low-level combinators, in parts they serve as \n an interface to the underlying Earley-parser for mathematical notation used in types and terms.\n This is perhaps meant with the fairly cryptic comment:\n \"Quasi-inner syntax based on outer tokens: concrete argument syntax of\n attributes, methods etc.\" at the beginning of this structure.\\\nML\\open Args\\ \n\ntext\\ Some more combinators\n\\<^item>\\<^ML>\\Args.symbolic : Token.T parser\\\n\\<^item>\\<^ML>\\Args.$$$ : string -> string parser\\\n\\<^item>\\<^ML>\\Args.maybe : 'a parser -> 'a option parser\\\n\\<^item>\\<^ML>\\Args.name_token: Token.T parser\\\n\nCommon Isar Syntax\n\\<^item>\\<^ML>\\Args.colon: string parser\\\n\\<^item>\\<^ML>\\Args.query: string parser\\\n\\<^item>\\<^ML>\\Args.bang: string parser\\\n\\<^item>\\<^ML>\\Args.query_colon: string parser\\\n\\<^item>\\<^ML>\\Args.bang_colon: string parser\\\n\\<^item>\\<^ML>\\Args.parens: 'a parser -> 'a parser\\\n\\<^item>\\<^ML>\\Args.bracks: 'a parser -> 'a parser\\\n\\<^item>\\<^ML>\\Args.mode: string -> bool parser\\\n\\<^item>\\<^ML>\\Args.name: string parser\\\n\\<^item>\\<^ML>\\Args.name_position: (string * Position.T) parser\\\n\\<^item>\\<^ML>\\Args.cartouche_inner_syntax: string parser\\\n\\<^item>\\<^ML>\\Args.cartouche_input: Input.source parser\\\n\n\nCommon Isar Syntax\n\\<^item>\\<^ML>\\Parse.embedded_input: Input.source parser\\\n\\<^item>\\<^ML>\\Parse.embedded : string parser\\\n\\<^item>\\<^ML>\\Args.binding : Binding.binding parser\\\n\nCommon Stuff related to Inner Syntax Parsing\n\\<^item>\\<^ML>\\Args.alt_name: string parser\\\n\\<^item>\\<^ML>\\Args.liberal_name : string parser\\\n\\<^item>\\<^ML>\\Args.var: indexname parser\\\n\\<^item>\\<^ML>\\Args.internal_source: Token.src parser\\\n\\<^item>\\<^ML>\\Args.internal_name: Token.name_value parser\\\n\\<^item>\\<^ML>\\Args.internal_typ : typ parser\\\n\\<^item>\\<^ML>\\Args.internal_term: term parser\\\n\\<^item>\\<^ML>\\Args.internal_fact: thm list parser\\\n\\<^item>\\<^ML>\\Args.internal_attribute: (morphism -> attribute) parser\\\n\\<^item>\\<^ML>\\Args.internal_declaration: declaration parser\\\n\\<^item>\\<^ML>\\Args.alt_name : string parser\\\n\\<^item>\\<^ML>\\Args.liberal_name: string parser\\\n\n\n\nCommon Isar Syntax\n\\<^item>\\<^ML>\\Args.named_source: (Token.T -> Token.src) -> Token.src parser\\\n\\<^item>\\<^ML>\\Args.named_typ : (string -> typ) -> typ parser\\\n\\<^item>\\<^ML>\\Args.named_term : (string -> term) -> term parser\\\n\\<^item>\\<^ML>\\Args.embedded_declaration: (Input.source -> declaration) -> declaration parser\\\n\\<^item>\\<^ML>\\Args.typ_abbrev : typ context_parser\\\n\\<^item>\\<^ML>\\Args.typ: typ context_parser\\\n\\<^item>\\<^ML>\\Args.term: term context_parser\\\n\\<^item>\\<^ML>\\Args.term_pattern: term context_parser\\\n\\<^item>\\<^ML>\\Args.term_abbrev : term context_parser \\\n\\<^item>\\<^ML>\\Args.named_source: (Token.T -> Token.src) -> Token.src parser\\\n\\<^item>\\<^ML>\\Args.named_typ : (string -> typ) -> typ parser\\\n\\<^item>\\<^ML>\\Args.named_term: (string -> term) -> term parser\\\n\nSyntax for some major Pure commands in Isar\n\\<^item>\\<^ML>\\Args.prop: term context_parser\\\n\\<^item>\\<^ML>\\Args.type_name: {proper: bool, strict: bool} -> string context_parser\\\n\\<^item>\\<^ML>\\Args.const: {proper: bool, strict: bool} -> string context_parser\\\n\\<^item>\\<^ML>\\Args.goal_spec: ((int -> tactic) -> tactic) context_parser\\\n\\<^item>\\<^ML>\\Args.context: Proof.context context_parser\\\n\\<^item>\\<^ML>\\Args.theory: theory context_parser\\\n\n\\\n\n\n\nsubsection\\ Bindings \\ \n\ntext\\ The structure \\<^ML_structure>\\Binding\\ serves as \n \\structured name bindings\\, as says the description, i.e. a mechanism to basically \n associate an input string-fragment to its position. This concept is vital in all parsing processes\n and the interaction with PIDE.\n\n Key are two things:\n\\<^enum> the type-synonym \\<^ML_type>\\bstring\\ which is synonym to \\<^ML_type>\\string\\\n and intended for \"primitive names to be bound\"\n\\<^enum> the projection \\<^ML>\\Binding.pos_of : Binding.binding -> Position.T\\\n\\<^enum> the constructor establishing a binding \\<^ML>\\Binding.make: bstring * Position.T -> Binding.binding\\\n\n\\\n\n\nsubsubsection\\ Example \\ \n\ntext\\Since this is so common in interface programming, there are a number of antiquotations\\\nML\\\nval H = @{binding here}; (* There are \"bindings\" consisting of a text-span and a position, \n where \"positions\" are absolute references to a file *) \n\nBinding.pos_of H; (* clicking on \"H\" activates the hyperlink to the defining occ of \"H\" above *)\n(* {offset=23, end_offset=27, id=-17214}: Position.T *)\n\n(* a modern way to construct a binding is by the following code antiquotation : *)\n\\<^binding>\\theory\\\n\n\\ \n\nsubsection \\Input streams. \\ \ntext\\Reads as : Generic input with position and range information, to be processed in a \nleft-to right manner. Preferable to strings if used for larger data. \n\nConstructor: \\<^ML>\\Input.source_explode : Input.source -> Symbol_Pos.T list\\\n\n\\\n\nsubsubsection \\Example :Input streams. \\ \n\nML\\ Input.source_explode (Input.string \" f @{thm refl}\");\n \n (* If stemming from the input window, this can be something like: \n \n [(\" \", {offset=14, id=-2769}), (\"f\", {offset=15, id=-2769}), (\" \", {offset=16, id=-2769}),\n (\"@\", {offset=17, id=-2769}), (\"{\", {offset=18, id=-2769}), (\"t\", {offset=19, id=-2769}),\n (\"h\", {offset=20, id=-2769}), (\"m\", {offset=21, id=-2769}), (\" \", {offset=22, id=-2769}),\n (\"r\", {offset=23, id=-2769}), (\"e\", {offset=24, id=-2769}), (\"f\", {offset=25, id=-2769}),\n (\"l\", {offset=26, id=-2769}), (\"}\", {offset=27, id=-2769})]\n *)\n\n\\\n \n\nsection\\Term Parsing\\ \n\ntext\\The heart of the parsers for mathematical notation, based on an Earley-parser that can cope\n with incremental changes of the grammar as required for sophisticated mathematical output, is hidden\n behind the API described in this section.\\\n \ntext\\ Note that the naming underlies the following convention. \n There are:\n \\<^enum> \"parser\"s \n \\<^enum> type-\"checker\"s, which usually also englobe the markup generation for PIDE\n \\<^enum> \"reader\"s which do both together with pretty-printing\n \n This is encapsulated in the data structure @{ML_structure Syntax} --- \n the table with const symbols, print and ast translations, ... The latter is accessible, e.g. \n from a Proof context via @{ML Proof_Context.syn_of}.\n\\\n\ntext\\ Inner Syntax Parsing combinators for elementary Isabelle Lexems\\ \ntext\\\n\\<^item> \\<^ML>\\ Syntax.parse_sort : Proof.context -> string -> sort\\\n\\<^item> \\<^ML>\\ Syntax.parse_typ : Proof.context -> string -> typ\\\n\\<^item> \\<^ML>\\ Syntax.parse_term : Proof.context -> string -> term\\\n\\<^item> \\<^ML>\\ Syntax.parse_prop : Proof.context -> string -> term\\\n\\<^item> \\<^ML>\\ Syntax.check_term : Proof.context -> term -> term\\\n\\<^item> \\<^ML>\\ Syntax.check_props: Proof.context -> term list -> term list\\\n\\<^item> \\<^ML>\\ Syntax.uncheck_sort: Proof.context -> sort -> sort\\\n\\<^item> \\<^ML>\\ Syntax.uncheck_typs: Proof.context -> typ list -> typ list\\\n\\<^item> \\<^ML>\\ Syntax.uncheck_terms: Proof.context -> term list -> term list\\\n\\\n\ntext\\In contrast to mere parsing, the following operators provide also type-checking\n and internal reporting to PIDE --- see below. I did not find a mechanism to address\n the internal serial-numbers used for the PIDE protocol, however, rumours have it\n that such a thing exists. The variants \\<^verbatim>\\_global\\ work on theories instead on \n \\<^ML_type>\\Proof.context\\s.\\\n\ntext\\\n\\<^item> \\<^ML>\\Syntax.read_sort: Proof.context -> string -> sort\\\n\\<^item> \\<^ML>\\Syntax.read_typ : Proof.context -> string -> typ\\\n\\<^item> \\<^ML>\\Syntax.read_term: Proof.context -> string -> term\\\n\\<^item> \\<^ML>\\Syntax.read_typs: Proof.context -> string list -> typ list\\\n\\<^item> \\<^ML>\\Syntax.read_sort_global: theory -> string -> sort\\\n\\<^item> \\<^ML>\\Syntax.read_typ_global: theory -> string -> typ\\\n\\<^item> \\<^ML>\\Syntax.read_term_global: theory -> string -> term\\\n\\<^item> \\<^ML>\\Syntax.read_prop_global: theory -> string -> term\\\n \\\ntext \\The following operations are concerned with the conversion of pretty-prints\nand, from there, the generation of (non-layouted) strings :\n\n\\<^item> \\<^ML>\\Syntax.pretty_term:Proof.context -> term -> Pretty.T\\\n\\<^item> \\<^ML>\\Syntax.pretty_typ:Proof.context -> typ -> Pretty.T \\\n\\<^item> \\<^ML>\\Syntax.pretty_sort:Proof.context -> sort -> Pretty.T \\\n\\<^item> \\<^ML>\\Syntax.pretty_classrel: Proof.context -> class list -> Pretty.T\\\n\\<^item> \\<^ML>\\Syntax.pretty_arity: Proof.context -> arity -> Pretty.T\\\n\\<^item> \\<^ML>\\Syntax.string_of_term: Proof.context -> term -> string \\\n\\<^item> \\<^ML>\\Syntax.string_of_typ: Proof.context -> typ -> string \\\n\\<^item> \\<^ML>\\Syntax.lookup_const : Syntax.syntax -> string -> string option\\\n\\\n\n\n\n\n\n\ntext\\\n Note that \\<^ML>\\Syntax.install_operations\\ is a late-binding interface, i.e. a collection of \n \"hooks\" used to resolve an apparent architectural cycle.\n The real work is done in \\<^file>\\~~/src/Pure/Syntax/syntax_phases.ML\\ \n \n Even the parsers and type checkers stemming from the theory-structure are registered via\n hooks (this can be confusing at times). Main phases of inner syntax processing, with standard \n implementations of parse/unparse operations were treated this way.\n At the very very end in, it sets up the entire syntax engine (the hooks) via:\n\n \\<^theory_text>\\Theory.setup\n (Syntax.install_operations\n {parse_sort = parse_sort,\n parse_typ = parse_typ,\n parse_term = parse_term false,\n parse_prop = parse_term true,\n unparse_sort = unparse_sort,\n unparse_typ = unparse_typ,\n unparse_term = unparse_term,\n check_typs = check_typs,\n check_terms = check_terms,\n check_props = check_props,\n uncheck_typs = uncheck_typs,\n uncheck_terms = uncheck_terms})\n \\\n\\\n\n\n\n(*\nDocument_Antiquotation\n*)\n\nsubsection*[ex33::example] \\Example\\\n\nML\\\n \n (* here follows the definition of the attribute parser : *)\n val Z = let val attribute = Parse.position Parse.name -- \n Scan.optional (Parse.$$$ \"=\" |-- Parse.!!! Parse.name) \"\";\n in (Scan.optional(Parse.$$$ \",\" |-- (Parse.enum \",\" attribute))) end ;\n \n \n (* Here is the code to register the above parsers as text antiquotations into the Isabelle\n Framework: *)\n Document_Output.antiquotation_pretty_source \\<^binding>\\theory\\ \n (Scan.lift (Parse.position Parse.embedded));\n \n Document_Output.antiquotation_raw \\<^binding>\\file\\ \n (Scan.lift (Parse.position Parse.path)) ;\n \n\\\n\ntext\\where we have the registration of the action\n \\<^ML>\\Scan.lift (Parse.position Args.cartouche_input)\\\n to be bound to the \\name\\ as a whole is a system \n transaction that, of course, has the type \\<^ML_type>\\theory -> theory\\ :\n\n @{ML [display] \\\n (fn name => (Document_Output.antiquotation_pretty_source \n name\n (Scan.lift (Parse.position Args.cartouche_input))))\n : binding -> \n (Proof.context -> Input.source * Position.T -> Pretty.T) -> \n theory -> theory\n \\}\n \\\n\n \nsection \\ Output: Very Low Level \\\ntext\\ For re-directing the output channels, the structure \\<^ML_structure>\\Output\\ may be relevant:\n \\<^ML>\\Output.output:string -> string\\ is the structure for the \"hooks\" with the target devices.\n \\\n\nML\\ Output.output \"bla_1:\" \\\n\ntext\\It provides a number of hooks that can be used for redirection hacks ...\\\n\nsection \\ Output: LaTeX \\\ntext\\The heart of the LaTeX generator is to be found in the structure \\<^ML_structure>\\Document_Output\\.\nThis is an own parsing and writing process, with the risc that a parsed file in the IDE parsing\nprocess can not be parsed for the LaTeX Generator. The reason is twofold:\n\n\\<^enum> The LaTeX Generator makes a rough attempt to mimic the LayOut in the thy-file; thus, its\n spacing is relevant.\n\\<^enum> there is a special bracket \\(*<*)\\ ... \\(*>*)\\ that allows to specify input that is checked by\n Isabelle, but excluded from the LaTeX generator (this is handled in an own sub-parser\n called \\<^ML>\\Document_Source.improper\\ where also other forms of comment parsers are provided.\n\nSince Isabelle2018, an own AST is provided for the LaTeX syntax, analogously to \n\\<^ML_structure>\\Pretty\\. Key functions of this structure \\<^ML_structure>\\Latex\\ are:\n\n\\<^item>\\<^ML>\\Latex.string: string -> Latex.text\\\n\\<^item>\\<^ML>\\Latex.text: string * Position.T -> Latex.text\\\n\n\\<^item>\\<^ML>\\Latex.output_ascii: string -> string\\\n\\<^item>\\<^ML>\\Latex.output_symbols: Symbol.symbol list -> string\\\n \n\n\\<^item>\\<^ML>\\Latex.environment: string -> Latex.text -> Latex.text\\\n\n\\<^item>\\<^ML>\\Latex.block: Latex.text -> XML.tree\\\n\\\n\n\n\nML\\ Latex.output_ascii;\n Latex.environment \"isa\" (Latex.string \"bg\");\n Latex.output_ascii \"a_b:c'é\";\n (* Note: *)\n space_implode \"sd &e sf dfg\" [\"qs\",\"er\",\"alpa\"]; \n \\\n\ntext\\Here is an abstract of the main interface to @{ML_structure Document_Output}:\\\n\ntext\\\n\\<^item>\\<^ML>\\Document_Output.output_document: Proof.context -> {markdown: bool} -> Input.source -> Latex.text \\\n\\<^item>\\<^ML>\\Document_Output.output_token: Proof.context -> Token.T -> Latex.text \\\n\\<^item>\\<^ML>\\Document_Output.output_source: Proof.context -> string -> Latex.text \\\n\\<^item>\\<^ML>\\Document_Output.present_thy: Options.T -> theory -> Document_Output.segment list -> Latex.text \\\n\n\\<^item>\\<^ML>\\Document_Output.isabelle: Proof.context -> Latex.text -> Latex.text\\\n\\<^item>\\<^ML>\\Document_Output.isabelle_typewriter: Proof.context -> Latex.text -> Latex.text\\\n\\<^item>\\<^ML>\\Document_Output.typewriter: Proof.context -> string -> Latex.text\\\n\\<^item>\\<^ML>\\Document_Output.verbatim: Proof.context -> string -> Latex.text\\\n\\<^item>\\<^ML>\\Document_Output.source: Proof.context -> {embedded: bool} -> Token.src -> Latex.text\\\n\\<^item>\\<^ML>\\Document_Output.pretty: Proof.context -> Pretty.T -> Latex.text\\\n\\<^item>\\<^ML>\\Document_Output.pretty_source: Proof.context -> {embedded: bool} -> Token.src -> Pretty.T -> Latex.text\\\n\\<^item>\\<^ML>\\Document_Output.pretty_items: Proof.context -> Pretty.T list -> Latex.text\\\n\\<^item>\\<^ML>\\Document_Output.pretty_items_source: Proof.context -> {embedded: bool} -> Token.src -> Pretty.T list -> Latex.text\\\n\nFinally a number of antiquotation registries :\n\n\\<^item>\\<^ML>\\Document_Output.antiquotation_pretty:\n binding -> 'a context_parser -> (Proof.context -> 'a -> Pretty.T) -> theory -> theory\\\n\\<^item>\\<^ML>\\Document_Output.antiquotation_pretty_source:\n binding -> 'a context_parser -> (Proof.context -> 'a -> Pretty.T) -> theory -> theory\\\n\\<^item>\\<^ML>\\Document_Output.antiquotation_raw:\n binding -> 'a context_parser -> (Proof.context -> 'a -> Latex.text) -> theory -> theory\\\n\\<^item>\\<^ML>\\Document_Output.antiquotation_verbatim:\n binding -> 'a context_parser -> (Proof.context -> 'a -> string) -> theory -> theory\\\n\\\n\n\ntext\\ Thus, \\<^ML_structure>\\Syntax_Phases\\ does the actual work of markup generation, including\n markup generation and generation of reports. Look at the following snippet: \n\\\nfun check_typs ctxt raw_tys =\n let\n val (sorting_report, tys) = Proof_Context.prepare_sortsT ctxt raw_tys;\n val _ = if Context_Position.is_visible ctxt then Output.report sorting_report else ();\n in\n tys\n |> apply_typ_check ctxt\n |> Term_Sharing.typs (Proof_Context.theory_of ctxt)\n end;\n\\\n\nwhich is the real implementation behind \\<^ML>\\Syntax.check_typ\\\n\n\\\nfun check_terms ctxt raw_ts =\n let\n val (sorting_report, raw_ts') = Proof_Context.prepare_sorts ctxt raw_ts;\n val (ts, ps) = Type_Infer_Context.prepare_positions ctxt raw_ts';\n\n val tys = map (Logic.mk_type o snd) ps;\n val (ts', tys') = ts @ tys\n |> apply_term_check ctxt\n |> chop (length ts);\n val typing_report =\n fold2 (fn (pos, _) => fn ty =>\n if Position.is_reported pos then\n cons (Position.reported_text pos Markup.typing\n (Syntax.string_of_typ ctxt (Logic.dest_type ty)))\n else I) ps tys' [];\n\n val _ =\n if Context_Position.is_visible ctxt then Output.report (sorting_report @ typing_report)\n else ();\n in Term_Sharing.terms (Proof_Context.theory_of ctxt) ts' end;\n\\\n\nwhich is the real implementation behind \\<^ML>\\Syntax.check_term\\. As one can see, check-routines \ninternally generate the markup.\n\\ \n \n\nsection*[cartouches::technical]\\Inner Syntax Cartouches\\\ntext\\ The cascade-syntax principle underlying recent isabelle versions requires a \n particular mechanism, called \"cartouche\" by Makarius who was influenced by French \n Wine and French culture when designing this.\n\n When parsing terms or types (via the Earley Parser), a standard mechanism for\n calling another parser inside the current process is needed that is bound to the \n \\(\\)\\ ... \\(\\)\\ paranthesis'. \\\n\ntext\\The following example --- drawn from the Isabelle/DOF implementation --- allows\n to parse UTF8 - Unicode strings as alternative to @{term \"''abc''\"} HOL-strings.\\\n\nML\\\\ \\Dynamic setup of inner syntax cartouche\\\n\n\n(* Author: Frédéric Tuong, Université Paris-Saclay *)\n(* Title: HOL/ex/Cartouche_Examples.thy\n Author: Makarius *)\n local\n fun mk_char (f_char, f_cons, _) (s, _) accu =\n fold\n (fn c => fn (accu, l) =>\n (f_char c accu, f_cons c l))\n (rev (map Char.ord (String.explode s)))\n accu;\n\n fun mk_string (_, _, f_nil) accu [] = (accu, f_nil)\n | mk_string f accu (s :: ss) = mk_char f s (mk_string f accu ss);\n in\n fun string_tr f f_mk accu content args =\n let fun err () = raise TERM (\"string_tr\", args) in\n (case args of\n [(c as Const (@{syntax_const \"_constrain\"}, _)) $ Free (s, _) $ p] =>\n (case Term_Position.decode_position p of\n SOME (pos, _) => c $ f (mk_string f_mk accu (content (s, pos))) $ p\n | NONE => err ())\n | _ => err ())\n end;\n end;\n\\\n\nsyntax \"_cartouche_string\" :: \"cartouche_position \\ _\" (\"_\")\n\nML\\\nstructure Cartouche_Grammar = struct\n fun list_comb_mk cst n c = list_comb (Syntax.const cst, String_Syntax.mk_bits_syntax n c)\n val nil1 = Syntax.const @{const_syntax String.empty_literal}\n fun cons1 c l = list_comb_mk @{const_syntax String.Literal} 7 c $ l\n\n val default =\n [ ( \"char list\"\n , ( Const (@{const_syntax Nil}, @{typ \"char list\"})\n , fn c => fn l => Syntax.const @{const_syntax Cons} $ list_comb_mk @{const_syntax Char} 8 c $ l\n , snd))\n , ( \"String.literal\", (nil1, cons1, snd))]\nend\n\\\n\nML\\\nfun parse_translation_cartouche binding l f_integer accu =\n let val cartouche_type = Attrib.setup_config_string binding (K (fst (hd l)))\n (* if there is no type specified, by default we set the first element\n to be the default type of cartouches *) in\n fn ctxt =>\n let val cart_type = Config.get ctxt cartouche_type in\n case List.find (fn (s, _) => s = cart_type) l of\n NONE => error (\"Unregistered return type for the cartouche: \\\"\" ^ cart_type ^ \"\\\"\")\n | SOME (_, (nil0, cons, f)) =>\n string_tr f (f_integer, cons, nil0) accu (Symbol_Pos.cartouche_content o Symbol_Pos.explode)\n end\n end\n\\\n\ntext\\The following registration of this cartouche for strings is fails because it has\n already been done in the surrounding Isabelle/DOF environment... \n \\<^verbatim>\\\n parse_translation \\\n [( @{syntax_const \"_cartouche_string\"}\n , parse_translation_cartouche \\<^binding>\\cartouche_type\\ Cartouche_Grammar.default (K I) ())]\n \\\n \\\n\\\n\ntext\\ Test for this cartouche... \\\nterm \"\\A \\ B\\ = ''''\"\n\n\n\nchapter*[c::conclusion]\\Conclusion\\\ntext\\ This interactive Isabelle Programming Cook-Book represents my current way \n to view and explain Isabelle programming API's to students and collaborators. \n It differs from the reference manual in some places on purpose, since I believe \n that a lot of internal Isabelle API's need a more conceptual view on what is happening \n (even if this conceptual view is at times over-abstracting a little).\n It is written in Isabelle/DOF and conceived as \"living document\" (a term that I owe to \n Simon Foster), i.e. as hypertext-heavy text making direct references to the Isabelle API's \n which were checked whenever this document is re-visited in Isabelle/jEdit.\n \n All hints and contributions of collegues and collaborators are greatly welcomed; all errors\n and the roughness of this presentation is entirely my fault.\n\\\n(*<*)\n\nparagraph\\Many thanks to Frederic Tuong, who contributed some example such as the string \ncartouche for Unicode Character Denotations as well as many local hints for improvements.\\\n\nsection*[bib::bibliography]\\Bibliography\\\n\nclose_monitor*[this] \ncheck_doc_global\n\nend\n(*>*)\n", "meta": {"author": "logicalhacking", "repo": "Isabelle_DOF", "sha": "07444efd2168aac992471259f3cd958bde777ea6", "save_path": "github-repos/isabelle/logicalhacking-Isabelle_DOF", "path": "github-repos/isabelle/logicalhacking-Isabelle_DOF/Isabelle_DOF-07444efd2168aac992471259f3cd958bde777ea6/Isabelle_DOF-Example-Extra/technical_report/TR_my_commented_isabelle/TR_MyCommentedIsabelle.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.1403362476923775, "lm_q1q2_score": 0.06415285359778848}} {"text": "(* \n This file is a part of IsarMathLib - \n a library of formalized mathematics written for Isabelle/Isar.\n\n Copyright (C) 2005-2019 Slawomir Kolodynski\n\n This program is free software Redistribution and use in source and binary forms, \n with or without modification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, \n this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright notice, \n this list of conditions and the following disclaimer in the documentation and/or \n other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products \n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,\nINCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE, DATA, OR PROFITS OR\nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\nSTRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\nUSE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*)\n\nsection \\ZF set theory basics\\\n\ntheory ZF1 imports ZF.Perm\n\nbegin\n\ntext\\The standard Isabelle distribution contains lots of facts about basic set\n theory. This theory file adds some more.\\\n\nsubsection\\Lemmas in Zermelo-Fraenkel set theory\\\n\ntext\\Here we put lemmas from the set theory that we could not find in \n the standard Isabelle distribution or just so that they are easier to find.\\\n\ntext\\A set cannot be a member of itself. This is exactly lemma \\mem_not_refl\\\n from Isabelle/ZF \\upair.thy\\, we put it here for easy reference. \\\n\nlemma mem_self: shows \"x\\x\" by (rule mem_not_refl)\n\ntext\\If one collection is contained in another, then we can say the same\n about their unions.\\\n\nlemma collection_contain: assumes \"A\\B\" shows \"\\A \\ \\B\"\nproof\n fix x assume \"x \\ \\A\"\n then obtain X where \"x\\X\" and \"X\\A\" by auto\n with assms show \"x \\ \\B\" by auto\nqed\n\ntext\\If all sets of a nonempty collection are the same, then its union \n is the same.\\\n\nlemma ZF1_1_L1: assumes \"C\\0\" and \"\\y\\C. b(y) = A\" \n shows \"(\\y\\C. b(y)) = A\" using assms by blast\n \ntext\\The union af all values of a constant meta-function belongs to \nthe same set as the constant.\\\n\nlemma ZF1_1_L2: assumes A1:\"C\\0\" and A2: \"\\x\\C. b(x) \\ A\" \n and A3: \"\\x y. x\\C \\ y\\C \\ b(x) = b(y)\"\n shows \"(\\x\\C. b(x))\\A\"\nproof -\n from A1 obtain x where D1: \"x\\C\" by auto\n with A3 have \"\\y\\C. b(y) = b(x)\" by blast\n with A1 have \"(\\y\\C. b(y)) = b(x)\" \n using ZF1_1_L1 by simp\n with D1 A2 show ?thesis by simp\nqed\n\ntext\\If two meta-functions are the same on a cartesian product,\n then the subsets defined by them are the same. I am surprised Isabelle\n can not handle this automatically.\\\n\nlemma ZF1_1_L4: assumes A1: \"\\x\\X.\\y\\Y. a(x,y) = b(x,y)\"\n shows \"{a(x,y). \\x,y\\ \\ X\\Y} = {b(x,y). \\x,y\\ \\ X\\Y}\"\nproof\n show \"{a(x, y). \\x,y\\ \\ X \\ Y} \\ {b(x, y). \\x,y\\ \\ X \\ Y}\"\n proof\n fix z assume \"z \\ {a(x, y) . \\x,y\\ \\ X \\ Y}\"\n with A1 show \"z \\ {b(x,y).\\x,y\\ \\ X\\Y}\" by auto \n qed\n show \"{b(x, y). \\x,y\\ \\ X \\ Y} \\ {a(x, y). \\x,y\\ \\ X \\ Y}\"\n proof\n fix z assume \"z \\ {b(x, y). \\x,y\\ \\ X \\ Y}\"\n with A1 show \"z \\ {a(x,y).\\x,y\\ \\ X\\Y}\" by auto\n qed\nqed\n\ntext\\If two meta-functions are the same on a cartesian product,\n then the subsets defined by them are the same. \n This is similar to \\ZF1_1_L4\\, except that\n the set definition varies over \\p\\X\\Y\\ rather than \n \\\\ x,y\\\\X\\Y\\.\\\n\nlemma ZF1_1_L4A: assumes A1: \"\\x\\X.\\y\\Y. a(\\ x,y\\) = b(x,y)\"\n shows \"{a(p). p \\ X\\Y} = {b(x,y). \\x,y\\ \\ X\\Y}\"\nproof\n { fix z assume \"z \\ {a(p). p\\X\\Y}\"\n then obtain p where D1: \"z=a(p)\" \"p\\X\\Y\" by auto\n let ?x = \"fst(p)\" let ?y = \"snd(p)\"\n from A1 D1 have \"z \\ {b(x,y). \\x,y\\ \\ X\\Y}\" by auto\n } then show \"{a(p). p \\ X\\Y} \\ {b(x,y). \\x,y\\ \\ X\\Y}\" by blast\nnext \n { fix z assume \"z \\ {b(x,y). \\x,y\\ \\ X\\Y}\"\n then obtain x y where D1: \"\\x,y\\ \\ X\\Y\" \"z=b(x,y)\" by auto\n let ?p = \"\\ x,y\\\" \n from A1 D1 have \"?p\\X\\Y\" \"z = a(?p)\" by auto\n then have \"z \\ {a(p). p \\ X\\Y}\" by auto\n } then show \"{b(x,y). \\x,y\\ \\ X\\Y} \\ {a(p). p \\ X\\Y}\" by blast\nqed\n\ntext\\A lemma about inclusion in cartesian products. Included here to remember\n that we need the $U\\times V \\neq \\emptyset$ assumption.\\\n\nlemma prod_subset: assumes \"U\\V\\0\" \"U\\V \\ X\\Y\" shows \"U\\X\" and \"V\\Y\"\n using assms by auto\n\ntext\\A technical lemma about sections in cartesian products.\\\n\nlemma section_proj: assumes \"A \\ X\\Y\" and \"U\\V \\ A\" and \"x \\ U\" \"y \\ V\"\n shows \"U \\ {t\\X. \\t,y\\ \\ A}\" and \"V \\ {t\\Y. \\x,t\\ \\ A}\"\n using assms by auto\n\ntext\\If two meta-functions are the same on a set, then they define the same\n set by separation.\\\n\nlemma ZF1_1_L4B: assumes \"\\x\\X. a(x) = b(x)\"\n shows \"{a(x). x\\X} = {b(x). x\\X}\"\n using assms by simp\n\ntext\\A set defined by a constant meta-function is a singleton.\\\n\nlemma ZF1_1_L5: assumes \"X\\0\" and \"\\x\\X. b(x) = c\"\n shows \"{b(x). x\\X} = {c}\" using assms by blast\n\ntext\\Most of the time, \\auto\\ does this job, but there are strange \n cases when the next lemma is needed.\\\n\nlemma subset_with_property: assumes \"Y = {x\\X. b(x)}\"\n shows \"Y \\ X\" \n using assms by auto\n\ntext\\We can choose an element from a nonempty set.\\\n\nlemma nonempty_has_element: assumes \"X\\0\" shows \"\\x. x\\X\"\n using assms by auto\n\n(*text{*If after removing an element from a set we get an empty set,\n then this set must be a singleton.*}\n\nlemma rem_point_empty: assumes \"a\\A\" and \"A-{a} = 0\"\n shows \"A = {a}\" using assms by auto; *)\n\ntext\\In Isabelle/ZF the intersection of an empty family is \n empty. This is exactly lemma \\Inter_0\\ from Isabelle's\n \\equalities\\ theory. We repeat this lemma here as it is very\n difficult to find. This is one reason we need comments before every \n theorem: so that we can search for keywords.\\\n\nlemma inter_empty_empty: shows \"\\0 = 0\" by (rule Inter_0)\n\ntext\\If an intersection of a collection is not empty, then the collection is\n not empty. We are (ab)using the fact the the intersection of empty collection \n is defined to be empty.\\\n\nlemma inter_nempty_nempty: assumes \"\\A \\ 0\" shows \"A\\0\"\n using assms by auto\n\ntext\\For two collections $S,T$ of sets we define the product collection\n as the collections of cartesian products $A\\times B$, where $A\\in S, B\\in T$.\\\n\ndefinition\n \"ProductCollection(T,S) \\ \\U\\T.{U\\V. V\\S}\"\n\ntext\\The union of the product collection of collections $S,T$ is the \n cartesian product of $\\bigcup S$ and $\\bigcup T$.\\\n\nlemma ZF1_1_L6: shows \"\\ ProductCollection(S,T) = \\S \\ \\T\"\n using ProductCollection_def by auto\n\ntext\\An intersection of subsets is a subset.\\\n\nlemma ZF1_1_L7: assumes A1: \"I\\0\" and A2: \"\\i\\I. P(i) \\ X\"\n shows \"( \\i\\I. P(i) ) \\ X\"\nproof -\n from A1 obtain i\\<^sub>0 where \"i\\<^sub>0 \\ I\" by auto\n with A2 have \"( \\i\\I. P(i) ) \\ P(i\\<^sub>0)\" and \"P(i\\<^sub>0) \\ X\"\n by auto\n thus \"( \\i\\I. P(i) ) \\ X\" by auto\nqed\n\ntext\\Isabelle/ZF has a \"THE\" construct that allows to define an element\n if there is only one such that is satisfies given predicate.\n In pure ZF we can express something similar using the indentity proven below.\\\n\nlemma ZF1_1_L8: shows \"\\ {x} = x\" by auto\n\ntext\\Some properties of singletons.\\\n\nlemma ZF1_1_L9: assumes A1: \"\\! x. x\\A \\ \\(x)\"\n shows \n \"\\a. {x\\A. \\(x)} = {a}\"\n \"\\ {x\\A. \\(x)} \\ A\"\n \"\\(\\ {x\\A. \\(x)})\"\nproof -\n from A1 show \"\\a. {x\\A. \\(x)} = {a}\" by auto\n then obtain a where I: \"{x\\A. \\(x)} = {a}\" by auto\n then have \"\\ {x\\A. \\(x)} = a\" by auto\n moreover\n from I have \"a \\ {x\\A. \\(x)}\" by simp\n hence \"a\\A\" and \"\\(a)\" by auto\n ultimately show \"\\ {x\\A. \\(x)} \\ A\" and \"\\(\\ {x\\A. \\(x)})\"\n by auto\nqed\n\ntext\\A simple version of \\ ZF1_1_L9\\.\\\n\ncorollary singleton_extract: assumes \"\\! x. x\\A\"\n shows \"(\\ A) \\ A\"\nproof -\n from assms have \"\\! x. x\\A \\ True\" by simp\n then have \"\\ {x\\A. True} \\ A\" by (rule ZF1_1_L9)\n thus \"(\\ A) \\ A\" by simp\nqed\n\ntext\\A criterion for when a set defined by comprehension is a singleton.\\\n\nlemma singleton_comprehension: \n assumes A1: \"y\\X\" and A2: \"\\x\\X. \\y\\X. P(x) = P(y)\"\n shows \"(\\{P(x). x\\X}) = P(y)\"\nproof - \n let ?A = \"{P(x). x\\X}\"\n have \"\\! c. c \\ ?A\"\n proof\n from A1 show \"\\c. c \\ ?A\" by auto\n next\n fix a b assume \"a \\ ?A\" and \"b \\ ?A\"\n then obtain x t where \n \"x \\ X\" \"a = P(x)\" and \"t \\ X\" \"b = P(t)\"\n by auto\n with A2 show \"a=b\" by blast\n qed\n then have \"(\\?A) \\ ?A\" by (rule singleton_extract)\n then obtain x where \"x \\ X\" and \"(\\?A) = P(x)\"\n by auto\n from A1 A2 \\x \\ X\\ have \"P(x) = P(y)\"\n by blast\n with \\(\\?A) = P(x)\\ show \"(\\?A) = P(y)\" by simp\nqed\n\ntext\\Adding an element of a set to that set does not change the set.\\\n\nlemma set_elem_add: assumes \"x\\X\" shows \"X \\ {x} = X\" using assms \n by auto\n\ntext\\Here we define a restriction of a collection of sets to a given set. \n In romantic math this is typically denoted $X\\cap M$ and means \n $\\{X\\cap A : A\\in M \\} $. Note there is also restrict$(f,A)$ \n defined for relations in ZF.thy.\\\n\ndefinition\n RestrictedTo (infixl \"{restricted to}\" 70) where\n \"M {restricted to} X \\ {X \\ A . A \\ M}\"\n\ntext\\A lemma on a union of a restriction of a collection\n to a set.\\\n\nlemma union_restrict: \n shows \"\\(M {restricted to} X) = (\\M) \\ X\"\n using RestrictedTo_def by auto\n\ntext\\Next we show a technical identity that is used to prove sufficiency \n of some condition for a collection of sets to be a base for a topology.\\\n\nlemma ZF1_1_L10: assumes A1: \"\\U\\C. \\A\\B. U = \\A\" \n shows \"\\\\ {\\{A\\B. U = \\A}. U\\C} = \\C\"\nproof\n show \"\\(\\U\\C. \\{A \\ B . U = \\A}) \\ \\C\" by blast\n show \"\\C \\ \\(\\U\\C. \\{A \\ B . U = \\A})\"\n proof\n fix x assume \"x \\ \\C\" \n show \"x \\ \\(\\U\\C. \\{A \\ B . U = \\A})\"\n proof -\n from \\x \\ \\C\\ obtain U where \"U\\C \\ x\\U\" by auto\n with A1 obtain A where \"A\\B \\ U = \\A\" by auto\n from \\U\\C \\ x\\U\\ \\A\\B \\ U = \\A\\ show \"x\\ \\(\\U\\C. \\{A \\ B . U = \\A})\" \n\tby auto\n qed\n qed\nqed\n\ntext\\Standard Isabelle uses a notion of \\cons(A,a)\\ that can be thought \n of as $A\\cup \\{a\\}$.\\\n\nlemma consdef: shows \"cons(a,A) = A \\ {a}\"\n using cons_def by auto\n\ntext\\If a difference between a set and a singleton is empty, then\n the set is empty or it is equal to the singleton.\\\n\nlemma singl_diff_empty: assumes \"A - {x} = 0\"\n shows \"A = 0 \\ A = {x}\"\n using assms by auto\n\ntext\\If a difference between a set and a singleton is the set, \n then the only element of the singleton is not in the set.\\\n\nlemma singl_diff_eq: assumes A1: \"A - {x} = A\"\n shows \"x \\ A\"\nproof -\n have \"x \\ A - {x}\" by auto\n with A1 show \"x \\ A\" by simp\nqed\n\ntext\\A basic property of sets defined by comprehension.\\\n\nlemma comprehension: assumes \"a \\ {x\\X. p(x)}\"\n shows \"a\\X\" and \"p(a)\" using assms by auto\n\ntext\\A basic property of a set defined by another type of comprehension.\\\n\nlemma comprehension_repl: assumes \"y \\ {p(x). x\\X}\"\n shows \"\\x\\X. y = p(x)\" using assms by auto\n\ntext\\The inverse of the \\comprehension\\ lemma.\\\n\nlemma mem_cond_in_set: assumes \"\\(c)\" and \"c\\X\"\n shows \"c \\ {x\\X. \\(x)}\" using assms by blast\n\ntext\\The image of a set by a greater relation is greater. \\\n\nlemma image_rel_mono: assumes \"r\\s\" shows \"r``(A) \\ s``(A)\" \n using assms by auto \n\ntext\\ A technical lemma about relations: if $x$ is in its image by a relation $U$\n and that image is contained in some set $C$, then the image of the singleton\n $\\{ x\\}$ by the relation $U \\cup C\\times C$ equals $C$. \\\n\nlemma image_greater_rel: \n assumes \"x \\ U``{x}\" and \"U``{x} \\ C\"\n shows \"(U \\ C\\C)``{x} = C\"\n using assms image_Un_left by blast \n\ntext\\Reformulation of the definition of composition of two relations: \\\n\nlemma rel_compdef: \n shows \"\\x,z\\ \\ r O s \\ (\\y. \\x,y\\ \\ s \\ \\y,z\\ \\ r)\" \n unfolding comp_def by auto\n\ntext\\Domain and range of the relation of the form $\\bigcup \\{U\\times U : U\\in P\\}$\n is $\\bigcup P$: \\\n\nlemma domain_range_sym: shows \"domain(\\{U\\U. U\\P}) = \\P\" and \"range(\\{U\\U. U\\P}) = \\P\" \n by auto\n\ntext\\An identity for the square (in the sense of composition) of a symmetric relation.\\\n\nlemma symm_sq_prod_image: assumes \"converse(r) = r\" \n shows \"r O r = \\{(r``{x})\\(r``{x}). x \\ domain(r)}\"\nproof\n { fix p assume \"p \\ r O r\"\n then obtain y z where \"\\y,z\\ = p\" by auto\n with \\p \\ r O r\\ obtain x where \"\\y,x\\ \\ r\" and \"\\x,z\\ \\ r\"\n using rel_compdef by auto\n from \\\\y,x\\ \\ r\\ have \"\\x,y\\ \\ converse(r)\" by simp\n with assms \\\\x,z\\ \\ r\\ \\\\y,z\\ = p\\ have \"\\x\\domain(r). p \\ (r``{x})\\(r``{x})\"\n by auto\n } thus \"r O r \\ (\\{(r``{x})\\(r``{x}). x \\ domain(r)})\"\n by blast\n { fix x assume \"x \\ domain(r)\"\n have \"(r``{x})\\(r``{x}) \\ r O r\"\n proof -\n { fix p assume \"p \\ (r``{x})\\(r``{x})\"\n then obtain y z where \"\\y,z\\ = p\" \"y \\ r``{x}\" \"z \\ r``{x}\"\n by auto\n from \\y \\ r``{x}\\ have \"\\x,y\\ \\ r\" by auto\n then have \"\\y,x\\ \\ converse(r)\" by simp\n with assms \\z \\ r``{x}\\ \\\\y,z\\ = p\\ have \"p \\ r O r\" by auto\n } thus ?thesis by auto\n qed\n } thus \"(\\{(r``{x})\\(r``{x}). x \\ domain(r)}) \\ r O r\" \n by blast\nqed \n\ntext\\A reflexive relation is contained in the union of products of its singleton images. \\\n\nlemma refl_union_singl_image: \n assumes \"A \\ X\\X\" and \"id(X)\\A\" shows \"A \\ \\{A``{x}\\A``{x}. x \\ X}\" \nproof -\n { fix p assume \"p\\A\"\n with assms(1) obtain x y where \"x\\X\" \"y\\X\" and \"p=\\x,y\\\" by auto\n with assms(2) \\p\\A\\ have \"\\x\\X. p \\ A``{x}\\A``{x}\" by auto\n } thus ?thesis by auto\nqed\n\ntext\\If the cartesian product of the images of $x$ and $y$ by a \n symmetric relation $W$ has a nonempty intersection with $R$\n then $x$ is in relation $W\\circ (R\\circ W)$ with $y$. \\\n\nlemma sym_rel_comp: \n assumes \"W=converse(W)\" and \"(W``{x})\\(W``{y}) \\ R \\ 0\"\n shows \"\\x,y\\ \\ (W O (R O W))\" \nproof -\n from assms(2) obtain s t where \"s\\W``{x}\" \"t\\W``{y}\" and \"\\s,t\\\\R\"\n by blast\n then have \"\\x,s\\ \\ W\" and \"\\y,t\\ \\ W\" by auto\n from \\\\x,s\\ \\ W\\ \\\\s,t\\ \\ R\\ have \"\\x,t\\ \\ R O W\" by auto\n from \\\\y,t\\ \\ W\\ have \"\\t,y\\ \\ converse(W)\" by blast\n with assms(1) \\\\x,t\\ \\ R O W\\ show ?thesis by auto\nqed\n\ntext\\ It's hard to believe but there are cases where we have to reference this rule. \\\n\nlemma set_mem_eq: assumes \"x\\A\" \"A=B\" shows \"x\\B\" using assms by simp\n\ntext\\Given some family $\\mathcal{A}$ of subsets of $X$ we can define the family of supersets of\n $\\mathcal{A}$. \\\n\ndefinition\n \"Supersets(X,\\) \\ {B\\Pow(X). \\A\\\\. A\\B}\"\n\ntext\\The family itself is in its supersets. \\\n\nlemma superset_gen: assumes \"A\\X\" \"A\\\\\" shows \"A \\ Supersets(X,\\)\"\n using assms unfolding Supersets_def by auto \n\ntext\\This can be done by the auto method, but sometimes takes a long time. \\\n\nlemma witness_exists: assumes \"x\\X\" and \"\\(x)\" shows \"\\x\\X. \\(x)\"\n using assms by auto\n\ntext\\The next lemma has to be used as a rule in some rare cases. \\\n\nlemma exists_in_set: assumes \"\\x. x\\A \\ \\(x)\" shows \"\\x\\A. \\(x)\"\n using assms by simp\n\ntext\\If $x$ belongs to a set where a property holds, then the property holds\n for $x$. This has to be used as rule in rare cases. \\\n\nlemma property_holds: assumes \"\\t\\X. \\(t)\" and \"x\\X\"\n shows \"\\(x)\" using assms by simp\n\ntext\\Set comprehensions defined by equal expressions are the equal. \n The second assertion is actually about functions, which are sets of pairs \n as illustrated in lemma \\fun_is_set_of_pairs\\ in \\func1.thy\\ \\\n\nlemma set_comp_eq: assumes \"\\x\\X. p(x) = q(x)\" \n shows \"{p(x). x\\X} = {q(x). x\\X}\" and \"{\\x,p(x)\\. x\\X} = {\\x,q(x)\\. x\\X}\"\n using assms by auto\n\ntext\\If $z$ is a pair, then the cartesian product of the singletons of its \n elements is the same as the singleton $\\{ z\\}$.\\ \n\nlemma pair_prod: assumes \"z = \\x,y\\\" shows \"{x}\\{y} = {z}\"\n using assms by blast\n\nend\n\n", "meta": {"author": "SKolodynski", "repo": "IsarMathLib", "sha": "879c6b779ca00364879aa0232b0aa9f18bafa85a", "save_path": "github-repos/isabelle/SKolodynski-IsarMathLib", "path": "github-repos/isabelle/SKolodynski-IsarMathLib/IsarMathLib-879c6b779ca00364879aa0232b0aa9f18bafa85a/IsarMathLib/ZF1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.1294027265554491, "lm_q1q2_score": 0.06369048674051439}} {"text": "(*\n * Copyright 2014, NICTA\n *\n * This software may be distributed and modified according to the terms of\n * the GNU General Public License version 2. Note that NO WARRANTY is provided.\n * See \"LICENSE_GPLv2.txt\" for details.\n *\n * @TAG(NICTA_GPL)\n *)\n(*<*)\ntheory RPCFrom imports\n \"../../tools/c-parser/CTranslation\"\n \"../../tools/autocorres/AutoCorres\"\nbegin\n\n(* THIS THEORY IS GENERATED. DO NOT EDIT. *)\n\ndeclare [[allow_underscore_idents=true]]\n\ninstall_C_file \"RPCFrom.c\"\n\n(* Use non-determinism instead of the standard option monad type stregthening and do not heap\n * abstract seL4_SetMR.\n *)\nautocorres [ts_rules = nondet, no_heap_abs = seL4_SetMR] \"RPCFrom.c\"\n\ncontext RPCFrom begin\n\n(* Repeated constants from C. *)\nabbreviation \"seL4_MsgMaxLength \\ 120\"\n\n(* Introduce this definition here so we can refer to it in the locale extension below. *)\ndefinition\n seL4_SetMR_lifted' :: \"int \\ word32 \\ lifted_globals \\ (unit \\ lifted_globals) set \\ bool\"\nwhere\n \"seL4_SetMR_lifted' i val \\\n do\n ret' \\ seL4_GetIPCBuffer';\n guard (\\s. i < seL4_MsgMaxLength);\n guard (\\s. 0 \\ i);\n modify (\\s. s \\heap_seL4_IPCBuffer__C :=\n (heap_seL4_IPCBuffer__C s)(ret' :=\n msg_C_update (\\a. Arrays.update a (nat i) val)\n (heap_seL4_IPCBuffer__C s ret'))\n \\)\n od\"\n\nend\n\nlocale RPCFrom_glue = RPCFrom +\n assumes seL4_SetMR_axiom: \"exec_concrete lift_global_heap (seL4_SetMR' i val) = seL4_SetMR_lifted' i val\"\n assumes swi_safe_to_ignore[simplified, simp]:\n \"asm_semantics_ok_to_ignore TYPE(nat) true (''swi '' @ x)\"\nbegin\n(*>*)\n\nchapter {* Assumptions *}\n\ntext {*\n This chapter introduces some definitions for properties that we assume to be invariant across the\n execution of user code. That is, the glue code lemmas in chapters that follow contain explicit\n assumptions that the user code in a component preserves the properties given below.\n\n Threads in seL4 communicate with one another via an Inter-Process Communication (IPC) mechanism\n provided by the kernel. Each thread has an assigned IPC buffer, a region of memory in their\n address space, that is taken by the kernel as an implicit parameter to any syscall. In an IPC\n message that involves communication with another thread, the sender writes the transfer payload\n to their IPC buffer before syscall invocation. CAmkES leverages this communication mechanism in\n implementing its own primitives.\n\n In seL4, the globals frame is a single page mapped read-only to userspace, whose first word\n contains a pointer to the current thread's IPC buffer. The CAmkES glue code uses this to marshal\n RPC arguments in to and out of the IPC buffer. For the glue code's operations to be valid, we\n require the globals frame not to have been modified. We create the following two definitions as\n shorthands for the globals frame still containing a valid pointer to the IPC buffer and the\n pointed to buffer still being valid, typed memory, respectively.\n*}\ndefinition\n globals_frame_intact :: \"lifted_globals \\ bool\"\nwhere\n \"globals_frame_intact s \\\n is_valid_seL4_IPCBuffer__C'ptr s (Ptr (scast seL4_GlobalsFrame))\"\n\ndefinition\n ipc_buffer_valid :: \"lifted_globals \\ bool\"\nwhere\n \"ipc_buffer_valid s \\ is_valid_seL4_IPCBuffer__C s\n (heap_seL4_IPCBuffer__C'ptr s (Ptr (scast seL4_GlobalsFrame)))\"\n\ntext {*\n One of the underlying tools we rely on does not currently fully abstract writes to arrays within\n structs. The glue code performs such operations when writing to threads' IPC buffers, in the\n function \\code{seL4\\_SetMR}. In order to work with a fully abstracted representation of these writes, we\n provide the following abstract definition of the function and axiomatise its equivalence to the\n partially abstracted representation we have. In future this axiomatisation will be removed and the\n abstraction framework will emit the definition below and an accompanying proof of equivalence in\n place of the axiom.\n*}\ntext {* \\newpage *}\n(* We repeat this definition because Isabelle's rendering of the original back to us via @{thm ...}\n * does not get formatted nicely. We use a different name in order not to interfere with any\n * following lemmas. Hopefully it won't confuse the reader.\n *)\ndefinition\n seL4_SetMR_lifted\nwhere\n \"seL4_SetMR_lifted i val \\\n do\n ret' \\ seL4_GetIPCBuffer';\n guard (\\s. i < seL4_MsgMaxLength);\n guard (\\s. 0 \\ i);\n modify (\\s. s \\heap_seL4_IPCBuffer__C :=\n (heap_seL4_IPCBuffer__C s)(ret' :=\n msg_C_update (\\a. Arrays.update a (nat i) val)\n (heap_seL4_IPCBuffer__C s ret'))\n \\)\n od\"\n\ntext {*\n The number of threads in a CAmkES component is dependent on the incoming and outgoing interfaces\n to that component. Per-thread data is generated as part of the connector glue code, including\n thread-local storage (TLS) variables. These variables are accessed via the current thread's TLS\n region. The following definitions are later used to express assumptions that the TLS region of\n the current thread has not been modified by intervening user code. In practice, non-malicious user\n code should never modify the TLS region or any thread-local variables.\n*}\ndefinition\n tls_ptr :: \"lifted_globals \\ camkes_tls_t_C ptr\"\nwhere\n \"tls_ptr s \\ Ptr (ptr_val (heap_seL4_IPCBuffer__C'ptr s\n (Ptr (scast seL4_GlobalsFrame))) && 0xFFFFF000)\"\n\ndefinition\n tls :: \"lifted_globals \\ camkes_tls_t_C\"\nwhere\n \"tls s \\ heap_camkes_tls_t_C s (tls_ptr s)\"\n\ndefinition\n tls_valid :: \"lifted_globals \\ bool\"\nwhere\n \"tls_valid s \\ is_valid_camkes_tls_t_C s (tls_ptr s)\"\n\ntext {*\n We make a further assumption about the execution of the kernel on behalf of a user thread that is\n explained in the next chapter.\n*}\n\nchapter {* System Calls *}\n\ntext {*\n A thread's IPC buffer contains a number of message registers that are used for transferring data\n during an IPC operation. The following two definitions are used to abbreviate the operation of\n setting a specific message register and setting the first four message registers, respectively.\n We have a specific definition for setting the first four message registers because this is a\n common operation performed by the seL4 syscall stubs (user-level kernel entry utility functions).\n*}\ndefinition\n setMR :: \"lifted_globals \\ nat \\ word32 \\ lifted_globals\"\nwhere\n \"setMR s i v \\\n s\\heap_seL4_IPCBuffer__C := (heap_seL4_IPCBuffer__C s)\n (heap_seL4_IPCBuffer__C'ptr s (Ptr (scast seL4_GlobalsFrame)) :=\n msg_C_update (\\a. Arrays.update a i v)\n (heap_seL4_IPCBuffer__C s (heap_seL4_IPCBuffer__C'ptr s\n (Ptr (scast seL4_GlobalsFrame)))))\\\"\n\ndefinition\n setMRs :: \"lifted_globals \\ word32 \\ word32 \\\n word32 \\ word32 \\ lifted_globals\"\nwhere\n \"setMRs s mr0 mr1 mr2 mr3 \\\n setMR (setMR (setMR (setMR s 0 mr0) 1 mr1) 2 mr2) 3 mr3\"\n\ntext {*\n Before showing properties of the syscall stubs, we introduce some lemmas specifying the effect\n of some seL4 supporting functions. The function \\code{seL4\\_GetIPCBuffer} returns a pointer to\n the current thread's IPC buffer, while the functions \\code{seL4\\_SetMR} and \\code{seL4\\_GetMR}\n write to and read from the message registers of the IPC buffer, respectively. The following\n lemmas state their effects, and are used below in reasoning about the effect of the syscall stubs\n themselves.\n\n Some of these are tagged ``[wp\\_unsafe],'' which allows the wp tactic to hint to an\n interactive user when it could have made further progress with this lemma available. These tags\n are included for convenience when adapting or exploring a generated proof. The optional ``notes''\n header of a lemma allows existing lemmas to be modified for the duration of the current proof.\n The \\code{seL4\\_SetMR} proof uses this to make the axiom we discussed previously available to\n Isabelle's simp tactic.\n*}\ntext {* \\newpage *}\nlemma seL4_GetIPCBuffer_wp':\n \"\\s'. \\\\s. globals_frame_intact s \\\n s = s'\\\n seL4_GetIPCBuffer'\n \\\\r s. r = heap_seL4_IPCBuffer__C'ptr s\n (Ptr (scast seL4_GlobalsFrame)) \\\n s = s'\\!\"\n apply (rule allI)\n apply (simp add:seL4_GetIPCBuffer'_def)\n apply wp\n apply (clarsimp simp:globals_frame_intact_def)\n done\n\n(*<*)\nlemmas seL4_GetIPCBuffer_wp[wp_unsafe] =\n seL4_GetIPCBuffer_wp'[THEN validNF_make_schematic_post, simplified]\n(*>*)\n\nlemma seL4_SetMR_wp[wp_unsafe]:\n notes seL4_SetMR_axiom[simp]\n shows\n \"\\\\s. globals_frame_intact s \\\n ipc_buffer_valid s \\\n i \\ 0 \\\n i < seL4_MsgMaxLength \\\n (\\x. P x (setMR s (nat i) v))\\\n exec_concrete lift_global_heap (seL4_SetMR' i v)\n \\P\\!\"\n apply (simp add:seL4_SetMR_lifted'_def)\n apply (wp seL4_GetIPCBuffer_wp)\n apply (simp add:setMR_def globals_frame_intact_def ipc_buffer_valid_def)\n done\n\nlemma seL4_GetMR_wp[wp_unsafe]:\n \"\\\\s. \\x. i \\ 0 \\\n i < seL4_MsgMaxLength \\\n globals_frame_intact s \\\n ipc_buffer_valid s \\\n P x s\\\n seL4_GetMR' i\n \\P\\!\"\n apply (simp add:seL4_GetMR'_def)\n apply (wp seL4_GetIPCBuffer_wp)\n apply (simp add:globals_frame_intact_def ipc_buffer_valid_def)\n done\n\ntext {*\n The C standard library provides a function, \\code{abort}, that is called by\n the CAmkES glue code in the event of an unrecoverable error. We do not\n provide a definition of the function itself and instead use the following\n lemma to later prove that all invocations to \\code{abort} are dead code that\n is never executed.\n*}\nlemma abort_wp[wp]:\n \"\\\\_. False\\ abort' \\P\\!\"\n by (rule validNF_false_pre)\n\ntext {*\n We now introduce lemmas specifying the behaviour of seL4 syscall stubs. These functions write\n syscall arguments into hardware registers, perform an assembly instruction to enter the kernel\n and then unpack the kernel's response. The following lemmas express that these invocations can\n never fail. We only provide lemmas for the syscalls used by the CAmkES glue code.\n*}\nlemma seL4_Call_wp[wp_unsafe]:\n notes seL4_SetMR_wp[wp] seL4_GetMR_wp[wp]\n shows\n \"\\\\s. globals_frame_intact s \\\n ipc_buffer_valid s \\\n (\\x v0 v1 v2 v3. P x (setMRs s v0 v1 v2 v3))\\\n seL4_Call' cap info\n \\P\\!\"\n apply (simp add:seL4_Call'_def)\n apply (wp seL4_GetIPCBuffer_wp)\n apply (simp add:globals_frame_intact_def ipc_buffer_valid_def setMRs_def\n setMR_def)\n done\n(* The remaining syscall WP lemmas are irrelevant for the proofs in this locale, but we prove them\n * here so they appear in a logical location if we're building a document.\n *)\nlemma seL4_Notify_wp[wp_unsafe]:\n \"\\\\s. \\x. P x s\\\n seL4_Notify' cap data\n \\P\\!\"\n apply (simp add:seL4_Notify'_def seL4_MessageInfo_new'_def)\n apply wp\n apply simp\n done\n\nlemma seL4_Poll_wp[wp_unsafe]:\n \"\\\\s. globals_frame_intact s \\\n ipc_buffer_valid s \\\n (\\x b v0 v1 v2 v3. P x (heap_w32_update\n (\\a. a(badge := b)) (setMRs s v0 v1 v2 v3))) \\\n badge \\ NULL \\\n is_valid_w32 s badge\\\n seL4_Poll' cap badge\n \\P\\!\"\n apply (simp add:seL4_Poll'_def seL4_GetIPCBuffer'_def)\n apply (wp seL4_SetMR_wp)\n apply (simp add:globals_frame_intact_def ipc_buffer_valid_def setMRs_def\n setMR_def)\n done\n\ntext {* \\newpage *}\nlemma seL4_ReplyWait_wp[wp_unsafe]:\n \"\\\\s. globals_frame_intact s \\\n ipc_buffer_valid s \\\n (\\x v0 v1 v2 v3. P x (setMRs s v0 v1 v2 v3))\\\n seL4_ReplyWait' cap info NULL\n \\P\\!\"\n apply (simp add:seL4_ReplyWait'_def seL4_GetMR'_def)\n apply (wp seL4_SetMR_wp seL4_GetIPCBuffer_wp)\n apply (simp add:globals_frame_intact_def ipc_buffer_valid_def setMRs_def\n setMR_def)\n done\n\nlemma seL4_Wait_wp[wp_unsafe]:\n \"\\\\s. globals_frame_intact s \\\n ipc_buffer_valid s \\\n (\\x v0 v1 v2 v3. P x (setMRs s v0 v1 v2 v3))\\\n seL4_Wait' cap NULL\n \\P\\!\"\n apply (simp add:seL4_Wait'_def)\n apply (wp seL4_SetMR_wp)\n apply (simp add:globals_frame_intact_def ipc_buffer_valid_def setMRs_def\n setMR_def)\n done\n\ntext {*\n It should be noted that each of these proofs about a system call stub implicitly assumes that the\n execution of the kernel itself has no effect on the user state. Obviously this is not true in\n practice or components would not be able to communicate via IPC. For now, the actual behaviour of\n the kernel is not required to show safe execution of the glue code. Further functional\n correctness proofs in future will involve a semantics of the kernel's execution and its effect on\n the user state.\n*}\n\n(*<*)\n\ndefinition\n thread_count :: word32\nwhere\n \"thread_count \\ 2\"\n\n(* Any array parameters will have caused a TLS array to be generated. Prove a WP lemma for each\n * here.\n *)\n\n(*>*)\n\nchapter {* RPC Send *}\n(*<*)\n(* This lemma captures the safety of the RPCFrom__run function\n * which is invoked on startup in this glue code. It is excluded from the final document because\n * the function itself is trivial and the proof uninteresting.\n *)\nlemma RPCFrom_run_nf: \"\\\\s. \\r. P r s\\ RPCFrom__run' \\P\\!\"\n apply (simp add: RPCFrom__run'_def)\n apply wp\n apply simp\n done\n(*>*)\n\ntext {*\n Having introduced supporting lemmas, we are now in a position to express the safety of the CAmkES\n glue code itself. The lemmas and proofs in this chapter are generated from the following CAmkES\n interface definition:\n \\camkeslisting{simple.camkes}\n This describes a CAmkES procedural interface containing six methods. To give some idea of what\n the code for this procedure looks like, the generated implementation of the first method follows.\n \\clisting{from-echo-int.c}\n\n We generate a proof for each\n method that the generated glue code does not fail. The purpose of these six is to\n demonstrate that proof generation generalises across the various CAmkES data types and\n parameter combinations. The same generation logic produces a proof for word-sized parameters\n (e.g. \\code{int}), parameters smaller than a word (e.g. \\code{char}) and parameters greater than\n a word (e.g. \\code{uint64\\_t}). Similarly the generation logic handles input, output and\n bidirectional parameters, as well as methods with and without a return value.\n\n The proofs themselves state that the glue code obeys the C99 standard and that, when invoked, it\n consistently terminates (returns to the user) and does not reference invalid memory. The\n assumptions are the properties of the globals frame and TLS region discussed previously and,\n where relevant, that any pointers passed to the glue code can be safely dereferenced.\n*}\n\nlemma RPCFrom_echo_int_nf:\n notes seL4_SetMR_wp[wp] seL4_GetMR_wp[wp]\n shows\n \"\\\\s0'. globals_frame_intact s0' \\\n ipc_buffer_valid s0'\\\n RPCFrom_echo_int' i\n \\\\_ s0'. globals_frame_intact s0' \\\n ipc_buffer_valid s0'\\!\"\n apply (simp add:RPCFrom_echo_int'_def)\n apply (wp seL4_Call_wp)\n apply (simp add:seL4_MessageInfo_new'_def)\n apply wp+\n apply (simp add:globals_frame_intact_def ipc_buffer_valid_def\n setMRs_def setMR_def)\n done\n\nlemma RPCFrom_echo_parameter_nf:\n notes seL4_SetMR_wp[wp] seL4_GetMR_wp[wp]\n shows\n \"\\\\s1'. globals_frame_intact s1' \\\n is_valid_w32 s1' (ptr_coerce pout) \\\n ipc_buffer_valid s1'\\\n RPCFrom_echo_parameter' pin pout\n \\\\_ s1'. globals_frame_intact s1' \\\n is_valid_w32 s1' (ptr_coerce pout) \\\n ipc_buffer_valid s1'\\!\"\n apply (simp add:RPCFrom_echo_parameter'_def)\n apply (wp seL4_Call_wp)\n apply (simp add:seL4_MessageInfo_new'_def)\n apply wp+\n apply (simp add:globals_frame_intact_def ipc_buffer_valid_def\n setMRs_def setMR_def)\n done\n\n text {* \\newpage *}\n\nlemma RPCFrom_echo_char_nf:\n notes seL4_SetMR_wp[wp] seL4_GetMR_wp[wp]\n shows\n \"\\\\s2'. globals_frame_intact s2' \\\n ipc_buffer_valid s2'\\\n RPCFrom_echo_char' i\n \\\\_ s2'. globals_frame_intact s2' \\\n ipc_buffer_valid s2'\\!\"\n apply (simp add:RPCFrom_echo_char'_def)\n apply (wp seL4_Call_wp)\n apply (simp add:seL4_MessageInfo_new'_def)\n apply wp+\n apply (simp add:globals_frame_intact_def ipc_buffer_valid_def\n setMRs_def setMR_def)\n done\n\nlemma RPCFrom_increment_char_nf:\n notes seL4_SetMR_wp[wp] seL4_GetMR_wp[wp]\n shows\n \"\\\\s3'. globals_frame_intact s3' \\\n is_valid_w8 s3' (ptr_coerce x) \\\n ipc_buffer_valid s3'\\\n RPCFrom_increment_char' x\n \\\\_ s3'. globals_frame_intact s3' \\\n is_valid_w8 s3' (ptr_coerce x) \\\n ipc_buffer_valid s3'\\!\"\n apply (simp add:RPCFrom_increment_char'_def)\n apply (wp seL4_Call_wp)\n apply (simp add:seL4_MessageInfo_new'_def)\n apply wp+\n apply (simp add:globals_frame_intact_def ipc_buffer_valid_def\n setMRs_def setMR_def)\n done\n\n text {* \\newpage *}\n\nlemma RPCFrom_increment_parameter_nf:\n notes seL4_SetMR_wp[wp] seL4_GetMR_wp[wp]\n shows\n \"\\\\s4'. globals_frame_intact s4' \\\n is_valid_w32 s4' (ptr_coerce x) \\\n ipc_buffer_valid s4'\\\n RPCFrom_increment_parameter' x\n \\\\_ s4'. globals_frame_intact s4' \\\n is_valid_w32 s4' (ptr_coerce x) \\\n ipc_buffer_valid s4'\\!\"\n apply (simp add:RPCFrom_increment_parameter'_def)\n apply (wp seL4_Call_wp)\n apply (simp add:seL4_MessageInfo_new'_def)\n apply wp+\n apply (simp add:globals_frame_intact_def ipc_buffer_valid_def\n setMRs_def setMR_def)\n done\n\nlemma RPCFrom_increment_64_nf:\n notes seL4_SetMR_wp[wp] seL4_GetMR_wp[wp]\n shows\n \"\\\\s5'. globals_frame_intact s5' \\\n is_valid_w64 s5' (ptr_coerce x) \\\n ipc_buffer_valid s5'\\\n RPCFrom_increment_64' x\n \\\\_ s5'. globals_frame_intact s5' \\\n is_valid_w64 s5' (ptr_coerce x) \\\n ipc_buffer_valid s5'\\!\"\n apply (simp add:RPCFrom_increment_64'_def)\n apply (wp seL4_Call_wp)\n apply (simp add:seL4_MessageInfo_new'_def)\n apply wp+\n apply (simp add:globals_frame_intact_def ipc_buffer_valid_def\n setMRs_def setMR_def)\n done\n\n(*<*)\nend\n\nend\n(*>*)\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/l4v/camkes/glue-proofs/RPCFrom.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326186278634367, "lm_q2_score": 0.14033624769237754, "lm_q1q2_score": 0.06360906904549277}} {"text": "(* Title: UD/UD_Reference.thy\n Author: Mihails Milehins\n Copyright 2021 (C) Mihails Milehins\n\nReference manual for the UD.\n*)\n\nsection\\UD\\\ntheory UD_Reference\n imports \n UD\n \"../Reference_Prerequisites\"\nbegin\n\n\n\nsubsection\\Introduction\\\n\n\nsubsubsection\\Background\\\n\ntext\\\nThis section presents a reference manual for the sub-framework UD. \nThe UD can be used for the elimination of \n\\textit{sort constraints} (e.g., see \\<^cite>\\\"altenkirch_constructive_2007\"\\)\nand unoverloading of definitions in the object logic Isabelle/HOL of the \nformal proof assistant Isabelle. \nThe UD evolved from the author's work on an extension of the \nframework \\textit{Types-To-Sets} \n(see \n\\<^cite>\\\"blanchette_types_2016\" and \"kuncar_types_2019\" and \"immler_smooth_2019\" and \"immler_automation_2019\"\\,\nfor a description of the framework Types-To-Sets\nand \\<^cite>\\\"milehins_extension_2021\"\\ for a description of the author's extension)\nand builds upon certain ideas expressed in \\<^cite>\\\"kaufmann_mechanized_2010\"\\.\n\\\n\n\nsubsubsection\\Purpose and scope\\\n\ntext\\\nThe primary functionality of the framework is available via the Isabelle/Isar \ncommand @{command ud}. This command automates the processes of the \nelimination of sort constraints and unoverloading of definitions.\nThus, the command @{command ud} allows for the synthesis\nof the convenience constants and theorems that are usually needed for the \napplication of the derivation step 2 of the original relativization algorithm\nof Types-To-Sets (see subsection 5.4 in \\<^cite>\\\"blanchette_types_2016\"\\). However, \nit is expected that the command can be useful for other purposes.\n\\\n\n\nsubsubsection\\Related and previous work\\\n\ntext\\\nThe functionality provided by the command @{command ud} shares similarities\nwith the functionality provided by the algorithms for the elimination of\nsort constraints and elimination of overloading that were \npresented in \\<^cite>\\\"kaufmann_mechanized_2010\"\\\nand with the algorithm associated with the command \n\\mbox{\\textbf{unoverload\\_definition}} that was proposed\nin \\<^cite>\\\"immler_automation_2019\"\\. \nNonetheless, technically, unlike \\mbox{\\textbf{unoverload\\_definition}}, \nthe command @{command ud} does\nnot require the additional axiom UO associated with Types-To-Sets for \nits operation (see \\<^cite>\\\"blanchette_types_2016\"\\, \n\\<^cite>\\\"immler_automation_2019\"\\), it uses \nthe \\textit{definitional axioms} (e.g., see \\<^cite>\\\"kaufmann_mechanized_2010\"\\)\ninstead of arbitrary theorems supplied by the user\nand it is independent of the infrastructure associated with\nthe \\textit{axiomatic type classes} \n\\<^cite>\\\"nipkow_type_1991\" and \"wenzel_type_1997\" and \"altenkirch_constructive_2007\"\\.\n\nIt should also be mentioned that the Isabelle/ML code from the main \ndistribution of Isabelle was frequently reused during the \ndevelopment of the UD. Lastly, it should be mentioned that the\nframework SpecCheck \\<^cite>\\\"kappelmann_speccheck_2021\"\\ was used for unit \ntesting the framework UD.\n\\\n\n\n\nsubsection\\Theory\\label{sec:ud_theory}\\\n\n\ntext\\\nThe general references for this subsection are\n\\<^cite>\\\"kaufmann_mechanized_2010\"\\ and \\<^cite>\\\"yang_comprehending_2017\"\\.\nThe command @{command ud} relies \non a restricted (non-recursive) variant of the \n\\textit{classical overloading elimination algorithm}\nthat was originally proposed in \\<^cite>\\\"kaufmann_mechanized_2010\"\\.\nIt is assumed that there exists \na variable $ud_{\\mathsf{with}}$ that stores theorems of the \nform $c_{\\tau} = c_{\\mathsf{with}}\\ \\bar{*}$, where $c_{\\tau}$ and \n$c_{\\mathsf{with}}$ are distinct \\textit{constant-instances} \nand $\\bar{*}$ is a finite sequence of \\textit{uninterpreted constant-instances},\nsuch that, if $c_{\\tau}$ depends on a type variable $\\alpha_{\\Upsilon}$, \nwith $\\Upsilon$ being a \\textit{type class} \n\\<^cite>\\\"nipkow_type_1991\" and \"wenzel_type_1997\" and \"altenkirch_constructive_2007\"\\\nthat depends on the overloaded \nconstants $\\bar{*'}$, then $\\bar{*}$ contains $\\bar{*'}$ as a subsequence. \nLastly, the binary operation $\\cup$ is defined in a manner such that \nfor any sequences $\\bar{*}$ and $\\bar{*'}$, $\\bar{*} \\cup \\bar{*'}$ \nis a sequence that consists of all elements of the union of the \nelements of $\\bar{*}$ and $\\bar{*'}$ without duplication. \nAssuming an underlying \n\\textit{well-formed definitional theory} $D$, \nthe input to the algorithm is a constant-instance $c_{\\sigma}$. \nGiven the constant-instance $c_{\\sigma}$, \nthere exists at most one definitional axiom\n$c_{\\tau} = \\phi_{\\tau}\\left[\\bar{*}\\right]$ \nin $D$ such that $c_{\\sigma} \\leq c_{\\tau}$: otherwise \nthe \\textit{orthogonality} of $D$ and, \ntherefore, the \\textit{well-formedness}\nof $D$ are violated ($\\phi$ is assumed to be parameterized by \nthe types that it can have with respect to the\ntype substitution operation, \nand $\\bar{*}$ in $c_{\\tau} = \\phi_{\\tau}\\left[\\bar{*}\\right]$ \nis a list of all uninterpreted constant-instances that \noccur in $\\phi_{\\tau}\\left[\\bar{*}\\right]$).\n\nIf a definitional axiom $c_{\\tau}=\\phi_{\\tau}\\left[\\bar{*}\\right]$ \nsuch that $c_{\\sigma} \\leq c_{\\tau}$ \nexists for the constant-instance $c_{\\sigma}$, \nthen the following derivation is applied to it by the algorithm\n\\[\n\\infer[(6)]\n{\\vdash c_{\\sigma} = c_{\\mathsf{with}}\\ \\left(\\bar{*} \\cup \\bar{*'}\\right)}\n{\n\\infer[(5)]\n{\n\\vdash c_{\\mathsf{with}}\\ \\left(\\bar{*} \\cup \\bar{*'}\\right) = \n\\phi_{\\mathsf{with}}\\left[\\bar{*} \\cup \\bar{*'}\\right]\n}\n{\n\\infer[(4)]\n{\\vdash c_{\\mathsf{with}}\\ ?\\bar{f} = \\phi_{\\mathsf{with}}\\left[?\\bar{f}\\right]}\n{\n\\infer[(3)]\n{\\vdash c_{\\mathsf{with}} = (\\lambda \\bar{f}.\\ \\phi_{\\mathsf{with}}\\left[\\bar{f}\\right])}\n{\n\\infer[(2)]\n{\\vdash c_{\\sigma}=\\phi_{\\mathsf{with}}\\left[\\bar{*} \\cup \\bar{*'}\\right]}\n{\n\\infer[(1)]\n{\\vdash c_{\\sigma}=\\phi_{\\sigma}\\left[\\bar{*}\\right]}\n{\\vdash c_{\\tau}=\\phi_{\\tau}\\left[\\bar{*}\\right]}\n}\n}\n}\n}\n}\n\\]\nIn step 1, the previously established \nproperty $c_{\\sigma} \\leq c_{\\tau}$ is used to create the \n(extended variant of the) type substitution \nmap $\\rho$ such that $\\sigma = \\rho \\left( \\tau \\right)$ \n(see \\<^cite>\\\"kuncar_types_2015\"\\) and perform the type\nsubstitution in $c_{\\tau}=\\phi_{\\tau}\\left[\\bar{*}\\right]$ \nto obtain $c_{\\sigma}=\\phi_{\\sigma}\\left[\\bar{*}\\right]$; \nin step 2, the collection of theorems $ud_{\\mathsf{with}}$ is unfolded,\nusing it as a term rewriting system, possibly introducing further uninterpreted\nconstants $\\bar{*'}$; in step 3, the term on the right-hand side of the\ntheorem is processed by removing the sort constraints from all type\nvariables that occur in it, replacing every uninterpreted constant-instance \n(this excludes all built-in constants of Isabelle/HOL) that occurs in it by a \nfresh term variable, and applying the abstraction until the resulting term \nis closed: this term forms the right-hand side of a new definitional axiom \nof a fresh constant $c_{\\mathsf{with}}$ (if the conditions associated with \nthe definitional principles of Isabelle/HOL \\<^cite>\\\"yang_comprehending_2017\"\\ \nare satisfied); step 4 is justified by the beta-contraction; \nstep 5 is a substitution of the uninterpreted constants $\\bar{*} \\cup \\bar{*'}$;\nstep 6 follows trivially from the results of the application of steps 2 and 5.\n\nThe implementation of the command @{command ud} closely follows the steps of \nthe algorithm outlined above. Thus, at the end of the successful\nexecution, the command declares the constant $c_{\\mathsf{with}}$ and stores the \nconstant-instance definition that is obtained at the end of step 3 of\nthe algorithm UD; furthermore, the command adds the theorem that is \nobtained after the execution of step 6 of the algorithm\nto $ud_{\\mathsf{with}}$.\n\nUnlike the classical overloading elimination algorithm, \nthe algorithm employed in the implementation\nof the command @{command ud} is not recursive. Thus, the users are responsible \nfor maintaining an adequate collection of theorems $ud_{\\mathsf{with}}$. \nNonetheless, in this case, the users can provide their own \nunoverloaded constants $c_{\\mathsf{with}}$ and the associated theorems \n$c_{\\sigma} = c_{\\mathsf{with}}\\ \\bar{*}$ for any constant-instance $c_{\\sigma}$. \nFrom the perspective of the relativization algorithm associated with\nTypes-To-Sets this can be useful because there is no \nguarantee that the automatically synthesized constants $c_{\\mathsf{with}}$ \nwill possess desirable parametricity characteristics\n(e.g., see \\<^cite>\\\"kuncar_types_2015\"\\ and \\<^cite>\\\"immler_smooth_2019\"\\).\nUnfortunately, the implemented algorithm still suffers from the fundamental \nlimitation that was already outlined in \\<^cite>\\\"kaufmann_mechanized_2010\"\\, \n\\<^cite>\\\"blanchette_types_2016\"\\ and \\<^cite>\\\"kuncar_types_2019\"\\: \nit does not offer a solution for handling the \nconstants whose types contain occurrences of the type constructors whose \ntype definitions contain occurrences of unresolvable overloading.\n\\\n\n\n\nsubsection\\Syntax\\\n\ntext\\\nThis subsection presents the syntactic categories that are associated with the \ncommand @{command ud}. It is important to note that the presentation is \nonly approximate.\n\\\n\ntext\\\n\n\\begin{matharray}{rcl}\n @{command_def \"ud\"} & : & \\theory \\ theory\\\\\\\n\\end{matharray}\n\n \\<^medskip>\n\n \\<^rail>\\@@{command ud} binding? const mixfix?\\\n\n \\<^descr> \\<^theory_text>\\ud\\ (\\b\\) \\const\\ (\\mixfix\\) provides access to the algorithm for\nthe elimination of sort constraints and unoverloading of definitions\nthat was described in subsection \\ref{sec:ud_theory}.\nThe optional binding \\b\\ is used for the specification\nof the names of the entities added by the command to the theory and the \noptional argument \\mixfix\\ is used for the specification \nof the concrete inner syntax for the constant in the usual manner\n(e.g., see \\<^cite>\\\"wenzel_isabelle/isar_2019-1\"\\). \nIf either \\b\\ or \\mixfix\\ are not specified by the user, then the command\nintroduces sensible defaults. Following the specification of the \ndefinition of the constant, an additional theorem that establishes\nthe relationship between the newly introduced constant and the \nconstant provided by the user as an input is established and added \nto the dynamic fact @{thm [source] ud_with}.\n\\\n\n\n\nsubsection\\Examples\\label{sec:ud_ex}\\\n\ntext\\\nIn this subsection, some of the capabilities of the UD are \ndemonstrated by example. The examples that are presented in this subsection are \nexpected to be sufficient for beginning an independent exploration of the \nframework, but do not cover the entire spectrum of the functionality \nand the problems that one may encounter while using it.\n\\\n\n\nsubsubsection\\Type classes\\\n\ndefinition mono where\n \"mono f \\ (\\x y. x \\ y \\ f x \\ f y)\"\n\ntext\\\nWe begin the exploration of the capabilities of the framework by considering\nthe constant @{const mono}.\nIt is defined as\n\\begin{center}\n@{thm [names_short = true] mono_def[no_vars]} \n\\end{center}\nfor any @{term [show_sorts] \"f::'a::order\\'b::order\"}.\nThe constants is unoverloaded using the command @{command ud}:\n\\\nud \\mono\\\ntext\\\nThe invocation of the command above declares the constant @{const mono.with} \nthat is defined as\n\\begin{center}\n@{thm mono.with_def[no_vars]}\n\\end{center}\nand provides the theorem @{thm [source] mono.with} given by\n\\begin{center}\n@{thm mono.with[no_vars]}.\n\\end{center}\nThe theorems establish the relationship between the unoverloaded constant\n@{const mono.with} and the overloaded constant @{const mono}:\nboth theorems are automatically added to the dynamic fact \n@{thm [source] ud_with}.\n\\\n\n\nsubsubsection\\Low-level overloading\\\n\ntext\\\nThe following example closely follows Example 5 in section 5.2. in \n\\<^cite>\\\"kaufmann_mechanized_2010\"\\. \n\\\n\nconsts pls :: \"'a \\ 'a \\ 'a\"\n\noverloading\npls_nat \\ \"pls::nat \\ nat \\ nat\"\npls_times \\ \"pls::'a \\ 'b \\ 'a \\ 'b \\ 'a \\ 'b\"\nbegin\ndefinition pls_nat :: \"nat \\ nat \\ nat\" where \"pls_nat a b = a + b\"\ndefinition pls_times :: \"'a \\ 'b \\ 'a \\ 'b \\ 'a \\ 'b\" \n where \"pls_times \\ \\x y. (pls (fst x) (fst y), pls (snd x) (snd y))\"\nend\n\nud pls_nat \\pls::nat \\ nat \\ nat\\\nud pls_times \\pls::'a \\ 'b \\ 'a \\ 'b \\ 'a \\ 'b\\\n\ntext\\\nAs expected, two new unoverloaded constants are produced via\nthe invocations of the command @{command ud} above. The first constant,\n\\<^const>\\pls_nat.with\\, corresponds to \\pls::nat \\ nat \\ nat\\ and is given by\n\\begin{center}\n@{thm pls_nat.with_def[no_vars]},\n\\end{center}\nthe second constant, \\<^const>\\pls_times.with\\, corresponds to\n\\begin{center}\n\\pls::'a \\ 'b \\ 'a \\ 'b \\ 'a \\ 'b\\ \n\\end{center}\nand is given by \n\\begin{center}\n@{thm pls_times.with_def[no_vars]}.\n\\end{center}\nThe theorems that establish the relationship between the overloaded and\nthe unoverloaded constants are given by \n\\begin{center}\n@{thm pls_nat.with} \n\\end{center}\nand \n\\begin{center}\n@{thm pls_times.with}.\n\\end{center}\nThe definitions of the constants \\<^const>\\pls_nat.with\\ and \n\\<^const>\\pls_times.with\\ are consistent with the ones suggested in\n\\<^cite>\\\"kaufmann_mechanized_2010\"\\. Nonetheless, of course, it is\nimportant to keep in mind that the command @{command ud}\nhas a more restricted scope of applicability than the\nalgorithm suggested in \\<^cite>\\\"kaufmann_mechanized_2010\"\\.\n\\\n\ntext\\\\newpage\\\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Conditional_Transfer_Rule/UD/UD_Reference.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.14223188955598276, "lm_q1q2_score": 0.061726003771331715}} {"text": "(*\n File: More_Loops.thy\n Author: Mathias Fleury, Daniela Kaufmann, JKU\n Maintainer: Mathias Fleury, JKU\n*)\ntheory More_Loops\nimports\n \"Refine_Monadic.Refine_While\"\n \"Refine_Monadic.Refine_Foreach\"\n \"HOL-Library.Rewrite\"\nbegin\n\nsubsection \\More Theorem about Loops\\\n\ntext \\Most theorem below have a counterpart in the Refinement Framework that is weaker (by missing\n assertions for example that are critical for code generation).\n\\\nlemma Down_id_eq:\n \\\\Id x = x\\\n by auto\n\nlemma while_upt_while_direct1:\n \"b \\ a \\\n do {\n (_,\\) \\ WHILE\\<^sub>T (FOREACH_cond c) (\\x. do {ASSERT (FOREACH_cond c x); FOREACH_body f x})\n ([a..);\n RETURN \\\n } \\ do {\n (_,\\) \\ WHILE\\<^sub>T (\\(i, x). i < b \\ c x) (\\(i, x). do {ASSERT (i < b); \\'\\f i x; RETURN (i+1,\\')\n}) (a,\\);\n RETURN \\\n }\"\n apply (rewrite at \\_ \\ \\\\ Down_id_eq[symmetric])\n apply (refine_vcg WHILET_refine[where R = \\{((l, x'), (i::nat, x::'a)). x= x' \\ i \\ b \\ i \\ a \\\n l = drop (i-a) [a..])\n subgoal by auto\n subgoal by (auto simp: FOREACH_cond_def)\n subgoal by (auto simp: FOREACH_body_def intro!: bind_refine[OF Id_refine])\n subgoal by auto\n done\n\nlemma while_upt_while_direct2:\n \"b \\ a \\\n do {\n (_,\\) \\ WHILE\\<^sub>T (FOREACH_cond c) (\\x. do {ASSERT (FOREACH_cond c x); FOREACH_body f x})\n ([a..);\n RETURN \\\n } \\ do {\n (_,\\) \\ WHILE\\<^sub>T (\\(i, x). i < b \\ c x) (\\(i, x). do {ASSERT (i < b); \\'\\f i x; RETURN (i+1,\\')\n}) (a,\\);\n RETURN \\\n }\"\n apply (rewrite at \\_ \\ \\\\ Down_id_eq[symmetric])\n apply (refine_vcg WHILET_refine[where R = \\{((i::nat, x::'a), (l, x')). x= x' \\ i \\ b \\ i \\ a \\\n l = drop (i-a) [a..])\n subgoal by auto\n subgoal by (auto simp: FOREACH_cond_def)\n subgoal by (auto simp: FOREACH_body_def intro!: bind_refine[OF Id_refine])\n subgoal by (auto simp: FOREACH_body_def intro!: bind_refine[OF Id_refine])\n subgoal by auto\n done\n\n\n\nlemma while_nfoldli:\n \"do {\n (_,\\) \\ WHILE\\<^sub>T (FOREACH_cond c) (\\x. do {ASSERT (FOREACH_cond c x); FOREACH_body f x}) (l,\\);\n RETURN \\\n } \\ nfoldli l c f \\\"\n apply (induct l arbitrary: \\)\n apply (subst WHILET_unfold)\n apply (simp add: FOREACH_cond_def)\n\n apply (subst WHILET_unfold)\n apply (auto\n simp: FOREACH_cond_def FOREACH_body_def\n intro: bind_mono Refine_Basic.bind_mono(1))\n done\nlemma nfoldli_while: \"nfoldli l c f \\\n \\\n (WHILE\\<^sub>T\\<^bsup>I\\<^esup>\n (FOREACH_cond c) (\\x. do {ASSERT (FOREACH_cond c x); FOREACH_body f x}) (l, \\) \\\n (\\(_, \\). RETURN \\))\"\nproof (induct l arbitrary: \\)\n case Nil thus ?case by (subst WHILEIT_unfold) (auto simp: FOREACH_cond_def)\nnext\n case (Cons x ls)\n show ?case\n proof (cases \"c \\\")\n case False thus ?thesis\n apply (subst WHILEIT_unfold)\n unfolding FOREACH_cond_def\n by simp\n next\n case [simp]: True\n from Cons show ?thesis\n apply (subst WHILEIT_unfold)\n unfolding FOREACH_cond_def FOREACH_body_def\n apply clarsimp\n apply (rule Refine_Basic.bind_mono)\n apply simp_all\n done\n qed\nqed\n\nlemma while_eq_nfoldli: \"do {\n (_,\\) \\ WHILE\\<^sub>T (FOREACH_cond c) (\\x. do {ASSERT (FOREACH_cond c x); FOREACH_body f x}) (l,\\);\n RETURN \\\n } = nfoldli l c f \\\"\n apply (rule antisym)\n apply (rule while_nfoldli)\n apply (rule order_trans[OF nfoldli_while[where I=\"\\_. True\"]])\n apply (simp add: WHILET_def)\n done\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/PAC_Checker/More_Loops.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.12421300673104345, "lm_q1q2_score": 0.061621306179300436}} {"text": "(* Title: Containers/Containers_Userguide.thy\n Author: Andreas Lochbihler, ETH Zurich *)\n(*<*)\ntheory Containers_Userguide imports\n Card_Datatype\n List_Proper_Interval\n Containers\nbegin\n(*>*)\nchapter \\User guide\\\ntext_raw \\\\label{chapter:Userguide}\\\n\ntext \\\n This user guide shows how to use and extend the lightweight containers framework (LC).\n For a more theoretical discussion, see \\<^cite>\\\"Lochbihler2013ITP\"\\.\n This user guide assumes that you are familiar with refinement in the code generator \\<^cite>\\\"HaftmannBulwahn2013codetut\" and \"HaftmannKrausKuncarNipkow2013ITP\"\\.\n The theory \\Containers_Userguide\\ generates it; so if you want to experiment with the examples, you can find their source code there.\n Further examples can be found in the @{dir \\Examples\\} folder.\n\\\n\nsection \\Characteristics\\\n\ntext_raw \\\n \\isastyletext\n \\begin{itemize}\n\\\ntext_raw \\\n \\isastyletext\n \\item \\textbf{Separate type classes for code generation}\n \\\\\n LC follows the ideal that type classes for code generation should be separate from the standard type classes in Isabelle.\n LC's type classes are designed such that every type can become an instance, so well-sortedness errors during code generation can always be remedied.\n\\\ntext_raw \\\n \\isastyletext\n \\item \\textbf{Multiple implementations}\n \\\\\n LC supports multiple simultaneous implementations of the same container type.\n For example, the following implements at the same time\n (i)~the set of @{typ bool} as a distinct list of the elements,\n (ii)~@{typ \"int set\"} as a RBT of the elements or as the RBT of the complement, and\n (iii)~sets of functions as monad-style lists:\n \\par\n\\\nvalue \"({True}, {1 :: int}, - {2 :: int, 3}, {\\x :: int. x * x, \\y. y + 1})\"\ntext_raw \\\n \\isastyletext\n \\par\n The LC type classes are the key to simultaneously supporting different implementations.\n\n \\item \\textbf{Extensibility}\n \\\\\n The LC framework is designed for being extensible.\n You can add new containers, implementations and element types any time.\n \\end{itemize}\n\\\n\nsection \\Getting started\\\ntext_raw \\\\label{section:getting:started}\\\n\ntext \\\n Add the entry theory @{theory Containers.Containers} for LC to the end of your imports.\n This will reconfigure the code generator such that it implements the types @{typ \"'a set\"} for sets and @{typ \"('a, 'b) mapping\"} for maps with one of the data structures supported.\n As with all the theories that adapt the code generator setup, it is important that @{theory Containers.Containers} comes at the end of the imports.\n\n \\textbf{Note:} LC should not be used together with the theory @{text \"HOL-Library.Code_Cardinality\"}.\n\n Run the following command, e.g., to check that LC works correctly and implements sets of @{typ int}s as red-black trees (RBT):\n\\\n\nvalue [code] \"{1 :: int}\"\n\ntext \\\n This should produce @{value [names_short] \"{1 :: int}\"}.\n Without LC, sets are represented as (complements of) a list of elements, i.e., @{term \"set [1 :: int]\"} in the example.\n\\\n\ntext \\\n If your exported code does not use your own types as elements of sets or maps and you have not declared any code equation for these containers, then your \\isacommand{export{\\isacharunderscore}code} command will use LC to implement @{typ \"'a set\"} and @{typ \"('a, 'b) mapping\"}.\n \n Our running example will be arithmetic expressions.\n The function @{term \"vars e\"} computes the variables that occur in the expression @{term e}\n\\\n\ntype_synonym vname = string\ndatatype expr = Var vname | Lit int | Add expr expr\nfun vars :: \"expr \\ vname set\" where\n \"vars (Var v) = {v}\"\n| \"vars (Lit i) = {}\"\n| \"vars (Add e\\<^sub>1 e\\<^sub>2) = vars e\\<^sub>1 \\ vars e\\<^sub>2\"\n\nvalue \"vars (Var ''x'')\"\n\ntext \\\n To illustrate how to deal with type variables, we will use the following variant where variable names are polymorphic:\n\\\n\ndatatype 'a expr' = Var' 'a | Lit' int | Add' \"'a expr'\" \"'a expr'\"\nfun vars' :: \"'a expr' \\ 'a set\" where\n \"vars' (Var' v) = {v}\"\n| \"vars' (Lit' i) = {}\"\n| \"vars' (Add' e\\<^sub>1 e\\<^sub>2) = vars' e\\<^sub>1 \\ vars' e\\<^sub>2\"\n\nvalue \"vars' (Var' (1 :: int))\"\n\nsection \\New types as elements\\\n\ntext \\\n This section explains LC's type classes and shows how to instantiate them.\n If you want to use your own types as the elements of sets or the keys of maps, you must instantiate up to eight type classes: @{class ceq} (\\S\\ref{subsection:ceq}), @{class ccompare} (\\S\\ref{subsection:ccompare}), @{class set_impl} (\\S\\ref{subsection:set_impl}), @{class mapping_impl} (\\S\\ref{subsection:mapping_impl}), @{class cenum} (\\S\\ref{subsection:cenum}), @{class finite_UNIV} (\\S\\ref{subsection:finite_UNIV}), @{class card_UNIV} (\\S\\ref{subsection:card_UNIV}), and @{class cproper_interval} (\\S\\ref{subsection:cproper_interval}).\n Otherwise, well-sortedness errors like the following will occur:\n\\begin{verbatim}\n*** Wellsortedness error:\n*** Type expr not of sort {ceq,ccompare}\n*** No type arity expr :: ceq\n*** At command \"value\"\n\\end{verbatim}\n\n In detail, the sort requirements on the element type @{typ \"'a\"} are:\n \\begin{itemize}\n \\item @{class ceq} (\\S\\ref{subsection:ceq}), @{class ccompare} (\\S\\ref{subsection:ccompare}), and @{class set_impl} (\\S\\ref{subsection:set_impl}) for @{typ \"'a set\"} in general\n \\item @{class cenum} (\\S\\ref{subsection:cenum}) for set comprehensions @{term \"{x. P x}\"},\n \\item @{class card_UNIV}, @{class cproper_interval} for @{typ \"'a set set\"} and any deeper nesting of sets (\\S\\ref{subsection:card_UNIV}),%\n \\footnote{%\n These type classes are only required for set complements (see \\S\\ref{subsection:well:sortedness}).\n }\n and\n \\item @{class equal},%\n \\footnote{%\n We deviate here from the strict separation of type classes, because it does not make sense to store types in a map on which we do not have equality, because the most basic operation @{term \"Mapping.lookup\"} inherently requires equality.\n }\n @{class ccompare} (\\S\\ref{subsection:ccompare}) and @{class mapping_impl} (\\S\\ref{subsection:mapping_impl}) for @{typ \"('a, 'b) mapping\"}.\n \\end{itemize}\n\\\n\nsubsection \\Equality testing\\\ntext_raw \\\\label{subsection:ceq}\\\n\n(*<*)context fixes dummy :: \"'a :: {cenum, ceq, ccompare, set_impl, mapping_impl}\" begin(*>*)\ntext \\\n The type class @{class ceq} defines the operation @{term [source] \"CEQ('a) :: ('a \\ 'a \\ bool) option\" } for testing whether two elements are equal.%\n \\footnote{%\n Technically, the type class @{class ceq} defines the operation @{term [source] ceq}.\n As usage often does not fully determine @{term [source] ceq}'s type, we use the notation @{term \"CEQ('a)\"} that explicitly mentions the type.\n In detail, @{term \"CEQ('a)\"} is translated to @{term [source] \"CEQ('a) :: ('a \\ 'a \\ bool) option\" } including the type constraint.\n We do the same for the other type class operators:\n @{term \"CCOMPARE('a)\"} constrains the operation @{term [source] ccompare} (\\S\\ref{subsection:ccompare}), \n @{term [source] \"SET_IMPL('a)\"} constrains the operation @{term [source] set_impl}, (\\S\\ref{subsection:set_impl}),\n @{term [source] \"MAPPING_IMPL('a)\"} (constrains the operation @{term [source] mapping_impl}, (\\S\\ref{subsection:mapping_impl}), and\n @{term \"CENUM('a)\"} constrains the operation @{term [source] cenum}, \\S\\ref{subsection:cenum}.\n }\n The test is embedded in an \\option\\ value to allow for types that do not support executable equality test such as @{typ \"'a \\ 'b\"}.\n Whenever possible, @{term \"CEQ('a)\"} should provide an executable equality operator.\n Otherwise, membership tests on such sets will raise an exception at run-time.\n\n For data types, the \\derive\\ command can automatically instantiates of @{class ceq},\n we only have to tell it whether an equality operation should be provided or not (parameter \\no\\).\n\\\n(*<*)end(*>*)\n\nderive (eq) ceq expr\n\ndatatype example = Example\nderive (no) ceq example\n\ntext \\\n In the remainder of this subsection, we look at how to manually instantiate a type for @{class ceq}.\n First, the simple case of a type constructor \\simple_tycon\\ without parameters that already is an instance of @{class equal}:\n\\\ntypedecl simple_tycon\naxiomatization where simple_tycon_equal: \"OFCLASS(simple_tycon, equal_class)\"\ninstance simple_tycon :: equal by (rule simple_tycon_equal)\n\ninstantiation simple_tycon :: ceq begin\ndefinition \"CEQ(simple_tycon) = Some (=)\"\ninstance by(intro_classes)(simp add: ceq_simple_tycon_def)\nend\n\ntext \\\n For polymorphic types, this is a bit more involved, as the next example with @{typ \"'a expr'\"} illustrates (note that we could have delegated all this to \\derive\\). \n First, we need an operation that implements equality tests with respect to a given equality operation on the polymorphic type.\n For data types, we can use the relator which the transfer package (method \\transfer\\) requires and the BNF package generates automatically.\n As we have used the old datatype package for @{typ \"'a expr'\"}, we must define it manually:\n\\\n\ncontext fixes R :: \"'a \\ 'b \\ bool\" begin\nfun expr'_rel :: \"'a expr' \\ 'b expr' \\ bool\"\nwhere\n \"expr'_rel (Var' v) (Var' v') \\ R v v'\"\n| \"expr'_rel (Lit' i) (Lit' i') \\ i = i'\"\n| \"expr'_rel (Add' e\\<^sub>1 e\\<^sub>2) (Add' e\\<^sub>1' e\\<^sub>2') \\ expr'_rel e\\<^sub>1 e\\<^sub>1' \\ expr'_rel e\\<^sub>2 e\\<^sub>2'\"\n| \"expr'_rel _ _ \\ False\"\nend\n\ntext \\If we give HOL equality as parameter, the relator is equality:\\\n\nlemma expr'_rel_eq: \"expr'_rel (=) e\\<^sub>1 e\\<^sub>2 \\ e\\<^sub>1 = e\\<^sub>2\"\nby(induct e\\<^sub>1 e\\<^sub>2 rule: expr'_rel.induct) simp_all\ntext \\\n Then, the instantiation is again canonical:\n\\\ninstantiation expr' :: (ceq) ceq begin\ndefinition\n \"CEQ('a expr') =\n (case ID CEQ('a) of None \\ None | Some eq \\ Some (expr'_rel eq))\"\ninstance\n by(intro_classes)\n (auto simp add: ceq_expr'_def expr'_rel_eq[abs_def] \n dest: Collection_Eq.ID_ceq \n split: option.split_asm)\nend\n(*<*)context fixes dummy :: \"'a :: ceq\" begin(*>*)\ntext \\\n Note the following two points:\n First, the instantiation should avoid to use @{term \"(=)\"} on terms of the polymorphic type.\n This keeps the LC framework separate from the type class @{class equal}, i.e., every choice of @{typ \"'a\"}\n in @{typ \"'a expr'\"} can be of sort @{class \"ceq\"}.\n The easiest way to achieve this is to obtain the equality test from @{term \"CEQ('a)\"}.\n Second, we use @{term \"ID CEQ('a)\"} instead of @{term \"CEQ('a)\"}.\n In proofs, we want that the simplifier uses assumptions like \\CEQ('a) = Some \\\\ for rewriting.\n However, @{term \"CEQ('a)\"} is a nullary constant, so the simplifier reverses such an equation, i.e., it only rewrites \\Some \\\\ to @{term \"CEQ('a :: ceq)\"}.\n Applying the identity function @{term \"ID\"} to @{term \"CEQ('a :: ceq)\"} avoids this, and the code generator eliminates all occurrences of @{term \"ID\"}.\n Although @{thm ID_def} by definition, do not use the conventional @{term \"id\"} instead of @{term ID}, because @{term \"id CEQ('a :: ceq)\"} immediately simplifies to @{term \"CEQ('a :: ceq)\"}.\n\\\n(*<*)end(*>*)\n\nsubsection \\Ordering\\\ntext_raw \\\\label{subsection:ccompare}\\\n\n(*<*)context fixes dummy :: \"'a :: {ccompare, ceq}\" begin(*>*)\ntext \\\n LC takes the order for storing elements in search trees from the type class @{class ccompare} rather than @{class compare}, because we cannot instantiate @{class compare} for some types (e.g., @{typ \"'a set\"} as @{term \"(\\)\"} is not linear).\n Similar to @{term \"CEQ('a)\"} in class @{term ceq}, the class @{class ccompare} specifies an optional comparator @{term [source] \"CCOMPARE('a) :: (('a \\ 'a \\ order)) option\" }.\n If you cannot or do not want to implement a comparator on your type, you can default to @{term \"None\"}.\n In that case, you will not be able to use your type as elements of sets or as keys in maps implemented by search trees.\n\n If the type is a data type or instantiates @{class compare} and we wish to use that comparator also for the search tree, instantiation is again canonical:\n For our data type @{typ expr}, derive does everything!\n\\\n(*<*)end(*>*)\n(*<*)(*>*)\nderive ccompare expr\n(*<*)(*>*)\n\ntext \\\n In general, the pattern for type constructors without parameters looks as follows:\n\\\naxiomatization where simple_tycon_compare: \"OFCLASS(simple_tycon, compare_class)\"\ninstance simple_tycon :: compare by (rule simple_tycon_compare)\n\nderive (compare) ccompare simple_tycon\n\n\ntext \\\n For polymorphic types like @{typ \"'a expr'\"}, we should not do everything manually:\n First, we must define a comparator that takes the comparator on the type variable @{typ \"'a\"} as a parameter.\n This is necessary to maintain the separation between Isabelle/HOL's type classes (like @{class compare}) and LC's.\n Such a comparator is again easily defined by derive.\n\\\n\nderive ccompare expr'\n\nthm ccompare_expr'_def comparator_expr'_simps\n\nsubsection \\Heuristics for picking an implementation\\\ntext_raw \\\\label{subsection:set_impl} \\label{subsection:mapping_impl}\\\n(*<*)context fixes dummy :: \"'a :: {ceq, ccompare, set_impl, mapping_impl}\" begin(*>*)\ntext \\\n Now, we have defined the necessary operations on @{typ expr} and @{typ \"'a expr'\"} to store them in a set \n or use them as the keys in a map.\n But before we can actually do so, we also have to say which data structure to use.\n The type classes @{class set_impl} and @{class mapping_impl} are used for this.\n\n They define the overloaded operations @{term [source] \"SET_IMPL('a) :: ('a, set_impl) phantom\" } and @{term [source] \"MAPPING_IMPL('a) :: ('a, mapping_impl) phantom\"}, respectively.\n The phantom type @{typ \"('a, 'b) phantom\"} from theory @{theory \"HOL-Library.Phantom_Type\"} is isomorphic to @{typ \"'b\"}, but formally depends on @{typ \"'a\"}.\n This way, the type class operations meet the requirement that their type contains exactly one type variable.\n The Haskell and ML compiler will get rid of the extra type constructor again.\n\n For sets, you can choose between @{term set_Collect} (characteristic function @{term P} like in @{term \"{x. P x}\"}), @{term set_DList} (distinct list), @{term set_RBT} (red-black tree), and @{term set_Monad} (list with duplicates).\n Additionally, you can define @{term \"set_impl\"} as @{term \"set_Choose\"} which picks the implementation based on the available operations (RBT if @{term \"CCOMPARE('a)\"} provides a linear order, else distinct lists if @{term \"CEQ('a)\"} provides equality testing, and lists with duplicates otherwise).\n @{term \"set_Choose\"} is the safest choice because it picks only a data structure when the required operations are actually available.\n If @{term set_impl} picks a specific implementation, Isabelle does not ensure that all required operations are indeed available.\n\n For maps, the choices are @{term \"mapping_Assoc_List\"} (associative list without duplicates), @{term \"mapping_RBT\"} (red-black tree), and @{term \"mapping_Mapping\"} (closures with function update).\n Again, there is also the @{term \"mapping_Choose\"} heuristics.\n \n For simple cases, \\derive\\ can be used again (even if the type is not a data type).\n Consider, e.g., the following instantiations:\n @{typ \"expr set\"} uses RBTs, @{typ \"(expr, _) mapping\"} and @{typ \"'a expr' set\"} use the heuristics, and @{typ \"('a expr', _) mapping\"} uses the same implementation as @{typ \"('a, _) mapping\"}.\n\\\n(*<*)end(*>*)\n\nderive (rbt) set_impl expr\nderive (choose) mapping_impl expr\nderive (choose) set_impl expr'\n\ntext \\\n More complex cases such as taking the implementation preference of a type parameter must be done manually.\n\\\n\ninstantiation expr' :: (mapping_impl) mapping_impl begin\ndefinition\n \"MAPPING_IMPL('a expr') = \n Phantom('a expr') (of_phantom MAPPING_IMPL('a))\"\ninstance ..\nend\n\n(*<*)\nlocale mynamespace begin\ndefinition empty where \"empty = Mapping.empty\" \ndeclare (in -) mynamespace.empty_def [code]\n(*>*)\ntext \\\n To see the effect of the different configurations, consider the following examples where @{term [names_short] \"empty\"} refers to @{term \"Mapping.empty\"}.\n For that, we must disable pretty printing for sets as follows:\n\\\ndeclare (*<*)(in -) (*>*)pretty_sets[code_post del]\ntext \\\n \\begin{center}\n \\small\n \\begin{tabular}{ll}\n \\toprule\n \\isamarkuptrue\\isacommand{value}\\isamarkupfalse\\ {\\isacharbrackleft}code{\\isacharbrackright}\n &\n \\textbf{result}\n \\\\\n \\midrule\n @{term [source] \"{} :: expr set\"}\n &\n @{value [names_short] \"{} :: expr set\"}\n \\\\\n @{term [source] \"empty :: (expr, unit) mapping\"}\n &\n @{value [names_short] \"empty :: (expr, unit) mapping\"}\n \\\\\n \\midrule\n @{term [source] \"{} :: string expr' set\"}\n &\n @{value [names_short] \"{} :: string expr' set\"}\n \\\\\n @{term [source] \"{} :: (nat \\ nat) expr' set\"}\n &\n @{value [names_short] \"{} :: (nat \\ nat) expr' set\"}\n \\\\\n @{term [source] \"{} :: bool expr' set\"}\n &\n @{value [names_short] \"{} :: bool expr' set\"}\n \\\\\n @{term [source] \"empty :: (bool expr', unit) mapping\"}\n &\n @{value [names_short] \"empty :: (bool expr', unit) mapping\"}\n \\\\\n \\bottomrule\n \\end{tabular}\n \\end{center}\n \n For @{typ expr}, @{term mapping_Choose} picks RBTs, because @{term \"CCOMPARE(expr)\"} provides a comparison operation for @{typ \"expr\"}.\n For @{typ \"'a expr'\"}, the effect of @{term set_Choose} is more pronounced:\n @{term \"CCOMPARE(string)\"} is not @{term \"None\"}, so neither is @{term \"CCOMPARE(string expr')\"}, and @{term set_Choose} picks RBTs.\n As @{typ \"nat \\ nat\"} neither provides equality tests (@{class ceq}) nor comparisons (@{class ccompare}), neither does @{typ \"(nat \\ nat) expr'\"}, so we use lists with duplicates.\n The last two examples show the difference between inheriting a choice and choosing freshly:\n By default, @{typ bool} prefers distinct (associative) lists over RBTs, because there are just two elements.\n As @{typ \"bool expr'\"} enherits the choice for maps from @{typ bool}, an associative list implements @{term [source] \"empty :: (bool expr', unit) mapping\"}.\n For sets, in contrast, @{term \"SET_IMPL('a expr')\"} discards @{typ 'a}'s preferences and picks RBTs, because there is a comparison operation.\n\n Finally, let's enable pretty-printing for sets again:\n\\\ndeclare (*<*)(in -) (*>*)pretty_sets [code_post]\n(*<*)\n (* The following value commands ensure that the code generator executes @{value ...} above,\n I could not find a way to specify [code] to @{value}. *)\n value [code] \"{} :: expr set\"\n value [code] \"empty :: (expr, unit) mapping\"\n value [code] \"{} :: string expr' set\"\n value [code] \"{} :: (nat \\ nat) expr' set\"\n value [code] \"{} :: bool expr' set\"\n value [code] \"empty :: (bool expr', unit) mapping\"\n(*>*) \n(*<*)end(*>*)\n\nsubsection \\Set comprehensions\\\ntext_raw \\\\label{subsection:cenum}\\\n\n(*<*)context fixes dummy :: \"'a :: cenum\" begin(*>*)\ntext \\\n If you use the default code generator setup that comes with Isabelle, set comprehensions @{term [source] \"{x. P x} :: 'a set\"} are only executable if the type @{typ 'a} has sort @{class enum}.\n Internally, Isabelle's code generator transforms set comprehensions into an explicit list of elements which it obtains from the list @{term enum} of all of @{typ \"'a\"}'s elements.\n Thus, the type must be an instance of @{class enum}, i.e., finite in particular.\n For example, @{term \"{c. CHR ''A'' \\ c \\ c \\ CHR ''D''}\"} evaluates to @{term \"set ''ABCD''\"}, the set of the characters A, B, C, and D.\n\n For compatibility, LC also implements such an enumeration strategy, but avoids the finiteness restriction.\n The type class @{class cenum} mimicks @{class enum}, but its single parameter @{term [source] \"cEnum :: ('a list \\ (('a \\ bool) \\ bool) \\ (('a \\ bool) \\ bool)) option\"} combines all of @{class enum}'s parameters, namely a list of all elements, a universal and an existential quantifier.\n \\option\\ ensures that every type can be an instance as @{term \"CENUM('a)\"} can always default to @{term None}.\n \n For types that define @{term \"CENUM('a)\"}, set comprehensions evaluate to a list of their elements.\n Otherwise, set comprehensions are represented as a closure.\n This means that if the generated code contains at least one set comprehension, all element types of a set must instantiate @{class cenum}.\n Infinite types default to @{term None}, and enumerations for finite types are canoncial, see @{theory Containers.Collection_Enum} for examples.\n\\\n(*<*)end(*>*)\n\ninstantiation expr :: cenum begin\ndefinition \"CENUM(expr) = None\"\ninstance by(intro_classes)(simp_all add: cEnum_expr_def)\nend\n\nderive (no) cenum expr'\nderive compare_order expr\n\ntext_raw \\\\par\\medskip \\isastyletext For example,\\\nvalue \"({b. b = True}, {x. compare x (Lit 0) = Lt})\"\ntext_raw \\\n \\isastyletext{}\n yields @{value \"({b. b = True}, {x. compare x (Lit 0) = Lt})\"}\n\\\n\ntext \\\n LC keeps complements of such enumerated set comprehensions, i.e., @{term \"- {b. b = True}\"} evaluates to @{value \"- {b. b = True}\"}.\n If you want that the complement operation actually computes the elements of the complements, you have to replace the code equations for @{term uminus} as follows:\n\\\ndeclare Set_uminus_code[code del] Set_uminus_cenum[code]\n(*<*)value \"- {b. b = True}\"(*>*)\ntext \\\n Then, @{term \"- {b. b = True}\"} becomes @{value \"- {b. b = True}\"}, but this applies to all complement invocations.\n For example, @{term [source] \"UNIV :: bool set\"} becomes @{value \"UNIV :: bool set\"}.\n\\\n(*<*)declare Set_uminus_cenum[code del] Set_uminus_code[code](*>*)\n\nsubsection \\Nested sets\\\ntext_raw \\\\label{subsection:finite_UNIV} \\label{subsection:card_UNIV} \\label{subsection:cproper_interval}\\\n\n(*<*)context fixes dummy :: \"'a :: {card_UNIV, cproper_interval}\" begin(*>*)\ntext \\\n To deal with nested sets such as @{typ \"expr set set\"}, the element type must provide three operations from three type classes:\n \\begin{itemize}\n \\item @{class finite_UNIV} from theory @{theory \"HOL-Library.Cardinality\"} defines the constant @{term [source] \"finite_UNIV :: ('a, bool) phantom\"} which designates whether the type is finite.\n \\item @{class card_UNIV} from theory @{theory \"HOL-Library.Cardinality\"} defines the constant @{term [source] \"card_UNIV :: ('a, nat) phantom\"} which returns @{term \"CARD('a)\"}, i.e., the number of values in @{typ 'a}.\n If @{typ \"'a\"} is infinite, @{term \"CARD('a) = 0\"}.\n \\item @{class cproper_interval} from theory @{theory Containers.Collection_Order} defines the function @{term [source] \"cproper_interval :: 'a option \\ 'a option \\ bool\"}.\n If the type @{typ \"'a\"} is finite and @{term \"CCOMPARE('a)\"} yields a linear order on @{typ \"'a\"}, then @{term \"cproper_interval x y\"} returns whether the open interval between @{term \"x\"} and @{term \"y\"} is non-empty.\n The bound @{term \"None\"} denotes unboundedness.\n \\end{itemize}\n\n Note that the type class @{class finite_UNIV} must not be confused with the type class @{class finite}.\n @{class finite_UNIV} allows the generated code to examine whether a type is finite whereas @{class finite} requires that the type in fact is finite.\n\\\n(*<*)end(*>*)\n\ntext \\\n For datatypes, the theory @{theory Containers.Card_Datatype} defines some machinery to assist in proving that the type is (in)finite and has a given number of elements -- see @{file \\Examples/Card_Datatype_Ex.thy\\} for examples.\n With this, it is easy to instantiate @{class card_UNIV} for our running examples:\n\\\n\nlemma inj_expr [simp]: \"inj Lit\" \"inj Var\" \"inj Add\" \"inj (Add e)\"\nby(simp_all add: fun_eq_iff inj_on_def)\n\nlemma infinite_UNIV_expr: \"\\ finite (UNIV :: expr set)\"\n including card_datatype\nproof -\n have \"rangeIt (Lit 0) (Add (Lit 0)) \\ UNIV\" by simp\n from finite_subset[OF this] show ?thesis by auto\nqed\n\ninstantiation expr :: card_UNIV begin\ndefinition \"finite_UNIV = Phantom(expr) False\"\ndefinition \"card_UNIV = Phantom(expr) 0\"\ninstance\n by intro_classes\n (simp_all add: finite_UNIV_expr_def card_UNIV_expr_def infinite_UNIV_expr)\nend\n\nlemma inj_expr' [simp]: \"inj Lit'\" \"inj Var'\" \"inj Add'\" \"inj (Add' e)\"\nby(simp_all add: fun_eq_iff inj_on_def)\n\nlemma infinite_UNIV_expr': \"\\ finite (UNIV :: 'a expr' set)\"\n including card_datatype\nproof -\n have \"rangeIt (Lit' 0) (Add' (Lit' 0)) \\ UNIV\" by simp\n from finite_subset[OF this] show ?thesis by auto\nqed\n\ninstantiation expr' :: (type) card_UNIV begin\ndefinition \"finite_UNIV = Phantom('a expr') False\"\ndefinition \"card_UNIV = Phantom('a expr') 0\"\ninstance\n by intro_classes\n (simp_all add: finite_UNIV_expr'_def card_UNIV_expr'_def infinite_UNIV_expr')\nend\n\ntext \\\n As @{typ expr} and @{typ \"'a expr'\"} are infinite, instantiating @{class cproper_interval} is trivial,\n because @{class cproper_interval} only makes assumptions about its parameters for finite types.\n Nevertheless, it is important to actually define @{term cproper_interval}, because the\n code generator requires a code equation.\n\\\n\ninstantiation expr :: cproper_interval begin\ndefinition cproper_interval_expr :: \"expr proper_interval\" \n where \"cproper_interval_expr _ _ = undefined\"\ninstance by(intro_classes)(simp add: infinite_UNIV_expr)\nend\n\ninstantiation expr' :: (ccompare) cproper_interval begin\ndefinition cproper_interval_expr' :: \"'a expr' proper_interval\" \n where \"cproper_interval_expr' _ _ = undefined\"\ninstance by(intro_classes)(simp add: infinite_UNIV_expr')\nend\n\nsubsubsection \\Instantiation of @{class proper_interval}\\\n\ntext \\\n To illustrate what to do with finite types, we instantiate @{class proper_interval} for @{typ expr}.\n Like @{class ccompare} relates to @{class compare}, the class @{class cproper_interval} has a counterpart @{class proper_interval} without the finiteness assumption.\n Here, we first have to gather the simplification rules of the comparator from the derive\n invocation, especially, how the strict order of the comparator, @{term lt_of_comp}, can be defined.\n \n Since the order on lists is not yet shown to be consistent with the comparators that are used\n for lists, this part of the userguide is currently not available.\n \n\\\n(*\ninstantiation expr :: proper_interval begin\n\nlemma less_expr_conv: \"(<) = lt_of_comp comparator_expr\" \"(\\) = le_of_comp comparator_expr\"\n using less_expr_def less_eq_expr_def unfolding compare_expr_def by auto\n\nlemma lt_of_comp_expr: \"lt_of_comp comparator_expr e1 e2 = (\n case e1 of \n Var x1 \\ \n (case e2 of \n Var x2 \\ lt_of_comp (comparator_list comparator_of) x1 x2 \n | Lit _ \\ True\n | Add _ _ \\ True)\n | Lit i1 \\\n (case e2 of\n Var _ \\ False\n | Lit i2 \\ lt_of_comp comparator_of i1 i2\n | Add _ _ \\ True)\n | Add a1 b1 \\\n (case e2 of\n Var _ \\ False\n | Lit _ \\ False\n | Add a2 b2 \\ lt_of_comp comparator_expr a1 a2 \n \\ le_of_comp comparator_expr a1 a2 \\ lt_of_comp comparator_expr b1 b2) \n )\"\n by (simp add: lt_of_comp_def le_of_comp_def comp_lex_code split: expr.split order.split)\n \nfun proper_interval_expr :: \"expr option \\ expr option \\ bool\"\nwhere\n \"proper_interval_expr None (Some (Var x)) \\ proper_interval None (Some x)\"\n| \"proper_interval_expr (Some (Var x)) (Some (Var y)) \\ proper_interval (Some x) (Some y)\"\n| \"proper_interval_expr (Some (Lit i)) (Some (Lit j)) \\ proper_interval (Some i) (Some j)\"\n| \"proper_interval_expr (Some (Lit i)) (Some (Var x)) \\ False\"\n| \"proper_interval_expr (Some (Add e1 e2)) (Some (Lit i)) \\ False\"\n| \"proper_interval_expr (Some (Add e1 e2)) (Some (Var x)) \\ False\"\n| \"proper_interval_expr (Some (Add e1 e2)) (Some (Add e1' e2')) \\ \n (case compare e1 e1' of Lt \\ True | Eq \\ proper_interval_expr (Some e2) (Some e2') | Gt \\ False)\"\n| \"proper_interval_expr _ _ \\ True\"\n\ninstance\nproof(intro_classes)\n fix x y :: expr\n show \"proper_interval None (Some y) = (\\z. z < y)\"\n unfolding less_expr_conv\n by (cases y)(auto simp add: lt_of_comp_expr intro: exI[where x=\"''''\"])\n\n { fix x y have \"x < Add x y\" unfolding less_expr_conv \n by(induct x arbitrary: y)(simp_all add: lt_of_comp_expr) }\n note le_Add = this\n thus \"proper_interval (Some x) None = (\\z. x < z)\"\n by(simp add: less_expr_def exI[where x=\"Add x y\"])\n\n note [simp] = less_expr_conv lt_of_comp_expr\n\n show \"proper_interval (Some x) (Some y) = (\\z. x < z \\ z < y)\"\n proof(induct \"Some x\" \"Some y\" arbitrary: x y rule: proper_interval_expr.induct)\n case 2\n show ?case by(auto simp add: proper_interval_list_aux_correct)\n next\n case (3 i j)\n show ?case by(auto intro: exI[where x=\"Lit (i + 1)\"])\n next\n case (7 e1 e2 e1' e2')\n thus ?case by(auto intro: le_Add simp add: le_less)\n next\n case (\"8_2\" i e1 e2)\n show ?case by(auto intro: exI[where x=\"Lit (i + 1)\"])\n next\n case (\"8_5\" x i) show ?case\n by(auto intro: exI[where x=\"Var (x @ [undefined])\"] simp add: less_append_same_iff)\n next\n case (\"8_6\" x e1 e2) show ?case\n by(auto intro: exI[where x=\"Lit 0\"])\n next\n case (\"8_7\" i e1 e2) show ?case\n by(auto intro: exI[where x=\"Lit (i + 1)\"])\n next\n case (\"8_10\" x i) show ?case\n by(auto intro: exI[where x=\"Lit (i - 1)\"])\n next\n case (\"8_12\" x e1 e2) show ?case\n by(auto intro: exI[where x=\"Lit 0\"])\n next\n case (\"8_13\" i e1 e2) show ?case\n by(auto intro: exI[where x=\"Lit (i + 1)\"])\n qed auto\nqed simp\nend\n*)\n(*<*)\nvalue \"{{Lit 1}}\"\nvalue \"{{{Lit 1}}}\"\nvalue \"{{{{Lit 1}}}}\"\n(*>*)\n\nsection \\New implementations for containers\\\ntext_raw \\\\label{section:new:implementation}\\\n\n(*<*)\ntypedecl 'v trie_raw\n(*>*)\n\ntext \\\n This section explains how to add a new implementation for a container type.\n If you do so, please consider to add your implementation to this AFP entry.\n\\\n\nsubsection \\Model and verify the data structure\\\ntext_raw \\\\label{subsection:implement:data:structure}\\\ntext \\\n First, you of course have to define the data structure and verify that it has the required properties.\n As our running example, we use a trie to implement @{typ \"('a, 'b) mapping\"}.\n A trie is a binary tree whose the nodes store the values, the keys are the paths from the root to the given node.\n We use lists of @{typ bool}ans for the keys where the @{typ bool}ean indicates whether we should go to the left or right child.\n\n For brevity, we skip this step and rather assume that the type @{typ \"'v trie_raw\"} of tries has following operations and properties:\n\\\ntype_synonym trie_key = \"bool list\"\naxiomatization\n trie_empty :: \"'v trie_raw\" and\n trie_update :: \"trie_key \\ 'v \\ 'v trie_raw \\ 'v trie_raw\" and\n trie_lookup :: \"'v trie_raw \\ trie_key \\ 'v option\" and\n trie_keys :: \"'v trie_raw \\ trie_key set\"\nwhere trie_lookup_empty: \"trie_lookup trie_empty = Map.empty\"\n and trie_lookup_update: \n \"trie_lookup (trie_update k v t) = (trie_lookup t)(k \\ v)\"\n and trie_keys_dom_lookup: \"trie_keys t = dom (trie_lookup t)\"\n\ntext \\\n This is only a minimal example.\n A full-fledged implementation has to provide more operations and -- for efficiency -- should use more than just @{typ bool}eans for the keys.\n\\\n\n(*<*) (* Implement trie by free term algebra *)\ncode_datatype trie_empty trie_update\nlemmas [code] = trie_lookup_empty trie_lookup_update\n\nlemma trie_keys_empty [code]: \"trie_keys trie_empty = {}\"\nby(simp add: trie_keys_dom_lookup trie_lookup_empty)\n\nlemma trie_keys_update [code]:\n \"trie_keys (trie_update k v t) = insert k (trie_keys t)\"\nby(simp add: trie_keys_dom_lookup trie_lookup_update)\n(*>*)\n\nsubsection \\Generalise the data structure\\\ntext_raw \\\\label{subsection:introduce:type:class}\\\ntext \\\n As @{typ \"('k, 'v) mapping\"} store keys of arbitrary type @{typ \"'k\"}, not just @{typ \"trie_key\"}, we cannot use @{typ \"'v trie_raw\"} directly.\n Instead, we must first convert arbitrary types @{typ \"'k\"} into @{typ \"trie_key\"}.\n Of course, this is not always possbile, but we only have to make sure that we pick tries as implementation only if the types do.\n This is similar to red-black trees which require an order.\n Hence, we introduce a type class to convert arbitrary keys into trie keys.\n We make the conversions optional such that every type can instantiate the type class, just as LC does for @{class ceq} and @{class ccompare}.\n\\\ntype_synonym 'a cbl = \"(('a \\ bool list) \\ (bool list \\ 'a)) option\"\nclass cbl =\n fixes cbl :: \"'a cbl\"\n assumes inj_to_bl: \"ID cbl = Some (to_bl, from_bl) \\ inj to_bl\"\n and to_bl_inverse: \"ID cbl = Some (to_bl, from_bl) \\ from_bl (to_bl a) = a\"\nbegin\nabbreviation from_bl where \"from_bl \\ snd (the (ID cbl))\"\nabbreviation to_bl where \"to_bl \\ fst (the (ID cbl))\"\nend\n\ntext \\\n It is best to immediately provide the instances for as many types as possible.\n Here, we only present two examples: @{typ unit} provides conversion functions, @{typ \"'a \\ 'b\"} does not.\n\\\ninstantiation unit :: cbl begin\ndefinition \"cbl = Some (\\_. [], \\_. ())\"\ninstance by(intro_classes)(auto simp add: cbl_unit_def ID_Some intro: injI)\nend\n\ninstantiation \"fun\" :: (type, type) cbl begin\ndefinition \"cbl = (None :: ('a \\ 'b) cbl)\"\ninstance by intro_classes(simp_all add: cbl_fun_def ID_None)\nend\n\nsubsection \\Hide the invariants of the data structure\\\ntext_raw \\\\label{subsection:hide:invariants}\\\ntext \\\n Many data structures have invariants on which the operations rely.\n You must hide such invariants in a \\isamarkuptrue\\isacommand{typedef}\\isamarkupfalse{} before connecting to the container, because the code generator cannot handle explicit invariants.\n The type must be inhabited even if the types of the elements do not provide the required operations.\n The easiest way is often to ignore all invariants in that case.\n\n In our example, we require that all keys in the trie represent encoded values.\n\\\ntypedef (overloaded) ('k :: cbl, 'v) trie = \n \"{t :: 'v trie_raw. \n trie_keys t \\ range (to_bl :: 'k \\ trie_key) \\ ID (cbl :: 'k cbl) = None}\"\nproof\n show \"trie_empty \\ ?trie\"\n by(simp add: trie_keys_dom_lookup trie_lookup_empty)\nqed\n\ntext \\\n Next, transfer the operations to the new type.\n The transfer package does a good job here.\n\\\n\nsetup_lifting type_definition_trie \\ \\also sets up code generation\\\n\nlift_definition empty :: \"('k :: cbl, 'v) trie\" \n is trie_empty\n by(simp add: trie_keys_empty)\n\nlift_definition lookup :: \"('k :: cbl, 'v) trie \\ 'k \\ 'v option\"\n is \"\\t. trie_lookup t \\ to_bl\" .\n\nlift_definition update :: \"'k \\ 'v \\ ('k :: cbl, 'v) trie \\ ('k, 'v) trie\"\n is \"trie_update \\ to_bl\"\n by(auto simp add: trie_keys_dom_lookup trie_lookup_update)\n\nlift_definition keys :: \"('k :: cbl, 'v) trie \\ 'k set\"\n is \"\\t. from_bl ` trie_keys t\" .\n\ntext \\\n And now we go for the properties.\n Note that some properties hold only if the type class operations are actually provided, i.e., @{term \"cbl \\ None\"} in our example.\n\\\n\nlemma lookup_empty: \"lookup empty = Map.empty\"\nby transfer(simp add: trie_lookup_empty fun_eq_iff)\n\ncontext\n fixes t :: \"('k :: cbl, 'v) trie\"\n assumes ID_cbl: \"ID (cbl :: 'k cbl) \\ None\"\nbegin\n\nlemma lookup_update: \"lookup (update k v t) = (lookup t)(k \\ v)\"\nusing ID_cbl\nby transfer(auto simp add: trie_lookup_update fun_eq_iff dest: inj_to_bl[THEN injD])\n\nlemma keys_conv_dom_lookup: \"keys t = dom (lookup t)\"\nusing ID_cbl\nby transfer(force simp add: trie_keys_dom_lookup to_bl_inverse intro: rev_image_eqI)\n\nend\n\nsubsection \\Connecting to the container\\\ntext_raw \\\\label{subsection:connect:container}\\\ntext \\\n Connecting to the container (@{typ \"('a, 'b) mapping\"} in our example) takes three steps:\n \\begin{enumerate}\n \\item Define a new pseudo-constructor\n \\item Implement the container operations for the new type\n \\item Configure the heuristics to automatically pick an implementation\n \\item Test thoroughly\n \\end{enumerate}\n Thorough testing is particularly important, because Isabelle does not check whether you have implemented all your operations, whether you have configured your heuristics sensibly, nor whether your implementation always terminates.\n\\\n\nsubsubsection \\Define a new pseudo-constructor\\\n\ntext \\\n Define a function that returns the abstract container view for a data structure value, and declare it as a datatype constructor for code generation with \\isamarkuptrue\\isacommand{code{\\isacharunderscore}datatype}\\isamarkupfalse.\n Unfortunately, you have to repeat all existing pseudo-constructors, because there is no way to extract the current set of pseudo-constructors from the code generator.\n We call them pseudo-constructors, because they do not behave like datatype constructors in the logic.\n For example, ours are neither injective nor disjoint.\n\\\n\ndefinition Trie_Mapping :: \"('k :: cbl, 'v) trie \\ ('k, 'v) mapping\" \nwhere [simp, code del]: \"Trie_Mapping t = Mapping.Mapping (lookup t)\"\n\ncode_datatype Assoc_List_Mapping RBT_Mapping Mapping Trie_Mapping\n\nsubsubsection \\Implement the operations\\\n\ntext \\\n Next, you have to prove and declare code equations that implement the container operations for the new implementation.\n Typically, these just dispatch to the operations on the type from \\S\\ref{subsection:hide:invariants}.\n Some operations depend on the type class operations from \\S\\ref{subsection:introduce:type:class} being defined; then, the code equation must check that the operations are indeed defined.\n If not, there is usually no way to implement the operation, so the code should raise an exception.\n Logically, we use the function @{term \"Code.abort\"} of type @{typ \"String.literal \\ (unit \\ 'a) \\ 'a\"} with definition @{term \"\\_ f. f ()\"}, but the generated code raises an exception \\texttt{Fail} with the given message (the unit closure avoids non-termination in strict languages).\n This function gets the exception message and the unit-closure of the equation's left-hand side as argument, because it is then trivial to prove equality.\n\n Again, we only show a small set of operations; a realistic implementation should cover as many as possible.\n\\\ncontext fixes t :: \"('k :: cbl, 'v) trie\" begin\n\nlemma lookup_Trie_Mapping [code]:\n \"Mapping.lookup (Trie_Mapping t) = lookup t\"\n \\ \\Lookup does not need the check on @{term cbl},\n because we have defined the pseudo-constructor @{term Trie_Mapping} in terms of @{term \"lookup\"}\\\nby simp(transfer, simp)\n\nlemma update_Trie_Mapping [code]:\n \"Mapping.update k v (Trie_Mapping t) = \n (case ID cbl :: 'k cbl of\n None \\ Code.abort (STR ''update Trie_Mapping: cbl = None'') (\\_. Mapping.update k v (Trie_Mapping t))\n | Some _ \\ Trie_Mapping (update k v t))\"\nby(simp split: option.split add: lookup_update Mapping.update.abs_eq)\n\nlemma keys_Trie_Mapping [code]:\n \"Mapping.keys (Trie_Mapping t) =\n (case ID cbl :: 'k cbl of\n None \\ Code.abort (STR ''keys Trie_Mapping: cbl = None'') (\\_. Mapping.keys (Trie_Mapping t))\n | Some _ \\ keys t)\"\nby(simp add: Mapping.keys.abs_eq keys_conv_dom_lookup split: option.split)\n\nend\n\ntext \\\n These equations do not replace the existing equations for the other constructors, but they do take precedence over them.\n If there is already a generic implementation for an operation @{term \"foo\"}, say @{term \"foo A = gen_foo A\"}, and you prove a specialised equation @{term \"foo (Trie_Mapping t) = trie_foo t\"}, then when you call @{term \"foo\"} on some @{term \"Trie_Mapping t\"}, your equation will kick in.\n LC exploits this sequentiality especially for binary operators on sets like @{term \"(\\)\"}, where there are generic implementations and faster specialised ones.\n\\\n\nsubsubsection \\Configure the heuristics\\\n\ntext \\\n Finally, you should setup the heuristics that automatically picks a container implementation based on the types of the elements (\\S\\ref{subsection:set_impl}).\n\n The heuristics uses a type with a single value, e.g., @{typ mapping_impl} with value @{term Mapping_IMPL}, but there is one pseudo-constructor for each container implementation in the generated code.\n All these pseudo-constructors are the same in the logic, but they are different in the generated code.\n Hence, the generated code can distinguish them, but we do not have to commit to anything in the logic.\n This allows to reconfigure and extend the heuristic at any time.\n\n First, define and declare a new pseudo-constructor for the heuristics.\n Again, be sure to redeclare all previous pseudo-constructors.\n\\\ndefinition mapping_Trie :: mapping_impl \nwhere [simp]: \"mapping_Trie = Mapping_IMPL\"\n\ncode_datatype \n mapping_Choose mapping_Assoc_List mapping_RBT mapping_Mapping mapping_Trie\n\ntext \\\n Then, adjust the implementation of the automatic choice.\n For every initial value of the container (such as the empty map or the empty set), there is one new constant (e.g., @{term mapping_empty_choose} and @{term set_empty_choose}) equivalent to it.\n Its code equation, however, checks the available operations from the type classes and picks an appropriate implementation.\n \n For example, the following prefers red-black trees over tries, but tries over associative lists:\n\\\n\nlemma mapping_empty_choose_code [code]:\n \"(mapping_empty_choose :: ('a :: {ccompare, cbl}, 'b) mapping) =\n (case ID CCOMPARE('a) of Some _ \\ RBT_Mapping RBT_Mapping2.empty\n | None \\\n case ID (cbl :: 'a cbl) of Some _ \\ Trie_Mapping empty \n | None \\ Assoc_List_Mapping DAList.empty)\"\nby(auto split: option.split simp add: DAList.lookup_empty[abs_def] Mapping.empty_def lookup_empty)\n\ntext \\\n There is also a second function for every such initial value that dispatches on the pseudo-constructors for @{typ mapping_impl}.\n This function is used to pick the right implementation for types that specify a preference.\n\\\nlemma mapping_empty_code [code]:\n \"mapping_empty mapping_Trie = Trie_Mapping empty\"\nby(simp add: lookup_empty Mapping.empty_def)\n\ntext \\\n For @{typ \"('k, 'v) mapping\"}, LC also has a function @{term \"mapping_impl_choose2\"} which is given two preferences and returns one (for @{typ \"'a set\"}, it is called @{term \"set_impl_choose2\"}).\n Polymorphic type constructors like @{typ \"'a + 'b\"} use it to pick an implementation based on the preferences of @{typ \"'a\"} and @{typ \"'b\"}.\n By default, it returns @{term mapping_Choose}, i.e., ignore the preferences.\n You should add a code equation like the following that overrides this choice if both preferences are your new data structure:\n\\\n\nlemma mapping_impl_choose2_Trie [code]:\n \"mapping_impl_choose2 mapping_Trie mapping_Trie = mapping_Trie\"\nby(simp add: mapping_Trie_def)\n\ntext \\\n If your new data structure is better than the existing ones for some element type, you should reconfigure the type's preferene.\n As all preferences are logically equal, you can prove (and declare) the appropriate code equation.\n For example, the following prefers tries for keys of type @{typ \"unit\"}:\n\\\n\nlemma mapping_impl_unit_Trie [code]:\n \"MAPPING_IMPL(unit) = Phantom(unit) mapping_Trie\"\nby(simp add: mapping_impl_unit_def)\n\nvalue \"Mapping.empty :: (unit, int) mapping\"\n\ntext \\\n You can also use your new pseudo-constructor with \\derive\\ in instantiations, just give its name as option:\n\\\nderive (mapping_Trie) mapping_impl simple_tycon\n\nsection \\Changing the configuration\\\n\ntext \\\n As containers are connected to data structures only by refinement in the code generator, this can always be adapted later on.\n You can add new data structures as explained in \\S\\ref{section:new:implementation}.\n If you want to drop one, you redeclare the remaining pseudo-constructors with \\isamarkuptrue\\isacommand{code{\\isacharunderscore}datatype}\\isamarkupfalse{} and delete all code equations that pattern-match on the obsolete pseudo-constructors.\n The command \\isamarkuptrue\\isacommand{code{\\isacharunderscore}thms}\\isamarkupfalse{} will tell you which constants have such code equations.\n You can also freely adapt the heuristics for picking implementations as described in \\S\\ref{subsection:connect:container}.\n\n One thing, however, you cannot change afterwards, namely the decision whether an element type supports an operation and if so how it does, because this decision is visible in the logic.\n\\\n\nsection \\New containers types\\\n\ntext \\\n We hope that the above explanations and the examples with sets and maps suffice to show what you need to do if you add a new container type, e.g., priority queues.\n There are three steps:\n \\begin{enumerate}\n \\item \\textbf{Introduce a type constructor for the container.}\n \\\\\n Your new container type must not be a composite type, like @{typ \"'a \\ 'b option\"} for maps, because refinement for code generation only works with a single type constructor.\n Neither should you reuse a type constructor that is used already in other contexts, e.g., do not use @{typ \"'a list\"} to model queues.\n\n Introduce a new type constructor if necessary (e.g., @{typ \"('a, 'b) mapping\"} for maps) -- if your container type already has its own type constructor, everything is fine.\n\n \\item \\textbf{Implement the data structures} \n \\\\\n and connect them to the container type as described in \\S\\ref{section:new:implementation}.\n\n \\item \\textbf{Define a heuristics for picking an implementation.}\n \\\\\n See \\<^cite>\\\"Lochbihler2013ITP\"\\ for an explanation.\n \\end{enumerate}\n\\\n\nsection \\Troubleshooting\\\n\ntext \\\n This section describes some difficulties in using LC that we have come across, provides some background for them, and discusses how to overcome them.\n If you experience other difficulties, please contact the author.\n\\\n\nsubsection \\Nesting of mappings\\\n\ntext \\\n Mappings can be arbitrarily nested on the value side, e.g., @{typ \"('a, ('b, 'c) mapping) mapping\"}.\n However, @{typ \"('a, 'b) mapping\"} cannot currently be the key of a mapping, i.e., code generation fails for @{typ \"(('a, 'b) mapping, 'c) mapping\"}.\n Simiarly, you cannot have a set of mappings like @{typ \"('a, 'b) mapping set\"} at the moment.\n There are no issues to make this work, we have just not seen the need for it.\n If you need to generate code for such types, please get in touch with the author.\n\\\n\nsubsection \\Wellsortedness errors\\\ntext_raw \\\\label{subsection:well:sortedness}\\\n\ntext \\\n LC uses its own hierarchy of type classes which is distinct from Isabelle/HOL's.\n This ensures that every type can be made an instance of LC's type classes.\n Consequently, you must instantiate these classes for your own types.\n The following lists where you can find information about the classes and examples how to instantiate them:\n \\begin{center}\n \\begin{tabular}{lll}\n \\textbf{type class} & \\textbf{user guide} & \\textbf{theory}\n \\\\\n @{class card_UNIV} & \\S\\ref{subsection:card_UNIV} & @{theory \"HOL-Library.Cardinality\"} \n %@{term \"Cardinality.card_UNIV_class\"}\n \\\\\n @{class cenum} & \\S\\ref{subsection:cenum} & @{theory Containers.Collection_Enum}\n %@{term \"Collection_Enum.cenum_class\"}\n \\\\\n @{class ceq} & \\S\\ref{subsection:ceq} & @{theory Containers.Collection_Eq}\n %@{term \"Collection_Eq.ceq_class\"}\n \\\\\n @{class ccompare} & \\S\\ref{subsection:ccompare} & @{theory Containers.Collection_Order}\n %@{term \"Collection_Order.ccompare_class\"}\n \\\\\n @{class cproper_interval} & \\S\\ref{subsection:cproper_interval} & @{theory Containers.Collection_Order}\n %@{term \"Collection_Order.cproper_interval_class\"}\n \\\\\n @{class finite_UNIV} & \\S\\ref{subsection:finite_UNIV} & @{theory \"HOL-Library.Cardinality\"}\n %@{term \"Cardinality.finite_UNIV_class\"}\n \\\\\n @{class mapping_impl} & \\S\\ref{subsection:mapping_impl} & @{theory Containers.Mapping_Impl}\n %@{term \"Mapping_Impl.mapping_impl_class\"}\n \\\\\n @{class set_impl} & \\S\\ref{subsection:set_impl} & @{theory Containers.Set_Impl}\n %@{term \"Set_Impl.set_impl_class\"}\n \\\\\n \\end{tabular}\n \\end{center}\n\n The type classes @{class card_UNIV} and @{class cproper_interval} are only required to implement the operations on set complements.\n If your code does not need complements, you can manually delete the code equations involving @{const \"Complement\"}, the theorem list @{thm [source] set_complement_code} collects them.\n It is also recommended that you remove the pseudo-constructor @{const Complement} from the code generator.\n Note that some set operations like @{term \"A - B\"} and @{const UNIV} have no code equations any more.\n\\\ndeclare set_complement_code[code del]\ncode_datatype Collect_set DList_set RBT_set Set_Monad\n(*<*)\ndatatype minimal_sorts = Minimal_Sorts bool\nderive (eq) ceq minimal_sorts\nderive (no) ccompare minimal_sorts\nderive (monad) set_impl minimal_sorts\nderive (no) cenum minimal_sorts\nvalue \"{Minimal_Sorts True} \\ {} \\ Minimal_Sorts ` {True, False}\"\n(*>*)\n\nsubsection \\Exception raised at run-time\\\ntext_raw \\\\label{subsection:set_impl_unsupported_operation}\\\n\ntext \\\n Not all combinations of data and container implementation are possible.\n For example, you cannot implement a set of functions with a RBT, because there is no order on @{typ \"'a \\ 'b\"}.\n If you try, the code will raise an exception \\texttt{Fail} (with an exception message) or \\texttt{Match}.\n They can occur in three cases:\n\n \\begin{enumerate}\n \\item\n You have misconfigured the heuristics that picks implementations (\\S\\ref{subsection:set_impl}), or you have manually picked an implementation that requires an operation that the element type does not provide.\n Printing a stack trace for the exception may help you in locating the error.\n\n \\item You are trying to invoke an operation on a set complement which cannot be implemented on a complement representation, e.g., @{term \"(`)\"}.\n If the element type is enumerable, provide an instance of @{class cenum} and choose to represent complements of sets of enumerable types by the elements rather than the elements of the complement (see \\S\\ref{subsection:cenum} for how to do this).\n\n \\item You use set comprehensions on types which do not provide an enumeration (i.e., they are represented as closures) or you chose to represent a map as a closure.\n\n A lot of operations are not implementable for closures, in particular those that return some element of the container\n\n Inspect the code equations with \\isacommand{code{\\isacharunderscore}thms} and look for calls to @{term \"Collect_set\"} and @{term \"Mapping\"} which are LC's constructor for sets and maps as closures.\n\n Note that the code generator preprocesses set comprehensions like @{term \"{i < 4|i :: int. i > 2}\"} to @{term \"(\\i :: int. i < 4) ` {i. i > 2}\"}, so this is a set comprehension over @{typ int} rather than @{typ bool}.\n \\end{enumerate}\n\\\n\n(*<*)\ndefinition test_set_impl_unsupported_operation1 :: \"unit \\ (int \\ int) set\"\nwhere \"test_set_impl_unsupported_operation1 _ = RBT_set RBT_Set2.empty \\ {}\"\n\ndefinition test_set_impl_unsupported_operation2 :: \"unit \\ bool set\"\nwhere \"test_set_impl_unsupported_operation2 _ = {i < 4 | i :: int. i > 2}\"\n\ndefinition test_mapping_impl_unsupported_operation :: \"unit \\ bool\"\nwhere \n \"test_mapping_impl_unsupported_operation _ = \n Mapping.is_empty (RBT_Mapping (RBT_Mapping2.empty) :: (Enum.finite_4, unit) mapping)\"\n\nML_val \\\nfun test_fail s f =\n let\n fun error s' = Fail (\"exception Fail \\\"\" ^ s ^ \"\\\" expected, but got \" ^ s')\n in\n (f (); raise (error \"no exception\") )\n handle\n Fail s' => if s = s' then () else raise (error s')\n end;\n\ntest_fail \"union RBT_set Set_Monad: ccompare = None\" @{code test_set_impl_unsupported_operation1};\ntest_fail \"image Collect_set\" @{code test_set_impl_unsupported_operation2};\ntest_fail \"is_empty RBT_Mapping: ccompare = None\" @{code test_mapping_impl_unsupported_operation};\n\\\n(*>*)\n\nsubsection \\LC slows down my code\\\n\ntext \\\n Normally, this will not happen, because LC's data structures are more efficient than Isabelle's list-based implementations.\n However, in some rare cases, you can experience a slowdown:\n\\\n(*<*)\ndefinition tiny_set :: \"nat set\"\nwhere tiny_set_code: \"tiny_set = {1, 2}\"\n(*>*)\ntext_raw \\\n \\isastyletext\n \\begin{enumerate}\n \\item \\textbf{Your containers contain just a few elements.}\n \\\\\n In that case, the overhead of the heuristics to pick an implementation outweighs the benefits of efficient implementations.\n You should identify the tiny containers and disable the heuristics locally.\n You do so by replacing the initial value like @{term \"{}\"} and @{term \"Mapping.empty\"} with low-overhead constructors like @{term \"Set_Monad\"} and @{term \"Mapping\"}.\n For example, if @{thm [source] tiny_set_code}: @{thm tiny_set_code} is your code equation with a tiny set,\n the following changes the code equation to directly use the list-based representation, i.e., disables the heuristics:\n \\par\n\\\nlemma empty_Set_Monad: \"{} = Set_Monad []\" by simp\ndeclare tiny_set_code[code del, unfolded empty_Set_Monad, code]\ntext_raw \\\n \\isastyletext\n \\par\n If you want to globally disable the heuristics, you can also declare an equation like @{thm [source] empty_Set_Monad} as [code].\n\n \\item \\textbf{The element type contains many type constructors and some type variables.}\n \\\\\n LC heavily relies on type classes, and type classes are implemented as dictionaries if the compiler cannot statically resolve them, i.e., if there are type variables.\n For type constructors with type variables (like @{typ \"'a * 'b\"}), LC's definitions of the type class parameters recursively calls itself on the type variables, i.e., @{typ \"'a\"} and @{typ \"'b\"}.\n If the element type is polymorphic, the compiler cannot precompute these recursive calls and therefore they have to be constructed repeatedly at run time.\n If you wrap your complicated type in a new type constructor, you can define optimised equations for the type class parameters.\n \\end{enumerate}\n\\\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Containers/Containers_Userguide.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.1347759261111811, "lm_q1q2_score": 0.06161102436985036}} {"text": "(*\n * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *)\n\n(*<*)\ntheory Chapter1_MinMax\nimports \"AutoCorres.AutoCorres\"\nbegin\n\nexternal_file \"minmax.c\"\n(*>*)\n\nsection \\Introduction\\\n\ntext \\\n\n AutoCorres is a tool that attempts to simplify the formal verification of C\n programs in the Isabelle/HOL theorem prover. It allows C code\n to be automatically abstracted to produce a higher-level functional\n specification.\n\n AutoCorres relies on the C-Parser~\\cite{CParser_download} developed by Michael Norrish\n at NICTA. This tool takes raw C code as input and produces a translation in\n SIMPL~\\cite{Simpl-AFP}, an imperative language written by Norbert Schirmer on top\n of Isabelle. AutoCorres takes this SIMPL code to produce a \"monadic\"\n specification, which is intended to be simpler to reason about in Isabelle.\n The composition of these two tools (AutoCorres applied after the C-Parser) can\n then be used to reason about C programs.\n\n This guide is written for users of Isabelle/HOL, with some knowledge of C, to\n get started proving properties of C programs. Using AutoCorres in conjunction\n with the verification condition generator (VCG) \\texttt{wp}, one\n should be able to do this without an understanding of SIMPL nor of the monadic\n representation produced by AutoCorres. We will see how this is possible in the\n next chapter.\n\n\\\n\nsection \\A First Proof with AutoCorres\\\n\ntext \\\n\n We will now show how to use these tools to prove correctness of some very\n simple C functions.\n\n\\\n\nsubsection \\Two simple functions: \\texttt{min} and \\texttt{max}\\\n\ntext \\\n\n Consider the following two functions, defined in a file \\texttt{minmax.c},\n which (we expect) return the minimum and maximum respectively of two unsigned\n integers.\n\n \\lstinputlisting[language=C, firstline=13]{minmax.c}\n\n It is easy to see that \\texttt{min} is correct, but perhaps less obvious why\n \\texttt{max} is correct. AutoCorres will hopefully allow us to prove these\n claims without too much effort.\n\n\\\n\nsubsection \\Invoking the C-parser\\\n\ntext \\\n\n As mentioned earlier, AutoCorres does not handle C code directly. The first\n step is to apply the\n C-Parser\\footnote{\\url{https://trustworthy.systems/software/TS/c-parser}} to\n obtain a SIMPL translation. We do this using the \\texttt{install-C-file}\n command in Isabelle, as shown.\n\n\\\n\ninstall_C_file \"minmax.c\"\n\n(* FIXME: Be consistent with \\texttt and \\emph *)\ntext \\\n\n For every function in the C source file, the C-Parser generates a\n corresponding Isabelle definition. These definitions are placed in an Isabelle\n \"locale\", whose name matches the input filename. For our file \\emph{minmax.c},\n the C-Parser will place definitions in the locale \\emph{minmax}.\\footnote{The\n C-parser uses locales to avoid having to make certain assumptions about the\n behaviour of the linker, such as the concrete addresses of symbols in your\n program.}\n\n For our purposes, we just have to remember to enter the appropriate locale\n before writing our proofs. This is done using the \\texttt{context} keyword in\n Isabelle.\n\n Let's look at the C-Parser's outputs for \\texttt{min} and \\texttt{max}, which\n are contained in the theorems \\texttt{min\\_body\\_def} and \\texttt{max\\_body\\_def}.\n These are simply definitions of the generated names \\emph{min\\_body} and\n \\emph{max\\_body}. We can also see here how our work is wrapped within the\n \\emph{minmax} context.\n\n\\\n\ncontext minmax begin\n\n thm min_body_def\n text \\@{thm [display] min_body_def}\\\n thm max_body_def\n text \\@{thm [display] max_body_def}\\\n\nend\n\ntext \\\n\n The definitions above show us the SIMPL generated for each of the\n functions; we can see that C-parser has translated \\texttt{min} and\n \\texttt{max} very literally and no detail of the C language has been\n omitted. For example:\n\n \\begin{itemize}\n \\item C \\texttt{return} statements have been translated into\n exceptions which are caught at the outside of the\n function's body;\n\n \\item \\emph{Guard} statements are used to ensure that behaviour\n deemed `undefined' by the C standard does not occur. In the\n above functions, we see that a guard statement is emitted\n that ensures that program execution does not hit the end\n of the function, ensuring that we always return a value\n (as is required by all non-\\texttt{void} functions).\n\n \\item Function parameters are modelled as local variables, which\n are setup prior to a function being called. Return variables\n are also modelled as local variables, which are then\n read by the caller.\n \\end{itemize}\n\n While a literal translation of C helps to improve confidence that the\n translation is sound, it does tend to make formal reasoning an arduous\n task.\n\n\\\n\nsubsection \\Invoking AutoCorres\\\n\ntext \\\n\n Now let's use AutoCorres to simplify our functions. This is done using\n the \\texttt{autocorres} command, in a similar manner to the\n \\texttt{install\\_C\\_file} command:\n\n\\\n\nautocorres \"minmax.c\"\n\ntext \\\n\n AutoCorres produces a definition in the \\texttt{minmax} locale\n for each function body produced by the C parser. For example,\n our \\texttt{min} function is defined as follows:\n\n\\\ncontext minmax begin\nthm min'_def\ntext \\@{thm [display] min'_def}\\\n\ntext \\\n\n Each function's definition is named identically to its name in\n C, but with a prime mark (\\texttt{'}) appended. For example,\n our functions \\texttt{min} above was named @{term min'}, while\n the function \\texttt{foo\\_Bar} would be named @{term foo_Bar'}.\n\n AutoCorres does not require you to trust its translation is sound,\n but also emits a \\emph{correspondence} or \\emph{refinement} proof,\n as follows:\n\n\\\n\n(* FIXME *)\n(* thm min_autocorres *)\n\ntext \\\n\n Informally, this theorem states that, assuming the abstract function\n @{term min'} can be proven to not fail for a partciular input, then\n for the associated input, the concrete C SIMPL program also will not\n fault, will always terminate, and will have a corresponding end state\n to the generated abstract program.\n\n For more technical details, see~\\cite{Greenaway_AK_12} and~\\cite{Greenaway_LAK_14}.\n\n\\\n\nsubsection \\Verifying \\texttt{min}\\\n\ntext \\\n\n In the abstracted version of @{term min'}, we can see that AutoCorres\n has simplified away the local variable reads and writes in the\n C-parser translation of \\texttt{min}, simplified away the exception\n throwing and handling code, and also simplified away the unreachable\n guard statement at the end of the function. In fact, @{term min'} has\n been simplified to the point that it exactly matches Isabelle's\n built-in function @{term min}:\n\n\\\nthm min_def\ntext \\@{thm [display] min_def}\\\n\ntext \\\n So, verifying @{term min'} (and by extension, the C function\n \\texttt{min}) should be easy:\n\\\nlemma min'_is_min: \"min' a b = min a b\"\n unfolding min_def min'_def\n by (rule refl)\n\nsubsection \\Verifying \\texttt{max}\\\n\ntext \\\n\n Now we also wish to verify that @{term max'} implements the built-in\n function @{term max}. @{term min'} was nearly too simple to bother\n verifying, but @{term max'} is a bit more complicated. Let's look at\n AutoCorres' output for \\texttt{max}:\n\n\\\nthm max'_def\ntext \\@{thm [display] max'_def}\\\n\ntext \\\n\n At this point, you might still doubt that @{term max'} is indeed\n correct, so perhaps a proof is in order. The basic idea is that\n subtracting from \\texttt{UINT\\_MAX} flips the ordering of unsigned\n ints. We can then use @{term min'} on the flipped numbers to compute\n the maximum.\n\n The next lemma proves that subtracting from \\texttt{UINT\\_MAX} flips\n the ordering. To prove it, we convert all words to @{typ int}'s, which\n does not change the meaning of the statement.\n\n\\\n\n lemma n1_minus_flips_ord:\n \"((a :: word32) \\ b) = ((-1 - a) \\ (-1 - b))\"\n apply (subst word_le_def)+\n apply (subst word_n1_ge [simplified uint_minus_simple_alt])+\n txt \\Now that our statement uses @{typ int}, we can apply Isabelle's built-in \\texttt{arith} method.\\\n apply arith\n done\n\ntext \\\n And now for the main proof:\n\\\n lemma max'_is_max: \"max' a b = max a b\"\n unfolding max'_def min'_def max_def\n using n1_minus_flips_ord\n by force\n\nend\n\ntext \\\n In the next section, we will see how to use AutoCorres to simplify\n larger, more realistic C programs.\n\\\n\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "seL4", "repo": "l4v", "sha": "9ba34e269008732d4f89fb7a7e32337ffdd09ff9", "save_path": "github-repos/isabelle/seL4-l4v", "path": "github-repos/isabelle/seL4-l4v/l4v-9ba34e269008732d4f89fb7a7e32337ffdd09ff9/tools/autocorres/doc/quickstart/Chapter1_MinMax.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.32766830082071396, "lm_q2_score": 0.18713268896245422, "lm_q1q2_score": 0.06131745022033855}} {"text": "theory Chapter8\nimports \"HOL-IMP.Compiler\" \"Short_Theory\"\nbegin\n\ntext\\\n\\section*{Chapter 8}\n\nFor the following exercises copy and adjust theory @{short_theory \"Compiler\"}.\nIntrepid readers only should attempt to adjust theory @{text Compiler2} too.\n\n\\begin{exercise}\nA common programming idiom is @{text \"IF b THEN c\"}, i.e.,\nthe @{text ELSE}-branch is a @{term SKIP} command.\nLook at how, for example, the command @{term \"IF Less (V ''x'') (N 5) THEN ''y'' ::= N 3 ELSE SKIP\"}\nis compiled by @{const ccomp} and identify a possible compiler optimization.\nModify the definition of @{const ccomp} such that it generates fewer instructions\nfor commands of the form @{term \"IF b THEN c ELSE SKIP\"}.\nIdeally the proof of theorem @{thm[source] ccomp_bigstep} should still work;\notherwise adapt it.\n\\end{exercise}\n\n\\begin{exercise}\nBuilding on Exercise~\\ref{exe:IMP:REPEAT}, extend the compiler @{const ccomp}\nand its correctness theorem @{thm[source] ccomp_bigstep} to @{text REPEAT}\nloops. Hint: the recursion pattern of the big-step semantics\nand the compiler for @{text REPEAT} should match.\n\\end{exercise}\n\n\\begin{exercise}\\label{exe:COMP:addresses}\nModify the machine language such that instead of variable names to values,\nthe machine state maps addresses (integers) to values. Adjust the compiler\nand its proof accordingly.\n\nIn the simple version of this exercise, assume the existence of a globally\nbijective function @{term \"addr_of :: vname => int\"} with @{term \"bij addr_of\"}\nto adjust the compiler. Use the @{text find_theorems} search to find applicable\ntheorems for bijectivte functions.\n\nFor the more advanced version and a slightly larger project, only assume that\nthe function works on a finite set of variables: those that occur in the\nprogram. For the other, unused variables, it should return a suitable default\naddress. In this version, you may want to split the work into two parts:\nfirst, update the compiler and machine language, assuming the existence of\nsuch a function and the (partial) inverse it provides. Second, separately\nconstruct this function from the input program, having extracted the\nproperties needed for it in the first part. In the end, rearrange you theory\nfile to combine both into a final theorem.\n\\end{exercise}\n\n\\begin{exercise}\nThis is a slightly more challenging project. Based on\n\\autoref{exe:COMP:addresses}, and similarly to \\autoref{exe:register-machine}\nand \\autoref{exe:accumulator}, define a second machine language that does not\npossess a built-in stack, but instead, in addition to the program counter, a\nstack pointer register. Operations that previously worked on the stack now\nwork on memory, accessing locations based on the stack pointer.\n\nFor instance, let @{term \"(pc, s, sp)\"} be a configuration of this new machine consisting of\nprogram counter, store, and stack pointer. Then the configuration after an @{const ADD} instruction\nis \\mbox{@{term \"(pc + 1::int, s(sp + 1 := s (sp + 1::int) + s sp), sp + 1)\"}}, that is, @{const ADD} dereferences\nthe memory at @{term \"sp + 1::int\"} and @{term sp}, adds these two values and stores them at\n@{term \"sp + 1::int\"}, updating the values on the stack. It also increases the stack pointer by one\nto pop one value from the stack and leave the result at the top of the stack. This means the stack grows downwards.\n\nModify the compiler from \\autoref{exe:COMP:addresses} to work on this new machine language. Reformulate and reprove the easy direction of compiler correctness.\n\n\\emph{Hint:} Let the stack start below @{text 0}, growing downwards, and use type @{typ nat} for addressing variable in @{const LOAD} and @{const STORE} instructions, so that it is clear by type that these instructions do not interfere with the stack.\n\n\\emph{Hint:} When the new machine pops a value from the stack, this now unused value is left behind in the store. This means, even after executing a purely arithmetic expression, the values in initial and final stores are not all equal. But: they are equal above a given address. Define an abbreviation for this concept and use it to express the intermediate correctness statements.\n\n\\end{exercise}\n\n\\\nend\n\n", "meta": {"author": "david-wang-0", "repo": "concrete-semantics", "sha": "master", "save_path": "github-repos/isabelle/david-wang-0-concrete-semantics", "path": "github-repos/isabelle/david-wang-0-concrete-semantics/concrete-semantics-main/templates/Chapter8.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.13846179767920996, "lm_q1q2_score": 0.061154838350703934}} {"text": "(* Title: Uint_Userguide.thy\n Author: Andreas Lochbihler, ETH Zurich\n*)\n\nchapter \\User guide for native words\\\n\n(*<*)\ntheory Uint_Userguide imports\n Uint32\n Uint16\n Code_Target_Bits_Int\nbegin\n(*>*)\n\ntext \\\n This tutorial explains how to best use the types for native\n words like @{typ \"uint32\"} in your formalisation.\n You can base your formalisation\n \\begin{enumerate}\n \\item either directly on these types,\n \\item or on the generic @{typ \"'a word\"} and only introduce native\n words a posteriori via code generator refinement.\n \\end{enumerate}\n\n The first option causes the least overhead if you have to prove only\n little about the words you use and start a fresh formalisation.\n Just use the native type @{typ uint32} instead of @{typ \"32 word\"}\n and similarly for \\uint64\\, \\uint16\\, and \\uint8\\.\n As native word types are meant only for code generation, the lemmas\n about @{typ \"'a word\"} have not been duplicated, but you can transfer\n theorems between native word types and @{typ \"'a word\"} using the\n transfer package.\n\n Note, however, that this option restricts your work a bit:\n your own functions cannot be ``polymorphic'' in the word length,\n but you have to define a separate function for every word length you need.\n\n The second option is recommended if you already have a formalisation\n based on @{typ \"'a word\"} or if your proofs involve words and their\n properties. It separates code generation from modelling and proving,\n i.e., you can work with words as usual. Consequently, you have to\n manually setup the code generator to use the native types wherever\n you want. The following describes how to achieve this with moderate\n effort.\n\n Note, however, that some target languages of the code generator\n (especially OCaml) do not support all the native word types provided.\n Therefore, you should only import those types that you need -- the\n theory file for each type mentions at the top the restrictions for\n code generation. For example, PolyML does not provide the Word16\n structure, and OCaml provides neither Word8 nor Word16.\n You can still use these theories provided that you also import\n the theory @{theory Native_Word.Code_Target_Bits_Int} (which implements\n @{typ int} by target-language integers), but these words will\n be implemented via Isabelle's \\HOL-Word\\ library, i.e.,\n you do not gain anything in terms of efficiency.\n\n \\textbf{There is a separate code target \\SML_word\\ for SML.}\n If you use one of the native words that PolyML does not support\n (such as \\uint16\\ and \\uint64\\ in 32-bit mode), but would\n like to map its operations to the Standard Basis Library functions,\n make sure to use the target \\SML_word\\ instead of \\SML\\;\n if you only use native word sizes that PolyML supports, you can stick\n with \\SML\\. This ensures that code generation within Isabelle\n as used by \\Quickcheck\\, \\value\\ and @\\{code\\} in ML blocks\n continues to work.\n\\\n\nsection \\Lifting functions from @{typ \"'a word\"} to native words\\\n\ntext \\\n This section shows how to convert functions from @{typ \"'a word\"} to native \n words. For example, the following function \\sum_squares\\ computes \n the sum of the first @{term n} square numbers in 16 bit arithmetic using\n a tail-recursive function \\gen_sum_squares\\ with accumulator;\n for convenience, \\sum_squares_int\\ takes an integer instead of a word.\n\\\n\nfunction gen_sum_squares :: \"16 word \\ 16 word \\ 16 word\" where (*<*)[simp del]:(*>*)\n\n \"gen_sum_squares accum n =\n (if n = 0 then accum else gen_sum_squares (accum + n * n) (n - 1))\"\n(*<*)by pat_completeness simp\ntermination by(relation \"measure (nat \\ uint \\ snd)\")\n (simp_all, metis (hide_lams, mono_tags) uint_1 uint_eq_0 uint_minus_simple_alt uint_sub_ge word_le_sub1 word_less_def word_neq_0_conv word_zero_le zle_diff1_eq)(*>*)\n\n\ndefinition sum_squares :: \"16 word \\ 16 word\" where\n \"sum_squares = gen_sum_squares 0\"\n\ndefinition sum_squares_int :: \"int \\ 16 word\" where\n \"sum_squares_int n = sum_squares (word_of_int n)\"\n\ntext \\\n The generated code for @{term sum_squares} and @{term sum_squares_int} \n emulates words with unbounded integers and explicit modulus as specified \n in the theory @{theory \"HOL-Word.Word\"}. But for efficiency, we want that the\n generated code uses machine words and machine arithmetic. Unfortunately,\n as @{typ \"'a word\"} is polymorphic in the word length, the code generator\n can only do this if we use another type for machine words. The theory\n @{theory Native_Word.Uint16} defines the type @{typ uint16} for machine words of\n 16~bits. We just have to follow two steps to use it:\n \n First, we lift all our functions from @{typ \"16 word\"} to @{typ uint16},\n i.e., @{term sum_squares}, @{term gen_sum_squares}, and \n @{term sum_squares_int} in our case. The theory @{theory Native_Word.Uint16} sets\n up the lifting package for this and has already taken care of the\n arithmetic and bit-wise operations.\n\\\nlift_definition gen_sum_squares_uint :: \"uint16 \\ uint16 \\ uint16\" \n is gen_sum_squares .\nlift_definition sum_squares_uint :: \"uint16 \\ uint16\" is sum_squares .\nlift_definition sum_squares_int_uint :: \"int \\ uint16\" is sum_squares_int .\n\ntext \\\n Second, we also have to transfer the code equations for our functions.\n The attribute \\Transfer.transferred\\ takes care of that, but it is\n better to check that the transfer succeeded: inspect the theorem to check\n that the new constants are used throughout.\n\\\n\nlemmas [Transfer.transferred, code] =\n gen_sum_squares.simps\n sum_squares_def\n sum_squares_int_def\n\ntext \\\n Finally, we export the code to standard ML. We use the target\n \\SML_word\\ instead of \\SML\\ to have the operations\n on @{typ uint16} mapped to the Standard Basis Library. As PolyML\n does not provide a Word16 type, the mapping for @{typ uint16} is only\n active in the refined target \\SML_word\\.\n\\\nexport_code sum_squares_int_uint in SML_word\n\ntext \\\n Nevertheless, we can still evaluate terms with @{term \"uint16\"} within \n Isabelle, i.e., PolyML, but this will be translated to @{typ \"16 word\"}\n and therefore less efficient.\n\\\n\nvalue \"sum_squares_int_uint 40\"\n\nsection \\Storing native words in datatypes\\\n\ntext \\\n The above lifting is necessary for all functions whose type mentions\n the word type. Fortunately, we do not have to duplicate functions that\n merely operate on datatypes that contain words. Nevertheless, we have\n to tell the code generator that these functions should call the new ones,\n which operate on machine words. This section shows how to achieve this\n with data refinement.\n\\\n\nsubsection \\Example: expressions and two semantics\\\n\ntext \\\n As the running example, we consider a language of expressions (literal values, less-than comparisions and conditional) where values are either booleans or 32-bit words.\n The original specification uses the type @{typ \"32 word\"}.\n\\\n\ndatatype val = Bool bool | Word \"32 word\"\ndatatype expr = Lit val | LT expr expr | IF expr expr expr\n\nabbreviation (input) word :: \"32 word \\ expr\" where \"word i \\ Lit (Word i)\"\nabbreviation (input) bool :: \"bool \\ expr\" where \"bool i \\ Lit (Bool i)\"\n\n\\ \\Denotational semantics of expressions, @{term None} denotes a type error\\\nfun eval :: \"expr \\ val option\" where\n \"eval (Lit v) = Some v\"\n| \"eval (LT e\\<^sub>1 e\\<^sub>2) = \n (case (eval e\\<^sub>1, eval e\\<^sub>2) \n of (Some (Word i\\<^sub>1), Some (Word i\\<^sub>2)) \\ Some (Bool (i\\<^sub>1 < i\\<^sub>2))\n | _ \\ None)\"\n| \"eval (IF e\\<^sub>1 e\\<^sub>2 e\\<^sub>3) =\n (case eval e\\<^sub>1 of Some (Bool b) \\ if b then eval e\\<^sub>2 else eval e\\<^sub>3\n | _ \\ None)\"\n\n\\ \\Small-step semantics of expressions, it gets stuck upon type errors.\\\ninductive step :: \"expr \\ expr \\ bool\" (\"_ \\ _\" [50, 50] 60) where\n \"e \\ e' \\ LT e e\\<^sub>2 \\ LT e' e\\<^sub>2\"\n| \"e \\ e' \\ LT (word i) e \\ LT (word i) e'\"\n| \"LT (word i\\<^sub>1) (word i\\<^sub>2) \\ bool (i\\<^sub>1 < i\\<^sub>2)\"\n| \"e \\ e' \\ IF e e\\<^sub>1 e\\<^sub>2 \\ IF e' e\\<^sub>1 e\\<^sub>2\"\n| \"IF (bool True) e\\<^sub>1 e\\<^sub>2 \\ e\\<^sub>1\"\n| \"IF (bool False) e\\<^sub>1 e\\<^sub>2 \\ e\\<^sub>2\"\n\n\\ \\Compile the inductive definition with the predicate compiler\\\ncode_pred (modes: i \\ o \\ bool as reduce, i \\ i \\ bool as step') step .\n\nsubsection \\Change the datatype to use machine words\\\n\ntext \\\n Now, we want to use @{typ uint32} instead of @{typ \"32 word\"}.\n The goal is to make the code generator use the new type without\n duplicating any of the types (@{typ val}, @{typ expr}) or the\n functions (@{term eval}, @{term reduce}) on such types.\n\n The constructor @{term Word} has @{typ \"32 word\"} in its type, so\n we have to lift it to \\Word'\\, and the same holds for the\n case combinator @{term case_val}, which @{term case_val'} replaces.%\n \\footnote{%\n Note that we should not declare a case translation for the new\n case combinator because this will break parsing case expressions\n with old case combinator.\n }\n Next, we set up the code generator accordingly:\n @{term Bool} and @{term Word'} are the new constructors for @{typ val},\n and @{term case_val'} is the new case combinator with an appropriate \n case certificate.%\n \\footnote{%\n Case certificates tell the code generator to replace the HOL\n case combinator for a datatype with the case combinator of the\n target language. Without a case certificate, the code generator\n generates a function that re-implements the case combinator; \n in a strict languages like ML or Scala, this means that the code\n evaluates all possible cases before it decides which one is taken.\n\n Case certificates are described in Haftmann's PhD thesis\n \\cite[Def.\\ 27]{Haftmann2009PhD}. For a datatype \\dt\\\n with constructors \\C\\<^sub>1\\ to \\C\\<^sub>n\\\n where each constructor \\C\\<^sub>i\\ takes \\k\\<^sub>i\\ parameters,\n the certificate for the case combinator \\case_dt\\\n looks as follows:\n\n {\n \\isamarkuptrue\\isacommand{lemma}\\isamarkupfalse\\isanewline%\n \\ \\ \\isakeyword{assumes}\\ {\\isachardoublequoteopen}CASE\\ {\\isasymequiv}\\ dt{\\isacharunderscore}case\\ c\\isactrlsub {\\isadigit{1}}\\ c\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ c\\isactrlsub{n}{\\isachardoublequoteclose}\\isanewline\n \\ \\ \\isakeyword{shows}\\ {\\isachardoublequoteopen}{\\isacharparenleft}CASE\\ {\\isacharparenleft}C\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {\\isadigit{1}}\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {\\isadigit{1}}\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ a\\isactrlsub {\\isadigit{1}}\\isactrlsub {k\\ensuremath{{}_1}}{\\isacharparenright}\\ {\\isasymequiv}\\ c\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {\\isadigit{1}}\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {\\isadigit{1}}\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ a\\isactrlsub {\\isadigit{1}}\\isactrlsub {k\\ensuremath{{}_1}}{\\isacharparenright}\\isanewline\n \\ \\ \\ \\ {\\isacharampersand}{\\isacharampersand}{\\isacharampersand}\\ {\\isacharparenleft}CASE\\ {\\isacharparenleft}C\\isactrlsub {\\isadigit{2}}\\ a\\isactrlsub {\\isadigit{2}}\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {\\isadigit{2}}\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ a\\isactrlsub {\\isadigit{2}}\\isactrlsub {k\\ensuremath{{}_2}}{\\isacharparenright}\\ {\\isasymequiv}\\ c\\isactrlsub {\\isadigit{2}}\\ a\\isactrlsub {\\isadigit{2}}\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {\\isadigit{2}}\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ a\\isactrlsub {\\isadigit{2}}\\isactrlsub {k\\ensuremath{{}_2}}{\\isacharparenright}\\isanewline\n \\ \\ \\ \\ {\\isacharampersand}{\\isacharampersand}{\\isacharampersand}\\ \\ldots\\isanewline\n \\ \\ \\ \\ {\\isacharampersand}{\\isacharampersand}{\\isacharampersand}\\ {\\isacharparenleft}CASE\\ {\\isacharparenleft}C\\isactrlsub {n}\\ a\\isactrlsub {n}\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {n}\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ a\\isactrlsub {n}\\isactrlsub {k\\ensuremath{{}_n}}{\\isacharparenright}\\ {\\isasymequiv}\\ c\\isactrlsub {n}\\ a\\isactrlsub {n}\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {n}\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ a\\isactrlsub {n}\\isactrlsub {k\\ensuremath{{}_n}}{\\isacharparenright}{\\isachardoublequoteclose}\\isanewline\n }\n }\n We delete the code equations for the old constructor @{term Word}\n and case combinator @{term case_val} such that the code generator\n reports missing adaptations.\n\\\n\nlift_definition Word' :: \"uint32 \\ val\" is Word .\n\ncode_datatype Bool Word'\n\nlift_definition case_val' :: \"(bool \\ 'a) \\ (uint32 \\ 'a) \\ val \\ 'a\" is case_val .\n\nlemmas [code, simp] = val.case [Transfer.transferred]\n\nlemma case_val'_cert:\n fixes bool word' b w\n assumes \"CASE \\ case_val' bool word'\"\n shows \"(CASE (Bool b) \\ bool b) &&& (CASE (Word' w) \\ word' w)\"\n by (simp_all add: assms)\n\nsetup \\Code.declare_case_global @{thm case_val'_cert}\\\n\ndeclare [[code drop: case_val Word]]\n\n\nsubsection \\Make functions use functions on machine words\\\n\ntext \\\n Finally, we merely have to change the code equations to use the \n new functions that operate on @{typ uint32}. As before, the\n attribute \\Transfer.transferred\\ does the job. In our example,\n we adapt the equality test on @{typ val} (code equations\n @{thm [source] val.eq.simps}) and the denotational and small-step \n semantics (code equations @{thm [source] eval.simps} and\n @{thm [source] step.equation}, respectively).\n\n We check that the adaptation has suceeded by exporting the functions.\n As we only use native word sizes that PolyML supports, we can use \n the usual target \\SML\\ instead of \\SML_word\\.\n\\\n\nlemmas [code] = \n val.eq.simps[THEN meta_eq_to_obj_eq, Transfer.transferred, THEN eq_reflection]\n eval.simps[Transfer.transferred]\n step.equation[Transfer.transferred]\n\nexport_code reduce step' eval checking SML\n\nsection \\Troubleshooting\\\n\ntext \\\n This section explains some possible problems when using native words.\n If you experience other difficulties, please contact the author.\n\\\n\nsubsection \\\\export_code\\ raises an exception \\label{section:export_code:exception}\\\n\ntext \\\n Probably, you have defined and are using a function on a native word type,\n but the code equation refers to emulated words. For example, the following\n defines a function \\double\\ that doubles a word. When we try to export\n code for \\double\\ without any further setup, \\export_code\\ will\n raise an exception or generate code that does not compile.\n\\\n\nlift_definition double :: \"uint32 \\ uint32\" is \"\\x. x + x\" .\n\ntext \\\n We have to prove a code equation that only uses the existing operations on\n @{typ uint32}. Then, \\export_code\\ works again.\n\\\n\nlemma double_code [code]: \"double n = n + n\"\nby transfer simp\n\nsubsection \\The generated code does not compile\\\n\ntext \\\n Probably, you have been exporting to a target language for which there\n is no setup, or your compiler does not provide the required API. Every\n theory for native words mentions at the start the limitations on code\n generation. Check that your concrete application meets all the\n requirements.\n\n Alternatively, this might be an instance of the problem described \n in \\S\\ref{section:export_code:exception}.\n\n For Haskell, you have to enable the extension TypeSynonymInstances with \\texttt{-XTypeSynonymInstances}\n if you are using polymorphic bit operations on the native word types.\n\\\n\nsubsection \\The generated code is too slow\\\n\ntext \\\n The generated code will most likely not be as fast as a direct implementation in the target language with manual tuning.\n This is because we want the configuration of the code generation to be sound (as it can be used to prove theorems in Isabelle).\n Therefore, the bit operations sometimes perform range checks before they call the target language API.\n Here are some examples:\n \\begin{itemize}\n \\item Shift distances and bit indices in target languages are often expected to fit into a bounded integer or word.\n However, the size of these types varies across target languages and platforms.\n Hence, no Isabelle/HOL type can model uniformly all of them.\n Instead, the bit operations use arbitrary-precision integers for such quantities and check at run-time that the values fit into a bounded integer or word, respectively -- if not, they raise an exception.\n \n \\item Division and modulo operations explicitly test whether the divisor is $0$ and return the HOL value of division by $0$ in that case.\n This is necessary because some languages leave the behaviour of division by 0 unspecified.\n \\end{itemize}\n \n If you have better ideas how to eliminate such checks and speed up the generated code without sacrificing soundness, please contact the author!\n\\\n\n(*<*)end(*>*)\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Native_Word/Uint_Userguide.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.13117322546005342, "lm_q1q2_score": 0.0604730579336021}} {"text": "(* Title: Miscellaneous Definitions and Lemmas\n Author: Peter Lammich \n Maintainer: Peter Lammich \n Thomas Tuerk \n*)\n\n(*\n CHANGELOG:\n 2010-05-09: Removed AC, AI locales, they are superseeded by concepts \n from OrderedGroups\n 2010-09-22: Merges with ext/Aux\n\n*)\n\nheader {* Miscellaneous Definitions and Lemmas *}\n\ntheory Misc\nimports Main \n \"~~/src/HOL/Library/Multiset\" \n \"~~/src/HOL/ex/Quicksort\"\n \"~~/src/HOL/Library/Option_ord\"\n \"~~/src/HOL/Library/Product_Lexorder\"\n \"~~/src/HOL/Library/Infinite_Set\"\n \"List_More\"\nbegin\ntext_raw {*\\label{thy:Misc}*}\n\ntext {* Here we provide a collection of miscellaneous definitions and helper lemmas *}\n\nsubsection \"Miscellaneous (1)\"\n(* TODO: To be moved to List.thy, Option.thy *)\nlemma equal_Nil_null [code_unfold]:\n \"HOL.equal [] = List.null\"\n by (auto simp add: List.null_def equal)\n\nlemma equal_None_is_none [code_unfold]:\n \"HOL.equal None = Option.is_none\"\n by (auto simp add: Option.is_none_def equal)\n\n\ntext {* This stuff is used in this theory itself, and thus occurs in first place or is simply not sorted into any other section of this theory. *}\n\nlemma IdD: \"(a,b)\\Id \\ a=b\" by simp\n\nsubsubsection \"AC-operators\"\n \ntext {* Locale to declare AC-laws as simplification rules *}\nlocale Assoc =\n fixes f\n assumes assoc[simp]: \"f (f x y) z = f x (f y z)\"\n\nlocale AC = Assoc +\n assumes commute[simp]: \"f x y = f y x\"\n\nlemma (in AC) left_commute[simp]: \"f x (f y z) = f y (f x z)\"\n by (simp only: assoc[symmetric]) simp\n\nlemmas (in AC) AC_simps = commute assoc left_commute\n\ntext {* Locale to define functions from surjective, unique relations *}\nlocale su_rel_fun =\n fixes F and f\n assumes unique: \"\\(A,B)\\F; (A,B')\\F\\ \\ B=B'\"\n assumes surjective: \"\\!!B. (A,B)\\F \\ P\\ \\ P\"\n assumes f_def: \"f A == THE B. (A,B)\\F\"\n\nlemma (in su_rel_fun) repr1: \"(A,f A)\\F\" proof (unfold f_def)\n obtain B where \"(A,B)\\F\" by (rule surjective)\n with theI[where P=\"\\B. (A,B)\\F\", OF this] show \"(A, THE x. (A, x) \\ F) \\ F\" by (blast intro: unique)\nqed\n \nlemma (in su_rel_fun) repr2: \"(A,B)\\F \\ B=f A\" using repr1\n by (blast intro: unique)\n\nlemma (in su_rel_fun) repr: \"(f A = B) = ((A,B)\\F)\" using repr1 repr2\n by (blast) \n\n\nlemma set_pair_flt_false[simp]: \"{ (a,b). False } = {}\"\n by simp\n\nlemma in_pair_collect_simp[simp]: \"(a,b)\\{(a,b). P a b} \\ P a b\"\n by auto\n\n -- \"Contract quantification over two variables to pair\"\nlemma Ex_prod_contract: \"(\\a b. P a b) \\ (\\z. P (fst z) (snd z))\"\n by auto\n\nlemma All_prod_contract: \"(\\a b. P a b) \\ (\\z. P (fst z) (snd z))\"\n by auto\n\n\nlemma nat_geq_1_eq_neqz: \"x\\1 \\ x\\(0::nat)\"\n by auto\n\nlemma nat_in_between_eq: \n \"(a b\\Suc a) \\ b = Suc a\"\n \"(a\\b \\ b b = a\"\n by auto\n\nlemma Suc_n_minus_m_eq: \"\\ n\\m; m>1 \\ \\ Suc (n - m) = n - (m - 1)\"\n by simp\n\nlemma Suc_to_right: \"Suc n = m \\ n = m - Suc 0\" by simp\nlemma Suc_diff[simp]: \"\\n m. n\\m \\ m\\1 \\ Suc (n - m) = n - (m - 1)\"\n by simp\n\nlemma if_not_swap[simp]: \"(if \\c then a else b) = (if c then b else a)\" by auto \nlemma all_to_meta: \"Trueprop (\\a. P a) \\ (\\a. P a)\"\n apply rule\n by auto\n\nlemma imp_to_meta: \"Trueprop (P\\Q) \\ (P\\Q)\"\n apply rule\n by auto\n\nlemma disjE1: \"\\ P \\ Q; P \\ R; \\\\P;Q\\ \\ R \\ \\ R\"\n by metis\nlemma disjE2: \"\\ P \\ Q; \\P; \\Q\\ \\ R; Q \\ R \\ \\ R\"\n by metis\n\nlemma TERMI: \"TERM x\" unfolding Pure.term_def .\n\n(* for some reason, there is no such rule in HOL *)\nlemma iffI2: \"\\P \\ Q; \\ P \\ \\ Q\\ \\ P \\ Q\"\nby metis\n\nlemma iffExI:\n \"\\ \\x. P x \\ Q x; \\x. Q x \\ P x \\ \\ (\\x. P x) \\ (\\x. Q x)\"\nby metis\n\nlemma bex2I[intro?]: \"\\ (a,b)\\S; (a,b)\\S \\ P a b \\ \\ \\a b. (a,b)\\S \\ P a b\"\n by blast\n\n\nsubsection {* Sets *}\n\n lemma subset_minus_empty: \"A\\B \\ A-B = {}\" by auto\n\n lemma set_notEmptyE: \"\\S\\{}; !!x. x\\S \\ P\\ \\ P\"\n by (metis equals0I)\n\n lemma inter_compl_diff_conv[simp]: \"A \\ -B = A - B\" by auto\n\n lemma setsum_subset_split: assumes P: \"finite A\" \"B\\A\" shows T: \"setsum f A = setsum f (A-B) + setsum f B\" proof -\n from P have 1: \"A = (A-B) \\ B\" by auto\n have 2: \"(A-B) \\ B = {}\" by auto\n from P have 3: \"finite B\" by (blast intro: finite_subset)\n from P have 4: \"finite (A-B)\" by simp\n from 2 3 4 setsum.union_disjoint have \"setsum f ((A-B) \\ B) = setsum f (A-B) + setsum f B\" by blast\n with 1 show ?thesis by simp\n qed\n\n\n lemma disjoint_mono: \"\\ a\\a'; b\\b'; a'\\b'={} \\ \\ a\\b={}\" by auto\n\n lemma disjoint_alt_simp1: \"A-B = A \\ A\\B = {}\" by auto\n lemma disjoint_alt_simp2: \"A-B \\ A \\ A\\B \\ {}\" by auto\n lemma disjoint_alt_simp3: \"A-B \\ A \\ A\\B \\ {}\" by auto\n\n lemma disjointI[intro?]: \"\\ \\x. \\x\\a; x\\b\\ \\ False \\ \\ a\\b={}\"\n by auto\n\n\n lemmas set_simps = subset_minus_empty disjoint_alt_simp1 disjoint_alt_simp2 disjoint_alt_simp3 Un_absorb1 Un_absorb2\n\n lemma set_minus_singleton_eq: \"x\\X \\ X-{x} = X\" \n by auto\n\n lemma set_diff_diff_left: \"A-B-C = A-(B\\C)\"\n by auto\n\n\n lemma image_update[simp]: \"x\\A \\ f(x:=n)`A = f`A\"\n by auto\n\n lemma set_union_code [code_unfold]:\n \"set xs \\ set ys = set (xs @ ys)\"\n by auto\n\n lemma pair_set_inverse[simp]: \"{(a,b). P a b}\\ = {(b,a). P a b}\"\n by auto\n\n lemma in_fst_imageE: \n assumes \"x \\ fst`S\"\n obtains y where \"(x,y)\\S\"\n using assms by auto\n\n lemma in_snd_imageE: \n assumes \"y \\ snd`S\"\n obtains x where \"(x,y)\\S\"\n using assms by auto\n\n lemma fst_image_mp: \"\\fst`A \\ B; (x,y)\\A \\ \\ x\\B\"\n by (metis Domain.DomainI fst_eq_Domain in_mono)\n\n lemma snd_image_mp: \"\\snd`A \\ B; (x,y)\\A \\ \\ y\\B\"\n by (metis Range.intros set_rev_mp snd_eq_Range)\n\n lemma inter_eq_subsetI: \"\\ S\\S'; A\\S' = B\\S' \\ \\ A\\S = B\\S\"\n by auto\n\ntext {*\n Decompose general union over sum types.\n*}\nlemma Union_plus:\n \"(\\ x \\ A <+> B. f x) = (\\ a \\ A. f (Inl a)) \\ (\\b \\ B. f (Inr b))\"\nby auto\n\nlemma Union_sum:\n \"(\\x. f (x::'a+'b)) = (\\l. f (Inl l)) \\ (\\r. f (Inr r))\"\n (is \"?lhs = ?rhs\")\nproof -\n have \"?lhs = (\\x \\ UNIV <+> UNIV. f x)\"\n by simp\n thus ?thesis\n by (simp only: Union_plus)\nqed\n\n\n subsubsection {* Finite Sets *}\n\n lemma card_1_singletonI: \"\\finite S; card S = 1; x\\S\\ \\ S={x}\"\n proof (safe, rule ccontr)\n case (goal1 x')\n hence \"finite (S-{x})\" \"S-{x} \\ {}\" by auto\n hence \"card (S-{x}) \\ 0\" by auto\n moreover from goal1(1-3) have \"card (S-{x}) = 0\" by auto\n ultimately have False by simp\n thus ?case ..\n qed\n\n lemma card_insert_disjoint': \"\\finite A; x \\ A\\ \\ card (insert x A) - Suc 0 = card A\"\n by (drule (1) card_insert_disjoint) auto\n\n lemma card_eq_UNIV[simp]: \"card (S::'a::finite set) = card (UNIV::'a set) \\ S=UNIV\"\n proof (auto)\n fix x\n assume A: \"card S = card (UNIV::'a set)\"\n show \"x\\S\" proof (rule ccontr)\n assume \"x\\S\" hence \"S\\UNIV\" by auto\n with psubset_card_mono[of UNIV S] have \"card S < card (UNIV::'a set)\" by auto\n with A show False by simp\n qed\n qed\n \n lemma card_eq_UNIV2[simp]: \"card (UNIV::'a set) = card (S::'a::finite set) \\ S=UNIV\"\n using card_eq_UNIV[of S] by metis\n\n lemma card_ge_UNIV[simp]: \"card (UNIV::'a::finite set) \\ card (S::'a set) \\ S=UNIV\"\n using card_mono[of \"UNIV::'a::finite set\" S, simplified]\n by auto\n \n lemmas length_remdups_card = length_remdups_concat[of \"[l]\", simplified] for l\n\nlemma card_Plus:\n assumes fina: \"finite (A::'a set)\" and finb: \"finite (B::'b set)\"\n shows \"card (A <+> B) = (card A) + (card B)\"\nproof -\n from fina finb\n have \"card ((Inl ` A) \\ (Inr ` B)) =\n (card ((Inl ` A)::('a+'b)set)) + (card ((Inr ` B)::('a+'b)set))\"\n by (auto intro: card_Un_disjoint finite_imageI)\n thus ?thesis\n by (simp add: Plus_def card_image inj_on_def)\nqed\n\n\n lemma fs_contract: \"fst ` { p | p. f (fst p) (snd p) \\ S } = { a . \\b. f a b \\ S }\"\n by (simp add: image_Collect)\n\n (* Nice lemma thanks to Andreas Lochbihler *)\n lemma finite_Collect:\n assumes fin: \"finite S\" and inj: \"inj f\"\n shows \"finite {a. f a : S}\"\n proof -\n def S' == \"S \\ range f\"\n hence \"{a. f a : S} = {a. f a : S'}\" by auto\n also have \"... = (inv f) ` S'\"\n proof\n show \"{a. f a : S'} <= inv f ` S'\"\n using inj by(force intro: image_eqI)\n show \"inv f ` S' <= {a. f a : S'}\"\n proof\n fix x\n assume \"x : inv f ` S'\"\n then obtain y where \"y : S'\" \"x = inv f y\" by blast\n moreover from `y : S'` obtain x' where \"f x' = y\"\n unfolding S'_def by blast\n hence \"f (inv f y) = y\" unfolding inv_def by(rule someI)\n ultimately show \"x : {a. f a : S'}\" by simp\n qed\n qed\n also have \"finite S'\" using fin unfolding S'_def by blast\n ultimately show ?thesis by simp\n qed \n\n -- \"Finite sets have an injective mapping to an initial segments of the \n natural numbers\"\n (* This lemma is also in the standard library (from Isabelle2009-1 on) \n as @{thm [source] Finite_Set.finite_imp_inj_to_nat_seg}. However, it is formulated with HOL's \n \\ there rather then with the meta-logic obtain *)\n lemma finite_imp_inj_to_nat_seg':\n fixes A :: \"'a set\"\n assumes A: \"finite A\"\n obtains f::\"'a \\ nat\" and n::\"nat\" where\n \"f`A = {i. i finite (lists P \\ { l. n = length l })\"\n proof -\n assume A: \"finite P\"\n have S: \"{ l. n = length l } = { l. length l = n }\" by auto\n have \"finite (lists P \\ { l. n = length l }) \n \\ finite (lists P \\ { l. length l = n })\" \n by (subst S) simp\n \n thus ?thesis using lists_of_len_fin1[OF A] by auto\n qed\n\n lemmas lists_of_len_fin = lists_of_len_fin1 lists_of_len_fin2\n\n\n (* Try (simp only: cset_fin_simps, fastforce intro: cset_fin_intros) when reasoning about finiteness of collected sets *)\n lemmas cset_fin_simps = Ex_prod_contract fs_contract[symmetric] image_Collect[symmetric]\n lemmas cset_fin_intros = finite_imageI finite_Collect inj_onI\n\n\nlemma Un_interval: \n fixes b1 :: \"'a::linorder\"\n assumes \"b1\\b2\" and \"b2\\b3\"\n shows \"{ f i | i. b1\\i \\ i { f i | i. b2\\i \\ ii \\ i A\"\n shows \"finite (B a)\"\nproof (rule ccontr)\n assume cc: \"\\finite (B a)\"\n from a have \"B a \\ UNION A B\" by auto\n from this cc have \"\\finite (UNION A B)\" by (auto intro: finite_subset)\n from this hyp show \"False\" ..\nqed\n\nlemma finite_if_eq_beyond_finite: \"finite S \\ finite {s. s - S = s' - S}\"\nproof (rule finite_subset[where B=\"(\\s. s \\ (s' - S)) ` Pow S\"], clarsimp)\n fix s\n have \"s = (s \\ S) \\ (s - S)\"\n by auto\n also assume \"s - S = s' - S\"\n finally show \"s \\ (\\s. s \\ (s' - S)) ` Pow S\" by blast\nqed blast\n\nlemma distinct_finite_subset:\n assumes \"finite x\"\n shows \"finite {ys. set ys \\ x \\ distinct ys}\" (is \"finite ?S\")\nproof (rule finite_subset)\n from assms show \"?S \\ {ys. set ys \\ x \\ length ys \\ card x}\"\n by clarsimp (metis distinct_card card_mono) \n from assms show \"finite ...\" by (rule finite_lists_length_le)\nqed\n \nlemma distinct_finite_set:\n shows \"finite {ys. set ys = x \\ distinct ys}\" (is \"finite ?S\")\nproof (cases \"finite x\")\n case False hence \"{ys. set ys = x} = {}\" by auto\n thus ?thesis by simp\nnext\n case True show ?thesis\n proof (rule finite_subset)\n show \"?S \\ {ys. set ys \\ x \\ length ys \\ card x}\"\n using distinct_card by force\n from True show \"finite ...\" by (rule finite_lists_length_le)\n qed\nqed\n\nlemma finite_set_image:\n assumes f: \"finite (set ` A)\"\n and dist: \"\\xs. xs \\ A \\ distinct xs\"\n shows \"finite A\"\nproof (rule finite_subset)\n from f show \"finite (set -` (set ` A) \\ {xs. distinct xs})\"\n proof (induct rule: finite_induct)\n case (insert x F)\n from distinct_finite_set have \"finite (set -` {x} \\ {xs. distinct xs})\" \n apply (simp add: vimage_def)\n by (metis Collect_conj_eq distinct_finite_set)\n with insert show ?case\n apply (subst vimage_insert) \n apply (subst Int_Un_distrib2)\n apply (rule finite_UnI) \n apply simp_all\n done\n qed simp\n moreover from dist show \"A \\ ...\"\n by (auto simp add: vimage_image_eq)\nqed\n\n\nsubsubsection {* Infinite Set *}\nlemma INFM_nat_inductI: \n assumes P0: \"P (0::nat)\"\n assumes PS: \"\\i. P i \\ \\j>i. P j \\ Q j\"\n shows \"\\\\<^sub>\\i. Q i\"\nproof -\n have \"\\i. \\j>i. P j \\ Q j\" proof\n fix i\n show \"\\j>i. P j \\ Q j\"\n apply (induction i)\n using PS[OF P0] apply auto []\n by (metis PS Suc_lessI)\n qed\n thus ?thesis unfolding INFM_nat by blast\nqed\n\nsubsection {* Functions *}\n\ndefinition \"inv_on f A x == SOME y. y\\A \\ f y = x\"\n\nlemma inv_on_f_f[simp]: \"\\inj_on f A; x\\A\\ \\ inv_on f A (f x) = x\"\n by (auto simp add: inv_on_def inj_on_def)\n\nlemma f_inv_on_f: \"\\ y\\f`A \\ \\ f (inv_on f A y) = y\"\n by (auto simp add: inv_on_def intro: someI2)\n\nlemma inv_on_f_range: \"\\ y \\ f`A \\ \\ inv_on f A y \\ A\"\n by (auto simp add: inv_on_def intro: someI2)\n\nlemma inj_on_map_inv_f [simp]: \"\\set l \\ A; inj_on f A\\ \\ map (inv_on f A) (map f l) = l\"\n apply (simp)\n apply (induct l)\n apply auto\n done\n\nlemma comp_cong_right: \"x = y \\ f o x = f o y\" by (simp)\nlemma comp_cong_left: \"x = y \\ x o f = y o f\" by (simp)\n\nlemma fun_comp_eq_conv: \"f o g = fg \\ (\\x. f (g x) = fg x)\"\n by auto\n\nsubsection {* Multisets *}\n\n(*\n The following is a syntax extension for multisets. Unfortunately, it depends on a change in the Library/Multiset.thy, so it is commented out here, until it will be incorporated \n into Library/Multiset.thy by its maintainers.\n\n The required change in Library/Multiset.thy is removing the syntax for single:\n - single :: \"'a => 'a multiset\" (\"{#_#}\")\n + single :: \"'a => 'a multiset\"\n\n And adding the following translations instead:\n \n + syntax\n + \"_multiset\" :: \"args \\ 'a multiset\" (\"{#(_)#}\")\n\n + translations\n + \"{#x, xs#}\" == \"{#x#} + {#xs#}\" \n + \"{# x #}\" == \"single x\"\n\n This translates \"{# \\ #}\" into a sum of singletons, that is parenthesized to the right. ?? Can we also achieve left-parenthesizing ??\n\n*)\n\n\n (* Let's try what happens if declaring AC-rules for multiset union as simp-rules *)\n(*declare union_ac[simp] -- don't do it !*)\n\n\nthm count_multiset_of_set\n\nlemma count_multiset_of_set_finite_iff:\n \"finite S \\ count (multiset_of_set S) a = (if a \\ S then 1 else 0)\"\n by simp\n\nlemma in_multiset_of_set[simp]:\n \"finite S \\ x \\# (multiset_of_set S) \\ x \\ S\"\n by (simp add: count_multiset_of_set_finite_iff)\n\ndeclare Multiset.finite_set_of_multiset_of_set[simp]\n\nlemma multiset_of_insert: \"finite S \\\n multiset_of_set (insert e S) =\n multiset_of_set (S - {e}) + {#e#}\"\n by (metis multiset_of_set.insert_remove union_commute)\n\nlemma multiset_of_set_set :\n \"distinct l \\\n multiset_of_set (set l) = multiset_of l\"\nproof (induct l)\n case Nil thus ?case by simp\nnext\n case (Cons e l)\n from Cons(2) have e_nin_l : \"e \\ set l\" by simp\n from Cons(2) have dist_l: \"distinct l\" by simp\n note ind_hyp = Cons(1)[OF dist_l]\n\n from e_nin_l have \"set l - {e} = set l\" by auto\n with ind_hyp show ?case\n by (simp add: multiset_of_insert)\nqed\n\nlemma ex_Melem_conv: \"(\\x. x \\# A) = (A \\ {#})\"\n by (metis all_not_in_conv mem_set_of_iff set_of_eq_empty_iff)\n\nsubsubsection {* Case distinction *}\ntext {* Install a (new) default case-distinction lemma for multisets, that distinguishes between empty multiset and multiset that is the union of of some multiset and a singleton multiset. \n This is the same case distinction as done by the @{thm [source] multiset_induct} rule that is installed as default induction rule for multisets by Multiset.thy. *}\nlemma mset_cases[case_names empty add, cases type: multiset]: \"\\ M={#} \\ P; !!x M'. M=M'+{#x#} \\ P \\ \\ P\"\n apply (induct M)\n apply auto\ndone\n\nlemma multiset_induct'[case_names empty add]: \"\\P {#}; \\M x. P M \\ P ({#x#}+M)\\ \\ P M\"\n by (induct rule: multiset_induct) (auto simp add: union_commute)\n\nlemma mset_cases'[case_names empty add]: \"\\ M={#} \\ P; !!x M'. M={#x#}+M' \\ P \\ \\ P\"\n apply (induct M rule: multiset_induct')\n apply auto\ndone\n \nsubsubsection {* Count *}\n lemma count_ne_remove: \"\\ x ~= t\\ \\ count S x = count (S-{#t#}) x\"\n by (auto)\n lemma mset_empty_count[simp]: \"(\\p. count M p = 0) = (M={#})\"\n by (auto simp add: multiset_eq_iff)\n\nsubsubsection {* Union, difference and intersection *}\n\n lemma size_diff_se: \"\\t :# S\\ \\ size S = size (S - {#t#}) + 1\" proof (unfold size_multiset_overloaded_eq)\n let ?SIZE = \"setsum (count S) (set_of S)\"\n assume A: \"t :# S\"\n from A have SPLITPRE: \"finite (set_of S) & {t}\\(set_of S)\" by auto\n hence \"?SIZE = setsum (count S) (set_of S - {t}) + setsum (count S) {t}\" by (blast dest: setsum_subset_split)\n hence \"?SIZE = setsum (count S) (set_of S - {t}) + count (S) t\" by auto\n moreover with A have \"count S t = count (S-{#t#}) t + 1\" by auto\n ultimately have D: \"?SIZE = setsum (count S) (set_of S - {t}) + count (S-{#t#}) t + 1\" by (arith)\n moreover have \"setsum (count S) (set_of S - {t}) = setsum (count (S-{#t#})) (set_of S - {t})\" proof -\n have \"ALL x:(set_of S - {t}) . count S x = count (S-{#t#}) x\" by (auto iff add: count_ne_remove)\n thus ?thesis by simp\n qed\n ultimately have D: \"?SIZE = setsum (count (S-{#t#})) (set_of S - {t}) + count (S-{#t#}) t + 1\" by (simp)\n moreover\n { assume CASE: \"count (S-{#t#}) t = 0\"\n from CASE have \"set_of S - {t} = set_of (S-{#t#})\" by (auto iff add: set_of_def)\n with CASE D have \"?SIZE = setsum (count (S-{#t#})) (set_of (S - {#t#})) + 1\" by simp\n }\n moreover\n { assume CASE: \"count (S-{#t#}) t ~= 0\"\n from CASE have 1: \"set_of S = set_of (S-{#t#})\" by (auto iff add: set_of_def)\n moreover from D have \"?SIZE = setsum (count (S-{#t#})) (set_of S - {t}) + setsum (count (S-{#t#})) {t} + 1\" by simp\n moreover from SPLITPRE setsum_subset_split have \"setsum (count (S-{#t#})) (set_of S) = setsum (count (S-{#t#})) (set_of S - {t}) + setsum (count (S-{#t#})) {t}\" by (blast)\n ultimately have \"?SIZE = setsum (count (S-{#t#})) (set_of (S-{#t#})) + 1\" by simp\n }\n ultimately show \"?SIZE = setsum (count (S-{#t#})) (set_of (S - {#t#})) + 1\" by blast\n qed\n\n (* TODO: Check whether this proof can be done simpler *)\n lemma mset_union_diff_comm: \"t :# S \\ T + (S - {#t#}) = (T + S) - {#t#}\" proof -\n assume \"t :# S\"\n hence \"count S t = count (S-{#t#}) t + 1\" by auto\n hence \"count (S+T) t = count (S-{#t#}+T) t + 1\" by auto\n hence \"count (S+T-{#t#}) t = count (S-{#t#}+T) t\" by (simp)\n moreover have \"ALL x. x~=t \\ count (S+T-{#t#}) x = count (S-{#t#}+T) x\" by auto\n ultimately show ?thesis by (auto simp add: union_ac iff add: multiset_eq_iff)\n qed\n\n lemma mset_diff_union_cancel[simp]: \"t :# S \\ (S - {#t#}) + {#t#} = S\"\n by (auto simp add: mset_union_diff_comm union_ac)\n\n(* lemma mset_diff_diff_left: \"A-B-C = A-((B::'a multiset)+C)\" proof -\n have \"ALL e . count (A-B-C) e = count (A-(B+C)) e\" by auto\n thus ?thesis by (simp add: multiset_eq_conv_count_eq)\n qed\n\n lemma mset_diff_commute: \"A-B-C = A-C-(B::'a multiset)\" proof -\n have \"A-B-C = A-(B+C)\" by (simp add: mset_diff_diff_left)\n also have \"\\ = A-(C+B)\" by (simp add: union_commute)\n thus ?thesis by (simp add: mset_diff_diff_left)\n qed\n\n lemma mset_diff_same_empty[simp]: \"(S::'a multiset) - S = {#}\"\n proof -\n have \"ALL e . count (S-S) e = 0\" by auto\n hence \"ALL e . ~ (e : set_of (S-S))\" by auto\n hence \"set_of (S-S) = {}\" by blast\n thus ?thesis by (auto)\n qed\n*)\n lemma mset_right_cancel_union: \"\\a :# A+B; ~(a :# B)\\ \\ a:#A\"\n by (simp)\n lemma mset_left_cancel_union: \"\\a :# A+B; ~(a :# A)\\ \\ a:#B\"\n by (simp)\n \n lemmas mset_cancel_union = mset_right_cancel_union mset_left_cancel_union\n\n lemma mset_right_cancel_elem: \"\\a :# A+{#b#}; a~=b\\ \\ a:#A\"\n apply(subgoal_tac \"~(a :# {#b#})\")\n apply(auto)\n done\n\n lemma mset_left_cancel_elem: \"\\a :# {#b#}+A; a~=b\\ \\ a:#A\"\n apply(subgoal_tac \"~(a :# {#b#})\")\n apply(auto)\n done\n\n lemmas mset_cancel_elem = mset_right_cancel_elem mset_left_cancel_elem\n\n lemma mset_diff_cancel1elem[simp]: \"~(a :# B) \\ {#a#}-B = {#a#}\" proof -\n assume A: \"~(a :# B)\"\n hence \"count ({#a#}-B) a = count ({#a#}) a\" by auto\n moreover have \"ALL e . e~=a \\ count ({#a#}-B) e = count ({#a#}) e\" by auto\n ultimately show ?thesis by (auto simp add: multiset_eq_iff)\n qed\n\n(* lemma diff_union_inverse[simp]: \"A + B - B = (A::'a multiset)\"\n by (auto iff add: multiset_eq_conv_count_eq)\n\n lemma diff_union_inverse2[simp]: \"B + A - B = (A::'a multiset)\"\n by (auto iff add: multiset_eq_conv_count_eq)\n*)\n lemma union_diff_assoc_se: \"t :# B \\ (A+B)-{#t#} = A + (B-{#t#})\"\n by (auto iff add: multiset_eq_iff)\n (*lemma union_diff_assoc_se2: \"t :# A \\ (A+B)-{#t#} = (A-{#t#}) + B\"\n by (auto iff add: multiset_eq_conv_count_eq)\n lemmas union_diff_assoc_se = union_diff_assoc_se1 union_diff_assoc_se2*)\n\n lemma union_diff_assoc: \"C-B={#} \\ (A+B)-C = A + (B-C)\"\n by (simp add: multiset_eq_iff)\n\n lemma mset_union_1_elem1[simp]: \"({#a#} = M+{#b#}) = (a=b & M={#})\" proof\n assume A: \"{#a#} = M+{#b#}\"\n from A have \"size {#a#} = size (M+{#b#})\" by simp\n hence \"1 = 1 + size M\" by auto\n hence \"M={#}\" by auto\n moreover with A have \"a=b\" by auto\n ultimately show \"a=b & M={#}\" by auto\n next\n assume \"a = b \\ M = {#}\"\n thus \"{#a#} = M+{#b#}\" by auto\n qed\n\n lemma mset_union_1_elem2[simp]: \"({#a#} = {#b#}+M) = (a=b & M={#})\" using mset_union_1_elem1\n by (simp add: union_ac)\n\n lemma mset_union_1_elem3[simp]: \"(M+{#b#}={#a#}) = (b=a & M={#})\" using mset_union_1_elem1\n by (auto dest: sym)\n\n lemma mset_union_1_elem4[simp]: \"({#b#}+M={#a#}) = (b=a & M={#})\" using mset_union_1_elem3\n by (simp add: union_ac)\n\n lemma mset_inter_1elem1[simp]: assumes A: \"~(a :# B)\" shows \"{#a#} #\\ B = {#}\" proof (unfold multiset_inter_def)\n from A have \"{#a#} - B = {#a#}\" by simp\n thus \"{#a#} - ({#a#} - B) = {#}\" by simp\n qed\n\n lemma mset_inter_1elem2[simp]: \"~(a :# B) \\ B #\\ {#a#} = {#}\" proof -\n assume \"~(a :# B)\"\n hence \"{#a#} #\\ B = {#}\" by simp\n thus ?thesis by (simp add: multiset_inter_commute)\n qed\n\n lemmas mset_inter_1elem = mset_inter_1elem1 mset_inter_1elem2\n\n\n lemmas mset_neutral_cancel1 = union_left_cancel[where N=\"{#}\", simplified] union_right_cancel[where N=\"{#}\", simplified]\n declare mset_neutral_cancel1[simp]\n\n lemma mset_neutral_cancel2[simp]: \"(c=n+c) = (n={#})\" \"(c=c+n) = (n={#})\"\n apply (auto simp add: union_ac)\n apply (subgoal_tac \"c+n=c\", simp_all)+\n done\n\n\n\n (* TODO: The proof seems too complicated, there should be an easier one ! *)\n lemma mset_union_2_elem: \"{#a#}+{#b#} = M + {#c#} \\ {#a#}=M & b=c | a=c & {#b#}=M\" \n proof -\n assume A: \"{#a#}+{#b#} = M + {#c#}\"\n hence \"{#a#}+{#b#}-{#b#} = M + {#c#} - {#b#}\" by auto\n hence AEQ: \"{#a#} = M + {#c#} - {#b#}\" by (auto simp add: union_assoc)\n { assume \"c=b\"\n with AEQ have \"{#a#} = M\" by auto \n } moreover {\n from A have \"{#b#}+{#a#} = M + {#c#}\" by (auto simp add: union_commute)\n moreover assume \"a=c\"\n ultimately have \"{#b#} = M\" by auto\n } moreover {\n assume NEQ: \"c~=b & a~=c\"\n from A have \"{#a#}+{#b#}-{#c#} = M + {#c#}-{#c#}\" by auto\n hence \"{#a#}+{#b#}-{#c#} = M\" by (auto simp add: union_assoc)\n with NEQ have \"{#a#}-{#c#}+{#b#} = M\" by (subgoal_tac \"~ (c :# {#b#})\", auto simp add: mset_inter_1elem multiset_union_diff_commute)\n with NEQ have \"{#a#}+{#b#} = M\" by (subgoal_tac \"~(a :# {#c#})\", auto simp add: mset_diff_cancel1elem)\n hence S1: \"size M = 2\" by auto\n moreover from A have \"size ({#a#}+{#b#}) = size (M + {#c#})\" by auto\n hence \"size M = 1\" by auto\n ultimately have \"False\" by simp\n }\n ultimately show ?thesis by blast\n qed\n\n lemma mset_diff_union_s_inverse[simp]: \"s :# S \\ {#s#} + (S - {# s #}) = S\" proof -\n assume \"s :# S\"\n hence \"S = S - {#s#} + {#s#}\" by (auto simp add: mset_union_diff_comm)\n thus ?thesis by (auto simp add: union_ac)\n qed\n\n lemma mset_un_iff: \"(a :# A + B) = (a :# A | a :# B)\"\n by (simp)\n lemma mset_un_cases[cases set, case_names left right]: \"\\a :# A + B; a:#A \\ P; a:#B \\ P\\ \\ P\"\n by (auto)\n\n lemma mset_unplusm_dist_cases[cases set, case_names left right]:\n assumes A: \"{#s#}+A = B+C\"\n assumes L: \"\\B={#s#}+(B-{#s#}); A=(B-{#s#})+C\\ \\ P\"\n assumes R: \"\\C={#s#}+(C-{#s#}); A=B+(C-{#s#})\\ \\ P\" \n shows P\n proof -\n from A[symmetric] have \"s :# B+C\" by simp\n thus ?thesis proof (cases rule: mset_un_cases)\n case left hence 1: \"B={#s#}+(B-{#s#})\" by simp\n with A have \"{#s#}+A = {#s#}+((B-{#s#})+C)\" by (simp add: union_ac)\n hence 2: \"A = (B-{#s#})+C\" by (simp)\n from L[OF 1 2] show ?thesis .\n next\n case right hence 1: \"C={#s#}+(C-{#s#})\" by simp\n with A have \"{#s#}+A = {#s#}+(B+(C-{#s#}))\" by (simp add: union_ac)\n hence 2: \"A = B+(C-{#s#})\" by (simp)\n from R[OF 1 2] show ?thesis .\n qed\n qed\n\n lemma mset_unplusm_dist_cases2[cases set, case_names left right]:\n assumes A: \"B+C = {#s#}+A\"\n assumes L: \"\\B={#s#}+(B-{#s#}); A=(B-{#s#})+C\\ \\ P\"\n assumes R: \"\\C={#s#}+(C-{#s#}); A=B+(C-{#s#})\\ \\ P\" \n shows P\n using mset_unplusm_dist_cases[OF A[symmetric]] L R by blast\n\n lemma mset_single_cases[cases set, case_names loc env]: \n assumes A: \"{#s#}+c = {#r'#}+c'\" \n assumes CASES: \"\\s=r'; c=c'\\ \\ P\" \"\\c'={#s#}+(c'-{#s#}); c={#r'#}+(c-{#r'#}); c-{#r'#} = c'-{#s#} \\ \\ P\" \n shows \"P\"\n proof -\n { assume CASE: \"s=r'\"\n with A have \"c=c'\" by simp\n with CASE CASES have ?thesis by auto\n } moreover {\n assume CASE: \"s\\r'\"\n have \"s:#{#s#}+c\" by simp\n with A have \"s:#{#r'#}+c'\" by simp\n with CASE have \"s:#c'\" by (auto elim!: mset_un_cases split: split_if_asm)\n from mset_diff_union_s_inverse[OF this, symmetric] have 1: \"c' = {#s#} + (c' - {#s#})\" .\n with A have \"{#s#}+c = {#s#}+({#r'#}+(c' - {#s#}))\" by (auto simp add: union_ac)\n hence 2: \"c={#r'#}+(c' - {#s#})\" by (auto)\n hence 3: \"c-{#r'#} = (c' - {#s#})\" by auto\n from 1 2 3 CASES have ?thesis by auto\n } ultimately show ?thesis by blast\n qed\n\n lemma mset_single_cases'[cases set, case_names loc env]: \n assumes A: \"{#s#}+c = {#r'#}+c'\" \n assumes CASES: \"\\s=r'; c=c'\\ \\ P\" \"!!cc. \\c'={#s#}+cc; c={#r'#}+cc; c'-{#s#}=cc; c-{#r'#}=cc\\ \\ P\" \n shows \"P\"\n using A CASES by (auto elim!: mset_single_cases)\n\n lemma mset_single_cases2[cases set, case_names loc env]: \n assumes A: \"c+{#s#} = c'+{#r'#}\" \n assumes CASES: \"\\s=r'; c=c'\\ \\ P\" \"\\c'=(c'-{#s#})+{#s#}; c=(c-{#r'#})+{#r'#}; c-{#r'#} = c'-{#s#} \\ \\ P\" \n shows \"P\" \n proof -\n from A have \"{#s#}+c = {#r'#}+c'\" by (simp add: union_ac)\n thus ?thesis proof (cases rule: mset_single_cases)\n case loc with CASES show ?thesis by simp\n next\n case env with CASES show ?thesis by (simp add: union_ac)\n qed\n qed\n\n lemma mset_single_cases2'[cases set, case_names loc env]: \n assumes A: \"c+{#s#} = c'+{#r'#}\" \n assumes CASES: \"\\s=r'; c=c'\\ \\ P\" \"!!cc. \\c'=cc+{#s#}; c=cc+{#r'#}; c'-{#s#}=cc; c-{#r'#}=cc\\ \\ P\" \n shows \"P\"\n using A CASES by (auto elim!: mset_single_cases2)\n\n lemma mset_un_single_un_cases[consumes 1, case_names left right]: assumes A: \"A+{#a#} = B+C\" and CASES: \"\\a:#B; A=(B-{#a#})+C\\ \\ P\" \"\\a:#C; A=B+(C-{#a#})\\ \\ P\" shows \"P\"\n proof -\n have \"a:#A+{#a#}\" by simp\n with A have \"a:#B+C\" by auto\n thus ?thesis proof (cases rule: mset_un_cases)\n case left hence \"B=B-{#a#}+{#a#}\" by auto\n with A have \"A+{#a#} = (B-{#a#})+C+{#a#}\" by (auto simp add: union_ac)\n hence \"A=(B-{#a#})+C\" by simp\n with CASES(1)[OF left] show ?thesis by blast\n next\n case right hence \"C=C-{#a#}+{#a#}\" by auto\n with A have \"A+{#a#} = B+(C-{#a#})+{#a#}\" by (auto simp add: union_ac)\n hence \"A=B+(C-{#a#})\" by simp\n with CASES(2)[OF right] show ?thesis by blast\n qed\n qed\n\n (* TODO: Can this proof be done more automatically ? *)\n lemma mset_distrib[consumes 1, case_names dist]: assumes A: \"(A::'a multiset)+B = M+N\" \"!!Am An Bm Bn. \\A=Am+An; B=Bm+Bn; M=Am+Bm; N=An+Bn\\ \\ P\" shows \"P\"\n proof -\n { \n fix X\n have \"!!A B M N P. \\ (X::'a multiset)=A+B; A+B = M+N; !!Am An Bm Bn. \\A=Am+An; B=Bm+Bn; M=Am+Bm; N=An+Bn\\ \\ P\\ \\ P\"\n proof (induct X)\n case empty thus ?case by simp\n next\n case (add X x A B M N) \n from add(2,3) have MN: \"X+{#x#} = M+N\" by simp\n from add(2) show ?case proof (cases rule: mset_un_single_un_cases)\n case left from MN show ?thesis proof (cases rule: mset_un_single_un_cases[case_names left' right'])\n case left' with left have \"X=A-{#x#}+B\" \"A-{#x#}+B = M-{#x#}+N\" by simp_all\n from \"add.hyps\"[OF this] obtain Am An Bm Bn where \"A - {#x#} = Am + An\" \"B = Bm + Bn\" \"M - {#x#} = Am + Bm\" \"N = An + Bn\" .\n hence \"A - {#x#} + {#x#} = Am+{#x#} + An\" \"B = Bm + Bn\" \"M - {#x#}+{#x#} = Am+{#x#} + Bm\" \"N = An + Bn\" by (simp_all add: union_ac)\n with left(1) left'(1) show ?thesis using \"add.prems\"(3) by auto\n next\n case right' with left have \"X=A-{#x#}+B\" \"A-{#x#}+B = M+(N-{#x#})\" by simp_all\n from \"add.hyps\"[OF this] obtain Am An Bm Bn where \"A - {#x#} = Am + An\" \"B = Bm + Bn\" \"M = Am + Bm\" \"N-{#x#} = An + Bn\" .\n hence \"A - {#x#} + {#x#} = Am + (An+{#x#})\" \"B = Bm + Bn\" \"M = Am + Bm\" \"N - {#x#}+{#x#} = (An+{#x#}) + Bn\" by (simp_all add: union_ac)\n with left(1) right'(1) show ?thesis using \"add.prems\"(3) by auto\n qed\n next\n case right from MN show ?thesis proof (cases rule: mset_un_single_un_cases[case_names left' right'])\n case left' with right have \"X=A+(B-{#x#})\" \"A+(B-{#x#}) = M-{#x#}+N\" by simp_all\n from \"add.hyps\"[OF this] obtain Am An Bm Bn where \"A = Am + An\" \"B-{#x#} = Bm + Bn\" \"M - {#x#} = Am + Bm\" \"N = An + Bn\" .\n hence \"A = Am + An\" \"B-{#x#}+{#x#} = Bm+{#x#} + Bn\" \"M - {#x#}+{#x#} = Am + (Bm+{#x#})\" \"N = An + Bn\" by (simp_all add: union_ac)\n with right(1) left'(1) show ?thesis using \"add.prems\"(3) by auto\n next\n case right' with right have \"X=A+(B-{#x#})\" \"A+(B-{#x#}) = M+(N-{#x#})\" by simp_all\n from \"add.hyps\"[OF this] obtain Am An Bm Bn where \"A = Am + An\" \"B-{#x#} = Bm + Bn\" \"M = Am + Bm\" \"N-{#x#} = An + Bn\" .\n hence \"A = Am + An\" \"B-{#x#}+{#x#} = Bm + (Bn+{#x#})\" \"M = Am + Bm\" \"N - {#x#}+{#x#} = An + (Bn+{#x#})\" by (simp_all add: union_ac)\n with right(1) right'(1) show ?thesis using \"add.prems\"(3) by auto\n qed\n qed\n qed\n } with A show ?thesis by blast\n qed\n\n\nsubsubsection {* Singleton multisets *} \n lemma mset_singletonI[intro!]: \"a :# {#a#}\"\n by auto\n\n lemma mset_singletonD[dest!]: \"b :# {#a#} \\ b=a\" \n apply(cases \"a=b\")\n apply(auto)\n done\n\nlemma mset_size_le1_cases[case_names empty singleton,consumes 1]: \"\\ size M \\ Suc 0; M={#} \\ P; !!m. M={#m#} \\ P \\ \\ P\"\n by (cases M) auto\n\nlemma diff_union_single_conv2: \"a :# J \\ J + I - {#a#} = (J - {#a#}) + I\" using diff_union_single_conv[of J a I]\n by (simp add: union_ac)\n\nlemmas diff_union_single_convs = diff_union_single_conv diff_union_single_conv2\n\nlemma mset_contains_eq: \"(m:#M) = ({#m#}+(M-{#m#})=M)\" proof (auto)\n assume \"{#m#} + (M - {#m#}) = M\"\n moreover have \"m :# {#m#} + (M - {#m#})\" by simp\n ultimately show \"m:#M\" by simp\nqed\n\n\nsubsubsection {* Pointwise ordering *}\n \n\n (*declare mset_le_trans[trans] Seems to be in there now. Why is this not done in Multiset.thy or order-class ? *)\n\n lemma mset_empty_minimal[simp, intro!]: \"{#} \\ c\"\n by (unfold mset_le_def, auto)\n lemma mset_empty_least[simp]: \"c \\ {#} = (c={#})\"\n by (unfold mset_le_def, auto)\n lemma mset_empty_leastI[intro!]: \"c={#} \\ c \\ {#}\"\n by (simp only: mset_empty_least)\n\n lemma mset_le_incr_right1: \"a\\(b::'a multiset) \\ a\\b+c\" using mset_le_mono_add[of a b \"{#}\" c, simplified] .\n lemma mset_le_incr_right2: \"a\\(b::'a multiset) \\ a\\c+b\" using mset_le_incr_right1\n by (auto simp add: union_commute)\n lemmas mset_le_incr_right = mset_le_incr_right1 mset_le_incr_right2\n\n lemma mset_le_decr_left1: \"a+c\\(b::'a multiset) \\ a\\b\" using mset_le_incr_right1 mset_le_mono_add_right_cancel\n by blast\n lemma mset_le_decr_left2: \"c+a\\(b::'a multiset) \\ a\\b\" using mset_le_decr_left1\n by (auto simp add: union_ac)\n lemmas mset_le_decr_left = mset_le_decr_left1 mset_le_decr_left2\n \n lemma mset_le_single_conv[simp]: \"({#e#}\\M) = (e:#M)\"\n by (unfold mset_le_def) auto\n\n lemma mset_le_trans_elem: \"\\e :# c; c \\ c'\\ \\ e :# c'\" using order_trans[of \"{#e#}\" c c', simplified]\n by assumption\n\n \n\n lemma mset_le_union: \"A+B \\ C \\ A\\C \\ B\\(C::'a multiset)\"\n by (auto dest: mset_le_decr_left)\n\n lemma mset_le_subtract_left: \"A+B \\ (X::'a multiset) \\ B \\ X-A \\ A\\X\"\n by (auto dest: mset_le_subtract[of \"A+B\" \"X\" \"A\"] mset_le_union)\n lemma mset_le_subtract_right: \"A+B \\ (X::'a multiset) \\ A \\ X-B \\ B\\X\"\n by (auto dest: mset_le_subtract[of \"A+B\" \"X\" \"B\"] mset_le_union)\n \n lemma mset_le_addE: \"\\ xs \\ (ys::'a multiset); !!zs. ys=xs+zs \\ P \\ \\ P\" using mset_le_exists_conv\n by blast\n\n lemma mset_le_sub_add_eq[simp,intro]: \"A\\(B::'a multiset) \\ B-A+A = B\"\n by (auto elim: mset_le_addE simp add: union_ac)\n\n lemma mset_2dist2_cases:\n assumes A: \"{#a#}+{#b#} \\ A+B\"\n assumes CASES: \"{#a#}+{#b#} \\ A \\ P\" \"{#a#}+{#b#} \\ B \\ P\" \"\\a :# A; b :# B\\ \\ P\" \"\\a :# B; b :# A\\ \\ P\"\n shows \"P\"\n proof -\n { assume C: \"a :# A\" \"b :# A-{#a#}\" \n with mset_le_mono_add[of \"{#a#}\" \"{#a#}\" \"{#b#}\" \"A-{#a#}\"] have \"{#a#}+{#b#} \\ A\" by auto\n } moreover {\n assume C: \"a :# A\" \"\\ (b :# A-{#a#})\"\n with A have \"b:#B\" by (unfold mset_le_def) (auto split: split_if_asm)\n } moreover {\n assume C: \"\\ (a :# A)\" \"b :# B-{#a#}\"\n with A have \"a :# B\" by (unfold mset_le_def) (auto split: split_if_asm)\n with C mset_le_mono_add[of \"{#a#}\" \"{#a#}\" \"{#b#}\" \"B-{#a#}\"] have \"{#a#}+{#b#} \\ B\" by auto\n } moreover {\n assume C: \"\\ (a :# A)\" \"\\ (b :# B-{#a#})\"\n with A have \"a:#B \\ b:#A\" by (unfold mset_le_def) (auto split: split_if_asm)\n } ultimately show P using CASES by blast\n qed\n\n lemma mset_union_subset: \"A+B \\ (C::'a multiset) \\ A\\C \\ B\\C\" \n apply (unfold mset_le_def)\n apply auto\n apply (subgoal_tac \"count A a + count B a \\ count C a\", arith, simp)+\n done\n\n lemma mset_union_subset_s: \"{#a#}+B \\ C \\ a :# C \\ B \\ C\"\n by (auto dest: mset_union_subset)\n\n (* TODO: Check which of these lemmas are already introduced by order-classes ! *)\n lemma mset_le_eq_refl: \"a=(b::'a multiset) \\ a\\b\"\n by simp\n\n lemma mset_singleton_eq[simplified,simp]: \"a :# {#b#} = (a=b)\"\n by auto -- {* The simplification is here due to the lemma @{thm [source] \"Multiset.count_single\"}, that will be applied first deleting any application potential for this rule*}\n lemma mset_le_single_single[simp]: \"({#a#} \\ {#b#}) = (a=b)\"\n by auto\n\n lemma mset_le_single_conv1[simp]: \"(M+{#a#} \\ {#b#}) = (M={#} \\ a=b)\"\n proof (auto) \n assume A: \"M+{#a#} \\ {#b#}\" thus \"a=b\" by (auto dest: mset_le_decr_left2)\n with A mset_le_mono_add_right_cancel[of M \"{#a#}\" \"{#}\", simplified] show \"M={#}\" by blast\n qed\n \n lemma mset_le_single_conv2[simp]: \"({#a#}+M \\ {#b#}) = (M={#} \\ a=b)\"\n by (simp add: union_ac)\n \n lemma mset_le_single_cases[consumes 1, case_names empty singleton]: \"\\M\\{#a#}; M={#} \\ P; M={#a#} \\ P\\ \\ P\"\n by (induct M) auto\n \n \n\n lemma mset_le_mono_add_single: \"\\a :# ys; b :# ws\\ \\ {#a#} + {#b#} \\ ys + ws\" using mset_le_mono_add[of \"{#a#}\" _ \"{#b#}\", simplified] .\n\n lemma mset_size1elem: \"\\size P \\ 1; q :# P\\ \\ P={#q#}\"\n by (auto elim: mset_size_le1_cases)\n lemma mset_size2elem: \"\\size P \\ 2; {#q#}+{#q'#} \\ P\\ \\ P={#q#}+{#q'#}\"\n by (auto elim: mset_le_addE)\n\n\nsubsubsection {* Image under function *}\n\ninductive_set \n mset_map_Set :: \"('a \\ 'b) \\ ('a multiset \\ 'b multiset) set\"\n for f:: \"'a \\ 'b\"\n where\n mset_map_Set_empty: \"({#},{#})\\mset_map_Set f\"\n | mset_map_Set_add: \"(A,B)\\mset_map_Set f \\ (A+{#a#},B+{#f a#})\\mset_map_Set f\"\n\nlemma mset_map_Set_empty_simps[simp]: \"(({#},B)\\mset_map_Set f) = (B={#})\" \"((A,{#})\\mset_map_Set f) = (A={#})\"\n by (auto elim: mset_map_Set.cases intro: mset_map_Set_empty)\n\nlemma mset_map_Set_single_left[simp]: \"(({#a#},B)\\mset_map_Set f) = (B={#f a#})\"\n by (auto elim: mset_map_Set.cases intro: mset_map_Set_add[of \"{#}\" \"{#}\", simplified])\nlemma mset_map_Set_single_rightE[cases set, case_names orig]: \"\\(A,{#b#})\\mset_map_Set f; !!a. \\A={#a#}; b=f a\\ \\ P\\ \\ P\"\n by (auto elim: mset_map_Set.cases)\n\nlemma mset_map_Set_sizes: \"(A,B)\\mset_map_Set f \\ size A = size B\"\n by (induct rule: mset_map_Set.induct) auto\n\ntext {* Intuitively, this lemma allows one to choose a single image element corresponding to an original element *}\nlemma mset_map_Set_choose[cases set, case_names choice]: assumes A: \"(A+{#a#},B)\\mset_map_Set f\" \"!!B'. \\B=B'+{#f a#}; (A,B')\\mset_map_Set f\\ \\ P\" shows \"P\" \nproof -\n { fix n\n have \"\\size B=n; (A+{#a#},B)\\mset_map_Set f; !!B'. \\B=B'+{#f a#}; (A,B')\\mset_map_Set f\\ \\ P \\ \\ P\" proof (induct n arbitrary: A a B P)\n\n (*have \"!!A a B P. \\size B=n; (A+{#a#},B)\\mset_map_Set f; !!B'. \\B=B'+{#f a#}; (A,B')\\mset_map_Set f\\ \\ P \\ \\ P\" proof (induct n)*)\n case 0 thus ?case by simp\n next\n case (Suc n') from Suc.prems(2) show ?case proof (cases rule: mset_map_Set.cases)\n case mset_map_Set_empty hence False by simp thus ?thesis ..\n next\n case (mset_map_Set_add A' B' a') \n hence \"A+{#a#}=A'+{#a'#}\" by simp\n thus ?thesis proof (cases rule: mset_single_cases2')\n case loc with mset_map_Set_add Suc.prems(3) show ?thesis by auto\n next\n case (env A'') \n from Suc.prems(1) mset_map_Set_add(2) have SIZE: \"size B' = n'\" by auto\n from mset_map_Set_add env have MM: \"(A'' + {#a#}, B') \\ mset_map_Set f\" by simp\n from Suc.hyps[OF SIZE MM] obtain B'' where B'': \"B'=B''+{#f a#}\" \"(A'',B'')\\mset_map_Set f\" by blast\n from mset_map_Set.mset_map_Set_add[OF B''(2)] env(2) have \"(A, B'' + {#f a'#}) \\ mset_map_Set f\" by simp\n moreover from B''(1) mset_map_Set_add have \"B=B'' + {#f a'#} + {#f a#}\" by (simp add: union_ac)\n ultimately show ?thesis using Suc.prems(3) by blast\n qed\n qed\n qed\n } with A show P by blast\nqed\n\nlemma mset_map_Set_unique: \"!!B B'. \\(A,B)\\mset_map_Set f; (A,B')\\mset_map_Set f\\ \\ B=B'\"\n by (induct A) (auto elim!: mset_map_Set_choose)\nlemma mset_map_Set_surjective: \"\\ !!B. (A,B)\\mset_map_Set f \\ P \\ \\ P\"\n by (induct A) (auto intro: mset_map_Set_add)\n\n\ndefinition\n mset_map :: \"('a \\ 'b) \\ 'a multiset \\ 'b multiset\" (infixr \"`#\" 90)\n where\n \"f `# A == (THE B. (A,B)\\mset_map_Set f)\"\n\n\ninterpretation mset_map: su_rel_fun \"mset_map_Set f\" \"op `# f\"\n apply (rule su_rel_fun.intro)\n apply (erule mset_map_Set_unique, assumption)\n apply (erule mset_map_Set_surjective)\n apply (rule mset_map_def)\n done\n \ntext {* Transfer the defining equations *}\nlemma mset_map_empty[simp]: \"f `# {#} = {#}\"\n apply (subst mset_map.repr)\n apply (rule mset_map_Set_empty)\n done\n\nlemma mset_map_add[simp]: \"f `# (A+{#a#}) = f `# A + {#f a#}\" \"f `# ({#a#}+A) = {#f a#} + f `# A\"\n by (auto simp add: mset_map.repr union_commute intro: mset_map_Set_add mset_map.repr1)\n\ntext {* Transfer some other lemmas *}\nlemma mset_map_single_rightE[consumes 1, case_names orig]: \"\\f `# P = {#y#}; !!x. \\ P={#x#}; f x = y \\ \\ Q \\ \\ Q\"\n by (auto simp add: mset_map.repr elim: mset_map_Set_single_rightE)\n\ntext {* And show some further equations *}\nlemma mset_map_single[simp]: \"f `# {#a#} = {#f a#}\" using mset_map_add(1)[where A=\"{#}\", simplified] .\n\nlemma mset_map_union: \"!!B. f `# (A+B) = f `# A + f `# B\"\n by (induct A) (auto simp add: union_ac)\n\nlemma mset_map_size: \"size A = size (f `# A)\"\n by (induct A) auto\n\nlemma mset_map_empty_eq[simp]: \"(f `# P = {#}) = (P={#})\" using mset_map_size[of P f]\n by auto\n\nlemma mset_map_le: \"!!B. A \\ B \\ f `# A \\ f `# B\" proof (induct A)\n case empty thus ?case by simp\nnext\n case (add A x B)\n hence \"A\\B-{#x#}\" and SM: \"{#x#}\\B\" using mset_le_subtract_right by (fastforce+)\n with \"add.hyps\" have \"f `# A \\ f `# (B-{#x#})\" by blast\n hence \"f `# (A+{#x#}) \\ f `# (B-{#x#}) + {#f x#}\" by auto\n also have \"\\ = f `# (B-{#x#}+{#x#})\" by simp\n also with SM have \"\\ = f `# B\" by simp\n finally show ?case .\nqed\n\nlemma mset_map_set_of: \"set_of (f `# A) = f ` set_of A\"\n by (induct A) auto\n\nlemma mset_map_split_orig: \"!!M1 M2. \\f `# P = M1+M2; !!P1 P2. \\P=P1+P2; f `# P1 = M1; f `# P2 = M2\\ \\ Q \\ \\ Q\"\n apply (induct P)\n apply fastforce\n apply (fastforce elim!: mset_un_single_un_cases simp add: union_ac) (* TODO: This proof need's quite long. Try to write a faster one. *)\n done\n\nlemma mset_map_id: \"\\!!x. f (g x) = x\\ \\ f `# g `# X = X\"\n by (induct X) auto\n\ntext {* The following is a very specialized lemma. Intuitively, it splits the original multiset\n by a splitting of some pointwise supermultiset of its image.\n\n Application:\n This lemma came in handy when proving the correctness of a constraint system that collects at most k sized submultisets of the sets of spawned threads.\n*}\nlemma mset_map_split_orig_le: assumes A: \"f `# P \\ M1+M2\" and EX: \"!!P1 P2. \\P=P1+P2; f `# P1 \\ M1; f `# P2 \\ M2\\ \\ Q\" shows \"Q\" \n using A EX by (auto elim: mset_le_distrib mset_map_split_orig)\n\n\nsubsection {* Lists *}\n\n -- \"Obtains a list from the pointwise characterization of its elements\"\n (* Put here, because other lemmas depends on it *)\nlemma obtain_list_from_elements:\n assumes A: \"\\ili. P li i)\"\n obtains l where \n \"length l = n\"\n \"\\il. length l=n \\ (\\iii x \\ l\\[]\"\n by auto\n\nlemma list_take_induct_tl2:\n \"\\length xs = length ys; \\n \n \\ \\n < length (tl xs). P ((tl ys) ! n) ((tl xs) ! n)\"\nby (induct xs ys rule: list_induct2) auto\n\nlemma not_distinct_split_distinct:\n assumes \"\\ distinct xs\"\n obtains y ys zs where \"distinct ys\" \"y \\ set ys\" \"xs = ys@[y]@zs\"\nusing assms\nproof (induct xs rule: rev_induct)\n case Nil thus ?case by simp\nnext\n case (snoc x xs) thus ?case by (cases \"distinct xs\") auto\nqed\n\nlemma distinct_length_le:\n assumes d: \"distinct ys\"\n and eq: \"set ys = set xs\"\n shows \"length ys \\ length xs\"\nproof -\n from d have \"length ys = card (set ys)\" by (simp add: distinct_card)\n also from eq List.card_set have \"card (set ys) = length (remdups xs)\" by simp\n also have \"... \\ length xs\" by simp\n finally show ?thesis .\nqed\n\nlemma find_SomeD:\n \"List.find P xs = Some x \\ P x\"\n \"List.find P xs = Some x \\ x\\set xs\"\n by (auto simp add: find_Some_iff)\n\nsubsubsection {* List Destructors *}\nlemma not_hd_in_tl:\n \"x \\ hd xs \\ x \\ set xs \\ x \\ set (tl xs)\"\nby (induct xs) simp_all\n\nlemma distinct_hd_tl:\n \"distinct xs \\ x = hd xs \\ x \\ set (tl (xs))\"\nby (induct xs) simp_all\n\nlemma in_set_tlD: \"x \\ set (tl xs) \\ x \\ set xs\"\nby (induct xs) simp_all\n\nlemma nth_tl: \"xs \\ [] \\ tl xs ! n = xs ! Suc n\"\nby (induct xs) simp_all\n\nlemma tl_subset:\n \"xs \\ [] \\ set xs \\ A \\ set (tl xs) \\ A\"\nby (metis in_set_tlD set_rev_mp subsetI)\n\nlemma tl_last:\n \"tl xs \\ [] \\ last xs = last (tl xs)\"\nby (induct xs) simp_all\n\nlemma tl_obtain_elem:\n assumes \"xs \\ []\" \"tl xs = []\"\n obtains e where \"xs = [e]\"\nusing assms\nby (induct xs rule: list_nonempty_induct) simp_all\n\nlemma butlast_subset:\n \"xs \\ [] \\ set xs \\ A \\ set (butlast xs) \\ A\"\nby (metis in_set_butlastD set_rev_mp subsetI)\n\nlemma butlast_rev_tl:\n \"xs \\ [] \\ butlast (rev xs) = rev (tl xs)\"\nby (induct xs rule: rev_induct) simp_all\n\nlemma hd_butlast:\n \"length xs > 1 \\ hd (butlast xs) = hd xs\"\nby (induct xs) simp_all\n\nlemma butlast_upd_last_eq[simp]: \"length l \\ 2 \\ \n butlast l [ length l - 2 := x ] = take (length l - 2) l @ [x]\"\n apply (case_tac l rule: rev_cases)\n apply simp\n apply simp\n apply (case_tac ys rule: rev_cases)\n apply simp\n apply simp\n done\n\n\nsubsubsection {* @{text \"list_all2\"} *}\nlemma list_all2_induct[consumes 1, case_names Nil Cons]:\n assumes \"list_all2 P l l'\"\n assumes \"Q [] []\"\n assumes \"\\x x' ls ls'. \\ P x x'; list_all2 P ls ls'; Q ls ls' \\ \n \\ Q (x#ls) (x'#ls')\"\n shows \"Q l l'\"\n using list_all2_lengthD[OF assms(1)] assms \n apply (induct rule: list_induct2)\n apply auto\n done\n\n\nsubsubsection {* Reverse lists *}\n lemma list_rev_decomp[rule_format]: \"l~=[] \\ (EX ll e . l = ll@[e])\"\n apply(induct_tac l)\n apply(auto)\n done\n \n (* Was already there as rev_induct\n lemma list_rev_induct: \"\\P []; !! l e . P l \\ P (l@[e]) \\ \\ P l\"\n by (blast intro: rev_induct)\n proof (induct l rule: measure_induct[of length])\n fix x :: \"'a list\"\n assume A: \"\\y. length y < length x \\ P [] \\ (\\x xa. P (x::'a list) \\ P (x @ [xa])) \\ P y\" \"P []\" and IS: \"\\l e. P l \\ P (l @ [e])\"\n show \"P x\" proof (cases \"x=[]\")\n assume \"x=[]\" with A show ?thesis by simp\n next\n assume CASE: \"x~=[]\"\n then obtain xx e where DECOMP: \"x=xx@[e]\" by (blast dest: list_rev_decomp)\n hence LEN: \"length xx < length x\" by auto\n with A IS have \"P xx\" by auto\n with IS have \"P (xx@[e])\" by auto\n with DECOMP show ?thesis by auto\n qed\n qed\n *)\n\n text {* Caution: Same order of case variables in snoc-case as @{thm [source] rev_exhaust}, the other way round than @{thm [source] rev_induct} ! *}\n lemma length_compl_rev_induct[case_names Nil snoc]: \"\\P []; !! l e . \\!! ll . length ll <= length l \\ P ll\\ \\ P (l@[e])\\ \\ P l\"\n apply(induct_tac l rule: length_induct)\n apply(case_tac \"xs\" rule: rev_cases)\n apply(auto)\n done\n\n lemma list_append_eq_Cons_cases[consumes 1]: \"\\ys@zs = x#xs; \\ys=[]; zs=x#xs\\ \\ P; !!ys'. \\ ys=x#ys'; ys'@zs=xs \\ \\ P \\ \\ P\"\n by (auto iff add: append_eq_Cons_conv)\n lemma list_Cons_eq_append_cases[consumes 1]: \"\\x#xs = ys@zs; \\ys=[]; zs=x#xs\\ \\ P; !!ys'. \\ ys=x#ys'; ys'@zs=xs \\ \\ P \\ \\ P\"\n by (auto iff add: Cons_eq_append_conv)\n\nlemma map_of_rev_distinct[simp]: \n \"distinct (map fst m) \\ map_of (rev m) = map_of m\"\n apply (induct m)\n apply simp\n\n apply simp\n apply (subst map_add_comm)\n apply force\n apply simp\n done\n\n\n-- {* Tail-recursive, generalized @{const rev}. May also be used for\n tail-recursively getting a list with all elements of the two \n operands, if the order does not matter, e.g. when implementing \n sets by lists. *}\nfun revg where\n \"revg [] b = b\" |\n \"revg (a#as) b = revg as (a#b)\"\n\nlemma revg_fun[simp]: \"revg a b = rev a @ b\"\n by (induct a arbitrary: b)\n auto\n\n\nsubsubsection \"Folding\"\n\ntext \"Ugly lemma about foldl over associative operator with left and right neutral element\"\nlemma foldl_A1_eq: \"!!i. \\ !! e. f n e = e; !! e. f e n = e; !!a b c. f a (f b c) = f (f a b) c \\ \\ foldl f i ww = f i (foldl f n ww)\"\nproof (induct ww)\n case Nil thus ?case by simp\nnext\n case (Cons a ww i) note IHP[simplified]=this\n have \"foldl f i (a # ww) = foldl f (f i a) ww\" by simp\n also from IHP have \"\\ = f (f i a) (foldl f n ww)\" by blast\n also from IHP(4) have \"\\ = f i (f a (foldl f n ww))\" by simp\n also from IHP(1)[OF IHP(2,3,4), where i=a] have \"\\ = f i (foldl f a ww)\" by simp\n also from IHP(2)[of a] have \"\\ = f i (foldl f (f n a) ww)\" by simp\n also have \"\\ = f i (foldl f n (a#ww))\" by simp\n finally show ?case .\nqed\n\n\nlemmas foldl_conc_empty_eq = foldl_A1_eq[of \"op @\" \"[]\", simplified]\nlemmas foldl_un_empty_eq = foldl_A1_eq[of \"op \\\" \"{}\", simplified, OF Un_assoc[symmetric]]\n\nlemma foldl_set: \"foldl (op \\) {} l = \\{x. x\\set l}\"\n apply (induct l)\n apply simp_all\n apply (subst foldl_un_empty_eq)\n apply auto\n done\n\nlemma (in monoid_mult) foldl_absorb1: \"x*foldl (op *) 1 zs = foldl (op *) x zs\"\n apply (rule sym)\n apply (rule foldl_A1_eq)\n apply (auto simp add: mult.assoc)\ndone\n\ntext {* Towards an invariant rule for foldl *}\nlemma foldl_rule_aux:\n fixes I :: \"'\\ \\ 'a list \\ bool\"\n assumes initial: \"I \\0 l0\"\n assumes step: \"!!l1 l2 x \\. \\ l0=l1@x#l2; I \\ (x#l2) \\ \\ I (f \\ x) l2\"\n shows \"I (foldl f \\0 l0) []\"\n using initial step\n apply (induct l0 arbitrary: \\0)\n apply auto\n done\n\nlemma foldl_rule_aux_P:\n fixes I :: \"'\\ \\ 'a list \\ bool\"\n assumes initial: \"I \\0 l0\"\n assumes step: \"!!l1 l2 x \\. \\ l0=l1@x#l2; I \\ (x#l2) \\ \\ I (f \\ x) l2\"\n assumes final: \"!!\\. I \\ [] \\ P \\\"\n shows \"P (foldl f \\0 l0)\"\nusing foldl_rule_aux[of I \\0 l0, OF initial, OF step] final\nby simp\n\n\nlemma foldl_rule:\n fixes I :: \"'\\ \\ 'a list \\ 'a list \\ bool\"\n assumes initial: \"I \\0 [] l0\"\n assumes step: \"!!l1 l2 x \\. \\ l0=l1@x#l2; I \\ l1 (x#l2) \\ \\ I (f \\ x) (l1@[x]) l2\"\n shows \"I (foldl f \\0 l0) l0 []\"\n using initial step\n apply (rule_tac I=\"\\\\ lr. \\ll. l0=ll@lr \\ I \\ ll lr\" in foldl_rule_aux_P)\n apply auto\n done\n\ntext {*\n Invariant rule for foldl. The invariant is parameterized with\n the state, the list of items that have already been processed and \n the list of items that still have to be processed.\n*}\nlemma foldl_rule_P:\n fixes I :: \"'\\ \\ 'a list \\ 'a list \\ bool\"\n -- \"The invariant holds for the initial state, no items processed yet and all items to be processed:\"\n assumes initial: \"I \\0 [] l0\" \n -- \"The invariant remains valid if one item from the list is processed\"\n assumes step: \"!!l1 l2 x \\. \\ l0=l1@x#l2; I \\ l1 (x#l2) \\ \\ I (f \\ x) (l1@[x]) l2\"\n -- \"The proposition follows from the invariant in the final state, i.e. all items processed and nothing to be processed\"\n assumes final: \"!!\\. I \\ l0 [] \\ P \\\"\n shows \"P (foldl f \\0 l0)\"\n using foldl_rule[of I, OF initial step] by (simp add: final)\n\n\ntext {* Invariant reasoning over @{const foldl} for distinct lists. Invariant rule makes no \n assumptions about ordering. *}\nlemma distinct_foldl_invar: \n \"\\ distinct S; I (set S) \\0; \n \\x it \\. \\x \\ it; it \\ set S; I it \\\\ \\ I (it - {x}) (f \\ x)\n \\ \\ I {} (foldl f \\0 S)\"\nproof (induct S arbitrary: \\0)\n case Nil thus ?case by auto\nnext\n case (Cons x S)\n\n note [simp] = Cons.prems(1)[simplified]\n\n show ?case\n apply simp\n apply (rule Cons.hyps)\n proof -\n from Cons.prems(1) show \"distinct S\" by simp\n from Cons.prems(3)[of x \"set (x#S)\", simplified, \n OF Cons.prems(2)[simplified]] \n show \"I (set S) (f \\0 x)\" .\n fix xx it \\\n assume A: \"xx\\it\" \"it \\ set S\" \"I it \\\"\n show \"I (it - {xx}) (f \\ xx)\" using A(2)\n apply (rule_tac Cons.prems(3))\n apply (simp_all add: A(1,3))\n apply blast\n done\n qed\nqed\n\nlemma foldl_length_aux: \"foldl (\\i x. Suc i) a l = a + length l\"\n by (induct l arbitrary: a) auto\n\nlemmas foldl_length[simp] = foldl_length_aux[where a=0, simplified]\n\nlemma foldr_length_aux: \"foldr (\\x i. Suc i) l a = a + length l\"\n by (induct l arbitrary: a rule: rev_induct) auto\n\nlemmas foldr_length[simp] = foldr_length_aux[where a=0, simplified]\n\ncontext comp_fun_commute begin\n\nlemma foldl_f_commute: \"f a (foldl (\\a b. f b a) b xs) = foldl (\\a b. f b a) (f a b) xs\"\nby(induct xs arbitrary: b)(simp_all add: fun_left_comm)\n\nlemma foldr_conv_foldl: \"foldr f xs a = foldl (\\a b. f b a) a xs\"\nby(induct xs arbitrary: a)(simp_all add: foldl_f_commute)\n\nend\n\nlemma filter_conv_foldr:\n \"filter P xs = foldr (\\x xs. if P x then x # xs else xs) xs []\"\nby(induct xs) simp_all\n\nlemma foldr_Cons: \"foldr Cons xs [] = xs\"\nby(induct xs) simp_all\n\nlemma foldr_snd_zip:\n \"length xs \\ length ys \\ foldr (\\(x, y). f y) (zip xs ys) b = foldr f ys b\"\nproof(induct ys arbitrary: xs)\n case (Cons y ys) thus ?case by(cases xs) simp_all\nqed simp\n\nlemma foldl_snd_zip:\n \"length xs \\ length ys \\ foldl (\\b (x, y). f b y) b (zip xs ys) = foldl f b ys\"\nproof(induct ys arbitrary: xs b)\n case (Cons y ys) thus ?case by(cases xs) simp_all\nqed simp\n\n\n\nlemma foldl_foldl_conv_concat: \"foldl (foldl f) a xs = foldl f a (concat xs)\"\nby(induct xs arbitrary: a) simp_all\n\nlemma foldl_list_update:\n \"n < length xs \\ foldl f a (xs[n := x]) = foldl f (f (foldl f a (take n xs)) x) (drop (Suc n) xs)\"\nby(simp add: upd_conv_take_nth_drop)\n\nlemma map_by_foldl:\n fixes l :: \"'a list\" and f :: \"'a \\ 'b\"\n shows \"foldl (\\l x. l@[f x]) [] l = map f l\"\nproof -\n {\n fix l'\n have \"foldl (\\l x. l@[f x]) l' l = l'@map f l\"\n by (induct l arbitrary: l') auto\n } thus ?thesis by simp\nqed\n\nsubsubsection {* Sorting *}\n lemma sorted_in_between:\n assumes A: \"0\\i\" \"i x\" \"xk\" and \"kx\" and \"xk. i\\k \\ k l!k\\x \\ x x\")\n case True \n from True Suc.hyps have \"d = j - (i + 1)\" by simp\n moreover from True have \"i+1 < j\"\n by (metis Suc.prems Suc_eq_plus1 Suc_lessI not_less)\n moreover from True have \"0\\i+1\" by simp\n ultimately obtain k where\n \"i+1\\k\" \"k x\" \"xk\" \"k x\" \"x l!j\" \n by (simp add: sorted_equals_nth_mono)\n also from nth_eq_iff_index_eq[OF D] B have \"l!i \\ l!j\"\n by auto\n finally show ?thesis .\nqed\n\nlemma distinct_sorted_strict_mono_iff:\n assumes \"distinct l\" \"sorted l\"\n assumes \"i il!j \\ i\\j\"\n by (metis assms distinct_sorted_strict_mono_iff leD le_less_linear)\n\n\nlemma sorted_hd_last:\n \"\\sorted l; l\\[]\\ \\ hd l \\ last l\"\n by (metis List.last_in_set eq_iff list.sel(1) last.simps sorted.cases)\n\nlemma (in linorder) sorted_hd_min: \n \"\\xs \\ []; sorted xs\\ \\ \\x \\ set xs. hd xs \\ x\"\n by (induct xs, auto simp add: sorted_Cons)\n\nlemma sorted_append_bigger: \n \"\\sorted xs; \\x \\ set xs. x \\ y\\ \\ sorted (xs @ [y])\"\n apply (induct xs)\n apply simp\nproof -\n case goal1\n from goal1 have s: \"sorted xs\" by (cases xs) simp_all\n from goal1 have a: \"\\x\\set xs. x \\ y\" by simp\n from goal1(1)[OF s a] goal1(2-) show ?case by (cases xs) simp_all\nqed\n\nlemma sorted_filter':\n \"sorted l \\ sorted (filter P l)\"\n using sorted_filter[where f=id, simplified] .\n\nsubsubsection {* Map *}\nlemma map_eq_consE: \"\\map f ls = fa#fl; !!a l. \\ ls=a#l; f a=fa; map f l = fl \\ \\ P\\ \\ P\"\n by auto\n\nlemma map_eq_concE: \"\\map f ls = fl@fl'; !!l l'. \\ ls=l@l'; map f l=fl; map f l' = fl' \\ \\ P\\ \\ P\"\nproof (induction fl arbitrary: ls P)\n case (Cons x xs)\n then obtain l ls' where [simp]: \"ls = l#ls'\" \"f l = x\" by force\n with Cons.prems(1) have \"map f ls' = xs @ fl'\" by simp\n from Cons.IH[OF this] guess ll ll' .\n with Cons.prems(2)[of \"l#ll\" ll'] show P by simp\nqed simp\n\nlemma map_fst_mk_snd[simp]: \"map fst (map (\\x. (x,k)) l) = l\" by (induct l) auto\nlemma map_snd_mk_fst[simp]: \"map snd (map (\\x. (k,x)) l) = l\" by (induct l) auto\nlemma map_fst_mk_fst[simp]: \"map fst (map (\\x. (k,x)) l) = replicate (length l) k\" by (induct l) auto\nlemma map_snd_mk_snd[simp]: \"map snd (map (\\x. (x,k)) l) = replicate (length l) k\" by (induct l) auto\n\nlemma map_zip1: \"map (\\x. (x,k)) l = zip l (replicate (length l) k)\" by (induct l) auto\nlemma map_zip2: \"map (\\x. (k,x)) l = zip (replicate (length l) k) l\" by (induct l) auto\nlemmas map_zip=map_zip1 map_zip2\n\nlemma map_append_res: \"\\ map f l = m1@m2; !!l1 l2. \\ l=l1@l2; map f l1 = m1; map f l2 = m2 \\ \\ P \\ \\ P\"\nproof (induction m1 arbitrary: l m2 P)\n case (Cons x xs)\n then obtain l' ls' where [simp]: \"l = l'#ls'\"\n \"f l' = x\" by force\n with Cons.prems(1) have \"map f ls' = xs @ m2\" by simp\n from Cons.IH[OF this] guess ll ll' .\n with Cons.prems(2)[of \"l'#ll\" ll'] show P by simp\nqed simp\n\nlemma map_id[simp]: \n \"map id l = l\" by (induct l, auto)\n\nlemma map_id'[simp]:\n \"map id = id\"\n by (rule ext) simp\n\n(* TODO/FIXME: hope nobody changes nth to be underdefined! *)\nlemma map_eq_nth_eq:\n assumes A: \"map f l = map f l'\" \n shows \"f (l!i) = f (l'!i)\"\nproof -\n from A have \"length l = length l'\"\n by (metis length_map)\n thus ?thesis using A\n apply (induct arbitrary: i rule: list_induct2)\n apply simp\n apply (simp add: nth_def split: nat.split)\n done\nqed\n\nlemma map_upd_eq:\n \"\\i f (l!i) = f x\\ \\ map f (l[i:=x]) = map f l\"\n by (metis list_update_beyond list_update_id map_update not_leE)\n\n\n\n\nlemma inj_map_inv_f [simp]: \"inj f \\ map (inv f) (map f l) = l\"\n by (simp)\n\nlemma inj_on_map_the: \"\\D \\ dom m; inj_on m D\\ \\ inj_on (the\\m) D\"\n apply (rule inj_onI)\n apply simp\n apply (case_tac \"m x\")\n apply (case_tac \"m y\")\n apply (auto intro: inj_onD) [1]\n apply (auto intro: inj_onD) [1]\n apply (case_tac \"m y\")\n apply (auto intro: inj_onD) [1]\n apply simp\n apply (rule inj_onD)\n apply assumption\n apply auto\n done\n\nlemma distinct_mapI: \"distinct (List.map f l) \\ distinct l\"\n by (induct l) auto\n\nlemma map_consI: \n \"w=map f ww \\ f a#w = map f (a#ww)\"\n \"w@l=map f ww@l \\ f a#w@l = map f (a#ww)@l\"\n by auto\n\n\nlemma restrict_map_subset_eq: \n fixes R\n shows \"\\m |` R = m'; R'\\R\\ \\ m|` R' = m' |` R'\"\n by (auto simp add: Int_absorb1)\n\nlemma restrict_map_self[simp]: \"m |` dom m = m\" \n apply (rule ext)\n apply (case_tac \"m x\") \n apply (auto simp add: restrict_map_def) \n done\n\nlemma restrict_map_UNIV[simp]: \"f |` UNIV = f\"\n by (auto simp add: restrict_map_def)\n\nlemma restrict_map_inv[simp]: \"f |` (- dom f) = Map.empty\"\n by (auto simp add: restrict_map_def intro: ext)\n\nlemma restrict_map_upd: \"(f |` S)(k \\ v) = f(k\\v) |` (insert k S)\"\n by (auto simp add: restrict_map_def intro: ext)\n\n (* TODO: Should we, instead, add the symmetric version to the simpset *)\nlemma map_upd_eq_restrict[simp]: \"m (x:=None) = m |` (-{x})\"\n by (auto intro: ext)\n\ndeclare Map.finite_dom_map_of [simp, intro!]\n\n\n\nlemma restrict_map_eq :\n \"((m |` A) k = None) \\ (k \\ dom m \\ A)\" \n \"((m |` A) k = Some v) \\ (m k = Some v \\ k \\ A)\" \nunfolding restrict_map_def\nby (simp_all add: dom_def)\n\n\ndefinition \"rel_of m P == {(k,v). m k = Some v \\ P (k, v)}\"\nlemma rel_of_empty[simp]: \"rel_of Map.empty P = {}\" \n by (auto simp add: rel_of_def)\n\nlemma remove1_tl: \"xs \\ [] \\ remove1 (hd xs) xs = tl xs\"\n by (cases xs) auto\n\nsubsubsection \"Filter an Revert\"\nprimrec filter_rev_aux where\n \"filter_rev_aux a P [] = a\"\n| \"filter_rev_aux a P (x#xs) = (\n if P x then filter_rev_aux (x#a) P xs else filter_rev_aux a P xs)\"\n\nlemma filter_rev_aux_alt: \"filter_rev_aux a P l = filter P (rev l) @ a\"\n by (induct l arbitrary: a) auto\n\ndefinition \"filter_rev == filter_rev_aux []\"\nlemma filter_rev_alt: \"filter_rev P l = filter P (rev l)\"\n unfolding filter_rev_def by (simp add: filter_rev_aux_alt)\n\ndefinition \"remove_rev x == filter_rev (Not o op = x)\"\nlemma remove_rev_alt_def :\n \"remove_rev x xs = (filter (\\y. y \\ x) (rev xs))\"\n unfolding remove_rev_def\n apply (simp add: filter_rev_alt comp_def)\n by metis\n\nsubsubsection \"zip\"\ntext {* Removing unnecessary premise from @{thm [display] zip_append}*}\nlemma zip_append': \"\\length xs = length us\\ \\ zip (xs @ ys) (us @ vs) = zip xs us @ zip ys vs\"\n by (simp add: zip_append1)\n\nlemma zip_map_parts[simp]: \"zip (map fst l) (map snd l) = l\" by (induct l) auto\n\nlemma pair_list_split: \"\\ !!l1 l2. \\ l = zip l1 l2; length l1=length l2; length l=length l2 \\ \\ P \\ \\ P\"\nproof (induct l arbitrary: P)\n case Nil thus ?case by auto\nnext\n case (Cons a l) from Cons.hyps obtain l1 l2 where IHAPP: \"l=zip l1 l2\" \"length l1 = length l2\" \"length l=length l2\" .\n obtain a1 a2 where [simp]: \"a=(a1,a2)\" by (cases a) auto\n from IHAPP have \"a#l = zip (a1#l1) (a2#l2)\" \"length (a1#l1) = length (a2#l2)\" \"length (a#l) = length (a2#l2)\"\n by (simp_all only:) (simp_all (no_asm_use))\n with Cons.prems show ?case by blast\nqed\n\nlemma set_zip_cart: \"x\\set (zip l l') \\ x\\set l \\ set l'\"\n by (auto simp add: set_zip)\n\nlemma zip_inj: \"\\length a = length b; length a' = length b'; zip a b = zip a' b'\\ \\ a=a' \\ b=b'\"\n (* TODO: Clean up proof *)\n apply (induct a b arbitrary: a' b' rule: list_induct2)\n apply (case_tac a')\n apply (case_tac b')\n apply simp\n apply simp\n apply (case_tac b')\n apply simp\n apply simp\n apply (case_tac a')\n apply (case_tac b')\n apply simp\n apply simp\n apply (case_tac b')\n apply simp\nproof -\n case goal1\n note [simp] = goal1(5,6)\n from goal1(4) have C: \"x=a\" \"y=aa\" \"zip xs ys = zip list lista\" by simp_all\n from goal1(2)[OF _ C(3)] goal1(3) have \"xs=list \\ ys = lista\" by simp_all\n thus ?case using C(1,2) by simp\nqed\n\nlemma zip_eq_zip_same_len[simp]: \n \"\\ length a = length b; length a' = length b' \\ \\ \n zip a b = zip a' b' \\ a=a' \\ b=b'\"\n by (auto dest: zip_inj)\n\nlemma map_prod_fun_zip: \"map (\\(x, y). (f x, g y)) (zip xs ys) = zip (map f xs) (map g ys)\"\nproof(induct xs arbitrary: ys)\n case Nil thus ?case by simp\nnext\n case (Cons x xs) thus ?case by(cases ys) simp_all\nqed\n\n\nsubsubsection {* Generalized Zip*}\ntext {* Zip two lists element-wise, where the combination of two elements is specified by a function. Note that this function is underdefined for lists of different length. *}\nfun zipf :: \"('a\\'b\\'c) \\ 'a list \\ 'b list \\ 'c list\" where\n \"zipf f [] [] = []\" |\n \"zipf f (a#as) (b#bs) = f a b # zipf f as bs\"\n\n\nlemma zipf_zip: \"\\length l1 = length l2\\ \\ zipf Pair l1 l2 = zip l1 l2\"\n apply (induct l1 arbitrary: l2)\n apply auto\n apply (case_tac l2)\n apply auto\n done\n\n -- \"All quantification over zipped lists\"\nfun list_all_zip where\n \"list_all_zip P [] [] \\ True\" |\n \"list_all_zip P (a#as) (b#bs) \\ P a b \\ list_all_zip P as bs\" |\n \"list_all_zip P _ _ \\ False\"\n\nlemma list_all_zip_alt: \"list_all_zip P as bs \\ length as = length bs \\ (\\iP as bs rule: list_all_zip.induct)\n apply auto\n apply (case_tac i)\n apply auto\n done\n \nlemma list_all_zip_map1: \"list_all_zip P (List.map f as) bs \\ list_all_zip (\\a b. P (f a) b) as bs\"\n apply (induct as arbitrary: bs)\n apply (case_tac bs)\n apply auto [2]\n apply (case_tac bs)\n apply auto [2]\n done\n\nlemma list_all_zip_map2: \"list_all_zip P as (List.map f bs) \\ list_all_zip (\\a b. P a (f b)) as bs\"\n apply (induct as arbitrary: bs)\n apply (case_tac bs)\n apply auto [2]\n apply (case_tac bs)\n apply auto [2]\n done\n\ndeclare list_all_zip_alt[mono]\n\nlemma lazI[intro?]: \"\\ length a = length b; !!i. i P (a!i) (b!i) \\ \n \\ list_all_zip P a b\"\n by (auto simp add: list_all_zip_alt)\n\nlemma laz_conj[simp]: \"list_all_zip (\\x y. P x y \\ Q x y) a b \n \\ list_all_zip P a b \\ list_all_zip Q a b\"\n by (auto simp add: list_all_zip_alt)\n\nlemma laz_len: \"list_all_zip P a b \\ length a = length b\" \n by (simp add: list_all_zip_alt)\n\nlemma laz_eq: \"list_all_zip (op =) a b \\ a=b\"\n apply (induct a arbitrary: b)\n apply (case_tac b)\n apply simp\n apply simp\n apply (case_tac b)\n apply simp\n apply simp\n done\n\n\nlemma laz_swap_ex:\n assumes A: \"list_all_zip (\\a b. \\c. P a b c) A B\"\n obtains C where \n \"list_all_zip (\\a c. \\b. P a b c) A C\"\n \"list_all_zip (\\b c. \\a. P a b c) B C\"\nproof -\n from A have \n [simp]: \"length A = length B\" and\n IC: \"\\ici. P (A!i) (B!i) ci\"\n by (auto simp add: list_all_zip_alt)\n from obtain_list_from_elements[OF IC] obtain C where \n \"length C = length B\"\n \"\\ia b. P a) A B \\ (length A = length B) \\ (\\a\\set A. P a)\"\n by (auto simp add: list_all_zip_alt set_conv_nth)\n\nlemma laz_weak_Pb[simp]:\n \"list_all_zip (\\a b. P b) A B \\ (length A = length B) \\ (\\b\\set B. P b)\"\n by (force simp add: list_all_zip_alt set_conv_nth)\n\n\n\nsubsubsection \"Collecting Sets over Lists\"\n\ndefinition \"list_collect_set f l == \\{ f a | a. a\\set l }\"\nlemma list_collect_set_simps[simp]:\n \"list_collect_set f [] = {}\"\n \"list_collect_set f [a] = f a\"\n \"list_collect_set f (a#l) = f a \\ list_collect_set f l\"\n \"list_collect_set f (l@l') = list_collect_set f l \\ list_collect_set f l'\"\nby (unfold list_collect_set_def) auto\n\nlemma list_collect_set_map_simps[simp]:\n \"list_collect_set f (map x []) = {}\"\n \"list_collect_set f (map x [a]) = f (x a)\"\n \"list_collect_set f (map x (a#l)) = f (x a) \\ list_collect_set f (map x l)\"\n \"list_collect_set f (map x (l@l')) = list_collect_set f (map x l) \\ list_collect_set f (map x l')\"\nby simp_all\n\nlemma list_collect_set_alt: \"list_collect_set f l = \\{ f (l!i) | i. iset (map f l)\"\n by (unfold list_collect_set_def) auto\n\nsubsubsection {* Sorted List with arbitrary Relations *}\n\ninductive sorted_by_rel :: \"('a \\ 'a \\ bool) \\ 'a list \\ bool\" where\n Nil [iff]: \"sorted_by_rel R []\"\n| Cons: \"\\y\\set xs. R x y \\ sorted_by_rel R xs \\ sorted_by_rel R (x # xs)\"\n\ninductive_simps sorted_by_rel_Cons[iff] : \"sorted_by_rel R (x # xs)\"\n\nlemma sorted_by_rel_single [iff]:\n \"sorted_by_rel R [x]\" by simp\n\nlemma sorted_by_rel_weaken :\nassumes R_weaken: \"\\x y. \\x \\ set l0; y \\ set l0; R x y\\ \\ R' x y\"\n and sort: \"sorted_by_rel R l0\"\nshows \"sorted_by_rel R' l0\" \nusing assms\nby (induct l0) (simp_all)\n\n\nlemma sorted_by_rel_map :\n \"sorted_by_rel R (map f xs) = sorted_by_rel (\\x y. R (f x) (f y)) xs\"\nby (induct xs) auto\n\nlemma sorted_by_rel_append :\n \"sorted_by_rel R (xs @ ys) =\n (sorted_by_rel R xs \\ sorted_by_rel R ys \\\n (\\x \\ set xs. \\y\\ set ys. R x y))\"\nby (induct xs) auto\n\nlemma sorted_by_rel_true [simp] :\n \"sorted_by_rel (\\_ _. True) l0\"\nby (induct l0) (simp_all)\n\nlemma (in linorder) sorted_by_rel_linord[simp]: \n \"sorted_by_rel op \\ l \\ sorted l\"\n by (induct l) (auto simp: sorted_Cons)\n\nlemma (in linorder) sorted_by_rel_rev_linord [simp] :\n \"sorted_by_rel op \\ l \\ sorted (rev l)\"\n by (induct l) (auto simp add: sorted_Cons sorted_append)\n\nlemma (in linorder) sorted_by_rel_map_linord [simp] :\n \"sorted_by_rel (\\(x::'a \\ 'b) y. fst x \\ fst y) l \n \\ sorted (map fst l)\"\n by (induct l) (auto simp add: sorted_Cons sorted_append)\n\nlemma (in linorder) sorted_by_rel_map_rev_linord [simp] :\n \"sorted_by_rel (\\(x::'a \\ 'b) y. fst x \\ fst y) l\n \\ sorted (rev (map fst l))\"\n by (induct l) (auto simp add: sorted_Cons sorted_append)\n\n\n\nsubsection {* Quicksort by Relation *}\n\ntext {* A functional implementation of quicksort on lists. It it similar to the \none in Isabelle/HOL's example directory. However, it uses tail-recursion for append and arbitrary\nrelations. *}\n\nfun partition_rev :: \"('a \\ bool) \\ ('a list \\ 'a list) \\ 'a list \\ ('a list \\ 'a list)\" where\n \"partition_rev P (yes, no) [] = (yes, no)\"\n | \"partition_rev P (yes, no) (x # xs) = \n partition_rev P (if P x then (x # yes, no) else (yes, x # no)) xs\"\n\nlemma partition_rev_filter_conv :\n \"partition_rev P (yes, no) xs = (rev (filter P xs) @ yes, rev (filter (Not \\ P) xs) @ no)\"\nby (induct xs arbitrary: yes no) (simp_all)\n\nfunction quicksort_by_rel :: \"('a \\ 'a \\ bool) \\ 'a list \\ 'a list \\ 'a list\" where\n \"quicksort_by_rel R sl [] = sl\"\n| \"quicksort_by_rel R sl (x#xs) = \n (let (xs_s, xs_b) = partition_rev (\\y. R y x) ([],[]) xs in\n quicksort_by_rel R (x # (quicksort_by_rel R sl xs_b)) xs_s)\"\nby pat_completeness simp_all\ntermination\nby (relation \"measure (\\(_, _, xs). length xs)\") \n (simp_all add: partition_rev_filter_conv less_Suc_eq_le)\n\nlemma quicksort_by_rel_remove_acc :\n \"quicksort_by_rel R sl xs = (quicksort_by_rel R [] xs @ sl)\"\nproof (induct xs arbitrary: sl rule: measure_induct_rule[of \"length\"]) \n case (less xs)\n note ind_hyp = this\n\n show ?case\n proof (cases xs)\n case Nil thus ?thesis by simp\n next\n case (Cons x xs') note xs_eq[simp] = this\n\n obtain xs1 xs2 where part_rev_eq[simp]: \"partition_rev (\\y. R y x) ([], []) xs' = (xs1, xs2)\"\n by (rule PairE)\n\n from part_rev_eq[symmetric]\n have length_le: \"length xs1 < length xs\" \"length xs2 < length xs\"\n unfolding partition_rev_filter_conv by (simp_all add: less_Suc_eq_le)\n \n note ind_hyp1a = ind_hyp[OF length_le(1), of \"x # quicksort_by_rel R [] xs2\"] \n note ind_hyp1b = ind_hyp[OF length_le(1), of \"x # quicksort_by_rel R [] xs2 @ sl\"] \n note ind_hyp2 = ind_hyp[OF length_le(2), of sl]\n\n show ?thesis by (simp add: ind_hyp1a ind_hyp1b ind_hyp2)\n qed\nqed\n\nlemma quicksort_by_rel_remove_acc_guared :\n \"sl \\ [] \\ quicksort_by_rel R sl xs = (quicksort_by_rel R [] xs @ sl)\"\nby (metis quicksort_by_rel_remove_acc)\n\nlemma quicksort_by_rel_permutes [simp]:\n \"multiset_of (quicksort_by_rel R sl xs) = multiset_of (xs @ sl)\"\nproof (induct xs arbitrary: sl rule: measure_induct_rule[of \"length\"]) \n case (less xs)\n note ind_hyp = this\n\n show ?case\n proof (cases xs)\n case Nil thus ?thesis by simp\n next\n case (Cons x xs') note xs_eq[simp] = this\n\n obtain xs1 xs2 where part_rev_eq[simp]: \"partition_rev (\\y. R y x) ([], []) xs' = (xs1, xs2)\"\n by (rule PairE)\n\n from part_rev_eq[symmetric] have xs'_multi_eq : \"multiset_of xs' = multiset_of xs1 + multiset_of xs2\"\n unfolding partition_rev_filter_conv\n by (simp add: multiset_of_filter multiset_partition)\n\n from part_rev_eq[symmetric]\n have length_le: \"length xs1 < length xs\" \"length xs2 < length xs\"\n unfolding partition_rev_filter_conv by (simp_all add: less_Suc_eq_le)\n \n note ind_hyp[OF length_le(1)] ind_hyp[OF length_le(2)]\n thus ?thesis by (simp add: xs'_multi_eq union_assoc)\n qed\nqed\n\n\n\nlemma sorted_by_rel_quicksort_by_rel:\n fixes R:: \"'x \\ 'x \\ bool\"\n assumes lin : \"\\x y. (R x y) \\ (R y x)\"\n and trans_R: \"\\x y z. R x y \\ R y z \\ R x z\"\n shows \"sorted_by_rel R (quicksort_by_rel R [] xs)\"\nproof (induct xs rule: measure_induct_rule[of \"length\"]) \n case (less xs)\n note ind_hyp = this\n\n show ?case\n proof (cases xs)\n case Nil thus ?thesis by simp\n next\n case (Cons x xs') note xs_eq[simp] = this\n\n obtain xs1 xs2 where part_rev_eq[simp]: \"partition_rev (\\y. R y x) ([], []) xs' = (xs1, xs2)\"\n by (rule PairE)\n\n from part_rev_eq[symmetric] have xs1_props: \"\\y. y \\ set xs1 \\ (R y x)\" and \n xs2_props: \"\\y. y \\ set xs2 \\ \\(R y x)\"\n unfolding partition_rev_filter_conv\n by simp_all\n\n from xs2_props lin have xs2_props': \"\\y. y \\ set xs2 \\ (R x y)\" by blast\n from xs2_props' xs1_props trans_R have xs1_props': \n \"\\y1 y2. y1 \\ set xs1 \\ y2 \\ set xs2 \\ (R y1 y2)\"\n by metis\n\n from part_rev_eq[symmetric]\n have length_le: \"length xs1 < length xs\" \"length xs2 < length xs\"\n unfolding partition_rev_filter_conv by (simp_all add: less_Suc_eq_le)\n \n note ind_hyps = ind_hyp[OF length_le(1)] ind_hyp[OF length_le(2)]\n thus ?thesis \n by (simp add: quicksort_by_rel_remove_acc_guared sorted_by_rel_append Ball_def\n xs1_props xs2_props' xs1_props')\n qed\nqed\n\nlemma sorted_quicksort_by_rel:\n \"sorted (quicksort_by_rel op\\ [] xs)\"\nunfolding sorted_by_rel_linord[symmetric]\nby (rule sorted_by_rel_quicksort_by_rel) auto\n\nlemma sort_quicksort_by_rel:\n \"sort = quicksort_by_rel op\\ []\"\n apply (rule ext, rule properties_for_sort) \n apply(simp_all add: sorted_quicksort_by_rel)\ndone\n\n\n\nsubsection {* Mergesort by Relation *}\n\ntext {* A functional implementation of mergesort on lists. It it similar to the \none in Isabelle/HOL's example directory. However, it uses tail-recursion for append and arbitrary\nrelations. *}\n\nfun mergesort_by_rel_split :: \"('a list \\ 'a list) \\ 'a list \\ ('a list \\ 'a list)\" where\n \"mergesort_by_rel_split (xs1, xs2) [] = (xs1, xs2)\"\n | \"mergesort_by_rel_split (xs1, xs2) [x] = (x # xs1, xs2)\"\n | \"mergesort_by_rel_split (xs1, xs2) (x1 # x2 # xs) = \n mergesort_by_rel_split (x1 # xs1, x2 # xs2) xs\" \n\n\n\n show ?case\n proof (cases xs)\n case Nil thus ?thesis using assms(1) by simp\n next\n case (Cons x1 xs') note xs_eq[simp] = this\n thus ?thesis\n proof (cases xs')\n case Nil thus ?thesis using assms(2) by simp\n next\n case (Cons x2 xs'') note xs'_eq[simp] = this\n show ?thesis \n by (simp add: ind_hyp assms(3))\n qed\n qed\nqed\n\nlemma mergesort_by_rel_split_length :\n \"length (fst (mergesort_by_rel_split (xs1, xs2) xs)) = length xs1 + (length xs div 2) + (length xs mod 2) \\\n length (snd (mergesort_by_rel_split (xs1, xs2) xs)) = length xs2 + (length xs div 2)\"\nby (induct xs arbitrary: xs1 xs2 rule: list_induct_first2)\n (simp_all)\n\nlemma multiset_of_mergesort_by_rel_split [simp]:\n \"multiset_of (fst (mergesort_by_rel_split (xs1, xs2) xs)) +\n multiset_of (snd (mergesort_by_rel_split (xs1, xs2) xs)) = \n multiset_of xs + multiset_of xs1 + multiset_of xs2\"\n apply (induct xs arbitrary: xs1 xs2 rule: list_induct_first2)\n apply (simp_all add: ac_simps)\ndone\n\nfun mergesort_by_rel_merge :: \"('a \\ 'a \\ bool) \\ 'a list \\ 'a list \\ 'a list\"\nwhere\n \"mergesort_by_rel_merge R (x#xs) (y#ys) =\n (if R x y then x # mergesort_by_rel_merge R xs (y#ys) else y # mergesort_by_rel_merge R (x#xs) ys)\"\n| \"mergesort_by_rel_merge R xs [] = xs\"\n| \"mergesort_by_rel_merge R [] ys = ys\"\n\ndeclare mergesort_by_rel_merge.simps [simp del]\n\nlemma mergesort_by_rel_merge_simps[simp] :\n \"mergesort_by_rel_merge R (x#xs) (y#ys) =\n (if R x y then x # mergesort_by_rel_merge R xs (y#ys) else y # mergesort_by_rel_merge R (x#xs) ys)\"\n \"mergesort_by_rel_merge R xs [] = xs\"\n \"mergesort_by_rel_merge R [] ys = ys\"\n apply (simp_all add: mergesort_by_rel_merge.simps)\n apply (cases ys) \n apply (simp_all add: mergesort_by_rel_merge.simps)\ndone\n\nlemma mergesort_by_rel_merge_induct [consumes 0, case_names Nil1 Nil2 Cons1 Cons2]:\nassumes \"\\xs::'a list. P xs []\" \"\\ys::'b list. P [] ys\"\n \"\\x xs y ys. R x y \\ P xs (y # ys) \\ P (x # xs) (y # ys)\"\n \"\\x xs y ys. \\(R x y) \\ P (x # xs) ys \\ P (x # xs) (y # ys)\"\nshows \"P xs ys\"\nproof (induct xs arbitrary: ys)\n case Nil thus ?case using assms(2) by simp\nnext\n case (Cons x xs) note P_xs = this\n show ?case\n proof (induct ys)\n case Nil thus ?case using assms(1) by simp\n next\n case (Cons y ys) note P_x_xs_ys = this\n show ?case using assms(3,4)[of x y xs ys] P_x_xs_ys P_xs by metis\n qed\nqed\n\nlemma multiset_of_mergesort_by_rel_merge [simp]:\n \"multiset_of (mergesort_by_rel_merge R xs ys) = multiset_of xs + multiset_of ys\"\nby (induct R xs ys rule: mergesort_by_rel_merge.induct) (simp_all add: ac_simps)\n\n\n\nlemma sorted_by_rel_mergesort_by_rel_merge [simp]:\n assumes lin : \"\\x y. (R x y) \\ (R y x)\"\n and trans_R: \"\\x y z. R x y \\ R y z \\ R x z\"\n shows \"sorted_by_rel R (mergesort_by_rel_merge R xs ys) \\ \n sorted_by_rel R xs \\ sorted_by_rel R ys\"\nproof (induct xs ys rule: mergesort_by_rel_merge_induct[where R = R]) \n case Nil1 thus ?case by simp\nnext\n case Nil2 thus ?case by simp\nnext\n case (Cons1 x xs y ys) thus ?case \n by (simp add: Ball_def) (metis trans_R)\nnext\n case (Cons2 x xs y ys) thus ?case \n apply (auto simp add: Ball_def)\n apply (metis lin)\n apply (metis lin trans_R)\n done\nqed\n\nfunction mergesort_by_rel :: \"('a \\ 'a \\ bool) \\ 'a list \\ 'a list\"\nwhere\n \"mergesort_by_rel R xs = \n (if length xs < 2 then xs else\n (mergesort_by_rel_merge R \n (mergesort_by_rel R (fst (mergesort_by_rel_split ([], []) xs)))\n (mergesort_by_rel R (snd (mergesort_by_rel_split ([], []) xs)))))\"\nby auto\ntermination\n apply (relation \"measure (\\(_, xs). length xs)\")\n apply (simp_all add: mergesort_by_rel_split_length)\nproof -\n fix xs :: \"'a list\"\n assume \"\\(length xs < 2)\"\n then obtain x1 x2 xs' where xs_eq: \"xs = x1 # x2 # xs'\"\n apply (cases xs, simp, rename_tac x1 xs0) \n apply (case_tac xs0, simp, rename_tac x2 xs')\n apply auto\n done \n show \"length xs div 2 + length xs mod 2 < length xs\" by (simp add: xs_eq)\nqed\n\ndeclare mergesort_by_rel.simps [simp del]\n\nlemma mergesort_by_rel_simps [simp, code] :\n \"mergesort_by_rel R [] = []\"\n \"mergesort_by_rel R [x] = [x]\"\n \"mergesort_by_rel R (x1 # x2 # xs) = \n (let (xs1, xs2) = (mergesort_by_rel_split ([x1], [x2]) xs) in\n mergesort_by_rel_merge R (mergesort_by_rel R xs1) (mergesort_by_rel R xs2))\"\napply (simp add: mergesort_by_rel.simps)\napply (simp add: mergesort_by_rel.simps)\napply (simp add: mergesort_by_rel.simps[of _ \"x1 # x2 # xs\"] split: prod.splits)\ndone\n\nlemma mergesort_by_rel_permutes [simp]:\n \"multiset_of (mergesort_by_rel R xs) = multiset_of xs\"\nproof (induct xs rule: length_induct)\n case (1 xs) note ind_hyp = this\n\n show ?case\n proof (cases xs)\n case Nil thus ?thesis by simp\n next\n case (Cons x1 xs') note xs_eq[simp] = this\n show ?thesis\n proof (cases xs')\n case Nil thus ?thesis by simp\n next\n case (Cons x2 xs'') note xs'_eq[simp] = this\n\n have \"length (fst (mergesort_by_rel_split ([], []) xs)) < length xs\" \n \"length (snd (mergesort_by_rel_split ([], []) xs)) < length xs\" \n by (simp_all add: mergesort_by_rel_split_length)\n with ind_hyp show ?thesis \n unfolding mergesort_by_rel.simps[of _ xs]\n by (simp add: ac_simps)\n qed\n qed\nqed\n\nlemma set_mergesort_by_rel [simp]: \"set (mergesort_by_rel R xs) = set xs\"\n by (simp add: set_count_greater_0)\n\nlemma sorted_by_rel_mergesort_by_rel:\n fixes R:: \"'x \\ 'x \\ bool\"\n assumes lin : \"\\x y. (R x y) \\ (R y x)\"\n and trans_R: \"\\x y z. R x y \\ R y z \\ R x z\"\n shows \"sorted_by_rel R (mergesort_by_rel R xs)\"\nproof (induct xs rule: measure_induct_rule[of \"length\"]) \n case (less xs)\n note ind_hyp = this\n\n show ?case\n proof (cases xs)\n case Nil thus ?thesis by simp\n next\n case (Cons x xs') note xs_eq[simp] = this\n thus ?thesis\n proof (cases xs')\n case Nil thus ?thesis by simp\n next\n case (Cons x2 xs'') note xs'_eq[simp] = this\n\n have \"length (fst (mergesort_by_rel_split ([], []) xs)) < length xs\" \n \"length (snd (mergesort_by_rel_split ([], []) xs)) < length xs\" \n by (simp_all add: mergesort_by_rel_split_length)\n with ind_hyp show ?thesis \n unfolding mergesort_by_rel.simps[of _ xs]\n by (simp add: sorted_by_rel_mergesort_by_rel_merge[OF lin trans_R])\n qed\n qed\nqed\n\nlemma sorted_mergesort_by_rel:\n \"sorted (mergesort_by_rel op\\ xs)\"\nunfolding sorted_by_rel_linord[symmetric]\nby (rule sorted_by_rel_mergesort_by_rel) auto\n\nlemma sort_mergesort_by_rel:\n \"sort = mergesort_by_rel op\\\"\n apply (rule ext, rule properties_for_sort) \n apply(simp_all add: sorted_mergesort_by_rel)\ndone\n\ndefinition \"mergesort = mergesort_by_rel op\\\"\n\nlemma sort_mergesort: \"sort = mergesort\"\n unfolding mergesort_def by (rule sort_mergesort_by_rel)\n\nsubsubsection {* Mergesort with Remdup *}\nterm merge\n\nfun merge :: \"'a::{linorder} list \\ 'a list \\ 'a list\" where\n \"merge [] l2 = l2\"\n | \"merge l1 [] = l1\"\n | \"merge (x1 # l1) (x2 # l2) =\n (if (x1 < x2) then x1 # (merge l1 (x2 # l2)) else \n (if (x1 = x2) then x1 # (merge l1 l2) else x2 # (merge (x1 # l1) l2)))\"\n\nlemma merge_correct :\nassumes l1_OK: \"distinct l1 \\ sorted l1\"\nassumes l2_OK: \"distinct l2 \\ sorted l2\"\nshows \"distinct (merge l1 l2) \\ sorted (merge l1 l2) \\ set (merge l1 l2) = set l1 \\ set l2\"\nusing assms\nproof (induct l1 arbitrary: l2) \n case Nil thus ?case by simp\nnext\n case (Cons x1 l1 l2) \n note x1_l1_props = Cons(2)\n note l2_props = Cons(3)\n\n from x1_l1_props have l1_props: \"distinct l1 \\ sorted l1\"\n and x1_nin_l1: \"x1 \\ set l1\"\n and x1_le: \"\\x. x \\ set l1 \\ x1 \\ x\"\n by (simp_all add: sorted_Cons Ball_def)\n\n note ind_hyp_l1 = Cons(1)[OF l1_props]\n\n show ?case\n using l2_props \n proof (induct l2)\n case Nil with x1_l1_props show ?case by simp\n next\n case (Cons x2 l2)\n note x2_l2_props = Cons(2)\n from x2_l2_props have l2_props: \"distinct l2 \\ sorted l2\"\n and x2_nin_l2: \"x2 \\ set l2\"\n and x2_le: \"\\x. x \\ set l2 \\ x2 \\ x\"\n by (simp_all add: sorted_Cons Ball_def)\n\n note ind_hyp_l2 = Cons(1)[OF l2_props]\n show ?case\n proof (cases \"x1 < x2\")\n case True note x1_less_x2 = this\n\n from ind_hyp_l1[OF x2_l2_props] x1_less_x2 x1_nin_l1 x1_le x2_le\n show ?thesis\n apply (auto simp add: sorted_Cons Ball_def)\n apply (metis linorder_not_le)\n apply (metis linorder_not_less xt1(6) xt1(9))\n done\n next\n case False note x2_le_x1 = this\n \n show ?thesis\n proof (cases \"x1 = x2\")\n case True note x1_eq_x2 = this\n\n from ind_hyp_l1[OF l2_props] x1_le x2_le x2_nin_l2 x1_eq_x2 x1_nin_l1\n show ?thesis by (simp add: x1_eq_x2 sorted_Cons Ball_def)\n next\n case False note x1_neq_x2 = this\n with x2_le_x1 have x2_less_x1 : \"x2 < x1\" by auto\n\n from ind_hyp_l2 x2_le_x1 x1_neq_x2 x2_le x2_nin_l2 x1_le\n show ?thesis \n apply (simp add: x2_less_x1 sorted_Cons Ball_def)\n apply (metis linorder_not_le x2_less_x1 xt1(7))\n done\n qed\n qed\n qed\nqed\n\nfunction merge_list :: \"'a::{linorder} list list \\ 'a list list \\ 'a list\" where\n \"merge_list [] [] = []\"\n | \"merge_list [] [l] = l\"\n | \"merge_list (la # acc2) [] = merge_list [] (la # acc2)\"\n | \"merge_list (la # acc2) [l] = merge_list [] (l # la # acc2)\"\n | \"merge_list acc2 (l1 # l2 # ls) = \n merge_list ((merge l1 l2) # acc2) ls\"\nby pat_completeness simp_all\ntermination\nby (relation \"measure (\\(acc, ls). 3 * length acc + 2 * length ls)\") (simp_all)\n\nlemma merge_list_correct :\nassumes ls_OK: \"\\l. l \\ set ls \\ distinct l \\ sorted l\"\nassumes as_OK: \"\\l. l \\ set as \\ distinct l \\ sorted l\"\nshows \"distinct (merge_list as ls) \\ sorted (merge_list as ls) \\ \n set (merge_list as ls) = set (concat (as @ ls))\"\nusing assms\nproof (induct as ls rule: merge_list.induct)\n case 1 thus ?case by simp\nnext\n case 2 thus ?case by simp\nnext\n case 3 thus ?case by simp\nnext\n case 4 thus ?case by auto\nnext\n case (5 acc l1 l2 ls) \n note ind_hyp = 5(1) \n note l12_l_OK = 5(2)\n note acc_OK = 5(3)\n\n from l12_l_OK acc_OK merge_correct[of l1 l2]\n have set_merge_eq: \"set (merge l1 l2) = set l1 \\ set l2\" by auto\n\n from l12_l_OK acc_OK merge_correct[of l1 l2]\n have \"distinct (merge_list (merge l1 l2 # acc) ls) \\\n sorted (merge_list (merge l1 l2 # acc) ls) \\\n set (merge_list (merge l1 l2 # acc) ls) =\n set (concat ((merge l1 l2 # acc) @ ls))\"\n by (rule_tac ind_hyp) auto\n with set_merge_eq show ?case by auto\nqed\n\n\ndefinition mergesort_remdups where\n \"mergesort_remdups xs = merge_list [] (map (\\x. [x]) xs)\"\n\nlemma mergesort_remdups_correct :\n \"distinct (mergesort_remdups l) \n \\ sorted (mergesort_remdups l) \n \\ (set (mergesort_remdups l) = set l)\"\nproof -\n let ?l' = \"map (\\x. [x]) l\"\n\n { fix xs\n assume \"xs \\ set ?l'\"\n then obtain x where xs_eq: \"xs = [x]\" by auto \n hence \"distinct xs \\ sorted xs\" by simp\n } note l'_OK = this\n\n from merge_list_correct[of \"?l'\" \"[]\", OF l'_OK]\n show ?thesis unfolding mergesort_remdups_def by simp\nqed\n\n(* TODO: Move *)\nlemma ex1_eqI: \"\\\\!x. P x; P a; P b\\ \\ a=b\"\n by blast\n\nlemma remdup_sort_mergesort_remdups:\n \"remdups o sort = mergesort_remdups\" (is \"?lhs=?rhs\")\nproof\n fix l\n have \"set (?lhs l) = set l\" and \"sorted (?lhs l)\" and \"distinct (?lhs l)\"\n by simp_all\n moreover note mergesort_remdups_correct\n ultimately show \"?lhs l = ?rhs l\" \n by (auto intro!: ex1_eqI[OF finite_sorted_distinct_unique[OF finite_set]])\nqed\n\nsubsubsection {* Take and Drop *}\n lemma drop_all_conc: \"drop (length a) (a@b) = b\"\n by (simp)\n\n lemma take_update[simp]: \"take n (l[i:=x]) = (take n l)[i:=x]\"\n apply (induct l arbitrary: n i)\n apply (auto split: nat.split)\n apply (case_tac n)\n apply simp_all\n apply (case_tac n)\n apply simp_all\n done\n\n lemma take_update_last: \"length list>n \\ take (Suc n) list [n:=x] = take n list @ [x]\"\n by (induct list arbitrary: n)\n (auto split: nat.split)\n\n lemma drop_upd_irrelevant: \"m < n \\ drop n (l[m:=x]) = drop n l\"\n apply (induct n arbitrary: l m)\n apply simp\n apply (case_tac l)\n apply (auto split: nat.split)\n done\n\nlemma set_drop_conv: \n \"set (drop n l) = { l!i | i. n\\i \\ i < length l }\" (is \"?L=?R\")\nproof (intro equalityI subsetI)\n fix x\n assume \"x\\?L\"\n then obtain i where L: \"i = l!(n+i)\" using L by simp\n finally show \"x\\?R\" using L by auto\nnext\n fix x\n assume \"x\\?R\"\n then obtain i where L: \"n\\i\" \"i?L\"\n by (auto simp add: in_set_conv_nth)\nqed\n\n\n\nlemma in_set_drop_conv_nth: \"x\\set (drop n l) \\ (\\i. n\\i \\ i x = l!i)\"\n apply (clarsimp simp: in_set_conv_nth)\n apply safe\n apply simp\n apply (metis le_add2 less_diff_conv add.commute)\n apply (rule_tac x=\"i-n\" in exI)\n apply auto []\n done\n\nlemma Union_take_drop_id: \"\\set (drop n l) \\ \\set (take n l) = \\set l\"\n by (metis Union_Un_distrib append_take_drop_id set_union_code sup_commute)\n\n\nlemma Un_set_drop_extend: \"\\j\\Suc 0; j < length l\\\n \\ l ! (j - Suc 0) \\ \\set (drop j l) = \\set (drop (j - Suc 0) l)\"\n apply safe \n apply simp_all\n apply (metis diff_Suc_Suc diff_zero gr0_implies_Suc in_set_drop_conv_nth\n le_refl less_eq_Suc_le order.strict_iff_order)\n apply (metis Nat.diff_le_self set_drop_subset_set_drop subset_code(1))\n by (metis diff_Suc_Suc gr0_implies_Suc in_set_drop_conv_nth \n less_eq_Suc_le min.semilattice_strict_iff_order minus_nat.diff_0)\n\nlemma drop_take_drop_unsplit: \n \"i\\j \\ drop i (take j l) @ drop j l = drop i l\"\nproof -\n assume \"i \\ j\"\n then obtain skf where \"i + skf = j\"\n by (metis Nat.le_iff_add)\n thus \"drop i (take j l) @ drop j l = drop i l\"\n by (metis append_take_drop_id diff_add_inverse drop_drop drop_take\n add.commute)\nqed\n\nlemma drop_last_conv[simp]: \"l\\[] \\ drop (length l - Suc 0) l = [last l]\"\n by (cases l rule: rev_cases) auto\n\nlemma take_butlast_conv[simp]: \"take (length l - Suc 0) l = butlast l\"\n by (cases l rule: rev_cases) auto\n\n\nsubsubsection {* Last and butlast *}\n(* Maybe this should go into List.thy, next to snoc_eq_iff_butlast *)\nlemma snoc_eq_iff_butlast': \n \"(ys = xs @ [x]) \\ (ys \\ [] \\ butlast ys = xs \\ last ys = x)\"\n by auto\n\nlemma butlast_upt: \"butlast [m.. butlast [n..length l \\ take (n - Suc 0) l = butlast (take n l)\"\n by (simp add: butlast_take)\n\nlemma butlast_eq_cons_conv: \"butlast l = x#xs \\ (\\xl. l=x#xs@[xl])\"\n by (metis Cons_eq_appendI append_butlast_last_id butlast.simps\n butlast_snoc eq_Nil_appendI) \n \nlemma butlast_eq_consE:\n assumes \"butlast l = x#xs\"\n obtains xl where \"l=x#xs@[xl]\"\n using assms\n by (auto simp: butlast_eq_cons_conv)\n\nlemma drop_eq_ConsD: \"drop n xs = x # xs' \\ drop (Suc n) xs = xs'\"\nby(induct xs arbitrary: n)(simp_all add: drop_Cons split: nat.split_asm)\n\nsubsubsection {* Miscellaneous *}\n lemma length_compl_induct[case_names Nil Cons]: \"\\P []; !! e l . \\!! ll . length ll <= length l \\ P ll\\ \\ P (e#l)\\ \\ P l\"\n apply(induct_tac l rule: length_induct)\n apply(case_tac \"xs\")\n apply(auto)\n done\n\n lemma list_size_conc[simp]: \"size_list f (a@b) = size_list f a + size_list f b\"\n by (induct a) auto\n\n\n lemma in_set_list_format: \"\\ e\\set l; !!l1 l2. l=l1@e#l2 \\ P \\ \\ P\"\n proof (induct l arbitrary: P)\n case Nil thus ?case by auto\n next\n case (Cons a l) show ?case proof (cases \"a=e\")\n case True with Cons show ?thesis by force\n next\n case False with Cons.prems(1) have \"e\\set l\" by auto\n with Cons.hyps obtain l1 l2 where \"l=l1@e#l2\" by blast\n hence \"a#l = (a#l1)@e#l2\" by simp\n with Cons.prems(2) show P by blast\n qed\n qed\n\nlemma in_set_upd_cases: \n assumes \"x\\set (l[i:=y])\"\n obtains \"iset l\"\n by (metis assms in_set_conv_nth length_list_update nth_list_update_eq \n nth_list_update_neq)\n\nlemma in_set_upd_eq_aux:\n assumes \"iset (l[i:=y]) \\ x=y \\ (\\y. x\\set (l[i:=y]))\"\n by (metis in_set_upd_cases assms list_update_overwrite \n set_update_memI)\n\nlemma in_set_upd_eq:\n assumes \"iset (l[i:=y]) \\ x=y \\ (x\\set l \\ (\\y. x\\set (l[i:=y])))\"\n by (metis in_set_upd_cases in_set_upd_eq_aux assms)\n\n\n text {* Simultaneous induction over two lists, prepending an element to one of the lists in each step *}\n lemma list_2pre_induct[case_names base left right]: assumes BASE: \"P [] []\" and LEFT: \"!!e w1' w2. P w1' w2 \\ P (e#w1') w2\" and RIGHT: \"!!e w1 w2'. P w1 w2' \\ P w1 (e#w2')\" shows \"P w1 w2\" \n proof -\n { -- \"The proof is done by induction over the sum of the lengths of the lists\"\n fix n\n have \"!!w1 w2. \\length w1 + length w2 = n; P [] []; !!e w1' w2. P w1' w2 \\ P (e#w1') w2; !!e w1 w2'. P w1 w2' \\ P w1 (e#w2') \\ \\ P w1 w2 \" \n apply (induct n)\n apply simp\n apply (case_tac w1)\n apply auto\n apply (case_tac w2)\n apply auto\n done\n } from this[OF _ BASE LEFT RIGHT] show ?thesis by blast\n qed\n\n\n lemma list_decomp_1: \"length l=1 \\ EX a . l=[a]\"\n by (case_tac l, auto)\n\n lemma list_decomp_2: \"length l=2 \\ EX a b . l=[a,b]\"\n by (case_tac l, auto simp add: list_decomp_1)\n\n\n\n lemma list_rest_coinc: \"\\length s2 <= length s1; s1@r1 = s2@r2\\ \\ EX r1p . r2=r1p@r1\"\n proof -\n assume A: \"length s2 <= length s1\" \"s1@r1 = s2@r2\"\n hence \"r1 = drop (length s1) (s2@r2)\" by (auto simp only:drop_all_conc dest: sym)\n moreover from A have \"length s1 = length s1 - length s2 + length s2\" by arith\n ultimately have \"r1 = drop ((length s1 - length s2)) r2\" by (auto)\n hence \"r2 = take ((length s1 - length s2)) r2 @ r1\" by auto\n thus ?thesis by auto\n qed\n\n lemma list_tail_coinc: \"n1#r1 = n2#r2 \\ n1=n2 & r1=r2\"\n by (auto)\n\n\n lemma last_in_set[intro]: \"\\l\\[]\\ \\ last l \\ set l\"\n by (induct l) auto\n\n lemma map_ident_id[simp]: \"map id = id\" \"map id x = x\"\n by (unfold id_def) auto\n\n lemma op_conc_empty_img_id[simp]: \"(op @ [] ` L) = L\" by auto\n\n\n lemma distinct_match: \"\\ distinct (al@e#bl) \\ \\ (al@e#bl = al'@e#bl') \\ (al=al' \\ bl=bl')\"\n proof (rule iffI, induct al arbitrary: al')\n case Nil thus ?case by (cases al') auto\n next\n case (Cons a al) note Cprems=Cons.prems note Chyps=Cons.hyps\n show ?case proof (cases al')\n case Nil with Cprems have False by auto\n thus ?thesis ..\n next\n case (Cons a' all')[simp]\n with Cprems have [simp]: \"a=a'\" and P: \"al@e#bl = all'@e#bl'\" by auto\n from Cprems(1) have D: \"distinct (al@e#bl)\" by auto\n from Chyps[OF D P] have [simp]: \"al=all'\" \"bl=bl'\" by auto\n show ?thesis by simp\n qed\n qed simp\n\n\n lemma prop_match: \"\\ list_all P al; \\P e; \\P e'; list_all P bl \\ \\ (al@e#bl = al'@e'#bl') \\ (al=al' \\ e=e' \\ bl=bl')\"\n apply (rule iffI, induct al arbitrary: al')\n apply (case_tac al', fastforce, fastforce)+\n done\n\n lemmas prop_matchD = rev_iffD1[OF _ prop_match[where P=P]] for P\n\n lemma list_match_lel_lel: \"\\\n c1 @ qs # c2 = c1' @ qs' # c2'; \n \\c21'. \\c1 = c1' @ qs' # c21'; c2' = c21' @ qs # c2\\ \\ P; \n \\c1' = c1; qs' = qs; c2' = c2\\ \\ P;\n \\c21. \\c1' = c1 @ qs # c21; c2 = c21 @ qs' # c2'\\ \\ P\n \\ \\ P\"\n apply (auto simp add: append_eq_append_conv2)\n apply (case_tac us)\n apply auto\n apply (case_tac us)\n apply auto\n done\n\n lemma distinct_tl[simp]: \"l\\[] \\ distinct l \\ distinct (tl l)\"\n by (cases l) auto\n\nlemma list_e_eq_lel[simp]: \n \"[e] = l1@e'#l2 \\ l1=[] \\ e'=e \\ l2=[]\"\n \"l1@e'#l2 = [e] \\ l1=[] \\ e'=e \\ l2=[]\"\n apply (cases l1, auto) []\n apply (cases l1, auto) []\n done\n\nlemma list_ee_eq_leel[simp]: \n \"([e1,e2] = l1@e1'#e2'#l2) \\ (l1=[] \\ e1=e1' \\ e2=e2' \\ l2=[])\"\n \"(l1@e1'#e2'#l2 = [e1,e2]) \\ (l1=[] \\ e1=e1' \\ e2=e2' \\ l2=[])\"\n apply (cases l1, auto) []\n apply (cases l1, auto) []\n done\n\nlemma list_se_match[simp]: \n \"l1 \\ [] \\ l1@l2 = [a] \\ l1 = [a] \\ l2 = []\"\n \"l2 \\ [] \\ l1@l2 = [a] \\ l1 = [] \\ l2 = [a]\"\n \"l1 \\ [] \\ [a] = l1@l2 \\ l1 = [a] \\ l2 = []\"\n \"l2 \\ [] \\ [a] = l1@l2 \\ l1 = [] \\ l2 = [a]\"\n apply (cases l1, simp_all)\n apply (cases l1, simp_all)\n apply (cases l1, auto) []\n apply (cases l1, auto) []\n done\n\n\n\nlemma xy_in_set_cases[consumes 2, case_names EQ XY YX]:\n assumes A: \"x\\set l\" \"y\\set l\"\n and C:\n \"!!l1 l2. \\ x=y; l=l1@y#l2 \\ \\ P\"\n \"!!l1 l2 l3. \\ x\\y; l=l1@x#l2@y#l3 \\ \\ P\"\n \"!!l1 l2 l3. \\ x\\y; l=l1@y#l2@x#l3 \\ \\ P\"\n shows P\nproof (cases \"x=y\")\n case True with A(1) obtain l1 l2 where \"l=l1@y#l2\" by (blast dest: split_list)\n with C(1) True show ?thesis by blast\nnext\n case False\n from A(1) obtain l1 l2 where S1: \"l=l1@x#l2\" by (blast dest: split_list)\n from A(2) obtain l1' l2' where S2: \"l=l1'@y#l2'\" by (blast dest: split_list)\n from S1 S2 have M: \"l1@x#l2 = l1'@y#l2'\" by simp\n thus P proof (cases rule: list_match_lel_lel[consumes 1, case_names 1 2 3])\n case (1 c) with S1 have \"l=l1'@y#c@x#l2\" by simp\n with C(3) False show ?thesis by blast\n next\n case 2 with False have False by blast\n thus ?thesis ..\n next\n case (3 c) with S1 have \"l=l1@x#c@y#l2'\" by simp\n with C(2) False show ?thesis by blast\n qed\nqed\n\n\n (* Placed here because it depends on xy_in_set_cases *)\nlemma distinct_map_eq: \"\\ distinct (List.map f l); f x = f y; x\\set l; y\\set l \\ \\ x=y\"\n by (erule (2) xy_in_set_cases) auto\n\n\n\nlemma upt_append: \n assumes \"iu'\"\n assumes NP: \"\\i. u\\i \\ i \\P i\"\n shows \"[i\\[0..[0..[0..[0..[u..[u..[0.. P (l!i)\"\nproof\n assume A: \"P (l!i)\"\n have \"[0..[0..[Suc i..[Suc i.. \\ i\"\n proof -\n have \"sorted (i#[k\\[Suc i.. last ?l\"\n by (rule sorted_hd_last) simp\n thus ?thesis by simp\n qed\n finally have \"i\\j\" . thus False using `jx\\set l. P x) \\ (\\i j=0\"\n by auto\n \nlemma filter_eq_snocD: \"filter P l = l'@[x] \\ x\\set l \\ P x\"\nproof -\n assume A: \"filter P l = l'@[x]\"\n hence \"x\\set (filter P l)\" by simp\n thus ?thesis by simp\nqed\n\n\n\n-- {* Congruence rules for @{const list_all} and @{const list_ex} *}\nlemma list_all_cong[fundef_cong]: \"\\ xs=ys; !!x. x\\set ys \\ f x \\ g x \\ \\ list_all f xs = list_all g ys\"\n apply (induct xs arbitrary: ys)\n apply auto\n done\n\nlemma list_ex_cong[fundef_cong]: \"\\ xs=ys; !!x. x\\set ys \\ f x \\ g x \\ \\ list_ex f xs = list_ex g ys\"\n apply (induct xs arbitrary: ys)\n apply auto\n done\n\n\nlemma lists_image_witness:\n assumes A: \"x\\lists (f`Q)\"\n obtains xo where \"xo\\lists Q\" \"x=map f xo\"\nproof - \n have \"\\ x\\lists (f`Q) \\ \\ \\xo\\lists Q. x=map f xo\"\n proof (induct x)\n case Nil thus ?case by auto\n next\n case (Cons x xs)\n then obtain xos where \"xos\\lists Q\" \"xs=map f xos\" by force\n moreover from Cons.prems have \"x\\f`Q\" by auto\n then obtain xo where \"xo\\Q\" \"x=f xo\" by auto\n ultimately show ?case\n by (rule_tac x=\"xo#xos\" in bexI) auto\n qed\n thus ?thesis\n apply (simp_all add: A)\n apply (erule_tac bexE)\n apply (rule_tac that)\n apply assumption+\n done\nqed\n\nlemma map_of_eq_empty_iff [simp]:\n \"map_of xs = Map.empty \\ xs=[]\"\nproof \n assume \"map_of xs = Map.empty\"\n thus \"xs = []\" by (induct xs) simp_all\nqed auto\n\nlemma map_of_None_filterD:\n \"map_of xs x = None \\ map_of (filter P xs) x = None\"\nby(induct xs) auto\n\nlemma map_of_concat: \"map_of (concat xss) = foldr (\\xs f. f ++ map_of xs) xss empty\"\nby(induct xss) simp_all\n\nlemma map_of_Some_split:\n \"map_of xs k = Some v \\ \\ys zs. xs = ys @ (k, v) # zs \\ map_of ys k = None\"\nproof(induct xs)\n case (Cons x xs)\n obtain k' v' where x: \"x = (k', v')\" by(cases x)\n show ?case\n proof(cases \"k' = k\")\n case True\n with `map_of (x # xs) k = Some v` x have \"x # xs = [] @ (k, v) # xs\" \"map_of [] k = None\" by simp_all\n thus ?thesis by blast\n next\n case False\n with `map_of (x # xs) k = Some v` x\n have \"map_of xs k = Some v\" by simp\n from `map_of xs k = Some v \\ \\ys zs. xs = ys @ (k, v) # zs \\ map_of ys k = None`[OF this]\n obtain ys zs where \"xs = ys @ (k, v) # zs\" \"map_of ys k = None\" by blast\n with False x have \"x # xs = (x # ys) @ (k, v) # zs\" \"map_of (x # ys) k = None\" by simp_all\n thus ?thesis by blast\n qed\nqed simp\n\nlemma map_add_find_left:\n \"g k = None \\ (f ++ g) k = f k\"\nby(simp add: map_add_def)\n\nlemma map_add_left_None:\n \"f k = None \\ (f ++ g) k = g k\"\nby(simp add: map_add_def split: option.split)\n\nlemma map_of_Some_filter_not_in:\n \"\\ map_of xs k = Some v; \\ P (k, v); distinct (map fst xs) \\ \\ map_of (filter P xs) k = None\"\napply(induct xs)\napply(auto)\napply(auto simp add: map_of_eq_None_iff)\ndone\n\nlemma distinct_map_fst_filterI: \"distinct (map fst xs) \\ distinct (map fst (filter P xs))\"\nby(induct xs) auto\n\nlemma distinct_map_fstD: \"\\ distinct (map fst xs); (x, y) \\ set xs; (x, z) \\ set xs \\ \\ y = z\"\nby(induct xs)(fastforce elim: notE rev_image_eqI)+\n\n\n\nlemma concat_filter_neq_Nil:\n \"concat [ys\\xs. ys \\ Nil] = concat xs\"\nby(induct xs) simp_all\n\nlemma distinct_concat': \n \"\\distinct [ys\\xs. ys \\ Nil]; \\ys. ys \\ set xs \\ distinct ys;\n \\ys zs. \\ys \\ set xs; zs \\ set xs; ys \\ zs\\ \\ set ys \\ set zs = {}\\\n \\ distinct (concat xs)\"\nby(erule distinct_concat[of \"[ys\\xs. ys \\ Nil]\", unfolded concat_filter_neq_Nil]) auto\n\nlemma distinct_idx:\n assumes \"distinct (map f l)\"\n assumes \"im. n \\ m \\ m < length xs \\ filter P xs ! n = xs ! m \\ filter P (take m xs) = take n (filter P xs)\"\nusing assms\nproof(induct xs rule: rev_induct)\n case Nil thus ?case by simp\nnext\n case (snoc x xs)\n show ?case\n proof(cases \"P x\")\n case False[simp]\n from `n < length (filter P (xs @ [x]))` have \"n < length (filter P xs)\" by simp\n hence \"\\m\\n. m < length xs \\ filter P xs ! n = xs ! m \\ filter P (take m xs) = take n (filter P xs)\" by(rule snoc)\n thus ?thesis by(auto simp add: nth_append)\n next\n case True[simp]\n show ?thesis\n proof(cases \"n = length (filter P xs)\")\n case False\n with `n < length (filter P (xs @ [x]))` have \"n < length (filter P xs)\" by simp\n moreover hence \"\\m\\n. m < length xs \\ filter P xs ! n = xs ! m \\ filter P (take m xs) = take n (filter P xs)\"\n by(rule snoc)\n ultimately show ?thesis by(auto simp add: nth_append)\n next\n case True[simp]\n hence \"filter P (xs @ [x]) ! n = (xs @ [x]) ! length xs\" by simp\n moreover have \"length xs < length (xs @ [x])\" by simp\n moreover have \"length xs \\ n\" by simp\n moreover have \"filter P (take (length xs) (xs @ [x])) = take n (filter P (xs @ [x]))\" by simp\n ultimately show ?thesis by blast\n qed\n qed\nqed\n\nlemma set_map_filter: \n \"set (List.map_filter g xs) = {y. \\x. x \\ set xs \\ g x = Some y}\"\n by (induct xs) (auto simp add: List.map_filter_def set_eq_iff)\n\nsubsection \"Natural Numbers\"\ntext {*\n The standard library contains theorem @{text less_iff_Suc_add}\n\n @{thm less_iff_Suc_add [no_vars]}\n\n that can be used to reduce ``less than'' to addition and successor.\n The following lemma is the analogous result for ``less or equal''.\n*}\nlemma le_iff_add:\n \"(m::nat) \\ n = (\\ k. n = m+k)\"\nproof\n assume le: \"m \\ n\"\n thus \"\\ k. n = m+k\"\n proof (auto simp add: order_le_less)\n assume \"m k. n = m+k\"\n thus \"m \\ n\" by auto\nqed\n\nlemma exists_leI:\n assumes hyp: \"(\\n' < n. \\ P n') \\ P (n::nat)\"\n shows \"\\n' \\ n. P n'\"\nproof (rule classical)\n assume contra: \"\\ (\\n'\\n. P n')\"\n hence \"\\n' < n. \\ P n'\" by auto\n hence \"P n\" by (rule hyp)\n thus \"\\n'\\n. P n'\" by auto\nqed\n\nsubsubsection {* Induction on nat *}\n lemma nat_compl_induct[case_names 0 Suc]: \"\\P 0; !! n . ALL nn . nn <= n \\ P nn \\ P (Suc n)\\ \\ P n\"\n apply(induct_tac n rule: nat_less_induct)\n apply(case_tac n)\n apply(auto)\n done\n\n lemma nat_compl_induct'[case_names 0 Suc]: \"\\P 0; !! n . \\!! nn . nn \\ n \\ P nn\\ \\ P (Suc n)\\ \\ P n\"\n apply(induct_tac n rule: nat_less_induct)\n apply(case_tac n)\n apply(auto)\n done\n\nsubsection {* Mod *}\ntext {*\n An ``induction'' law for modulus arithmetic: if $P$ holds for some\n $ii P ((Suc i) mod p)\"\n and base: \"P i\" and i: \"i(P 0)\"\n from i have p: \"0k. 0 \\ P (p-k)\" (is \"\\k. ?A k\")\n proof\n fix k\n show \"?A k\"\n proof (induct k)\n show \"?A 0\" by simp -- \"by contradiction\"\n next\n fix n\n assume ih: \"?A n\"\n show \"?A (Suc n)\"\n proof (clarsimp)\n assume y: \"P (p - Suc n)\"\n have n: \"Suc n < p\"\n proof (rule ccontr)\n assume \"\\(Suc n < p)\"\n hence \"p - Suc n = 0\"\n by simp\n with y contra show \"False\"\n by simp\n qed\n hence n2: \"Suc (p - Suc n) = p-n\" by arith\n from p have \"p - Suc n < p\" by arith\n with y step have z: \"P ((Suc (p - Suc n)) mod p)\"\n by blast\n show \"False\"\n proof (cases \"n=0\")\n case True\n with z n2 contra show ?thesis by simp\n next\n case False\n with p have \"p-n < p\" by arith\n with z n2 False ih show ?thesis by simp\n qed\n qed\n qed\n qed\n moreover\n from i obtain k where \"0 i+k=p\"\n by (blast dest: less_imp_add_positive)\n hence \"0 i=p-k\" by auto\n moreover\n note base\n ultimately\n show \"False\" by blast\nqed\n\nlemma mod_induct:\n assumes step: \"\\i P ((Suc i) mod p)\"\n and base: \"P i\" and i: \"ij P j\" (is \"?A j\")\n proof (induct j)\n from step base i show \"?A 0\"\n by (auto elim: mod_induct_0)\n next\n fix k\n assume ih: \"?A k\"\n show \"?A (Suc k)\"\n proof\n assume suc: \"Suc k < p\"\n hence k: \"k b \\ 0 < a \\ x mod (a + 1) \\ b\"\n by (metis add_pos_nonneg discrete not_less order.strict_trans2 \n semiring_numeral_div_class.pos_mod_bound zero_le_one)\n\nlemma mod_ge:\n \"(b::'a::semiring_numeral_div) \\ 0 \\ 0 < a \\ b \\ x mod (a+1)\"\n by (metis dual_order.trans less_add_one order.strict_trans \n semiring_numeral_div_class.pos_mod_sign)\n\nsubsection {* Integer *}\ntext {* Some setup from @{text \"int\"} transferred to @{text \"integer\"} *}\n\nlemma atLeastLessThanPlusOne_atLeastAtMost_integer: \"{l.. u \\\n {(0::integer).. u\")\n apply (subst image_atLeastZeroLessThan_integer, assumption)\n apply (rule finite_imageI)\n apply auto\n done\n\nlemma finite_atLeastLessThan_integer [iff]: \"finite {l..bool\"}*}\n lemma boolfun_cases_helper: \"g=(\\x. False) | g=(\\x. x) | g=(\\x. True) | g= (\\x. \\x)\" \n proof -\n { assume \"g False\" \"g True\"\n hence \"g = (\\x. True)\" by (rule_tac ext, case_tac x, auto)\n } moreover {\n assume \"g False\" \"\\g True\"\n hence \"g = (\\x. \\x)\" by (rule_tac ext, case_tac x, auto)\n } moreover {\n assume \"\\g False\" \"g True\"\n hence \"g = (\\x. x)\" by (rule_tac ext, case_tac x, auto)\n } moreover {\n assume \"\\g False\" \"\\g True\"\n hence \"g = (\\x. False)\" by (rule_tac ext, case_tac x, auto)\n } ultimately show ?thesis by fast\n qed\n\n lemma boolfun_cases[case_names False Id True Neg]: \"\\g=(\\x. False) \\ P g; g=(\\x. x) \\ P g; g=(\\x. True) \\ P g; g=(\\x. \\x) \\ P g\\ \\ P g\"\n proof -\n note boolfun_cases_helper[of g]\n moreover assume \"g=(\\x. False) \\ P g\" \"g=(\\x. x) \\ P g\" \"g=(\\x. True) \\ P g\" \"g=(\\x. \\x) \\ P g\"\n ultimately show ?thesis by fast\n qed\n\n\nsubsection {* Definite and indefinite description *}\n text \"Combined definite and indefinite description for binary predicate\"\n lemma some_theI: assumes EX: \"\\a b . P a b\" and BUN: \"!! b1 b2 . \\\\a . P a b1; \\a . P a b2\\ \\ b1=b2\" \n shows \"P (SOME a . \\b . P a b) (THE b . \\a . P a b)\"\n proof -\n from EX have \"EX b . P (SOME a . EX b . P a b) b\" by (rule someI_ex)\n moreover from EX have \"EX b . EX a . P a b\" by blast\n with BUN theI'[of \"\\b . EX a . P a b\"] have \"EX a . P a (THE b . EX a . P a b)\" by (unfold Ex1_def, blast)\n moreover note BUN\n ultimately show ?thesis by (fast)\n qed\n\n lemma some_insert_self[simp]: \"S\\{} \\ insert (SOME x. x\\S) S = S\"\n by (auto intro: someI)\n\n lemma some_elem[simp]: \"S\\{} \\ (SOME x. x\\S) \\ S\"\n by (auto intro: someI)\n \nsubsubsection{* Hilbert Choice with option *}\n\ndefinition Eps_Opt where\n \"Eps_Opt P = (if (\\x. P x) then Some (SOME x. P x) else None)\"\n\nlemma some_opt_eq_trivial[simp] :\n \"Eps_Opt (\\y. y = x) = Some x\"\nunfolding Eps_Opt_def by simp\n\nlemma some_opt_sym_eq_trivial[simp] :\n \"Eps_Opt (op = x) = Some x\"\nunfolding Eps_Opt_def by simp\n\nlemma some_opt_false_trivial[simp] :\n \"Eps_Opt (\\_. False) = None\"\nunfolding Eps_Opt_def by simp\n\nlemma Eps_Opt_eq_None[simp] :\n \"Eps_Opt P = None \\ \\(Ex P)\"\nunfolding Eps_Opt_def by simp\n\nlemma Eps_Opt_eq_Some_implies :\n \"Eps_Opt P = Some x \\ P x\"\nunfolding Eps_Opt_def \nby (metis option.inject option.simps(2) someI_ex)\n\nlemma Eps_Opt_eq_Some :\nassumes P_prop: \"\\x'. P x \\ P x' \\ x' = x\"\nshows \"Eps_Opt P = Some x \\ P x\"\nusing P_prop\nunfolding Eps_Opt_def \nby (metis option.inject option.simps(2) someI_ex)\n\nsubsection {* Product Type *}\n\nlemma nested_prod_case_simp: \"(\\(a,b) c. f a b c) x y = \n (case_prod (\\a b. f a b y) x)\"\n by (auto split: prod.split)\n\nlemma fn_fst_conv: \"(\\x. (f (fst x))) = (\\(a,_). f a)\"\n by auto\nlemma fn_snd_conv: \"(\\x. (f (snd x))) = (\\(_,b). f b)\"\n by auto\n\nfun pairself where \n \"pairself f (a,b) = (f a, f b)\"\n\nlemma pairself_image_eq[simp]: \n \"pairself f ` {(a,b). P a b} = {(f a, f b)| a b. P a b}\"\n by force\n\nlemma pairself_image_cart[simp]: \"pairself f ` (A\\B) = f`A \\ f`B\"\n by (auto simp: image_def)\n\nlemma in_prod_fst_sndI: \"fst x \\ A \\ snd x \\ B \\ x\\A\\B\"\n by (cases x) auto\n\nlemma inj_Pair[simp]: \n \"inj_on (\\x. (x,c x)) S\"\n \"inj_on (\\x. (c x,x)) S\"\n by (auto intro!: inj_onI)\n\ndeclare Product_Type.swap_inj_on[simp]\n\nlemma img_fst [intro]:\n assumes \"(a,b) \\ S\"\n shows \"a \\ fst ` S\"\nby (rule image_eqI[OF _ assms]) simp\n\nlemma img_snd [intro]:\n assumes \"(a,b) \\ S\"\n shows \"b \\ snd ` S\"\nby (rule image_eqI[OF _ assms]) simp\n\nlemma range_prod:\n \"range f \\ (range (fst \\ f)) \\ (range (snd \\ f))\"\nproof\n fix y\n assume \"y \\ range f\"\n then obtain x where y: \"y = f x\" by auto\n hence \"y = (fst(f x), snd(f x))\"\n by simp\n thus \"y \\ (range (fst \\ f)) \\ (range (snd \\ f))\"\n by (fastforce simp add: image_def)\nqed\n\nlemma finite_range_prod:\n assumes fst: \"finite (range (fst \\ f))\"\n and snd: \"finite (range (snd \\ f))\"\n shows \"finite (range f)\"\nproof -\n from fst snd have \"finite (range (fst \\ f) \\ range (snd \\ f))\"\n by (rule finite_SigmaI)\n thus ?thesis\n by (rule finite_subset[OF range_prod])\nqed\n\nlemma fstE:\n \"x = (a,b) \\ P (fst x) \\ P a\"\nby (metis fst_conv)\n\nlemma sndE:\n \"x = (a,b) \\ P (snd x) \\ P b\"\nby (metis snd_conv)\n\n\n\nsubsection {* Directed Graphs and Relations *}\n\n subsubsection \"Reflexive-Transitive Closure\"\n lemma r_le_rtrancl[simp]: \"S\\S\\<^sup>*\" by auto\n lemma rtrancl_mono_rightI: \"S\\S' \\ S\\S'\\<^sup>*\" by auto\n\n text {* Pick first non-reflexive step *}\n lemma converse_rtranclE'[consumes 1, case_names base step]:\n assumes \"(u,v)\\R\\<^sup>*\"\n obtains \"u=v\"\n | vh where \"u\\vh\" and \"(u,vh)\\R\" and \"(vh,v)\\R\\<^sup>*\"\n using assms\n apply (induct rule: converse_rtrancl_induct)\n apply auto []\n apply (case_tac \"y=z\")\n apply auto\n done\n\n lemma in_rtrancl_insert: \"x\\R\\<^sup>* \\ x\\(insert r R)\\<^sup>*\"\n by (metis in_mono rtrancl_mono subset_insertI)\n\n\n lemma rtrancl_apply_insert: \"R\\<^sup>*``(insert x S) = insert x (R\\<^sup>*``(S\\R``{x}))\"\n apply (auto)\n apply (erule converse_rtranclE)\n apply auto [2]\n apply (erule converse_rtranclE)\n apply (auto intro: converse_rtrancl_into_rtrancl) [2]\n done\n\n text {* A point-free induction rule for elements reachable from an initial set *}\n lemma rtrancl_reachable_induct[consumes 0, case_names base step]:\n assumes I0: \"I \\ INV\"\n assumes IS: \"E``INV \\ INV\"\n shows \"E\\<^sup>*``I \\ INV\"\n by (metis I0 IS Image_closed_trancl Image_mono subset_refl)\n \n\n\n text {* A path in a graph either does not use nodes from S at all, or it has a prefix leading to a node in S and a suffix that does not use nodes in S *}\n lemma rtrancl_last_visit[cases set, case_names no_visit last_visit_point]: \n shows\n \"\\ (q,q')\\R\\<^sup>*; \n (q,q')\\(R-UNIV\\S)\\<^sup>* \\ P; \n !!qt. \\ qt\\S; (q,qt)\\R\\<^sup>+; (qt,q')\\(R-UNIV\\S)\\<^sup>* \\ \\ P \n \\ \\ P\"\n proof (induct rule: converse_rtrancl_induct[case_names refl step])\n case refl thus ?case by auto\n next\n case (step q qh)\n show P proof (rule step.hyps(3))\n assume A: \"(qh,q')\\(R-UNIV\\S)\\<^sup>*\"\n show P proof (cases \"qh\\S\")\n case False \n with step.hyps(1) A have \"(q,q')\\(R-UNIV\\S)\\<^sup>*\" \n by (auto intro: converse_rtrancl_into_rtrancl)\n with step.prems(1) show P .\n next\n case True\n from step.hyps(1) have \"(q,qh)\\R\\<^sup>+\" by auto\n with step.prems(2) True A show P by blast\n qed\n next\n fix qt\n assume A: \"qt\\S\" \"(qh,qt)\\R\\<^sup>+\" \"(qt,q')\\(R-UNIV\\S)\\<^sup>*\"\n with step.hyps(1) have \"(q,qt)\\R\\<^sup>+\" by auto\n with step.prems(2) A(1,3) show P by blast\n qed\n qed\n\n text {* Less general version of @{text rtrancl_last_visit}, but there's a short automatic proof *}\n lemma rtrancl_last_visit': \"\\ (q,q')\\R\\<^sup>*; (q,q')\\(R-UNIV\\S)\\<^sup>* \\ P; !!qt. \\ qt\\S; (q,qt)\\R\\<^sup>*; (qt,q')\\(R-UNIV\\S)\\<^sup>* \\ \\ P \\ \\ P\"\n by (induct rule: converse_rtrancl_induct) (auto intro: converse_rtrancl_into_rtrancl)\n\n lemma rtrancl_last_visit_node:\n assumes \"(s,s')\\R\\<^sup>*\"\n shows \"s\\sh \\ (s,s')\\(R \\ (UNIV \\ (-{sh})))\\<^sup>* \\\n (s,sh)\\R\\<^sup>* \\ (sh,s')\\(R \\ (UNIV \\ (-{sh})))\\<^sup>*\"\n using assms\n proof (induct rule: converse_rtrancl_induct)\n case base thus ?case by auto\n next\n case (step s st)\n moreover {\n assume P: \"(st,s')\\ (R \\ UNIV \\ - {sh})\\<^sup>*\"\n {\n assume \"st=sh\" with step have ?case\n by auto\n } moreover {\n assume \"st\\sh\"\n with `(s,st)\\R` have \"(s,st)\\(R \\ UNIV \\ - {sh})\\<^sup>*\" by auto\n also note P\n finally have ?case by blast\n } ultimately have ?case by blast\n } moreover {\n assume P: \"(st, sh) \\ R\\<^sup>* \\ (sh, s') \\ (R \\ UNIV \\ - {sh})\\<^sup>*\"\n with step(1) have ?case\n by (auto dest: converse_rtrancl_into_rtrancl)\n } ultimately show ?case by blast\n qed\n\n text {* Find last point where a path touches a set *}\n lemma rtrancl_last_touch: \"\\ (q,q')\\R\\<^sup>*; q\\S; !!qt. \\ qt\\S; (q,qt)\\R\\<^sup>*; (qt,q')\\(R-UNIV\\S)\\<^sup>* \\ \\ P \\ \\ P\"\n by (erule rtrancl_last_visit') auto\n\n text {* A path either goes over edge once, or not at all *}\n lemma trancl_over_edgeE:\n assumes \"(u,w)\\(insert (v1,v2) E)\\<^sup>+\"\n obtains \"(u,w)\\E\\<^sup>+\"\n | \"(u,v1)\\E\\<^sup>*\" and \"(v2,w)\\E\\<^sup>*\"\n using assms\n proof induct\n case (base z) thus ?thesis\n by (metis insertE prod.inject r_into_trancl' rtrancl_eq_or_trancl) \n next\n case (step y z) thus ?thesis\n by (metis (hide_lams, no_types) \n Pair_inject insertE rtrancl.simps trancl.simps trancl_into_rtrancl)\n qed\n\n lemma rtrancl_image_advance: \"\\q\\R\\<^sup>* `` Q0; (q,x)\\R\\ \\ x\\R\\<^sup>* `` Q0\"\n by (auto intro: rtrancl_into_rtrancl)\n\n lemma trancl_image_by_rtrancl: \"(E\\<^sup>+)``Vi \\ Vi = (E\\<^sup>*)``Vi\"\n by (metis Image_Id Un_Image rtrancl_trancl_reflcl)\n\n lemma reachable_mono: \"\\R\\R'; X\\X'\\ \\ R\\<^sup>*``X \\ R'\\<^sup>*``X'\"\n by (metis Image_mono rtrancl_mono)\n\n lemma finite_reachable_advance: \n \"\\ finite (E\\<^sup>*``{v0}); (v0,v)\\E\\<^sup>* \\ \\ finite (E\\<^sup>*``{v})\"\n by (erule finite_subset[rotated]) auto\n\nlemma rtrancl_mono_mp: \"U\\V \\ x\\U\\<^sup>* \\ x\\V\\<^sup>*\" by (metis in_mono rtrancl_mono)\nlemma trancl_mono_mp: \"U\\V \\ x\\U\\<^sup>+ \\ x\\V\\<^sup>+\" by (metis trancl_mono)\n\nlemma rtrancl_mapI: \"(a,b)\\E\\<^sup>* \\ (f a, f b)\\(pairself f `E)\\<^sup>*\"\n apply (induction rule: rtrancl_induct)\n apply (force intro: rtrancl.intros)+\n done\n\nlemma rtrancl_image_advance_rtrancl:\n assumes \"q \\ R\\<^sup>*``Q0\"\n assumes \"(q,x) \\ R\\<^sup>*\"\n shows \"x \\ R\\<^sup>*``Q0\"\n using assms\n by (metis rtrancl_idemp rtrancl_image_advance)\n\nlemma nth_step_trancl:\n \"\\n m. \\ \\ n. n < length xs - 1 \\ (xs ! Suc n, xs ! n) \\ R \\ \\ n < length xs \\ m < n \\ (xs ! n, xs ! m) \\ R\\<^sup>+\"\nproof (induction xs)\n case (Cons x xs)\n hence \"\\n. n < length xs - 1 \\ (xs ! Suc n, xs ! n) \\ R\" \n apply clarsimp\n by (metis One_nat_def diff_Suc_eq_diff_pred nth_Cons_Suc zero_less_diff) \n note IH = this[THEN Cons.IH]\n\n from Cons obtain n' where n': \"Suc n' = n\" by (cases n) blast+\n\n show ?case\n proof (cases m)\n case \"0\" with Cons have \"xs \\ []\" by auto\n with \"0\" Cons.prems(1)[of m] have \"(xs ! 0, x) \\ R\" by simp\n moreover from IH[where m = 0] have \"\\n. n < length xs \\ n > 0 \\ (xs ! n, xs ! 0) \\ R\\<^sup>+\" by simp\n ultimately have \"\\n. n < length xs \\ (xs ! n, x) \\ R\\<^sup>+\" by (metis trancl_into_trancl gr0I r_into_trancl')\n with Cons \"0\" show ?thesis by auto\n next\n case (Suc m') with Cons.prems n' have \"n' < length xs\" \"m' < n'\" by auto\n with IH have \"(xs ! n', xs ! m') \\ R\\<^sup>+\" by simp\n with Suc n' show ?thesis by auto\n qed\nqed simp\n\nlemma Image_empty_trancl_Image_empty:\n \"R `` {v} = {} \\ R\\<^sup>+ `` {v} = {}\"\n unfolding Image_def\n by (auto elim: converse_tranclE)\n\nlemma Image_empty_rtrancl_Image_id:\n \"R `` {v} = {} \\ R\\<^sup>* `` {v} = {v}\"\n unfolding Image_def\n by (auto elim: converse_rtranclE)\n\nlemma trans_rtrancl_eq_reflcl:\n \"trans A \\ A^* = A^=\"\n by (simp add: rtrancl_trancl_reflcl)\n\nlemma refl_on_reflcl_Image:\n \"refl_on B A \\ C \\ B \\ A^= `` C = A `` C\"\n by (auto simp add: Image_def dest: refl_onD)\n\nlemma Image_absorb_rtrancl:\n \"\\ trans A; refl_on B A; C \\ B \\ \\ A^* `` C = A `` C\"\n by (simp add: trans_rtrancl_eq_reflcl refl_on_reflcl_Image)\n\n\n\n subsubsection \"Converse Relation\"\n lemma converse_subset[simp]: \"G\\ \\ H\\ \\ G\\H\"\n by auto\n\n (* [simp] - candidate *)\n lemma Sigma_converse: \"(A\\B)\\ = B\\A\" by auto\n\n lemmas converse_add_simps = Sigma_converse trancl_converse[symmetric] converse_Un converse_Int\n\nlemma dom_ran_disj_comp[simp]: \"Domain R \\ Range R = {} \\ R O R = {}\"\n by auto\n\n subsubsection \"Cyclicity\"\n lemma acyclic_union: \n \"acyclic (A\\B) \\ acyclic A\" \n \"acyclic (A\\B) \\ acyclic B\" \n by (metis Un_upper1 Un_upper2 acyclic_subset)+\n\n lemma cyclicE: \"\\\\acyclic g; !!x. (x,x)\\g\\<^sup>+ \\ P\\ \\ P\"\n by (unfold acyclic_def) blast\n \n lemma acyclic_empty[simp, intro!]: \"acyclic {}\" by (unfold acyclic_def) auto\n\n lemma acyclic_insert_cyclic: \"\\acyclic g; \\acyclic (insert (x,y) g)\\ \\ (y,x)\\g\\<^sup>*\"\n by (unfold acyclic_def) (auto simp add: trancl_insert)\n \n\n text {*\n This lemma makes a case distinction about a path in a graph where a couple of edges with the same \n endpoint have been inserted: If there is a path from a to b, then there's such a path in the original graph, or \n there's a path that uses an inserted edge only once.\n\n Originally, this lemma was used to reason about the graph of an updated acquisition history. Any path in \n this graph is either already contained in the original graph, or passes via an \n inserted edge. Because all the inserted edges point to the same target node, in the\n second case, the path can be short-circuited to use exactly one inserted edge.\n *}\n lemma trancl_multi_insert[cases set, case_names orig via]: \n \"\\ (a,b)\\(r\\X\\{m})\\<^sup>+; \n (a,b)\\r\\<^sup>+ \\ P; \n !!x. \\ x\\X; (a,x)\\r\\<^sup>*; (m,b)\\r\\<^sup>* \\ \\ P \n \\ \\ P\"\n proof (induct arbitrary: P rule: trancl_induct)\n case (base b) thus ?case by auto\n next\n case (step b c) show ?case proof (rule step.hyps(3))\n assume A: \"(a,b)\\r\\<^sup>+\" \n note step.hyps(2) \n moreover {\n assume \"(b,c)\\r\" \n with A have \"(a,c)\\r\\<^sup>+\" by auto \n with step.prems have P by blast\n } moreover {\n assume \"b\\X\" \"c=m\"\n with A have P by (rule_tac step.prems(2)) simp+\n } ultimately show P by auto\n next\n fix x\n assume A: \"x \\ X\" \"(a, x) \\ r\\<^sup>*\" \"(m, b) \\ r\\<^sup>*\"\n note step.hyps(2) \n moreover {\n assume \"(b,c)\\r\" \n with A(3) have \"(m,c)\\r\\<^sup>*\" by auto \n with step.prems(2)[OF A(1,2)] have P by blast\n } moreover {\n assume \"b\\X\" \"c=m\"\n with A have P by (rule_tac step.prems(2)) simp+\n } ultimately show P by auto\n qed\n qed\n\n text {*\n Version of @{thm [source] trancl_multi_insert} for inserted edges with the same startpoint.\n *}\n lemma trancl_multi_insert2[cases set, case_names orig via]: \n \"\\(a,b)\\(r\\{m}\\X)\\<^sup>+; (a,b)\\r\\<^sup>+ \\ P; !!x. \\ x\\X; (a,m)\\r\\<^sup>*; (x,b)\\r\\<^sup>* \\ \\ P \\ \\ P\"\n proof -\n case goal1 from goal1(1) have \"(b,a)\\((r\\{m}\\X)\\<^sup>+)\\\" by simp\n also have \"((r\\{m}\\X)\\<^sup>+)\\ = (r\\\\X\\{m})\\<^sup>+\" by (simp add: converse_add_simps)\n finally have \"(b, a) \\ (r\\ \\ X \\ {m})\\<^sup>+\" .\n thus ?case \n by (auto elim!: trancl_multi_insert \n intro: goal1(2,3) \n simp add: trancl_converse rtrancl_converse\n )\n qed\n\n \n subsubsection {* Wellfoundedness *}\n lemma wf_min: assumes A: \"wf R\" \"R\\{}\" \"!!m. m\\Domain R - Range R \\ P\" shows P proof -\n have H: \"!!x. wf R \\ \\y. (x,y)\\R \\ x\\Domain R - Range R \\ (\\m. m\\Domain R - Range R)\"\n by (erule_tac wf_induct_rule[where P=\"\\x. \\y. (x,y)\\R \\ x\\Domain R - Range R \\ (\\m. m\\Domain R - Range R)\"]) auto\n from A(2) obtain x y where \"(x,y)\\R\" by auto\n with A(1,3) H show ?thesis by blast\n qed\n\n lemma finite_wf_eq_wf_converse: \"finite R \\ wf (R\\) \\ wf R\" \n by (metis acyclic_converse finite_acyclic_wf finite_acyclic_wf_converse wf_acyclic)\n \n \n\n -- \"Useful lemma to show well-foundedness of some process approaching a finite upper bound\"\n lemma wf_bounded_supset: \"finite S \\ wf {(Q',Q). Q'\\Q \\ Q'\\ S}\"\n proof -\n assume [simp]: \"finite S\"\n hence [simp]: \"!!x. finite (S-x)\" by auto\n have \"{(Q',Q). Q\\Q' \\ Q'\\ S} \\ inv_image ({(s'::nat,s). s'Q. card (S-Q))\"\n proof (intro subsetI, case_tac x, simp)\n fix a b\n assume A: \"b\\a \\ a\\S\"\n hence \"S-a \\ S-b\" by blast\n thus \"card (S-a) < card (S-b)\" by (auto simp add: psubset_card_mono)\n qed\n moreover have \"wf ({(s'::nat,s). s' (fst a, fst b)\\r \\ \\ (a,b)\\r<*lex*>s\"\n apply (cases a, cases b)\n apply auto\n done\n\n lemma lex_prod_sndI: \"\\ fst a = fst b; (snd a, snd b)\\s \\ \\ (a,b)\\r<*lex*>s\"\n apply (cases a, cases b)\n apply auto\n done\n\n lemma wf_no_path: \"Domain R \\ Range R = {} \\ wf R\"\n apply (rule wf_no_loop)\n by simp\n\ntext {* Extend a wf-relation by a break-condition *}\ndefinition \"brk_rel R \\ \n {((False,x),(False,y)) | x y. (x,y)\\R} \n \\ {((True,x),(False,y)) | x y. True}\"\n\nlemma brk_rel_wf[simp,intro!]: \n assumes WF[simp]: \"wf R\" \n shows \"wf (brk_rel R)\"\nproof -\n have \"wf {((False,x),(False,y)) | x y. (x,y)\\R}\"\n proof -\n have \"{((False,x),(False,y)) | x y. (x,y)\\R} \\ inv_image R snd\"\n by auto\n from wf_subset[OF wf_inv_image[OF WF] this] show ?thesis .\n qed\n moreover have \"wf {((True,x),(False,y)) | x y. True}\"\n by (rule wf_no_path) auto\n ultimately show ?thesis\n unfolding brk_rel_def\n apply (subst Un_commute)\n by (blast intro: wf_Un)\nqed\n\n\nsubsubsection {* Restrict Relation *}\ndefinition rel_restrict :: \"('a \\ 'a) set \\ 'a set \\ ('a \\ 'a) set\"\nwhere\n \"rel_restrict R A \\ {(v,w). (v,w) \\ R \\ v \\ A \\ w \\ A}\"\n\nlemma rel_restrict_alt_def:\n \"rel_restrict R A = R \\ (-A) \\ (-A)\"\nunfolding rel_restrict_def\nby auto\n\nlemma rel_restrict_empty[simp]:\n \"rel_restrict R {} = R\"\nby (simp add: rel_restrict_def)\n\nlemma rel_restrict_notR:\n assumes \"(x,y) \\ rel_restrict A R\"\n shows \"x \\ R\" and \"y \\ R\"\nusing assms\nunfolding rel_restrict_def\nby auto\n\nlemma rel_restrict_sub:\n \"rel_restrict R A \\ R\"\nunfolding rel_restrict_def \nby auto\n\nlemma rel_restrict_Int_empty:\n \"A \\ Field R = {} \\ rel_restrict R A = R\"\nunfolding rel_restrict_def Field_def\nby auto\n\nlemma Domain_rel_restrict:\n \"Domain (rel_restrict R A) \\ Domain R - A\"\nunfolding rel_restrict_def\nby auto\n\nlemma Range_rel_restrict:\n \"Range (rel_restrict R A) \\ Range R - A\"\nunfolding rel_restrict_def\nby auto\n\nlemma Field_rel_restrict:\n \"Field (rel_restrict R A) \\ Field R - A\"\nunfolding rel_restrict_def Field_def\nby auto\n\nlemma rel_restrict_compl:\n \"rel_restrict R A \\ rel_restrict R (-A) = {}\"\nunfolding rel_restrict_def\nby auto\n\nlemma finite_rel_restrict:\n \"finite R \\ finite (rel_restrict R A)\"\nby (metis finite_subset rel_restrict_sub)\n\nlemma R_subset_Field: \"R \\ Field R \\ Field R\"\n unfolding Field_def\n by auto\n\nlemma homo_rel_restrict_mono:\n \"R \\ B \\ B \\ rel_restrict R A \\ (B - A) \\ (B - A)\"\nproof -\n assume A: \"R \\ B \\ B\"\n hence \"Field R \\ B\" unfolding Field_def by auto\n with Field_rel_restrict have \"Field (rel_restrict R A) \\ B - A\" \n by (metis Diff_mono order_refl order_trans)\n with R_subset_Field show ?thesis by blast\nqed\n\nlemma rel_restrict_union:\n \"rel_restrict R (A \\ B) = rel_restrict (rel_restrict R A) B\"\nunfolding rel_restrict_def\nby auto\n\nlemma rel_restrictI:\n \"x \\ R \\ y \\ R \\ (x,y) \\ E \\ (x,y) \\ rel_restrict E R\"\nunfolding rel_restrict_def\nby auto\n\nlemma rel_restrict_lift:\n \"(x,y) \\ rel_restrict E R \\ (x,y) \\ E\"\nunfolding rel_restrict_def\nby simp\n\nlemma rel_restrict_trancl_mem:\n \"(a,b) \\ (rel_restrict A R)\\<^sup>+ \\ (a,b) \\ rel_restrict (A\\<^sup>+) R\"\nby (induction rule: trancl_induct) (auto simp add: rel_restrict_def)\n\nlemma rel_restrict_trancl_sub:\n \"(rel_restrict A R)\\<^sup>+ \\ rel_restrict (A\\<^sup>+) R\"\nby (metis subrelI rel_restrict_trancl_mem)\n\nlemma rel_restrict_mono:\n \"A \\ B \\ rel_restrict A R \\ rel_restrict B R\"\nunfolding rel_restrict_def by auto\n\nlemma rel_restrict_mono2:\n \"R \\ S \\ rel_restrict A S \\ rel_restrict A R\"\nunfolding rel_restrict_def by auto\n\n\n\n\nlemma finite_reachable_restrictedI:\n assumes F: \"finite Q\"\n assumes I: \"I\\Q\"\n assumes R: \"Range E \\ Q\"\n shows \"finite (E\\<^sup>*``I)\"\nproof -\n from I R have \"E\\<^sup>*``I \\ Q\"\n by (force elim: rtrancl.cases)\n also note F\n finally (finite_subset) show ?thesis .\nqed\n\n\nsubsubsection {* Miscellaneous *}\n\n lemma Image_empty[simp]: \"{} `` X = {}\"\n by auto\n\n lemma Image_subseteq_Range: fixes R shows \"R``A \\ Range R\"\n by auto\n\n lemma finite_Range: fixes R shows \"finite R \\ finite (Range R)\"\n proof -\n assume \"finite R\"\n hence \"finite (snd ` R)\" by auto\n also have \"snd ` R = Range R\" by force\n finally show ?thesis .\n qed\n\n lemma finite_Image: fixes R shows \"\\ finite R \\ \\ finite (R `` A)\"\n by (rule finite_subset[OF Image_subseteq_Range finite_Range])\n\n lemma finite_rtrancl_Image: \n fixes R\n shows \"\\ finite R; finite A \\ \\ finite ((R\\<^sup>*) `` A)\"\n proof -\n assume A: \"finite R\" \"finite A\"\n have \"(R\\<^sup>* `` A) \\ Range R \\ A\"\n proof safe\n case goal1 thus ?case by (induct rule: rtrancl_induct) auto\n qed\n thus ?thesis\n apply (erule_tac finite_subset)\n apply (simp add: A finite_Range)\n done\n qed\n\n lemma pair_vimage_is_Image[simp]: \"(Pair u -` E) = E``{u}\"\n by auto\n\nlemma fst_in_Field: \"fst ` R \\ Field R\"\n by (simp add: Field_def fst_eq_Domain)\n\nlemma snd_in_Field: \"snd ` R \\ Field R\"\n by (simp add: Field_def snd_eq_Range)\n\nlemma ran_map_of:\n \"ran (map_of xs) \\ snd ` set (xs)\"\nby (induct xs) (auto simp add: ran_def)\n\nlemma Image_subset_snd_image:\n \"A `` B \\ snd ` A\"\nunfolding Image_def image_def\nby force\n\nlemma finite_Image_subset:\n \"finite (A `` B) \\ C \\ A \\ finite (C `` B)\"\nby (metis Image_mono order_refl rev_finite_subset)\n\n\n\n\nsubsection {* @{text \"option\"} Datatype *}\n\n\nlemma the_Some_eq_id[simp]: \"(the o Some) = id\" by auto\n\nlemma not_Some_eq2[simp]: \"(\\x y. v \\ Some (x,y)) = (v = None)\"\n by (cases v) auto\n\n\nsubsection \"Maps\"\n primrec the_default where\n \"the_default _ (Some x) = x\"\n | \"the_default x None = x\"\n\n lemma map_add_dom_app_simps[simp]:\n \"\\ m\\dom l2 \\ \\ (l1++l2) m = l2 m\"\n \"\\ m\\dom l1 \\ \\ (l1++l2) m = l2 m\" \n \"\\ m\\dom l2 \\ \\ (l1++l2) m = l1 m\" \n by (auto simp add: map_add_def split: option.split_asm)\n\n lemma map_add_upd2[simp]: \"m\\dom e2 \\ e1(m \\ u1) ++ e2 = (e1 ++ e2)(m \\ u1)\"\n apply (unfold map_add_def)\n apply (rule ext)\n apply (auto split: option.split)\n done\n\n lemma ran_add[simp]: \"dom f \\ dom g = {} \\ ran (f++g) = ran f \\ ran g\" by (fastforce simp add: ran_def map_add_def split: option.split_asm option.split)\n\n lemma dom_empty_simp[simp]: \"dom l = {} \\ l=empty\"\n by (auto simp add: dom_def intro: ext)\n \n lemma nempty_dom: \"\\e\\empty; !!m. m\\dom e \\ P \\ \\ P\"\n by (subgoal_tac \"dom e \\ {}\") (blast, auto)\n\n lemma map_add_empty[simp]:\n \"(empty = f++g) \\ f=empty \\ g=empty\"\n \"(f++g = empty) \\ f=empty \\ g=empty\"\n apply (safe)\n apply (rule ext, drule_tac x=x in fun_cong, simp add: map_add_def split: option.split_asm)\n apply (rule ext, drule_tac x=x in fun_cong, simp add: map_add_def split: option.split_asm)\n apply simp\n apply (rule ext, drule_tac x=x in fun_cong, simp add: map_add_def split: option.split_asm)\n apply (rule ext, drule_tac x=x in fun_cong, simp add: map_add_def split: option.split_asm)\n apply simp\n done\n\n\n lemma le_map_dom_mono: \"m\\m' \\ dom m \\ dom m'\"\n apply (safe)\n apply (drule_tac x=x in le_funD)\n apply simp\n apply (erule le_some_optE)\n apply simp\n done\n\n lemma map_add_first_le: fixes m::\"'a\\('b::order)\" shows \"\\ m\\m' \\ \\ m++n \\ m'++n\"\n apply (rule le_funI)\n apply (auto simp add: map_add_def split: option.split elim: le_funE)\n done\n\n lemma map_add_distinct_le: shows \"\\ m\\m'; n\\n'; dom m' \\ dom n' = {} \\ \\ m++n \\ m'++n'\"\n apply (rule le_funI)\n apply (auto simp add: map_add_def split: option.split)\n apply (fastforce elim: le_funE)\n apply (drule le_map_dom_mono)\n apply (drule le_map_dom_mono)\n apply (case_tac \"m x\")\n apply simp\n apply (force)\n apply (fastforce dest!: le_map_dom_mono)\n apply (erule le_funE)\n apply (erule_tac x=x in le_funE)\n apply simp\n done\n\n lemma map_add_left_comm: assumes A: \"dom A \\ dom B = {}\" shows \"A ++ (B ++ C) = B ++ (A ++ C)\"\n proof -\n have \"A ++ (B ++ C) = (A++B)++C\" by simp\n also have \"\\ = (B++A)++C\" by (simp add: map_add_comm[OF A])\n also have \"\\ = B++(A++C)\" by simp\n finally show ?thesis .\n qed\n lemmas map_add_ac = map_add_assoc map_add_comm map_add_left_comm\n\n lemma le_map_restrict[simp]: fixes m :: \"'a \\ ('b::order)\" shows \"m |` X \\ m\"\n by (rule le_funI) (simp add: restrict_map_def)\n\nlemma map_of_distinct_upd:\n \"x \\ set (map fst xs) \\ [x \\ y] ++ map_of xs = (map_of xs) (x \\ y)\"\n by (induct xs) (auto simp add: fun_upd_twist)\n\nlemma map_of_distinct_upd2:\n assumes \"x \\ set(map fst xs)\"\n \"x \\ set (map fst ys)\"\n shows \"map_of (xs @ (x,y) # ys) = (map_of (xs @ ys))(x \\ y)\"\n apply(insert assms)\n apply(induct xs)\n apply (auto intro: ext)\n done\n\nlemma map_of_distinct_upd3:\n assumes \"x \\ set(map fst xs)\"\n \"x \\ set (map fst ys)\"\n shows \"map_of (xs @ (x,y) # ys) = (map_of (xs @ (x,y') # ys))(x \\ y)\"\n apply(insert assms)\n apply(induct xs)\n apply (auto intro: ext)\n done\n\nlemma map_of_distinct_upd4:\n assumes \"x \\ set(map fst xs)\"\n \"x \\ set (map fst ys)\"\n shows \"map_of (xs @ ys) = (map_of (xs @ (x,y) # ys))(x := None)\"\n apply(insert assms)\n apply(induct xs)\n apply (auto simp add: map_of_eq_None_iff\n intro: ext)\n by (metis fun_upd_triv map_of_eq_None_iff restrict_complement_singleton_eq)\n\nlemma map_of_distinct_lookup:\n assumes \"x \\ set(map fst xs)\"\n \"x \\ set (map fst ys)\"\n shows \"map_of (xs @ (x,y) # ys) x = Some y\"\nproof -\n have \"map_of (xs @ (x,y) # ys) = (map_of (xs @ ys)) (x \\ y)\"\n using assms map_of_distinct_upd2 by simp\n thus ?thesis\n by simp\nqed\n\nlemma ran_distinct: \n assumes dist: \"distinct (map fst al)\" \n shows \"ran (map_of al) = snd ` set al\"\nusing assms proof (induct al)\n case Nil then show ?case by simp\nnext\n case (Cons kv al)\n then have \"ran (map_of al) = snd ` set al\" by simp\n moreover from Cons.prems have \"map_of al (fst kv) = None\"\n by (simp add: map_of_eq_None_iff)\n ultimately show ?case by (simp only: map_of.simps ran_map_upd) simp\nqed\n\nlemma ran_is_image:\n \"ran M = (the \\ M) ` (dom M)\"\nunfolding ran_def dom_def image_def\nby auto\n\nlemma map_card_eq_iff:\n assumes finite: \"finite (dom M)\"\n and card_eq: \"card (dom M) = card (ran M)\"\n and indom: \"x \\ dom M\"\n shows \"(M x = M y) \\ (x = y)\"\nproof -\n from ran_is_image finite card_eq have *: \"inj_on (the \\ M) (dom M)\" using eq_card_imp_inj_on by metis\n thus ?thesis\n proof (cases \"y \\ dom M\")\n case False with indom show ?thesis by auto\n next\n case True with indom have \"the (M x) = the (M y) \\ (x = y)\" using inj_on_eq_iff[OF *] by auto\n thus ?thesis by auto\n qed\nqed\n\nlemma map_dom_ran_finite:\n \"finite (dom M) \\ finite (ran M)\"\nby (simp add: ran_is_image)\n\nsubsection{* Connection between Maps and Sets of Key-Value Pairs *}\n\ndefinition map_to_set where\n \"map_to_set m = {(k, v) . m k = Some v}\"\n\ndefinition set_to_map where\n \"set_to_map S k = Eps_Opt (\\v. (k, v) \\ S)\"\n\nlemma set_to_map_simp :\nassumes inj_on_fst: \"inj_on fst S\"\nshows \"(set_to_map S k = Some v) \\ (k, v) \\ S\"\nproof (cases \"\\v. (k, v) \\ S\")\n case True \n note kv_ex = this\n then obtain v' where kv'_in: \"(k, v') \\ S\" by blast\n\n with inj_on_fst have kv''_in: \"\\v''. (k, v'') \\ S \\ v' = v''\"\n unfolding inj_on_def Ball_def\n by auto\n\n show ?thesis\n unfolding set_to_map_def \n by (simp add: kv_ex kv''_in)\nnext\n case False\n hence kv''_nin: \"\\v''. (k, v'') \\ S\" by simp\n thus ?thesis\n by (simp add: set_to_map_def)\nqed\n\nlemma inj_on_fst_map_to_set :\n \"inj_on fst (map_to_set m)\"\nunfolding map_to_set_def inj_on_def by simp\n\nlemma map_to_set_inverse :\n \"set_to_map (map_to_set m) = m\"\nproof\n fix k\n show \"set_to_map (map_to_set m) k = m k\"\n proof (cases \"m k\")\n case None note mk_eq = this\n hence \"\\v. (k, v) \\ map_to_set m\" \n unfolding map_to_set_def by simp\n with set_to_map_simp [OF inj_on_fst_map_to_set, of m k]\n show ?thesis unfolding mk_eq by auto\n next\n case (Some v) note mk_eq = this\n hence \"(k, v) \\ map_to_set m\" \n unfolding map_to_set_def by simp\n with set_to_map_simp [OF inj_on_fst_map_to_set, of m k v]\n show ?thesis unfolding mk_eq by auto\n qed\nqed\n\nlemma set_to_map_inverse :\nassumes inj_on_fst_S: \"inj_on fst S\"\nshows \"map_to_set (set_to_map S) = S\"\nproof (rule set_eqI)\n fix kv\n from set_to_map_simp [OF inj_on_fst_S, of \"fst kv\" \"snd kv\"]\n show \"(kv \\ map_to_set (set_to_map S)) = (kv \\ S)\"\n unfolding map_to_set_def\n by auto\nqed\n\nlemma map_to_set_empty[simp]: \"map_to_set empty = {}\"\n unfolding map_to_set_def by simp\n\n\n\nlemma map_to_set_empty_iff: \"map_to_set m = {} \\ m = Map.empty\"\n \"{} = map_to_set m \\ m = Map.empty\"\n unfolding map_to_set_def by auto\n\nlemma set_to_map_empty_iff: \"set_to_map S = Map.empty \\ S = {}\" (is ?T1)\n \"Map.empty = set_to_map S \\ S = {}\" (is ?T2)\nproof -\n show T1: ?T1\n apply (simp only: set_eq_iff) \n apply (simp only: fun_eq_iff) \n apply (simp add: set_to_map_def)\n apply auto\n done\n from T1 show ?T2 by auto\nqed\n\nlemma map_to_set_upd[simp]: \"map_to_set (m (k \\ v)) = insert (k, v) (map_to_set m - {(k, v') |v'. True})\"\n unfolding map_to_set_def \n apply (simp add: set_eq_iff)\n apply metis\ndone\n\nlemma set_to_map_insert: \nassumes k_nin: \"fst kv \\ fst ` S\"\nshows \"set_to_map (insert kv S) = (set_to_map S) (fst kv \\ snd kv)\"\nproof \n fix k'\n obtain k v where kv_eq[simp]: \"kv = (k, v)\" by (rule PairE)\n\n from k_nin have k_nin': \"\\v'. (k, v') \\ S\" \n by (auto simp add: image_iff Ball_def)\n\n show \"set_to_map (insert kv S) k' = (set_to_map S(fst kv \\ snd kv)) k'\"\n by (simp add: set_to_map_def k_nin')\nqed\n\nlemma map_to_set_dom :\n \"dom m = fst ` (map_to_set m)\"\nunfolding dom_def map_to_set_def\nby (auto simp add: image_iff)\n\nlemma map_to_set_ran :\n \"ran m = snd ` (map_to_set m)\"\nunfolding ran_def map_to_set_def\nby (auto simp add: image_iff)\n\nlemma set_to_map_dom :\n \"dom (set_to_map S) = fst ` S\"\nunfolding set_to_map_def[abs_def] dom_def\nby (auto simp add: image_iff Bex_def)\n\nlemma set_to_map_ran :\n \"ran (set_to_map S) \\ snd ` S\"\nunfolding set_to_map_def[abs_def] ran_def subset_iff\nby (auto simp add: image_iff Bex_def)\n (metis Eps_Opt_eq_Some)\n\nlemma finite_map_to_set:\n\"finite (map_to_set m) = finite (dom m)\"\nunfolding map_to_set_def map_to_set_dom\n apply (intro iffI finite_imageI)\n apply assumption\n apply (rule finite_imageD[of fst])\n apply assumption\n apply (simp add: inj_on_def)\ndone\n\nlemma card_map_to_set :\n \"card (map_to_set m) = card (dom m)\"\nunfolding map_to_set_def map_to_set_dom\n apply (rule card_image[symmetric])\n apply (simp add: inj_on_def)\ndone\n\nlemma map_of_map_to_set :\n\"distinct (map fst l) \\\n map_of l = m \\ set l = map_to_set m\"\nproof (induct l arbitrary: m)\n case Nil thus ?case by (simp add: map_to_set_empty_iff) blast\nnext\n case (Cons kv l m)\n obtain k v where kv_eq[simp]: \"kv = (k, v)\" by (rule PairE)\n\n from Cons(2) have dist_l: \"distinct (map fst l)\" and kv'_nin: \"\\v'. (k, v') \\ set l\"\n by (auto simp add: image_iff)\n note ind_hyp = Cons(1)[OF dist_l]\n \n from kv'_nin have l_eq: \"set (kv # l) = map_to_set m \\ (set l = map_to_set (m (k := None))) \\ m k = Some v\"\n apply (simp add: map_to_set_def restrict_map_def set_eq_iff)\n apply (auto)\n apply (metis)\n apply (metis option.inject)\n done\n\n from kv'_nin have m_eq: \"map_of (kv # l) = m \\ map_of l = (m (k := None)) \\ m k = Some v\"\n apply (simp add: fun_eq_iff restrict_map_def map_of_eq_None_iff image_iff Ball_def)\n apply metis\n done\n\n show ?case\n unfolding m_eq l_eq \n using ind_hyp[of \"m (k := None)\"] \n by metis\nqed\n\nlemma map_to_set_map_of :\n\"distinct (map fst l) \\ map_to_set (map_of l) = set l\"\nby (metis map_of_map_to_set)\n\nsubsubsection {* Mapping empty set to None *}\ndefinition \"dflt_None_set S \\ if S={} then None else Some S\"\n\nlemma the_dflt_None_empty[simp]: \"dflt_None_set {} = None\" \n unfolding dflt_None_set_def by simp\n\nlemma the_dflt_None_nonempty[simp]: \"S\\{} \\ dflt_None_set S = Some S\"\n unfolding dflt_None_set_def by simp\n\nlemma the_dflt_None_set[simp]: \"the_default {} (dflt_None_set x) = x\"\n unfolding dflt_None_set_def by auto\n\nsubsection {* Orderings *}\n\nlemma (in order) min_arg_le[simp]:\n \"n \\ min m n \\ min m n = n\" \n \"m \\ min m n \\ min m n = m\" \n by (auto simp: min_def)\n\nlemma (in linorder) min_arg_not_ge[simp]: \n \"\\ min m n < m \\ min m n = m\"\n \"\\ min m n < n \\ min m n = n\"\n by (auto simp: min_def)\n\nlemma (in linorder) min_eq_arg[simp]: \n \"min m n = m \\ m\\n\"\n \"min m n = n \\ n\\m\"\n by (auto simp: min_def)\n\nlemma min_simps[simp]:\n \"a<(b::'a::order) \\ min a b = a\"\n \"b<(a::'a::order) \\ min a b = b\"\n by (auto simp add: min_def dest: less_imp_le)\n\nlemma ord_eq_le_eq_trans: \"\\ a=b; b\\c; c=d \\ \\ a\\d\" by auto\n\n\nsubsection {* CCPOs *}\n\ncontext ccpo \nbegin\n\nlemma ccpo_Sup_mono:\n assumes C: \"Complete_Partial_Order.chain (op \\) A\" \n \"Complete_Partial_Order.chain (op \\) B\"\n assumes B: \"\\x\\A. \\y\\B. x\\y\"\n shows \"Sup A \\ Sup B\"\nproof (rule ccpo_Sup_least)\n fix x\n assume \"x\\A\"\n with B obtain y where I: \"y\\B\" and L: \"x\\y\" by blast\n note L\n also from I ccpo_Sup_upper have \"y\\Sup B\" by (blast intro: C)\n finally show \"x\\Sup B\" .\nqed (rule C)\n\nlemma fixp_mono: \n assumes M: \"monotone op\\ op\\ f\" \"monotone op\\ op\\ g\"\n assumes LE: \"\\Z. f Z \\ g Z\"\n shows \"ccpo_class.fixp f \\ ccpo_class.fixp g\"\n unfolding fixp_def[abs_def]\n apply (rule ccpo_Sup_mono)\n apply (rule chain_iterates M)+\nproof rule\n fix x\n assume \"x\\ccpo_class.iterates f\"\n thus \"\\y\\ccpo_class.iterates g. x\\y\"\n proof (induct)\n case (step x)\n then obtain y where I: \"y\\ccpo_class.iterates g\" and L: \"x\\y\" by blast\n hence \"g y \\ ccpo_class.iterates g\" and \"f x \\ g y\"\n apply -\n apply (erule iterates.step)\n apply (rule order_trans)\n apply (erule monotoneD[OF M(1)])\n apply (rule LE)\n done\n thus \"\\y\\ccpo_class.iterates g. f x \\ y\" ..\n next\n case (Sup M) \n def N \\ \"{SOME y. y\\ccpo_class.iterates g \\ x\\y | x. x\\M}\"\n\n have N1: \"\\y\\N. y\\ccpo_class.iterates g \\ (\\x\\M. x\\y)\"\n unfolding N_def\n apply auto\n apply (metis (lifting) Sup.hyps(2) tfl_some)\n by (metis (lifting) Sup.hyps(2) tfl_some)\n\n have N2: \"\\x\\M. \\y\\N. x\\y\"\n unfolding N_def\n apply auto\n by (metis (lifting) Sup.hyps(2) tfl_some)\n\n have \"N \\ ccpo_class.iterates g\" using Sup\n using N1 by auto\n hence C_chain: \"Complete_Partial_Order.chain op\\ N\"\n using chain_iterates[OF M(2)]\n unfolding chain_def by auto\n\n have \"Sup N \\ ccpo_class.iterates g\" and \"Sup M \\ Sup N\"\n apply -\n apply (rule iterates.Sup[OF C_chain])\n using N1 apply blast\n apply (rule ccpo_Sup_mono)\n apply (rule Sup.hyps)\n apply (rule C_chain)\n apply (rule N2)\n done\n\n thus ?case by blast\n qed\nqed\n\nend\n\n\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Automatic_Refinement/Lib/Misc.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.14608724333058226, "lm_q1q2_score": 0.05950621352918321}} {"text": "(*\n * Copyright 2019, NTU\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * Author: Albert Rizaldi, NTU Singapore\n *)\n\ntheory Double_Inverter\n imports VHDL_Hoare_Complete\nbegin\n\ntext \\datatypes for all signals\\\n\ndatatype sig = IN | TEMP | OUT\n\n\\ \\VHDL program for double inverter\\\ndefinition two_inverter :: \"sig conc_stmt\" where\n \"two_inverter \\ (process {IN} : Bassign_trans TEMP (Bsig IN) 1)\n || (process {TEMP} : Bassign_trans OUT (Bsig TEMP) 1)\"\n\nlemma potential_tyenv:\n assumes \"conc_wt \\ two_inverter\"\n shows \"\\ki len. \\ IN = Bty \\ \\ TEMP = Bty \\ \\ OUT = Bty\n \\ \\ IN = Lty ki len \\ \\ TEMP = Lty ki len \\ \\ OUT = Lty ki len\"\n using assms unfolding two_inverter_def\nproof (rule conc_wt_cases(2))\n assume \"conc_wt \\ ( process {IN} : Bassign_trans TEMP (Bsig IN) 1)\"\n hence \"seq_wt \\ (Bassign_trans TEMP (Bsig IN) 1)\"\n by blast\n hence \"bexp_wt \\ (Bsig IN) (\\ TEMP)\"\n by blast\n hence \"\\ TEMP = \\ IN\"\n by (rule bexp_wt_cases_all) auto\n assume \"conc_wt \\ ( process {TEMP} : Bassign_trans OUT (Bsig TEMP) 1)\"\n hence \"seq_wt \\ (Bassign_trans OUT (Bsig TEMP) 1)\"\n by blast\n hence \"bexp_wt \\ (Bsig TEMP) (\\ OUT)\"\n by blast\n hence \"\\ OUT = \\ TEMP\"\n by (rule bexp_wt_cases_all) auto\n obtain ki len where \"\\ TEMP = Bty \\ \\ TEMP = Lty ki len\"\n using ty.exhaust by meson\n thus ?thesis\n using \\\\ OUT = \\ TEMP\\ \\\\ TEMP = \\ IN\\ by auto\nqed\n\n\\ \\the first invariant for double inverter\\\ndefinition inv_first :: \"sig assn2\" where\n \"inv_first \\ (\\tw. \\i < fst tw. wline_of tw TEMP (i + 1) = wline_of tw IN i)\"\n\n\\ \\the second invariant for double inverter\\\ndefinition inv_second :: \"sig assn2\" where\n \"inv_second \\ (\\tw. \\i < fst tw. wline_of tw OUT (i + 1) = wline_of tw TEMP i)\"\n\ndefinition inv_first_hold :: \"sig assn2\" where\n \"inv_first_hold \\ (\\tw. disjnt {IN} (event_of tw) \\\n (\\i \\ fst tw. wline_of tw TEMP (i + 1) = wline_of tw IN (fst tw)))\"\n\ndefinition inv_second_hold :: \"sig assn2\" where\n \"inv_second_hold \\ (\\tw. disjnt {TEMP} (event_of tw) \\\n (\\i \\ fst tw. wline_of tw OUT (i + 1) = wline_of tw TEMP (fst tw)))\"\n\nsubsection \\First invariant hold at the next time\\\n\nlemma inv_first_next_time:\n assumes \"inv_first tw\"\n defines \"tw' \\ tw[ TEMP, 1 :=\\<^sub>2 wline_of tw IN (fst tw)]\"\n shows \"inv_first (next_time_world tw', snd tw')\"\nproof -\n let ?t' = \"next_time_world tw'\"\n define v where \"v = wline_of tw IN (fst tw)\"\n have assms2: \"beval_world_raw (snd tw) (fst tw) (Bsig IN) v\"\n using assms(2) unfolding beval_world_raw2_def v_def\n by (metis beval_world_raw2_Bsig beval_world_raw2_def)\n have \"fst tw' < ?t'\"\n using next_time_world_at_least using nat_less_le by blast\n moreover have \"fst tw = fst tw'\"\n unfolding tw'_def worldline_upd2_def worldline_upd_def by auto\n ultimately have \"fst tw < ?t'\"\n by auto\n have \"\\i fst tw \\ i \\ i < ?t' - 1 \\ i = ?t' - 1\"\n using next_time_world_at_least \\i < next_time_world tw'\\ not_less by linarith\n moreover\n { assume \"i < fst tw\"\n hence \"wline_of tw TEMP (i + 1) = wline_of tw IN i\"\n using assms(1) unfolding inv_first_def by auto\n moreover have \"wline_of tw TEMP (i + 1) = wline_of tw' TEMP (i + 1)\" and \"wline_of tw IN i = wline_of tw' IN i\"\n using worldline_upd2_before_dly \\i < fst tw\\ unfolding tw'_def\n by (metis add_mono1 trans_less_add1)+\n ultimately have \"wline_of tw' TEMP (i + 1) = wline_of tw' IN i\"\n by auto }\n moreover\n { assume \"fst tw \\ i \\ i < ?t' - 1\"\n hence \"wline_of tw' TEMP (i + 1) = wline_of tw' TEMP (fst tw + 1)\"\n using unchanged_until_next_time_world\n by (metis (mono_tags, lifting) Suc_eq_plus1 \\get_time tw = get_time tw'\\ le_Suc_eq le_add1\n le_less_trans less_diff_conv)\n have \"wline_of tw' IN i = wline_of tw' IN (fst tw)\"\n using unchanged_until_next_time_world \\fst tw \\ i \\ i < ?t' - 1\\\n by (metis \\get_time tw = get_time tw'\\ \\i < next_time_world tw'\\)\n hence \"wline_of tw' TEMP (fst tw + 1) = wline_of tw' IN (fst tw)\"\n by (metis assms2 beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic\n less_add_one tw'_def worldline_upd2_at_dly worldline_upd2_before_dly)\n hence \"wline_of tw' TEMP (i + 1) = wline_of tw' IN i\"\n using \\wline_of tw' IN i = wline_of tw' IN (get_time tw)\\ \\wline_of tw' TEMP (i + 1) = wline_of tw' TEMP (get_time tw + 1)\\\n by simp }\n moreover\n { assume \"i = ?t' - 1\"\n hence \"wline_of tw' TEMP (i + 1) = wline_of tw' TEMP ?t'\"\n using \\i < ?t'\\ by auto\n also have \"... = wline_of tw' TEMP (fst tw + 1)\"\n using \\fst tw < ?t'\\ unfolding tw'_def worldline_upd2_def worldline_upd_def by auto\n also have \"... = wline_of tw' IN (fst tw)\"\n by (metis assms2 beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic\n less_add_one tw'_def worldline_upd2_at_dly worldline_upd2_before_dly)\n also have \"... = wline_of tw' IN i\"\n by (metis \\get_time tw = get_time tw'\\ \\i < get_time tw \\ wline_of tw' TEMP (i + 1) = wline_of tw' IN i\\\n \\i < next_time_world tw'\\ calculation not_less unchanged_until_next_time_world)\n finally have \"wline_of tw' TEMP (i + 1) = wline_of tw' IN i\"\n by auto }\n ultimately show \"wline_of tw' TEMP (i + 1) = wline_of tw' IN i\"\n by auto\n qed\n thus ?thesis\n unfolding inv_first_def by auto\nqed\n\nlemma seq_part_when_not_disjnt1:\n \"\\ [\\tw. (inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)]\n Bassign_trans TEMP (Bsig IN) 1\n [inv_second]\"\nproof (intro Assign2_altI, rule, rule, rule)\n fix tw v\n assume \"((inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)) \\ beval_world_raw2 tw (Bsig IN) v\"\n hence \"inv_first tw\" and \"inv_second tw\" and \"inv_first_hold tw\" and \"inv_second_hold tw\" and \"\\ disjnt {IN} (event_of tw)\"\n and \" beval_world_raw2 tw (Bsig IN) v\"\n by auto\n define tw1 where \"tw1 = tw [TEMP, 1 :=\\<^sub>2 v]\"\n define t' where \"t' = next_time_world tw1\"\n\n have \"fst tw < t'\"\n unfolding t'_def by (metis fst_conv next_time_world_at_least tw1_def worldline_upd2_def)\n have \"fst tw = fst tw1\"\n by (simp add: tw1_def worldline_upd2_def)\n also have \"... < next_time_world tw1\"\n using next_time_world_at_least by metis\n finally have \"fst tw < next_time_world tw1\"\n by auto\n\n have 0: \"inv_second tw1\" \\ \\unaffected invariant\\\n unfolding inv_second_def\n proof (rule, rule)\n fix i\n assume \"i < fst tw1\"\n hence \"i < fst tw\"\n using \\fst tw = fst tw1\\ by auto\n have \"wline_of tw1 OUT (i + 1) = wline_of tw OUT (i + 1)\"\n unfolding tw1_def by (meson \\i < get_time tw\\ add_mono1 worldline_upd2_before_dly)\n also have \"... = wline_of tw TEMP i\"\n using \\inv_second tw\\ \\i < fst tw\\ unfolding inv_second_def by auto\n also have \"... = wline_of tw1 TEMP i\"\n unfolding tw1_def using \\i < fst tw\\ by (metis trans_less_add1 worldline_upd2_before_dly)\n finally show \"wline_of tw1 OUT (i + 1) = wline_of tw1 TEMP i\"\n by auto\n qed\n thus \"inv_second tw[ TEMP, 1 :=\\<^sub>2 v] \"\n unfolding tw1_def by auto\nqed\n\nlemma seq_part_when_not_disjnt2:\n \"\\ [\\tw. (inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)]\n Bassign_trans TEMP (Bsig IN) 1\n [\\tw. inv_first (next_time_world tw, snd tw)]\"\nproof (intro Assign2_altI, rule, rule, rule)\n fix tw v\n assume \"((inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)) \\ beval_world_raw2 tw (Bsig IN) v\"\n hence \"inv_first tw\" and \"inv_second tw\" and \"inv_first_hold tw\" and \"inv_second_hold tw\" and \"\\ disjnt {IN} (event_of tw)\"\n and \" beval_world_raw2 tw (Bsig IN) v\"\n by auto\n define tw1 where \"tw1 = tw [TEMP, 1 :=\\<^sub>2 v]\"\n then obtain v' where \"beval_world_raw2 tw1 (Bsig TEMP) v'\"\n by (meson beval_world_raw2_Bsig)\n define tw2 where \"tw2 = tw1[OUT, 1 :=\\<^sub>2 v']\"\n define t' where \"t' = next_time_world tw1\"\n\n have \"fst tw < t'\"\n unfolding t'_def by (metis fst_conv next_time_world_at_least tw1_def worldline_upd2_def)\n have \"fst tw = fst tw1\"\n by (simp add: tw1_def worldline_upd2_def)\n also have \"... = fst tw2\"\n by (simp add: tw1_def tw2_def worldline_upd2_def)\n also have \"... < next_time_world tw2\"\n using next_time_world_at_least by metis\n finally have \"fst tw < next_time_world tw2\"\n by auto\n have \"fst tw1 < next_time_world tw2\"\n by (simp add: \\get_time tw1 = get_time tw2\\ \\get_time tw2 < next_time_world tw2\\)\n\n have 4: \"inv_first (t', snd tw1)\"\n unfolding inv_first_def\n proof (rule, rule)\n fix i\n assume \"i < fst (t', snd tw1)\"\n hence \"i < t'\"\n by auto\n hence \"i < fst tw \\ fst tw \\ i \\ i < t' - 1 \\ i = t' - 1\"\n using \\fst tw < t'\\ by linarith\n moreover\n { assume \"i < fst tw\"\n hence \"wline_of tw1 TEMP (i + 1) = wline_of tw TEMP (i + 1)\"\n unfolding tw1_def by (meson add_mono1 worldline_upd2_before_dly)\n also have \"... = wline_of tw IN i\"\n using \\inv_first tw\\ \\i < fst tw\\ unfolding inv_first_def by auto\n also have \"... = wline_of tw1 IN i\"\n unfolding tw1_def by (metis \\i < get_time tw\\ add.right_neutral add_mono_thms_linordered_field(5)\n worldline_upd2_before_dly zero_less_one)\n finally have \"wline_of tw1 TEMP (i + 1) = wline_of tw1 IN i\"\n by auto }\n moreover\n { assume \"fst tw \\ i \\ i < t' - 1\"\n hence \"wline_of tw1 TEMP (i + 1) = wline_of tw1 TEMP (fst tw + 1)\"\n using unchanged_until_next_time_world\n unfolding `fst tw = fst tw1` t'_def\n by (metis (no_types, lifting) One_nat_def Suc_lessI Suc_less_eq \\get_time tw < t'\\ \\get_time\n tw = get_time tw1\\ add.right_neutral add_Suc_right diff_is_0_eq' le_Suc_eq le_add1\n less_diff_conv t'_def zero_less_diff)\n also have \"... = wline_of tw IN (fst tw)\"\n unfolding tw1_def\n by (metis \\beval_world_raw2 tw (Bsig IN) v\\ beval_world_raw2_Bsig beval_world_raw2_def\n beval_world_raw_deterministic worldline_upd2_at_dly)\n also have \"... = wline_of tw1 IN (fst tw)\"\n unfolding tw1_def by (metis less_add_one worldline_upd2_before_dly)\n also have \"... = wline_of tw1 IN i\"\n using unchanged_until_next_time_world\n unfolding `fst tw = fst tw1` t'_def\n by (metis \\get_time tw = get_time tw1\\ \\get_time tw \\ i \\ i < t' - 1\\ \\i < t'\\ t'_def)\n finally have \"wline_of tw1 TEMP (i + 1) = wline_of tw1 IN i\"\n by auto }\n moreover\n { assume \"i = t' - 1\"\n hence \"wline_of tw1 TEMP (i + 1) = wline_of tw1 TEMP t'\"\n using \\i < t'\\ by force\n also have \"... = wline_of tw1 TEMP (fst tw + 1)\"\n unfolding t'_def using \\fst tw < t'\\\n by (simp add: t'_def tw1_def worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw IN (fst tw)\"\n unfolding tw1_def\n by (metis \\beval_world_raw2 tw (Bsig IN) v\\ beval_world_raw2_Bsig beval_world_raw2_def\n beval_world_raw_deterministic worldline_upd2_at_dly)\n also have \"... = wline_of tw1 IN (fst tw)\"\n unfolding tw1_def by (metis less_add_one worldline_upd2_before_dly)\n also have \"... = wline_of tw1 IN i\"\n by (metis \\get_time tw = get_time tw1\\ \\i < get_time tw \\ wline_of tw1 TEMP (i + 1) =\n wline_of tw1 IN i\\ \\i < t'\\ calculation not_less t'_def unchanged_until_next_time_world)\n finally have \"wline_of tw1 TEMP (i + 1) = wline_of tw1 IN i\"\n by auto }\n ultimately have \"wline_of tw1 TEMP (i + 1) = wline_of tw1 IN i\"\n by auto\n thus \"wline_of (t', snd tw1) TEMP (i + 1) = wline_of (t', snd tw1) IN i\"\n by auto\n qed\n thus \" inv_first (next_time_world tw[ TEMP, 1 :=\\<^sub>2 v], snd tw[ TEMP, 1 :=\\<^sub>2 v])\"\n unfolding tw1_def tw2_def t'_def by auto\nqed\n\nlemma aux1:\n \"\\tw. inv_first (next_time_world tw, snd tw) \\ \\j \\ {fst tw <.. next_time_world tw}. inv_first (j, snd tw)\"\n unfolding inv_first_def by simp\n\nlemma seq_part_when_not_disjnt2_post:\n \"\\ [\\tw. (inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)]\n Bassign_trans TEMP (Bsig IN) 1\n [\\tw. \\j \\ {fst tw <.. next_time_world tw}. inv_first (j, snd tw)]\"\n apply (rule Conseq2[rotated])\n apply (rule seq_part_when_not_disjnt2)\n by (auto simp add: aux1)\n\nlemma seq_part_when_not_disjnt3:\n \"\\ [\\tw. (inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)]\n Bassign_trans TEMP (Bsig IN) 1\n [inv_second_hold]\"\nproof (intro Assign2_altI, rule, rule, rule)\n fix tw v\n assume \"((inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)) \\ beval_world_raw2 tw (Bsig IN) v\"\n hence \"inv_first tw\" and \"inv_second tw\" and \"inv_first_hold tw\" and \"inv_second_hold tw\" and \"\\ disjnt {IN} (event_of tw)\"\n and \" beval_world_raw2 tw (Bsig IN) v\"\n by auto\n define tw1 where \"tw1 = tw [TEMP, 1 :=\\<^sub>2 v]\"\n then obtain v' where \"beval_world_raw2 tw1 (Bsig TEMP) v'\"\n by (meson beval_world_raw2_Bsig)\n define tw2 where \"tw2 = tw1[OUT, 1 :=\\<^sub>2 v']\"\n define t' where \"t' = next_time_world tw1\"\n\n have \"fst tw < t'\"\n unfolding t'_def by (metis fst_conv next_time_world_at_least tw1_def worldline_upd2_def)\n have \"fst tw = fst tw1\"\n by (simp add: tw1_def worldline_upd2_def)\n also have \"... = fst tw2\"\n by (simp add: tw1_def tw2_def worldline_upd2_def)\n also have \"... < next_time_world tw2\"\n using next_time_world_at_least by metis\n finally have \"fst tw < next_time_world tw2\"\n by auto\n have \"fst tw1 < next_time_world tw2\"\n by (simp add: \\get_time tw1 = get_time tw2\\ \\get_time tw2 < next_time_world tw2\\)\n\n have \"beval_world_raw (snd tw1) (fst tw1) (Bsig TEMP) v'\"\n using \\beval_world_raw2 tw1 (Bsig TEMP) v'\\ unfolding beval_world_raw2_def by auto\n\n \\ \\second unaffected invariant\\\n have 1: \"inv_second_hold tw1\"\n unfolding inv_second_hold_def\n proof (rule, rule, rule)\n fix i\n have \"get_time tw = get_time tw[ TEMP, 1 :=\\<^sub>2 v]\"\n using \\fst tw = fst tw1\\ unfolding tw1_def by auto\n assume \"disjnt {TEMP} (event_of tw1)\"\n hence \"disjnt {TEMP} (event_of tw)\"\n unfolding tw1_def event_of_alt_def sym[OF \\get_time tw = get_time tw[ TEMP, 1 :=\\<^sub>2 v]\\]\n worldline_upd2_def worldline_upd_def by auto\n assume \"fst tw1 \\ i\"\n hence \"fst tw \\ i\"\n using \\fst tw = fst tw1\\ by auto\n hence \"wline_of tw OUT (i + 1) = wline_of tw TEMP (fst tw)\"\n using `inv_second_hold tw` \\disjnt {TEMP} (event_of tw)\\ unfolding inv_second_hold_def\n by auto\n moreover have \"wline_of tw OUT (i + 1) = wline_of tw1 OUT (i + 1)\" and \"wline_of tw TEMP (fst tw) = wline_of tw1 TEMP (fst tw)\"\n by (simp add: tw1_def worldline_upd2_def worldline_upd_def)+\n ultimately show \"wline_of tw1 OUT (i + 1) = wline_of tw1 TEMP (get_time tw1)\"\n using \\fst tw = fst tw1\\ by auto\n qed\n\n thus \"inv_second_hold tw[ TEMP, 1 :=\\<^sub>2 v]\"\n unfolding tw1_def by auto\nqed\n\nlemma seq_part_when_not_disjnt4:\n \"\\ [\\tw. (inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)]\n Bassign_trans TEMP (Bsig IN) 1\n [\\tw. \\j \\ {fst tw <.. next_time_world tw}. inv_first_hold (j, snd tw)]\"\nproof (intro Assign2_altI, rule, rule, rule, rule)\n fix tw v j\n assume \"((inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)) \\ beval_world_raw2 tw (Bsig IN) v\"\n hence \"inv_first tw\" and \"inv_second tw\" and \"inv_first_hold tw\" and \"inv_second_hold tw\" and \"\\ disjnt {IN} (event_of tw)\"\n and \" beval_world_raw2 tw (Bsig IN) v\"\n by auto\n define tw1 where \"tw1 = tw [TEMP, 1 :=\\<^sub>2 v]\"\n then obtain v' where \"beval_world_raw2 tw1 (Bsig TEMP) v'\"\n by (meson beval_world_raw2_Bsig)\n assume \"j \\ {fst tw1 <.. next_time_world tw1}\"\n define tw2 where \"tw2 = tw1[OUT, 1 :=\\<^sub>2 v']\"\n\n have \"fst tw < j\"\n by (metis \\j \\ {get_time tw1<..next_time_world tw1}\\ greaterThanAtMost_iff snd_conv snd_swap swap_simp tw1_def worldline_upd2_def)\n have \"fst tw = fst tw1\"\n by (simp add: tw1_def worldline_upd2_def)\n also have \"... = fst tw2\"\n by (simp add: tw1_def tw2_def worldline_upd2_def)\n also have \"... < next_time_world tw2\"\n using next_time_world_at_least by metis\n finally have \"fst tw < next_time_world tw2\"\n by auto\n have \"fst tw1 < next_time_world tw2\"\n by (simp add: \\get_time tw1 = get_time tw2\\ \\get_time tw2 < next_time_world tw2\\)\n\n have 5: \"inv_first_hold (j, snd tw1)\"\n unfolding inv_first_hold_def\n proof (rule, rule, rule)\n fix i\n assume \"disjnt {IN} (event_of (j, snd tw1))\"\n assume \"fst (j, snd tw1) \\ i\"\n hence \"j \\ i\"\n by auto\n hence \"wline_of tw1 TEMP (i + 1) = wline_of tw IN (fst tw)\"\n using `fst tw < j`\n by (smt \\beval_world_raw2 tw (Bsig IN) v\\ add_less_cancel_right beval_world_raw2_Bsig\n beval_world_raw2_def beval_world_raw_deterministic less_le_trans o_apply order.asym snd_conv\n tw1_def worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw1 IN (fst tw)\"\n by (metis less_add_one tw1_def worldline_upd2_before_dly)\n also have \"... = wline_of tw1 IN (j - 1)\"\n using `fst tw < j` unchanged_until_next_time_world\n by (metis (no_types, lifting) \\get_time tw = get_time tw1\\ \\j \\ {get_time\n tw1<..next_time_world tw1}\\ add_diff_cancel_left' diff_add diff_is_0_eq' diff_zero discrete\n greaterThanAtMost_iff not_less)\n also have \"... = wline_of tw1 IN j\"\n using \\disjnt {IN} (event_of (j, snd tw1))\\ unfolding event_of_alt_def\n using \\get_time tw < j\\ by auto\n finally show \"wline_of (j, snd tw1) TEMP (i + 1) = wline_of (j, snd tw1) IN (get_time (j, snd tw1))\"\n by auto\n qed\n thus \" inv_first_hold (j, snd tw[ TEMP, 1 :=\\<^sub>2 v])\"\n unfolding tw1_def by auto\nqed\n\nlemma seq_part_when_not_disjnt_2post_4:\n \"\\ [\\tw. (inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)]\n Bassign_trans TEMP (Bsig IN) 1\n [\\tw. \\j \\ {fst tw <.. next_time_world tw}. inv_first (j, snd tw) \\ inv_first_hold (j, snd tw)]\"\n apply (rule Conj_univ_qtfd)\n apply (rule seq_part_when_not_disjnt2_post)\n apply (rule seq_part_when_not_disjnt4)\n done\n \nlemma seq_part_when_not_disjnt5:\n \"\\ [\\tw. (inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)]\n Bassign_trans TEMP (Bsig IN) 1\n [\\tw. let x = wline_of tw TEMP (fst tw) in inv_first (next_time_world tw[ OUT, 1 :=\\<^sub>2 x], snd tw[ OUT, 1 :=\\<^sub>2 x])]\"\nproof (intro Assign2_altI, rule, rule, rule)\n fix tw v\n assume \"((inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)) \\ beval_world_raw2 tw (Bsig IN) v\"\n hence \"inv_first tw\" and \"inv_second tw\" and \"inv_first_hold tw\" and \"inv_second_hold tw\" and \"\\ disjnt {IN} (event_of tw)\"\n and \" beval_world_raw2 tw (Bsig IN) v\"\n by auto\n define tw1 where \"tw1 = tw [TEMP, 1 :=\\<^sub>2 v]\"\n then obtain v' where \"beval_world_raw2 tw1 (Bsig TEMP) v'\"\n by (meson beval_world_raw2_Bsig)\n define tw2 where \"tw2 = tw1[OUT, 1 :=\\<^sub>2 v']\"\n define t' where \"t' = next_time_world tw1\"\n have \"fst tw < t'\"\n unfolding t'_def by (metis fst_conv next_time_world_at_least tw1_def worldline_upd2_def)\n have \"fst tw = fst tw1\"\n by (simp add: tw1_def worldline_upd2_def)\n also have \"... = fst tw2\"\n by (simp add: tw1_def tw2_def worldline_upd2_def)\n also have \"... < next_time_world tw2\"\n using next_time_world_at_least by metis\n finally have \"fst tw < next_time_world tw2\"\n by auto\n have \"fst tw1 < next_time_world tw2\"\n by (simp add: \\get_time tw1 = get_time tw2\\ \\get_time tw2 < next_time_world tw2\\)\n\n have 2: \"inv_first (next_time_world tw2, snd tw2)\"\n unfolding inv_first_def\n proof (rule, rule)\n fix i\n assume \"i < fst (next_time_world tw2, snd tw2)\"\n hence \"i < next_time_world tw2\"\n by auto\n with \\fst tw < next_time_world tw2\\\n have \"i < fst tw \\ fst tw \\ i \\ i < next_time_world tw2 - 1 \\ i = next_time_world tw2 - 1\"\n by auto\n moreover\n { assume \"i < fst tw\"\n have \"wline_of tw2 TEMP (i + 1) = wline_of tw TEMP (i + 1)\"\n by (metis \\get_time tw = get_time tw1\\ \\i < get_time tw\\ add_mono1 tw1_def tw2_def\n worldline_upd2_before_dly)\n also have \"... = wline_of tw IN i\"\n using \\inv_first tw\\ \\i < fst tw\\ unfolding inv_first_def by auto\n also have \"... = wline_of tw2 IN i\"\n by (metis \\get_time tw = get_time tw1\\ \\i < get_time tw\\ add.right_neutral\n add_mono_thms_linordered_field(5) tw1_def tw2_def worldline_upd2_before_dly zero_less_one)\n finally have \"wline_of tw2 TEMP (i + 1) = wline_of tw2 IN i\"\n by auto }\n moreover\n { assume \"fst tw \\ i \\ i < next_time_world tw2 - 1\"\n hence \"fst tw2 \\ i \\ i < next_time_world tw2 - 1\"\n by (simp add: \\get_time tw = get_time tw1\\ \\get_time tw1 = get_time tw2\\)\n hence \"wline_of tw2 TEMP (i + 1) = wline_of tw2 TEMP (fst tw2 + 1)\"\n by (metis (no_types, lifting) One_nat_def Suc_less_eq \\get_time tw2 < next_time_world tw2\\\n add.right_neutral add_Suc_right le_Suc_eq less_diff_conv not_less\n unchanged_until_next_time_world)\n also have \"... = wline_of tw1 TEMP (fst tw2 + 1)\"\n by (metis \\get_time tw1 = get_time tw2\\ sig.distinct(6) tw2_def worldline_upd2_at_dly_nonsig)\n also have \"... = wline_of tw1 TEMP (fst tw + 1)\"\n by (simp add: \\get_time tw = get_time tw1\\ \\get_time tw1 = get_time tw2\\)\n also have \"... = wline_of tw IN (fst tw) \"\n unfolding tw1_def\n by (metis \\beval_world_raw2 tw (Bsig IN) v\\ beval_world_raw2_Bsig beval_world_raw2_def\n beval_world_raw_deterministic worldline_upd2_at_dly)\n also have \"... = wline_of tw1 IN (fst tw1)\"\n by (metis \\get_time tw = get_time tw1\\ less_add_one tw1_def worldline_upd2_before_dly)\n also have \"... = wline_of tw2 IN (fst tw2)\"\n by (metis \\get_time tw1 = get_time tw2\\ less_add_one tw2_def worldline_upd2_before_dly)\n also have \"... = wline_of tw2 IN i\"\n using \\get_time tw2 \\ i \\ i < next_time_world tw2 - 1\\ \\i < next_time_world tw2\\\n unchanged_until_next_time_world by metis\n finally have \"wline_of tw2 TEMP (i + 1) = wline_of tw2 IN i\"\n by auto }\n moreover\n { assume \"i = next_time_world tw2 - 1\"\n hence \"wline_of tw2 TEMP (i + 1) = wline_of tw2 TEMP (next_time_world tw2)\"\n using \\i < next_time_world tw2\\ by force\n also have \"... = wline_of tw2 TEMP (fst tw2 + 1)\"\n unfolding tw2_def\n by (smt \\get_time tw < next_time_world tw2\\ \\get_time tw = get_time tw1\\ \\get_time tw1 =\n get_time tw2\\ comp_apply discrete leD less_imp_le_nat snd_conv tw1_def tw2_def\n worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw2 TEMP (fst tw1 + 1)\"\n by (simp add: \\get_time tw1 = get_time tw2\\)\n also have \"... = wline_of tw1 TEMP (fst tw1 + 1)\"\n unfolding tw2_def by (metis sig.distinct(6) worldline_upd2_at_dly_nonsig)\n also have \"... = wline_of tw IN (fst tw)\"\n unfolding tw1_def\n by (metis \\beval_world_raw2 tw (Bsig IN) v\\ \\get_time tw = get_time tw1\\\n beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic tw1_def\n worldline_upd2_at_dly)\n also have \"... = wline_of tw1 IN (fst tw)\"\n by (metis less_add_one tw1_def worldline_upd2_before_dly)\n also have \"... = wline_of tw2 IN (fst tw2)\"\n by (metis \\get_time tw = get_time tw1\\ \\get_time tw1 = get_time tw2\\ less_add_one tw2_def\n worldline_upd2_before_dly)\n also have \"... = wline_of tw2 IN i\"\n by (metis \\get_time tw = get_time tw1\\ \\get_time tw1 = get_time tw2\\ \\i < get_time tw \\\n wline_of tw2 TEMP (i + 1) = wline_of tw2 IN i\\ \\i < next_time_world tw2\\ calculation\n not_less unchanged_until_next_time_world)\n finally have \"wline_of tw2 TEMP (i + 1) = wline_of tw2 IN i\"\n by auto }\n ultimately have \"wline_of tw2 TEMP (i + 1) = wline_of tw2 IN i\"\n by auto\n thus \" wline_of (next_time_world tw2, snd tw2) TEMP (i + 1) = wline_of (next_time_world tw2, snd tw2) IN i\"\n by auto\n qed\n thus \"let xa = wline_of tw[ TEMP, 1 :=\\<^sub>2 v] TEMP (get_time tw[ TEMP, 1 :=\\<^sub>2 v])\n in inv_first (next_time_world tw[ TEMP, 1 :=\\<^sub>2 v][ OUT, 1 :=\\<^sub>2 xa], snd tw[ TEMP, 1 :=\\<^sub>2 v][ OUT, 1 :=\\<^sub>2 xa])\"\n unfolding tw2_def tw1_def using \\beval_world_raw2 tw1 (Bsig TEMP) v'\\ tw1_def\n by (metis beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic)\nqed\n\nlemma seq_part_when_not_disjnt5_post:\n \"\\ [\\tw. (inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)]\n Bassign_trans TEMP (Bsig IN) 1\n [\\tw. let x = wline_of tw TEMP (fst tw); tw' = tw[OUT,1 :=\\<^sub>2 x] in \\j \\ {fst tw' <.. next_time_world tw'}. inv_first (j, snd tw')]\"\n apply (rule Conseq2[rotated])\n apply (rule seq_part_when_not_disjnt5)\n by (auto simp add: Let_def aux1)\n\nlemma seq_part_when_not_disjnt6:\n \"\\ [\\tw. (inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)]\n Bassign_trans TEMP (Bsig IN) 1\n [\\tw. let x = wline_of tw TEMP (fst tw); tw' = tw [OUT, 1 :=\\<^sub>2 x] in\n \\j \\ {fst tw' <.. next_time_world tw'}. inv_first_hold (j, snd tw')]\"\nproof (intro Assign2_altI, rule, rule, rule)\n fix tw v \n assume \"((inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)) \\ beval_world_raw2 tw (Bsig IN) v\"\n hence \"inv_first tw\" and \"inv_second tw\" and \"inv_first_hold tw\" and \"inv_second_hold tw\" and \"\\ disjnt {IN} (event_of tw)\"\n and \" beval_world_raw2 tw (Bsig IN) v\"\n by auto\n define tw1 where \"tw1 = tw [TEMP, 1 :=\\<^sub>2 v]\"\n then obtain v' where \"beval_world_raw2 tw1 (Bsig TEMP) v'\"\n by (meson beval_world_raw2_Bsig)\n define tw2 where \"tw2 = tw1[OUT, 1 :=\\<^sub>2 v']\"\n { fix j\n assume \"j \\ {fst tw2 <.. next_time_world tw2}\"\n have \"fst tw < j\"\n by (metis \\j \\ {get_time tw2<..next_time_world tw2}\\ greaterThanAtMost_iff snd_conv snd_swap\n swap_simp tw1_def tw2_def worldline_upd2_def)\n have \"fst tw = fst tw1\"\n by (simp add: tw1_def worldline_upd2_def)\n also have \"... = fst tw2\"\n by (simp add: tw1_def tw2_def worldline_upd2_def)\n also have \"... < next_time_world tw2\"\n using next_time_world_at_least by metis\n finally have \"fst tw < next_time_world tw2\"\n by auto\n have \"fst tw1 < next_time_world tw2\"\n by (simp add: \\get_time tw1 = get_time tw2\\ \\get_time tw2 < next_time_world tw2\\)\n \n have 3: \"inv_first_hold (j, snd tw2)\"\n unfolding inv_first_hold_def\n proof (rule, rule, rule)\n fix i\n assume \"disjnt {IN} (event_of (j, snd tw2))\"\n assume \"fst (j, snd tw2) \\ i\"\n hence \"j \\ i\" and \"fst tw1 < i\"\n using \\get_time (j, snd tw2) \\ i\\ \\get_time tw < j\\ \\get_time tw = get_time tw1\\ by auto\n hence \"wline_of tw2 TEMP (i + 1) = wline_of tw1 TEMP (i + 1)\"\n by (simp add: tw2_def worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw IN (fst tw)\"\n unfolding tw1_def\n by (smt \\beval_world_raw2 tw (Bsig IN) v\\ \\get_time tw = get_time tw1\\ \\get_time tw1 < i\\\n beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic discrete\n dual_order.strict_trans2 less_add_one o_apply order.asym snd_conv worldline_upd2_def\n worldline_upd_def)\n also have \"... = wline_of tw2 IN (fst tw2)\"\n by (metis \\get_time tw = get_time tw1\\ \\get_time tw1 = get_time tw2\\ less_add_one tw1_def tw2_def worldline_upd2_before_dly)\n also have \"... = wline_of tw2 IN (j - 1)\"\n using unchanged_until_next_time_world\n by (metis (no_types, lifting) \\j \\ {get_time tw2<..next_time_world tw2}\\\n cancel_comm_monoid_add_class.diff_cancel diff_add diff_is_0_eq discrete greaterThanAtMost_iff\n le_0_eq le_Suc_eq le_add_diff_inverse less_imp_le_nat nat_neq_iff plus_1_eq_Suc)\n also have \"... = wline_of tw2 IN j\"\n using \\disjnt {IN} (event_of (j, snd tw2))\\\n unfolding event_of_alt_def using \\get_time tw2 < next_time_world tw2\\ \n using \\j \\ {get_time tw2<..next_time_world tw2}\\ by auto\n finally have \"wline_of tw2 TEMP (i + 1) = wline_of tw2 IN j\"\n by auto\n thus \" wline_of (j, snd tw2) TEMP (i + 1) = wline_of (j, snd tw2) IN (get_time (j, snd tw2))\"\n by auto\n qed }\n hence \"\\v' j. beval_world_raw2 tw1 (Bsig TEMP) v' \\ j \\ {fst tw1[OUT, 1 :=\\<^sub>2 v'] <.. next_time_world tw1[OUT, 1 :=\\<^sub>2 v']} \\ inv_first_hold (j, snd tw1[OUT, 1 :=\\<^sub>2 v'])\"\n by (metis (full_types) \\beval_world_raw2 tw1 (Bsig TEMP) v'\\ beval_world_raw2_def beval_world_raw_deterministic tw2_def)\n thus \" let va = wline_of tw[ TEMP, 1 :=\\<^sub>2 v] TEMP (get_time tw[ TEMP, 1 :=\\<^sub>2 v]); tw' = tw[ TEMP, 1 :=\\<^sub>2 v][ OUT, 1 :=\\<^sub>2 va]\n in \\j\\{get_time tw'<..next_time_world tw'}. inv_first_hold (j, snd tw')\"\n using \\beval_world_raw2 tw1 (Bsig TEMP) v'\\ unfolding tw1_def tw2_def\n by (metis beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic)\nqed\n\nlemma seq_part_when_not_disjnt_5post_6:\n \"\\ [\\tw. (inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)]\n Bassign_trans TEMP (Bsig IN) 1\n [\\tw. let x = wline_of tw TEMP (fst tw); tw' = tw [OUT, 1 :=\\<^sub>2 x] in\n \\j \\ {fst tw' <.. next_time_world tw'}. inv_first (j, snd tw') \\ inv_first_hold (j, snd tw')]\"\n apply (intro Assign2_altI, rule, rule, rule)\n by (metis (no_types, lifting) BassignE_hoare2 seq_part_when_not_disjnt5_post seq_part_when_not_disjnt6)\n\nlemma seq_part_when_not_disjnt:\n \" \\ [\\tw. (inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw) \\ \\ disjnt {IN} (event_of tw)]\n Bassign_trans TEMP (Bsig IN) 1\n [\\tw. (\\j\\{get_time tw<..next_time_world tw}. inv_first (j, snd tw) \\ inv_first_hold (j, snd tw)) \n \\ (let v = wline_of tw TEMP (get_time tw); tw' = tw[ OUT, 1 :=\\<^sub>2 v] in \\j\\{get_time tw'<..next_time_world tw'}. inv_first (j, snd tw') \\ inv_first_hold (j, snd tw')) \n \\ inv_second tw \\ inv_second_hold tw]\"\n using seq_part_when_not_disjnt1 seq_part_when_not_disjnt_2post_4 seq_part_when_not_disjnt3\n seq_part_when_not_disjnt5_post seq_part_when_not_disjnt_5post_6\n by (intro Conj)\n\nlemma inv_first_disjnt_next_time_no_process_later:\n assumes \"inv_first tw\" and \"inv_first_hold tw\" and \"disjnt {IN} (event_of tw)\"\n shows \"\\j \\ {fst tw <.. next_time_world tw}. inv_first (j, snd tw)\"\n unfolding inv_first_def\nproof (rule, rule, rule)\n fix i j\n assume \"j \\ {fst tw <.. next_time_world tw}\"\n assume \" i < get_time (j, snd tw)\"\n hence \"i < j\"\n by auto\n hence \"i < fst tw \\ fst tw \\ i\"\n by auto\n moreover\n { assume \"i < fst tw\"\n hence \"wline_of tw TEMP (i + 1) = wline_of tw IN i\"\n using assms(1) unfolding inv_first_def by auto }\n moreover\n { assume \"fst tw \\ i\"\n moreover have \"(\\i \\ fst tw. wline_of tw TEMP (i + 1) = wline_of tw IN (fst tw))\"\n using assms(2-3) unfolding inv_first_hold_def by auto\n ultimately have \"wline_of tw TEMP (i + 1) = wline_of tw IN (fst tw)\"\n by auto\n also have \"... = wline_of tw IN i\"\n by (metis (no_types, lifting) \\get_time tw \\ i\\ \\i < j\\ \\j \\ {get_time tw<..next_time_world\n tw}\\ discrete greaterThanAtMost_iff le_trans unchanged_until_next_time_world)\n finally have \"wline_of tw TEMP (i + 1) = wline_of tw IN i\"\n by auto }\n ultimately have \"wline_of tw TEMP (i + 1) = wline_of tw IN i\"\n by auto\n thus \"wline_of (j, snd tw) TEMP (i + 1) = wline_of (j, snd tw) IN i\"\n by auto\nqed\n\nlemma inv_first_disjnt_next_time:\n assumes \"inv_first tw\" and \"inv_first_hold tw\" and \"disjnt {IN} (event_of tw)\"\n shows \"let v = wline_of tw TEMP (fst tw); tw' = tw [OUT, 1 :=\\<^sub>2 v] in \\j \\ {fst tw' <.. next_time_world tw'}. inv_first (j, snd tw')\"\n unfolding inv_first_def Let_def\nproof (rule, rule, rule)\n fix i j :: nat\n let ?v = \"wline_of tw TEMP (fst tw)\"\n assume \"i < get_time (j, snd tw[ OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)])\"\n hence \"i < j\"\n by auto\n let ?tw = \"tw[OUT, 1 :=\\<^sub>2 ?v]\"\n assume \"j \\ {fst ?tw <.. next_time_world ?tw}\"\n have \"fst ?tw < next_time_world ?tw\"\n using next_time_world_at_least by metis\n moreover have \"fst ?tw = fst tw\"\n by (simp add: worldline_upd2_def)\n finally have \"fst tw < next_time_world ?tw\"\n by auto\n have \"i < fst tw \\ fst tw \\ i\"\n by auto\n moreover\n { assume \"i < fst tw\"\n hence \"wline_of ?tw TEMP (i + 1) = wline_of tw TEMP (i + 1)\"\n by (meson add_mono1 worldline_upd2_before_dly)\n also have \"... = wline_of tw IN i\"\n using assms(1) unfolding inv_first_def using \\i < get_time tw\\ by blast\n also have \"... = wline_of ?tw IN i\"\n by (metis \\i < get_time tw\\ add.right_neutral add_mono_thms_linordered_field(5)\n worldline_upd2_before_dly zero_less_one)\n finally have \"wline_of ?tw TEMP (i + 1) = wline_of ?tw IN i\"\n by auto }\n moreover\n { assume \"fst tw \\ i\"\n have \"wline_of ?tw TEMP (i + 1) = wline_of tw TEMP (i + 1)\"\n using \\i < j\\ \\fst tw < next_time_world ?tw\\\n by (simp add: worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw IN i\"\n using assms(2-3) unfolding inv_first_hold_def\n by (smt \\get_time tw \\ i\\ \\get_time tw[ OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)] = get_time\n tw\\ \\i < j\\ \\j \\ {get_time tw[ OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)]<..next_time_world\n tw[ OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)]}\\ antisym_conv calculation comp_apply\n greaterThanAtMost_iff le_eq_less_or_eq le_trans less_imp_le_nat nat_neq_iff sig.distinct(3)\n snd_conv snd_conv unchanged_until_next_time_world worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of ?tw IN i\"\n by (simp add: worldline_upd2_def worldline_upd_def)\n finally have \"wline_of ?tw TEMP (i + 1) = wline_of ?tw IN i\"\n by auto }\n ultimately have \"wline_of ?tw TEMP (i + 1) = wline_of ?tw IN i\"\n by auto\n thus \"wline_of (j, snd tw[ OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)]) TEMP (i + 1) = wline_of (j, snd tw[ OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)]) IN i\"\n by auto\nqed\n\nlemma inv_first_hold_disjnt_next_time_no_process_later:\n assumes \"inv_first_hold tw\" and \"disjnt {IN} (event_of tw)\"\n shows \"\\j \\ {fst tw <.. next_time_world tw}. inv_first_hold (j, snd tw)\"\n unfolding inv_first_hold_def\nproof (rule, rule, rule, rule)\n fix i j\n assume \"j \\ {fst tw <.. next_time_world tw}\"\n assume \"disjnt {IN} (event_of (j, snd tw))\"\n assume \"fst (j, snd tw) \\ i\"\n hence \"j \\ i\"\n by auto\n moreover have \"fst tw < j\"\n using \\j \\ {get_time tw<..next_time_world tw}\\ greaterThanAtMost_iff by blast\n ultimately have \"fst tw \\ i\"\n by auto\n moreover have \"(\\i \\ fst tw. wline_of tw TEMP (i + 1) = wline_of tw IN (fst tw))\"\n using assms unfolding inv_first_hold_def by auto\n ultimately have \"wline_of tw TEMP (i + 1) = wline_of tw IN (fst tw)\"\n by auto\n also have \"... = wline_of tw IN (j - 1)\"\n using unchanged_until_next_time_world\n by (metis (no_types, lifting) \\j \\ {get_time tw<..next_time_world tw}\\ add_diff_cancel_left'\n diff_add diff_is_0_eq' discrete greaterThanAtMost_iff le_numeral_extra(4) not_less)\n also have \"... = wline_of tw IN (j)\"\n using \\disjnt {IN} (event_of (j, snd tw))\\\n unfolding event_of_alt_def using \\get_time tw < j\\ by auto\n finally have \"wline_of tw TEMP (i + 1) = wline_of tw IN (j)\"\n by auto\n thus \"wline_of (j, snd tw) TEMP (i + 1) =\n wline_of (j, snd tw) IN (get_time (j, snd tw))\"\n by auto\nqed\n\nlemma inv_first_hold_disjnt_next_time:\n assumes \"inv_first_hold tw\" and \"disjnt {IN} (event_of tw)\"\n shows \"let v = wline_of tw TEMP (fst tw); tw' = tw [OUT, 1 :=\\<^sub>2 v] in \\j \\ {fst tw' <.. next_time_world tw'}. inv_first_hold (j, snd tw')\"\n unfolding inv_first_hold_def Let_def\nproof (rule, rule, rule, rule)\n let ?v = \"wline_of tw TEMP (fst tw)\"\n let ?tw = \"tw[OUT, 1 :=\\<^sub>2 ?v]\"\n fix i j \n assume \"j \\ {fst ?tw <.. next_time_world ?tw}\"\n assume \"disjnt {IN} (event_of (j, snd ?tw))\"\n assume \"fst (j, snd ?tw) \\ i\"\n hence \"j \\ i\"\n by auto\n moreover have \"fst ?tw < j\"\n using \\j \\ {get_time tw[ OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)]<..next_time_world tw[ OUT,\n 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)]}\\ greaterThanAtMost_iff by blast\n moreover have \"fst tw = fst ?tw\"\n by (simp add: worldline_upd2_def)\n ultimately have \"fst tw < j\"\n by auto\n have \"wline_of ?tw TEMP (i + 1) = wline_of tw TEMP (i + 1)\"\n by (simp add: worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw IN (fst tw)\"\n using assms(1-2) \\fst tw < j\\ \\j \\ i\\ unfolding inv_first_hold_def by auto\n also have \"... = wline_of ?tw IN (fst tw)\"\n by (metis less_add_one worldline_upd2_before_dly)\n also have \"... = wline_of ?tw IN (fst ?tw)\"\n using \\get_time tw = get_time tw[ OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)]\\ by auto\n also have \"... = wline_of ?tw IN (j - 1)\"\n using unchanged_until_next_time_world\n by (smt \\j \\ {get_time tw[ OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)]<..next_time_world tw[\n OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)]}\\ diff_add discrete dual_order.strict_iff_order\n greaterThanAtMost_iff less_one not_less)\n also have \"... = wline_of ?tw IN j\"\n using \\disjnt {IN} (event_of (j, snd ?tw))\\\n unfolding event_of_alt_def using \\get_time tw < j\\ by auto\n finally have \"wline_of ?tw TEMP (i + 1) = wline_of ?tw IN j\"\n by auto\n thus \"wline_of (j, snd tw[ OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)]) TEMP (i + 1) =\n wline_of (j, snd tw[ OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)]) IN (get_time (j, snd tw[ OUT, 1 :=\\<^sub>2 wline_of tw TEMP (get_time tw)]))\"\n by auto\nqed\n\nlemma conc_next_time:\n \"\\ \\\\tw. inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw\\\n process {IN} : Bassign_trans TEMP (Bsig IN) 1\n \\\\tw. (\\j\\{get_time tw<..next_time_world tw}. inv_first (j, snd tw) \\ inv_first_hold (j, snd tw)) \\\n (let v = wline_of tw TEMP (get_time tw); tw' = tw[ OUT, 1 :=\\<^sub>2 v]\n in \\j\\{get_time tw'<..next_time_world tw'}. inv_first (j, snd tw') \\ inv_first_hold (j, snd tw')) \\\n inv_second tw \\ inv_second_hold tw\\\"\n apply (rule Single)\n apply (rule seq_part_when_not_disjnt)\n using inv_first_disjnt_next_time inv_first_hold_disjnt_next_time\n inv_first_disjnt_next_time_no_process_later inv_first_hold_disjnt_next_time_no_process_later\n by meson\n\nlemma snd_seq_part_when_not_disjnt:\n \"\\ [\\tw. ((\\j\\{get_time tw<..next_time_world tw}. inv_first (j, snd tw) \\ inv_first_hold (j, snd tw)) \\\n (let v = wline_of tw TEMP (get_time tw); tw' = tw[ OUT, 1 :=\\<^sub>2 v]\n in \\j\\{get_time tw'<..next_time_world tw'}. inv_first (j, snd tw') \\ inv_first_hold (j, snd tw')) \\\n inv_second tw \\ inv_second_hold tw) \\\n \\ disjnt {TEMP} (event_of tw)]\n Bassign_trans OUT (Bsig TEMP) 1\n [\\tw. (\\j\\{get_time tw<..next_time_world tw}. inv_first (j, snd tw) \\ inv_first_hold (j, snd tw)) \\\n (\\j\\{get_time tw<..next_time_world tw}. inv_second (j, snd tw) \\ inv_second_hold (j, snd tw))]\"\nproof (rule Assign2_altI, rule, rule, rule, rule, rule_tac[!] ballI)\n fix tw v j \n assume asm: \"( ( (\\j\\{get_time tw<..next_time_world tw}. inv_first (j, snd tw) \\ inv_first_hold (j, snd tw)) \n \\ (let v = wline_of tw TEMP (get_time tw); tw' = tw[ OUT, 1 :=\\<^sub>2 v] in \\j\\{get_time tw'<..next_time_world tw'}. inv_first (j, snd tw') \\ inv_first_hold (j, snd tw')) \n \\ inv_second tw \\ inv_second_hold tw\n ) \n \\ \\ disjnt {TEMP} (event_of tw)) \n \\ beval_world_raw2 tw (Bsig TEMP) v\"\n let ?tw' = \"tw[ OUT, 1 :=\\<^sub>2 v]\"\n assume \"j \\ {get_time ?tw' <..next_time_world ?tw'}\"\n\n hence 0: \"inv_first (j, snd ?tw')\" and \"inv_second tw\" and 1: \"inv_first_hold (j, snd ?tw')\" and \"inv_second_hold tw\"\n and \"\\ disjnt {TEMP} (event_of tw)\" and \"beval_world_raw2 tw (Bsig TEMP) v\"\n using asm beval_world_raw2_def beval_world_raw_deterministic\n by (metis beval_world_raw2_Bsig)+\n\n \\ \\general facts\\\n have \"fst ?tw' < j\"\n using next_time_world_at_least\n using \\j \\ {get_time tw[ OUT, 1 :=\\<^sub>2 v]<..next_time_world tw[ OUT, 1 :=\\<^sub>2 v]}\\\n greaterThanAtMost_iff by blast\n moreover have \"fst tw = fst ?tw'\"\n unfolding worldline_upd2_def worldline_upd_def by auto\n ultimately have \"fst tw < j\"\n by linarith\n\n have 2: \"inv_second (j, snd ?tw')\"\n unfolding inv_second_def\n proof (rule, rule)\n fix i\n assume \"i < fst (j, snd ?tw')\"\n hence \"i < j\"\n by auto\n have \"i < fst tw \\ fst tw \\ i \\ i < j - 1 \\ i = j - 1\"\n using \\fst tw < j\\ by linarith\n moreover\n { assume \"i < fst tw\"\n hence \"wline_of ?tw' OUT (i + 1) = wline_of tw OUT (i + 1)\"\n by (metis add_mono1 worldline_upd2_before_dly)\n also have \"... = wline_of tw TEMP i\"\n using \\inv_second tw\\ \\i < fst tw\\ unfolding inv_second_def by auto\n also have \"... = wline_of ?tw' TEMP i\"\n by (simp add: worldline_upd2_def worldline_upd_def)\n finally have \"wline_of ?tw' OUT (i + 1) = wline_of ?tw' TEMP i\"\n by auto }\n moreover\n { assume \"fst tw \\ i \\ i < j - 1\"\n hence \"fst ?tw' \\ i \\ i < j - 1\"\n using `fst tw = fst ?tw'` by linarith\n hence \"wline_of ?tw' OUT (i + 1) = wline_of ?tw' OUT (fst ?tw' + 1)\"\n by (smt \\j \\ {get_time tw[ OUT, 1 :=\\<^sub>2 v]<..next_time_world tw[ OUT, 1 :=\\<^sub>2 v]}\\\n dual_order.strict_trans1 greaterThanAtMost_iff le_add1 less_diff_conv not_less\n unchanged_until_next_time_world)\n also have \"... = wline_of ?tw' OUT (fst tw + 1)\"\n using \\get_time tw = get_time ?tw'\\ by auto\n also have \"... = wline_of tw TEMP (fst tw) \"\n by (metis \\beval_world_raw2 tw (Bsig TEMP) v\\ beval_world_raw2_Bsig beval_world_raw2_def\n beval_world_raw_deterministic worldline_upd2_at_dly)\n also have \"... = wline_of ?tw' TEMP (fst ?tw')\"\n by (metis \\get_time tw = get_time ?tw'\\ less_add_one worldline_upd2_before_dly)\n also have \"... = wline_of ?tw' TEMP i\"\n using \\get_time ?tw' \\ i \\ i < j - 1\\ \\i < j\\ unchanged_until_next_time_world\n by (metis (no_types, lifting) \\j \\ {get_time tw[ OUT, 1 :=\\<^sub>2 v]<..next_time_world tw[ OUT, 1\n :=\\<^sub>2 v]}\\ dual_order.strict_trans1 greaterThanAtMost_iff)\n finally have \"wline_of ?tw' OUT (i + 1) = wline_of ?tw' TEMP i\"\n by auto }\n moreover\n { assume \"i = j - 1\"\n hence \"wline_of ?tw' OUT (i + 1) = wline_of ?tw' OUT j\"\n using \\i < j\\ by auto\n also have \"... = wline_of tw TEMP (fst tw)\"\n using \\fst tw < j\\\n by (smt \\beval_world_raw2 tw (Bsig TEMP) v\\ beval_world_raw2_Bsig beval_world_raw2_def\n beval_world_raw_deterministic discrete leD o_apply snd_conv worldline_upd2_def\n worldline_upd_def)\n also have \"... = wline_of ?tw' TEMP (fst ?tw')\"\n by (metis \\get_time tw = get_time ?tw'\\ less_add_one worldline_upd2_before_dly)\n also have \"... = wline_of ?tw' TEMP i\"\n by (metis (no_types, lifting) Nat.le_diff_conv2 \\i < j\\ \\i = j - 1\\ \\j \\ {get_time tw[ OUT,\n 1 :=\\<^sub>2 v]<..next_time_world tw[ OUT, 1 :=\\<^sub>2 v]}\\ discrete greaterThanAtMost_iff le_add2\n le_trans unchanged_until_next_time_world)\n finally have \"wline_of ?tw' OUT (i + 1) = wline_of ?tw' TEMP i\"\n by auto }\n ultimately have \"wline_of ?tw' OUT (i + 1) = wline_of ?tw' TEMP i\"\n using \\i < j\\ by fastforce\n thus \"wline_of (j, snd ?tw') OUT (i + 1) = wline_of (j, snd ?tw') TEMP i\"\n by auto\n qed\n\n have 3: \"inv_second_hold (j, snd ?tw')\"\n unfolding inv_second_hold_def\n proof (rule, rule, rule)\n fix i\n assume \"disjnt {TEMP} (event_of (j, snd ?tw'))\"\n assume \"fst (j, snd ?tw') \\ i\"\n hence \"j \\ i\"\n by auto\n hence \"beval_world_raw2 tw (Bsig TEMP) (wline_of ?tw' OUT (i + 1))\"\n using `fst tw < j` unfolding worldline_upd2_def worldline_upd_def\n using \\beval_world_raw2 tw (Bsig TEMP) v\\ by auto\n also have \"... = wline_of tw TEMP (fst tw)\"\n by (metis beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic calculation)\n also have \"... = wline_of ?tw' TEMP (fst ?tw')\"\n by (metis \\get_time tw = get_time ?tw'\\ less_add_one worldline_upd2_before_dly)\n also have \"... = wline_of ?tw' TEMP (j - 1)\"\n using unchanged_until_next_time_world \\fst tw < j\\\n by (metis (no_types, hide_lams) \\get_time tw[ OUT, 1 :=\\<^sub>2 v] < j\\ \\j \\ {get_time tw[ OUT, 1\n :=\\<^sub>2 v]<..next_time_world tw[ OUT, 1 :=\\<^sub>2 v]}\\ add_leE add_le_imp_le_diff discrete\n greaterThanAtMost_iff less_diff_conv2 not_less)\n also have \"... = wline_of ?tw' TEMP j\"\n using \\disjnt {TEMP} (event_of (j, snd ?tw'))\\ unfolding event_of_alt_def\n using \\get_time tw < j\\ by auto\n finally have \"wline_of ?tw' OUT (i + 1) = wline_of ?tw' TEMP j\"\n using \\wline_of tw TEMP (get_time tw) = wline_of ?tw' TEMP (get_time ?tw')\\ \\wline_of ?tw' OUT (i\n + 1) = wline_of tw TEMP (get_time tw)\\ \\wline_of ?tw' TEMP (get_time ?tw') = wline_of ?tw' TEMP\n (j - 1)\\ \\wline_of ?tw' TEMP (j - 1) = wline_of ?tw' TEMP j\\ by auto\n thus \"wline_of (j, snd ?tw') OUT (i + 1) = wline_of (j, snd ?tw') TEMP (get_time (j, snd ?tw'))\"\n by auto\n qed\n\n show \" inv_first (j, snd tw[ OUT, 1 :=\\<^sub>2 v]) \\ inv_first_hold (j, snd tw[ OUT, 1 :=\\<^sub>2 v])\" and \n \" inv_second (j, snd tw[ OUT, 1 :=\\<^sub>2 v]) \\ inv_second_hold (j, snd tw[ OUT, 1 :=\\<^sub>2 v])\"\n using 0 1 2 3 by auto\nqed\n\nlemma inv_second_next_time_world:\n assumes \"inv_second tw\" and \"inv_second_hold tw\" and \" disjnt {TEMP} (event_of tw)\"\n shows \"\\j \\ {fst tw <.. next_time_world tw}. inv_second (j, snd tw)\"\n unfolding inv_second_def\nproof (rule, rule, rule)\n fix j\n assume \"j \\ {fst tw <.. next_time_world tw}\"\n have *: \"(\\i \\ fst tw. wline_of tw OUT (i + 1) = wline_of tw TEMP (fst tw))\"\n using assms(2-3) unfolding inv_second_hold_def by auto\n fix i\n assume \"i < fst (j, snd tw)\"\n hence \"i < j\"\n by auto\n hence \"i < fst tw \\ fst tw \\ i\"\n by auto\n moreover\n { assume \"i < fst tw\"\n hence \"wline_of tw OUT (i + 1) = wline_of tw TEMP i\"\n using assms(1) unfolding inv_second_def by auto }\n moreover\n { assume \"fst tw \\ i\"\n with * have \"wline_of tw OUT (i + 1) = wline_of tw TEMP (fst tw)\"\n by blast\n also have \"... = wline_of tw TEMP i\"\n using \\i < j\\ unchanged_until_next_time_world\n using \\get_time tw \\ i\\ \n by (metis (mono_tags, hide_lams) \\j \\ {get_time tw<..next_time_world tw}\\ dual_order.trans\n greaterThanAtMost_iff not_less)\n finally have \"wline_of tw OUT (i + 1) = wline_of tw TEMP i\"\n by auto }\n ultimately have \"wline_of tw OUT (i + 1) = wline_of tw TEMP i\"\n by auto\n thus \" wline_of (j, snd tw) OUT (i + 1) = wline_of (j, snd tw) TEMP i\"\n by auto\nqed \n\nlemma inv_second_hold_next_time_world:\n assumes \"inv_second_hold tw\" and \"disjnt {TEMP} (event_of tw)\"\n shows \" \\j \\ {fst tw <.. next_time_world tw}. inv_second_hold (j, snd tw)\"\n unfolding inv_second_hold_def\nproof (rule, rule, rule, rule)\n fix j\n assume \"j \\ {fst tw <.. next_time_world tw}\"\n have *: \"(\\i \\ fst tw. wline_of tw OUT (i + 1) = wline_of tw TEMP (fst tw))\"\n using assms(1-2) unfolding inv_second_hold_def by auto\n fix i\n assume \"disjnt {TEMP} (event_of (j, snd tw))\"\n assume \"get_time (j, snd tw) \\ i\"\n hence \"j \\ i\"\n by auto\n hence \"fst tw \\ i\"\n using \\j \\ {get_time tw<..next_time_world tw}\\ by auto\n hence \"wline_of tw OUT (i + 1) = wline_of tw TEMP (fst tw)\"\n using * by blast\n also have \"... = wline_of tw TEMP (j - 1)\"\n using unchanged_until_next_time_world\n by (smt One_nat_def \\j \\ {get_time tw<..next_time_world tw}\\ add_diff_cancel_left' diff_add\n diff_is_0_eq' discrete greaterThanAtMost_iff not_less plus_1_eq_Suc)\n also have \"... = wline_of tw TEMP (j)\"\n using \\disjnt {TEMP} (event_of (j, snd tw))\\\n unfolding event_of_alt_def\n by (smt comp_apply diff_0_eq_0 disjnt_insert1 fst_conv mem_Collect_eq snd_conv)\n finally have \"wline_of tw OUT (i + 1) = wline_of tw TEMP (j)\"\n by auto\n thus \"wline_of (j, snd tw) OUT (i + 1) =\n wline_of (j, snd tw) TEMP (get_time (j, snd tw))\"\n by auto\nqed\n\nlemma conc_next_time_second:\n \"\\ \\\\tw. (\\j\\{get_time tw<..next_time_world tw}. inv_first (j, snd tw) \\ inv_first_hold (j, snd tw)) \\\n (let v = wline_of tw TEMP (get_time tw); tw' = tw[ OUT, 1 :=\\<^sub>2 v]\n in \\j\\{get_time tw'<..next_time_world tw'}. inv_first (j, snd tw') \\ inv_first_hold (j, snd tw')) \\\n inv_second tw \\ inv_second_hold tw\\\n process {TEMP} : Bassign_trans OUT (Bsig TEMP) 1\n \\\\tw. (\\i\\{get_time tw<..next_time_world tw}. inv_first (i, snd tw) \\ inv_first_hold (i, snd tw)) \\\n (\\i\\{get_time tw<..next_time_world tw}. inv_second (i, snd tw) \\ inv_second_hold (i, snd tw))\\\"\n apply (rule Single)\n apply (rule snd_seq_part_when_not_disjnt)\n using inv_second_hold_next_time_world inv_second_next_time_world\n by auto\n\nlemma pre_conc_next_time_combined:\n \"\\ \\\\tw. inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw\\\n two_inverter\n \\\\tw. (\\i\\{fst tw<..next_time_world tw}. inv_first (i, snd tw) \\ inv_first_hold (i, snd tw))\n \\ (\\i\\{fst tw<..next_time_world tw}. inv_second (i, snd tw) \\ inv_second_hold (i, snd tw))\\\"\n unfolding two_inverter_def\n apply (rule Parallel[where R=\"\\tw. (\\j \\ {fst tw <.. next_time_world tw}. inv_first (j, snd tw) \\ inv_first_hold (j, snd tw))\n \\ (let v = wline_of tw TEMP (fst tw); tw' = tw[OUT, 1 :=\\<^sub>2 v] in (\\j \\ {fst tw' <.. next_time_world tw'}. inv_first (j, snd tw') \\ inv_first_hold (j, snd tw')))\n \\ inv_second tw \\ inv_second_hold tw\"])\n apply (rule conc_next_time)\n apply (rule conc_next_time_second)\n by (auto simp add: conc_stmt_wf_def)\n\nlemma conc_next_time_combined:\n \"\\ \\\\tw. inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw\\\n two_inverter\n \\\\tw. \\i\\{get_time tw<..next_time_world tw}. inv_first (i, snd tw) \\ inv_second (i, snd tw) \\ inv_first_hold (i, snd tw) \\ inv_second_hold (i, snd tw)\\\"\n apply (rule Conseq'[rotated])\n apply (rule pre_conc_next_time_combined)\n by auto\n\ntheorem sim_correctness_two_inverter:\n \" \\\\<^sub>s \\\\tw. inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw\\\n two_inverter\n \\\\tw. inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw\\\"\n apply (rule While)\n apply (rule conc_next_time_combined)\n done\n\ncorollary sim_correctness_two_inverter2:\n \"\\\\<^sub>s \\\\tw. inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw\\\n two_inverter\n \\\\tw. inv_first tw \\ inv_second tw\\\"\n apply (rule Conseq_sim[rotated 1])\n apply (rule sim_correctness_two_inverter)\n apply simp+\n done\n\nsubsection \\Initialisation satisfies invariants\\\n\nlemma init_hoare1:\n \" \\\\<^sub>I \\\\tw. get_time tw = 0\\\n process {IN} : Bassign_trans TEMP (Bsig IN) 1\n \\\\tw. let v' = wline_of tw TEMP (fst tw) in inv_first (next_time_world tw[ OUT, 1 :=\\<^sub>2 v'], snd tw[ OUT, 1 :=\\<^sub>2 v'])\\\"\nproof (rule SingleI, rule Assign2_altI, rule, rule, rule)\n fix tw :: \"nat \\ sig worldline_init\"\n fix v\n assume \"get_time tw = 0 \\ beval_world_raw2 tw (Bsig IN) v\"\n define tw1 where \"tw1 = tw[ TEMP, 1 :=\\<^sub>2 v]\"\n obtain v' where \"beval_world_raw2 tw1 (Bsig TEMP) v'\"\n by (meson beval_world_raw2_Bsig)\n define tw2 where \"tw2 = tw1[ OUT, 1 :=\\<^sub>2 v']\"\n define t' where \"t' = next_time_world tw1\"\n\n have \"fst tw1 < next_time_world tw1\"\n using next_time_world_at_least by metis\n moreover have \"fst tw1 = fst tw\"\n unfolding tw1_def worldline_upd2_def by auto\n ultimately have \"fst tw < next_time_world tw1\"\n by auto\n\n have \"inv_first (next_time_world tw2, snd tw2)\"\n unfolding inv_first_def\n proof (rule, rule)\n fix i\n assume \"i < fst (next_time_world tw2, snd tw2)\"\n hence \"i < next_time_world tw2\"\n by auto\n have \"fst tw < next_time_world tw2\"\n using next_time_world_at_least by (metis \\get_time tw = 0 \\ beval_world_raw2 tw (Bsig IN) v\\ neq0_conv not_less0)\n have \"fst tw1 < next_time_world tw2\"\n using next_time_world_at_least\n by (simp add: \\get_time tw < next_time_world tw2\\ \\get_time tw1 = get_time tw\\)\n have \"i < fst tw \\ fst tw \\ i \\ i < next_time_world tw2 - 1 \\ i = next_time_world tw2 - 1\"\n using \\i < next_time_world tw2\\ by linarith\n moreover\n { assume \"i < fst tw\"\n hence \"False\"\n using \\get_time tw = 0 \\ beval_world_raw2 tw (Bsig IN) v\\ by auto\n hence \" wline_of tw2 TEMP (i + 1) = wline_of tw2 IN i\"\n by auto }\n moreover\n { assume \"fst tw \\ i \\ i < next_time_world tw2 - 1\"\n hence \"wline_of tw2 TEMP (i + 1) = wline_of tw1 TEMP (i + 1)\"\n unfolding tw2_def by (simp add: worldline_upd2_def worldline_upd_def)\n have \"beval_world_raw2 tw (Bsig IN) ...\"\n unfolding tw1_def using \\fst tw \\ i \\ i < next_time_world tw2 - 1\\\n by (simp add: \\get_time tw = 0 \\ beval_world_raw2 tw (Bsig IN) v\\ worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw IN (fst tw)\"\n by (metis beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic calculation)\n also have \"... = wline_of tw1 IN (fst tw1)\"\n by (metis \\get_time tw1 = get_time tw\\ less_add_one tw1_def worldline_upd2_before_dly)\n also have \"... = wline_of tw2 IN (fst tw2)\"\n by (simp add: tw2_def worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw2 IN i\"\n by (metis \\get_time tw = 0 \\ beval_world_raw2 tw (Bsig IN) v\\ \\get_time tw1 = get_time tw\\ \\i < next_time_world tw2\\ snd_conv\n snd_swap swap_simp tw2_def unchanged_until_next_time_world worldline_upd2_def zero_le)\n finally have \"wline_of tw2 TEMP (i + 1) = wline_of tw2 IN i\"\n using \\wline_of tw IN (get_time tw) = wline_of tw1 IN (get_time tw1)\\ \\wline_of tw1 IN\n (get_time tw1) = wline_of tw2 IN (get_time tw2)\\ \\wline_of tw1 TEMP (i + 1) = wline_of tw IN\n (get_time tw)\\ \\wline_of tw2 IN (get_time tw2) = wline_of tw2 IN i\\ \\wline_of tw2 TEMP (i +\n 1) = wline_of tw1 TEMP (i + 1)\\ by auto }\n moreover\n { assume \"i = next_time_world tw2 - 1\"\n hence \"wline_of tw2 TEMP (i + 1) = wline_of tw2 TEMP (next_time_world tw2)\"\n using \\get_time tw < next_time_world tw2\\ by force\n also have \"... = wline_of tw1 TEMP (next_time_world tw2)\"\n unfolding tw2_def by (simp add: worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw1 IN (fst tw)\"\n unfolding tw1_def using \\fst tw < next_time_world tw2\\\n by (smt One_nat_def Suc_diff_1 \\get_time tw = 0 \\ beval_world_raw2 tw (Bsig IN) v\\\n add.commute beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic\n comp_def not_add_less2 plus_1_eq_Suc snd_conv worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw2 IN (fst tw2)\"\n by (simp add: \\get_time tw1 = get_time tw\\ tw2_def worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw2 IN i\"\n by (metis \\get_time tw = 0 \\ beval_world_raw2 tw (Bsig IN) v\\ \\get_time tw1 = get_time tw\\ \\i < next_time_world tw2\\ fst_swap\n not_less not_less_zero snd_conv swap_simp tw2_def unchanged_until_next_time_world\n worldline_upd2_def)\n finally have \"wline_of tw2 TEMP (i + 1) = wline_of tw2 IN i\"\n by auto }\n ultimately have \"wline_of tw2 TEMP (i + 1) = wline_of tw2 IN i\"\n by auto\n thus \"wline_of (next_time_world tw2, snd tw2) TEMP (i + 1) =\n wline_of (next_time_world tw2, snd tw2) IN i\"\n by auto\n qed\n\n thus \" let v' = wline_of tw[ TEMP, 1 :=\\<^sub>2 v] TEMP (get_time tw[ TEMP, 1 :=\\<^sub>2 v])\n in inv_first (next_time_world tw[ TEMP, 1 :=\\<^sub>2 v][ OUT, 1 :=\\<^sub>2 v'], snd tw[ TEMP, 1 :=\\<^sub>2 v][ OUT, 1 :=\\<^sub>2 v'])\"\n unfolding t'_def tw1_def tw2_def\n using \\beval_world_raw2 tw1 (Bsig TEMP) v'\\ tw1_def\n by (metis beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic)\nqed\n\nlemma init_hoare2:\n \"\\\\<^sub>I \\\\tw. let v = wline_of tw TEMP (fst tw) in inv_first (next_time_world tw[ OUT, 1 :=\\<^sub>2 v], snd tw[ OUT, 1 :=\\<^sub>2 v])\\\n process {TEMP} : Bassign_trans OUT (Bsig TEMP) 1\n \\\\tw. inv_first (next_time_world tw, snd tw)\\\"\n apply (rule SingleI)\n apply (rule Assign2_altI)\n apply (rule, rule)\n by (metis beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic)\n\ntheorem init_preserves_inv_first:\n \" init_sim_hoare (\\tw. fst tw = 0) two_inverter inv_first\"\n unfolding two_inverter_def\n apply (rule AssignI)\n apply (rule ParallelI[where R=\"\\tw. let v = wline_of tw TEMP (fst tw) in\n inv_first (next_time_world tw[ OUT, 1 :=\\<^sub>2 v], snd tw[ OUT, 1 :=\\<^sub>2 v])\"])\n apply (rule init_hoare1)\n apply (rule init_hoare2)\n by (auto simp add: conc_stmt_wf_def)\n\nlemma init_hoare3:\n \"\\\\<^sub>I \\\\tw. get_time tw = 0\\ process {IN} : Bassign_trans TEMP (Bsig IN) 1 \\inv_second\\\"\nproof (rule SingleI, rule Assign2_altI, rule, rule, rule)\n fix tw :: \"nat \\ sig worldline_init\"\n fix x\n assume \"fst tw = 0 \\ beval_world_raw2 tw (Bsig IN) x\"\n let ?tw = \"tw[ TEMP, 1 :=\\<^sub>2 x]\"\n have \"fst tw = fst ?tw\"\n unfolding worldline_upd2_def worldline_upd_def by auto\n thus \"inv_second tw[ TEMP, 1 :=\\<^sub>2 x]\"\n using \\fst tw = 0 \\ beval_world_raw2 tw (Bsig IN) x\\ unfolding inv_second_def by auto\nqed\n\nlemma init_hoare4:\n \"\\\\<^sub>I \\inv_second\\\n process {TEMP} : Bassign_trans OUT (Bsig TEMP) 1\n \\\\tw. inv_second (next_time_world tw, snd tw)\\\"\n apply (rule SingleI)\n apply (rule Assign2_altI)\nproof (rule)+\n fix tw x\n assume \"inv_second tw \\ beval_world_raw2 tw (Bsig TEMP) x\"\n define tw' where \"tw' = tw [OUT, 1 :=\\<^sub>2 x]\"\n have \"fst tw < next_time_world tw'\"\n using next_time_world_at_least\n by (metis fst_conv tw'_def worldline_upd2_def)\n have \"inv_second (next_time_world tw', snd tw')\"\n unfolding inv_second_def\n proof (rule, rule)\n fix i\n assume \"i < fst (next_time_world tw', snd tw')\"\n hence \"i < next_time_world tw'\"\n by auto\n hence \"i < fst tw \\ fst tw \\ i \\ i < next_time_world tw' - 1 \\ i = next_time_world tw' - 1\"\n by linarith\n moreover\n { assume \"i < fst tw\"\n hence \"wline_of tw' OUT (i + 1) = wline_of tw OUT (i + 1)\"\n unfolding tw'_def by (meson add_mono1 worldline_upd2_before_dly)\n also have \"... = wline_of tw TEMP i\"\n using \\inv_second tw \\ beval_world_raw2 tw (Bsig TEMP) x\\ \\i < fst tw\\ unfolding inv_second_def by auto\n also have \"... = wline_of tw' TEMP i\"\n unfolding tw'_def by (simp add: worldline_upd2_def worldline_upd_def)\n finally have \"wline_of tw' OUT (i + 1) = wline_of tw' TEMP i\"\n by auto }\n moreover\n { assume \"fst tw \\ i \\ i < next_time_world tw' - 1\"\n hence \"wline_of tw' OUT (i + 1) = wline_of tw TEMP (fst tw)\"\n unfolding tw'_def\n by (smt Suc_eq_plus1 Suc_lessI \\get_time tw < next_time_world tw'\\ \\inv_second tw \\\n beval_world_raw2 tw (Bsig TEMP) x\\ beval_world_raw2_Bsig beval_world_raw2_def\n beval_world_raw_deterministic le_Suc_eq le_less less_diff_conv not_less_iff_gr_or_eq\n prod.sel(1) tw'_def unchanged_until_next_time_world worldline_upd2_at_dly\n worldline_upd2_def)\n also have \"... = wline_of tw' TEMP (fst tw')\"\n by (metis less_add_one prod.sel(1) tw'_def worldline_upd2_before_dly worldline_upd2_def)\n also have \"... = wline_of tw' TEMP i\"\n by (metis \\get_time tw \\ i \\ i < next_time_world tw' - 1\\ \\i < next_time_world tw'\\ snd_conv\n snd_swap swap_simp tw'_def unchanged_until_next_time_world worldline_upd2_def)\n finally have \"wline_of tw' OUT (i + 1) = wline_of tw' TEMP i\"\n by auto }\n moreover\n { assume \"i = next_time_world tw' - 1\"\n hence \"wline_of tw' OUT (i + 1) = wline_of tw' OUT (next_time_world tw')\"\n using \\i < next_time_world tw'\\ by force\n also have \"... = wline_of tw TEMP (fst tw)\"\n unfolding tw'_def using \\fst tw < next_time_world tw'\\\n by (smt \\inv_second tw \\ beval_world_raw2 tw (Bsig TEMP) x\\ beval_world_raw2_Bsig\n beval_world_raw2_def beval_world_raw_deterministic discrete not_less o_apply snd_conv\n tw'_def worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw' TEMP (fst tw')\"\n unfolding tw'_def by (simp add: worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw' TEMP i\"\n by (metis \\i < get_time tw \\ wline_of tw' OUT (i + 1) = wline_of tw' TEMP i\\ \\i <\n next_time_world tw'\\ calculation fst_conv less_imp_le_nat nat_neq_iff tw'_def\n unchanged_until_next_time_world worldline_upd2_def)\n finally have \"wline_of tw' OUT (i + 1) = wline_of tw' TEMP i\"\n by auto }\n ultimately have \"wline_of tw' OUT (i + 1) = wline_of tw' TEMP i\"\n by auto\n thus \"wline_of (next_time_world tw', snd tw') OUT (i + 1) =\n wline_of (next_time_world tw', snd tw') TEMP i \"\n by auto\n qed\n thus \"inv_second (next_time_world tw[ OUT, 1 :=\\<^sub>2 x], snd tw[ OUT, 1 :=\\<^sub>2 x]) \"\n unfolding tw'_def by auto\nqed\n\ntheorem init_preserves_inv_second:\n \" init_sim_hoare (\\tw. fst tw = 0) two_inverter inv_second\"\n unfolding two_inverter_def\n apply (rule AssignI)\n apply (rule ParallelI[where R=\"inv_second\"])\n apply (rule init_hoare3)\n apply (rule init_hoare4)\n unfolding conc_stmt_wf_def by auto\n\nlemma init_hoare5:\n \"\\\\<^sub>I \\\\tw. True\\\n process {IN} : Bassign_trans TEMP (Bsig IN) 1\n \\\\tw. let v' = wline_of tw TEMP (fst tw) in inv_first_hold (next_time_world tw[ OUT, 1 :=\\<^sub>2 v'], snd tw[ OUT, 1 :=\\<^sub>2 v'])\\\"\n apply (rule SingleI)\n apply (rule Assign2_altI)\nproof (rule, rule, rule)\n fix tw v\n assume \"True \\ beval_world_raw2 tw (Bsig IN) v\"\n define tw1 where \"tw1 = tw [ TEMP, 1 :=\\<^sub>2 v]\"\n obtain v' where \"beval_world_raw2 tw1 (Bsig TEMP) v'\"\n by (meson beval_world_raw2_Bsig)\n define tw2 where \"tw2 = tw1[ OUT, 1 :=\\<^sub>2 v']\"\n define t' where \"t' = next_time_world tw2\"\n have \"inv_first_hold (t', snd tw2)\"\n unfolding inv_first_hold_def\n proof (rule, rule, rule)\n have \"fst tw < t'\"\n unfolding t'_def using next_time_world_at_least\n by (metis prod.sel(1) tw1_def tw2_def worldline_upd2_def)\n fix i\n assume \"disjnt {IN} (event_of (t', snd tw2))\"\n assume \"fst (t', snd tw2) \\ i\"\n hence \"t' \\ i\"\n by auto\n have \"wline_of tw2 TEMP (i + 1) = wline_of tw1 TEMP (i + 1)\"\n unfolding tw2_def by (simp add: worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw IN (fst tw)\"\n unfolding tw1_def using \\fst tw < t'\\ \\t' \\ i\\\n by (smt \\True \\ beval_world_raw2 tw (Bsig IN) v\\ add_less_cancel_right beval_world_raw2_Bsig\n beval_world_raw2_def beval_world_raw_deterministic less_le_trans o_apply order.asym snd_conv\n worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw2 IN (fst tw2)\"\n by (metis fst_conv less_add_one tw1_def tw2_def worldline_upd2_before_dly worldline_upd2_def)\n also have \"... = wline_of tw2 IN (t' - 1)\"\n unfolding t'_def using unchanged_until_next_time_world\n by (metis (no_types, lifting) Suc_diff_1 diff_less gr_implies_not_zero le_0_eq less_Suc_eq_le\n next_time_world_at_least not_less zero_less_one)\n also have \"... = wline_of tw2 IN t'\"\n using \\disjnt {IN} (event_of (t', snd tw2))\\ unfolding event_of_alt_def\n using \\get_time tw < t'\\ by auto\n finally have \"wline_of tw2 TEMP (i + 1) = wline_of tw2 IN t'\"\n by auto\n thus \"wline_of (t', snd tw2) TEMP (i + 1) = wline_of (t', snd tw2) IN (get_time (t', snd tw2))\"\n by auto\n qed\n thus \" let v' = wline_of tw[ TEMP, 1 :=\\<^sub>2 v] TEMP (get_time tw[ TEMP, 1 :=\\<^sub>2 v])\n in inv_first_hold (next_time_world tw[ TEMP, 1 :=\\<^sub>2 v][ OUT, 1 :=\\<^sub>2 v'], snd tw[ TEMP, 1 :=\\<^sub>2 v][ OUT, 1 :=\\<^sub>2 v'])\"\n unfolding t'_def tw2_def tw1_def using \\beval_world_raw2 tw1 (Bsig TEMP) v'\\ tw1_def\n by (metis beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic)\nqed\n\nlemma init_hoare6:\n \"\\\\<^sub>I \\\\tw. let v = wline_of tw TEMP (fst tw) in inv_first_hold (next_time_world tw[ OUT, 1 :=\\<^sub>2 v], snd tw[ OUT, 1 :=\\<^sub>2 v])\\\n process {TEMP} : Bassign_trans OUT (Bsig TEMP) 1\n \\\\tw. inv_first_hold (next_time_world tw, snd tw)\\\"\n apply (rule SingleI)\n apply (rule Assign2_altI)\n by (metis beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic)\n\ntheorem init_preserves_inv_first_hold:\n \"init_sim_hoare (\\tw. True) two_inverter inv_first_hold\"\n unfolding two_inverter_def\n apply (rule AssignI)\n apply (rule ParallelI[where R=\"\\tw. let v = wline_of tw TEMP (fst tw) in inv_first_hold (next_time_world tw[ OUT, 1 :=\\<^sub>2 v], snd tw[ OUT, 1 :=\\<^sub>2 v])\"])\n apply (rule init_hoare5)\n apply (rule init_hoare6)\n unfolding conc_stmt_wf_def by (auto)\n\nlemma init_hoare7:\n \" \\\\<^sub>I \\\\tw. True\\\n process {IN} : Bassign_trans TEMP (Bsig IN) 1\n \\\\tw. let v' = wline_of tw TEMP (fst tw) in inv_second_hold (next_time_world tw[ OUT, 1 :=\\<^sub>2 v'], snd tw[ OUT, 1 :=\\<^sub>2 v'])\\\"\nproof (rule SingleI, rule Assign2_altI, rule, rule, rule)\n fix tw v\n define tw1 where \"tw1 = tw [ TEMP, 1 :=\\<^sub>2 v]\"\n obtain v' where \"beval_world_raw2 tw1 (Bsig TEMP) v'\"\n by (meson beval_world_raw2_Bsig)\n define tw2 where \"tw2 = tw1[ OUT, 1 :=\\<^sub>2 v']\"\n define t' where \"t' = next_time_world tw2\"\n have \"inv_second_hold (t', snd tw2)\"\n unfolding inv_second_hold_def\n proof (rule, rule, rule)\n fix i\n assume \"disjnt {TEMP} (event_of (t', snd tw2))\"\n assume \"fst (t', snd tw2) \\ i\"\n hence \"t' \\ i\"\n by auto\n moreover have \"fst tw < t'\"\n unfolding t'_def using next_time_world_at_least\n by (metis fst_conv tw1_def tw2_def worldline_upd2_def)\n ultimately have \"fst tw < i + 1\"\n by auto\n hence \"wline_of tw2 OUT (i + 1) = wline_of tw1 TEMP (fst tw1)\"\n unfolding tw2_def\n by (smt \\beval_world_raw2 tw1 (Bsig TEMP) v'\\ \\get_time tw < t'\\ \\t' \\ i\\\n add_less_cancel_right beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic\n comp_def dual_order.strict_trans1 order.asym prod.sel(1) snd_conv tw1_def worldline_upd2_def\n worldline_upd_def)\n also have \"... = wline_of tw2 TEMP (fst tw2)\"\n by (simp add: tw2_def worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw2 TEMP (t' - 1)\"\n using unchanged_until_next_time_world\n by (metis (no_types, lifting) Pair_inject Suc_diff_1 \\get_time tw < t'\\ diff_less\n gr_implies_not_zero le_Suc_eq less_imp_le_nat nat_neq_iff prod.collapse t'_def tw1_def tw2_def\n worldline_upd2_def zero_less_one)\n also have \"... = wline_of tw2 TEMP t'\"\n using \\disjnt {TEMP} (event_of (t', snd tw2))\\ unfolding event_of_alt_def\n using \\get_time tw < t'\\ by auto\n finally have \"wline_of tw2 OUT (i + 1) = wline_of tw2 TEMP t'\"\n by auto\n thus \"wline_of (t', snd tw2) OUT (i + 1) = wline_of (t', snd tw2) TEMP (get_time (t', snd tw2))\"\n by auto\n qed\n thus \" let v' = wline_of tw[ TEMP, 1 :=\\<^sub>2 v] TEMP (get_time tw[ TEMP, 1 :=\\<^sub>2 v])\n in inv_second_hold (next_time_world tw[ TEMP, 1 :=\\<^sub>2 v][ OUT, 1 :=\\<^sub>2 v'], snd tw[ TEMP, 1 :=\\<^sub>2 v][ OUT, 1 :=\\<^sub>2 v'])\"\n unfolding tw1_def tw2_def t'_def\n using \\beval_world_raw2 tw1 (Bsig TEMP) v'\\ tw1_def\n by (metis beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic)\nqed\n\nlemma init_hoare8:\n \"\\\\<^sub>I \\\\tw. let v = wline_of tw TEMP (fst tw) in inv_second_hold (next_time_world tw[ OUT, 1 :=\\<^sub>2 v], snd tw[ OUT, 1 :=\\<^sub>2 v])\\\n process {TEMP} : Bassign_trans OUT (Bsig TEMP) 1\n \\\\tw. inv_second_hold (next_time_world tw, snd tw)\\\"\n apply (rule SingleI)\n apply (rule Assign2_altI)\n by (metis beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic)\n\ntheorem init_preserves_inv_second_hold:\n \"init_sim_hoare (\\tw. True) two_inverter inv_second_hold\"\n unfolding two_inverter_def\n apply (rule AssignI)\n apply (rule ParallelI[where R=\"\\tw. let v = wline_of tw TEMP (fst tw) in inv_second_hold (next_time_world tw[ OUT, 1 :=\\<^sub>2 v], snd tw[ OUT, 1 :=\\<^sub>2 v])\"])\n apply (rule init_hoare7)\n apply (rule init_hoare8)\n unfolding conc_stmt_wf_def by auto\n\ncorollary init_preserves_invs:\n \"init_sim_hoare (\\tw. fst tw = 0) two_inverter (\\tw. inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw)\"\n by (auto intro!: ConjI_sim\n simp add: init_preserves_inv_first init_preserves_inv_second\n ConseqI_sim[OF _ init_preserves_inv_first_hold]\n ConseqI_sim[OF _ init_preserves_inv_second_hold])\n\nlemma\n assumes \"sim_fin w (i + 1) two_inverter tw'\"\n shows \"wline_of tw' TEMP (i + 1) = wline_of tw' IN i\"\nproof -\n obtain tw where \"init_sim (0, w) two_inverter tw\" and \"tw, i + 1, two_inverter \\\\<^sub>S tw'\"\n using premises_sim_fin_obt[OF assms] by auto\n hence \"i + 1 = fst tw'\"\n using world_maxtime_lt_fst_tres by blast\n have \"conc_stmt_wf two_inverter\"\n unfolding conc_stmt_wf_def two_inverter_def by auto\n moreover have \"nonneg_delay_conc two_inverter\"\n unfolding two_inverter_def by auto\n ultimately have \"init_sim_valid (\\tw. fst tw = 0) two_inverter (\\tw. inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw)\"\n using init_sim_hoare_soundness[OF init_preserves_invs] by auto\n hence \"inv_first tw\" and \"inv_first_hold tw\" and \"inv_second tw\" and \"inv_second_hold tw\"\n using \\init_sim (0, w) two_inverter tw\\ fst_conv unfolding init_sim_valid_def\n by metis+\n moreover have \"\\\\<^sub>s \\\\tw. inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw\\ two_inverter \\\\tw. inv_first tw \\ inv_second tw\\\"\n using conc_sim_soundness[OF sim_correctness_two_inverter2] \\conc_stmt_wf two_inverter\\ \\nonneg_delay_conc two_inverter\\\n by auto\n ultimately have \"inv_first tw'\"\n using \\tw, i + 1, two_inverter \\\\<^sub>S tw'\\ unfolding sim_hoare_valid_def by blast\n hence \"\\i < fst tw'. wline_of tw' TEMP (i + 1) = wline_of tw' IN i\"\n unfolding inv_first_def by auto\n with \\i + 1 = fst tw'\\ show ?thesis\n by (metis less_add_one)\nqed\n\nlemma\n assumes \"sim_fin w (i + 1) two_inverter tw'\"\n shows \"wline_of tw' OUT (i + 1) = wline_of tw' TEMP i\"\nproof -\n obtain tw where \"init_sim (0, w) two_inverter tw\" and \"tw, i + 1, two_inverter \\\\<^sub>S tw'\"\n using premises_sim_fin_obt[OF assms] by auto\n hence \"i + 1 = fst tw'\"\n using world_maxtime_lt_fst_tres by blast\n have \"conc_stmt_wf two_inverter\"\n unfolding conc_stmt_wf_def two_inverter_def by auto\n moreover have \"nonneg_delay_conc two_inverter\"\n unfolding two_inverter_def by auto\n ultimately have \"init_sim_valid (\\tw. fst tw = 0) two_inverter (\\tw. inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw)\"\n using init_sim_hoare_soundness[OF init_preserves_invs] by auto\n hence \"inv_first tw\" and \"inv_first_hold tw\" and \"inv_second tw\" and \"inv_second_hold tw\"\n using \\init_sim (0, w) two_inverter tw\\ fst_conv unfolding init_sim_valid_def\n by metis+\n moreover have \"\\\\<^sub>s \\\\tw. inv_first tw \\ inv_second tw \\ inv_first_hold tw \\ inv_second_hold tw\\ two_inverter \\\\tw. inv_first tw \\ inv_second tw\\\"\n using conc_sim_soundness[OF sim_correctness_two_inverter2] \\conc_stmt_wf two_inverter\\ \\nonneg_delay_conc two_inverter\\\n by auto\n ultimately have \"inv_second tw'\"\n using \\tw, i + 1, two_inverter \\\\<^sub>S tw'\\ unfolding sim_hoare_valid_def by blast\n hence \"\\i < fst tw'. wline_of tw' OUT (i + 1) = wline_of tw' TEMP i\"\n unfolding inv_second_def by auto\n with \\i + 1 = fst tw'\\ show ?thesis\n by (metis less_add_one)\nqed\n\nend", "meta": {"author": "rizaldialbert", "repo": "vhdl-semantics", "sha": "352f89c9ccdfe830c054757dfd86caeadbd67159", "save_path": "github-repos/isabelle/rizaldialbert-vhdl-semantics", "path": "github-repos/isabelle/rizaldialbert-vhdl-semantics/vhdl-semantics-352f89c9ccdfe830c054757dfd86caeadbd67159/Double_Inverter.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.1225232189263307, "lm_q1q2_score": 0.057914701088824405}} {"text": "(*\nCopyright 2009-2014 Christian Sternagel, René Thiemann\n\nThis file is part of IsaFoR/CeTA.\n\nIsaFoR/CeTA is free software: you can redistribute it and/or modify it under the\nterms of the GNU Lesser General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\n\nIsaFoR/CeTA is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along\nwith IsaFoR/CeTA. If not, see .\n*)\n\nheader {* Generating Show-Functions for Data Types *}\n\ntheory Show_Generator\nimports\n \"../Datatype_Order_Generator/Derive_Manager\"\n Show\nbegin\n\nsubsection {* Introduction *}\n\ntext {*\n The show-generator registers itself at the derive-manager for the class @{class show}. To be more\n precise, it automatically generates the functions @{const shows_prec} and @{const shows_list} for\n some data type @{text dtyp} and proves the following instantiation.\n \\begin{itemize}\n \\item @{text \"instantiation dtyp :: (show, ..., show) show\"}\n \\end{itemize}\n All the non-recursive types that are used in the data type must have a similar instantiation. For\n recursive type-dependencies this is automatically generated.\n\n For example, for the data type @{text \"datatype tree = Leaf nat | Node (tree list)\"} we require\n that @{text nat} is already in @{class show}, whereas for type @{typ \"'a list\"} nothing is\n required, since it is used recursively.\n\n However, if we define @{text \"datatype tree = Leaf (nat list) | Node tree tree\"} then also\n @{typ \"'a list\"} must provide a @{class show} instance.\n*}\n\nsubsection {* Implementation Notes *}\n\ntext {*\n The generator uses the recursors from the data type package to define the show function.\n Constructors are displayed by their short names and arguments are separated by blanks and\n surrounded by parenthesis.\n\n The associativity is proven using the induction theorem from the data type package.\n*}\n\nsubsection {* Features and Limitations *}\n\ntext {*\n The show-generator has been developed mainly for data types without explicit mutual recursion. For\n mutual recursive data types -- like @{text \"datatype a = C b and b = D a a\"} -- only for the first\n mentioned data type -- here @{text a} -- instantiations of the @{class show} are derived.\n\n Indirect recursion like in @{text \"datatype tree = Leaf nat | Node (tree list)\"} should work\n without problems.\n*}\n\nsubsection {* Installing the Generator *}\n\ndefinition shows_sep_paren :: \"shows \\ shows\"\nwhere\n \"shows_sep_paren s = ('' ('' +#+ s +@+ shows '')'')\"\n\ntext {*\n The four crucial properties which are used to ensure associativity.\n*}\nlemma append_assoc_trans:\n assumes \"\\r s. b r @ s = b (r @ s)\"\n shows \"(op @ a +@+ b) r @ s = (op @ a +@+ b) (r @ s)\"\n using assms by simp\n\nlemma shows_sep_paren:\n assumes \"\\r s. a r @ s = a (r @ s)\"\n and \"\\r s. b r @ s = b (r @ s)\"\n shows \"(shows_sep_paren a +@+ b) r @ s = (shows_sep_paren a +@+ b) (r @ s)\"\n unfolding shows_sep_paren_def by (simp add: assms)\n\nlemma shows_sep_paren_final:\n assumes \"\\r s. a r @ s = a (r @ s)\"\n shows \"(shows_sep_paren a) r @ s = (shows_sep_paren a) (r @ s)\"\n unfolding shows_sep_paren_def by (simp add: assms)\n\nML_file \"show_generator.ML\"\n\nsetup {* Show_Generator.setup *}\n\nend\n\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Show/Show_Generator.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4649015862011227, "lm_q2_score": 0.12421299862599397, "lm_q1q2_score": 0.057746820088022476}} {"text": "(*\n * Copyright 2014, NICTA\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * @TAG(NICTA_BSD)\n *)\n\ntheory WPTutorial\nimports \"Refine.Bits_R\"\nbegin\n\ntext \\\nThis is a tutorial on the use of the various Hoare mechanisms developed\nfor the L4.verified project. We import Bits_R above, which is a compromise\nbetween the twin goals of getting the Hoare setup from L4.verified and not\nimporting existing properties. It's probably best to work from a prebuilt\nRefine Isabelle image which includes Bits_R.\n\\\n\ntext \\The point of our apparatus is to prove Hoare triples. These are a\ntriple of a precondition, function, and postcondition. In our state-monadic\nworld, the precondition is a function of the state, and the postcondition\nis a function of the return value and the state. In example 1 below,\nthe precondition doesn't impose any restriction on the state, and the\npostcondition only requires that the return value be the obvious one.\\\n\ntext \\The weakest precondition tool, wp, attempts to construct the\nweakest precondition for a given postcondition. Use wp (with the command\n\"apply wp\") to solve example 1\\\n\nlemma example_1:\n \"\\\\s. True\\ return 1 \\\\rv s. rv = 1\\\"\n apply wp\n apply simp\n done\n\ntext \\The wp tool works in reverse order (from postcondition to weakest\nprecondition, rather than from precondition to strongest postcondition).\nIt stops when it encounters a postcondition/function pair it doesn't\nknow any rules for. Try example 2 below, noting where wp gets stuck.\n\nThe wp method already knows how to handle most monadic operations\n(liftE, catch, assert, when, if-then-else, etc) but there are some\nexceptions. One is the split operator, which hides behind Isabelle syntax\nthat looks like (\\(x, y). blah), {(x, y). blah}, (\\(x, y) \\ S. blah).\nSolve the problem by unfolding it with (simp add: split_def).\n\nThe intermediate precondition seen when wp stops is a schematic variable.\nThe wp tool uses Isabelle's underlying unification mechanism to set the\nprecondition as it goes. This usually works well, but there are some\nproblems, especially with tuples. Note the strange behaviour if we use\nclarsimp instead of (simp add: split_def) to deal with the split constant.\nThe root cause of this strange behaviour is that the unification mechanism\ndoes not know how to construct a ?P such that \"?P (a, b) = a\". This is\nannoying, since it means that clarsimp/clarify/safe must frequently be\navoided.\n\\\n\nlemma example_2:\n \"\\\\s. s = [(True, False), (False, True)]\\ do\n v \\ gets length;\n (x, y) \\ gets hd;\n return x\n od \\\\rv s. rv\\\"\n apply wp\n apply (simp add: split_def)\n apply wp+\n apply simp\n done\n\ntext \\\nAn additional annoyance to the clarsimp/tuple issue described above is\nthe splitter. The wp tool is designed to work on a hoare triple with a\nschematic precondition. Note how the simplifier splits the problem\nin two because it contains an if constant. Delete the split\nrule from the simpset with (simp split del: if_split) to avoid this\nissue and see where wp gets stuck.\n\nWe still need to deal with the if constant. In this (somewhat contrived)\nexample we can give the simplifier the rule if_apply_def2 to make\nprogress.\n\nNote that wp can deal with a function it knows nothing about if\nthe postcondition is constant in the return value and state.\n\\\n\nlemma example_3:\n \"\\\\s. s = [False, True]\\ do\n x \\ gets hd;\n possible_state_change_that_isnt_defined;\n y \\ gets (if x then \\ else \\);\n return $ y \\ \\ x\n od \\\\rv s. rv\\\"\n apply wp\n apply (simp add: if_apply_def2 split del: if_split)\n apply wp+\n apply simp\n done\n\ntext \\Let's make this more interesting by introducing some functions\nfrom the abstract specification. The set_endpoint function (an abbreviation\nfor the function set_simple_ko) is used to set the contents of an endpoint\nobject somewhere in the kernel object heap (kheap). The cap derivation\ntree (cdt) lives in an entirely different field of the state to the kheap,\nso this fact about it should be unchanged by the endpoint update.\nSolve example 4 - you'll have to unfold enough definitions that wp knows\nwhat to do.\\\n\nlemma example_4:\n \"\\\\s. cdt s (42, [True, False]) = None\\\n set_endpoint ptr Structures_A.IdleEP\n \\\\rv s. cdt s (42, [True, False]) = None\\\"\n apply (simp add: set_simple_ko_def set_object_def get_object_def)\n apply wp\n apply clarsimp\n done\n\ntext \\\nExample 4 proved that a property about the cdt was preserved from\nbefore set_endpoint to after. This preservation property is true for\nany property that just talks about the cdt. Example 5 rephrases\nexample 4 in this style. Get used to this style of Hoare triple,\nit is very common in our proofs.\n\\\n\nlemma example_5:\n \"\\\\s. P (cdt s)\\\n set_endpoint ptr Structures_A.IdleEP\n \\\\rv s. P (cdt s)\\\"\n apply (simp add: set_simple_ko_def set_object_def get_object_def)\n apply wp\n apply clarsimp\n done\n\ntext \\\nThe set_cap function from the abstract specification is not much different\nto set_endpoint. However, caps can live within CSpace objects or within\nTCBs, and the set_cap function handles this issue with a case division.\n\nThe wp tool doesn't know anything about how to deal with case statements.\nIn addition to the tricks we've learned already, use the wpc tool to break\nup the case statement into components so that wp can deal with it to solve\nexample 6.\n\\\n\nlemma example_6:\n \"\\\\s. P (cdt s)\\\n set_cap cap ptr\n \\\\rv s. P (cdt s)\\\"\n apply (simp add: set_cap_def split_def set_object_def\n get_object_def)\n apply (wp | wpc)+\n apply simp\n done\n\ntext \\\nThe wp method can be given additional arguments which are theorems to use\nas summaries. Solve example 7 by supplying example 6 as a rule to\nuse with (wp example_6).\n\\\n\nlemma example_7:\n \"\\\\s. cdt s ptr' = None\\ do\n set_cap cap.NullCap ptr;\n v \\ gets (\\s. cdt s ptr);\n assert (v = None);\n set_cap cap.NullCap ptr';\n set_cap cap.IRQControlCap ptr';\n return True\n od \\\\rv s. cdt s ptr = None \\ cdt s ptr' = None\\\"\n apply (wp example_6)\n apply simp\n done\n\ntext \\\nThere isn't a good reason not to use example_6 whenever possible, so we can\ndeclare example_6 a member of the wp rule set by changing its proof site to\n\"lemma example_6[wp]:\", by doing \"declare example_6[wp]\", or by putting it\nin a group of lemmas declared wp with \"lemmas foo[wp] = example_6\".\nPick one of those options and remove the manual reference to example_6 from\nthe proof of example_7.\n\\\n\ntext \\\nThese preservation Hoare triples are often easy to prove and apply, so much\nof the effort is in typing them all out. To speed this up we have the crunch\ntool. Let's prove that setup_reply_master and set_endpoint don't change\nanother field of the state, machine_state. I've typed out the required\ncrunch command below. Let's explain the bits. The naming scheme\n\"machine_state_preserved:\" sets a common suffix for all the lemmas\nproved. Just like with lemma names, we could add the theorems to the wp set\nwith \"machine_state_preserved[wp]:\". What follows is a list of functions.\nThe crunch tool also descends through the call graph of functions, so it\nproves a rule about set_cap because setup_reply_master calls it. The last\nargument is the term to appear in the precondition and postcondition.\n\nThe final, optional bit of the crunch syntax is a group of modifiers, which\ngo between the parentheses inserted below. The crunch command doesn't\ncurrently work. We need to provide some additional simp and wp rules\nwith syntax like (simp: some rules wp: some rules). If you look at the way\ncrunch failed, you'll spot which simp rule we need to add to make some\nprogress.\n\nBut not much more progress. To get through set_endpoint, we need to deal\nwith a slightly complex postcondition to get_object, one which incorporates\nan assertion about its return value. We can solve this problem by simply\nthrowing the extra assumption away - supplying the wp rule hoare_drop_imps\ndoes this. There are standard sets of simp and wp rules which are frequently\nhelpful to crunch, crunch_simps and crunch_wps, which contain the rules we\nadded here.\n\\\n\ncrunch machine_state_preserved:\n setup_reply_master, set_simple_ko\n \"\\s. P (machine_state s)\"\n (simp: split_def wp: crunch_wps)\n\nend\n", "meta": {"author": "CompSoftVer", "repo": "CSim2", "sha": "b09a4d77ea089168b1805db5204ac151df2b9eff", "save_path": "github-repos/isabelle/CompSoftVer-CSim2", "path": "github-repos/isabelle/CompSoftVer-CSim2/CSim2-b09a4d77ea089168b1805db5204ac151df2b9eff/lib/WPTutorial.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.12252321412020205, "lm_q1q2_score": 0.05743773432367095}} {"text": "(* Author: Norbert Schirmer\n Maintainer: Norbert Schirmer, norbert.schirmer at web de\n License: LGPL\n*)\n\n(* Title: UserGuide.thy\n Author: Norbert Schirmer, TU Muenchen\n\nCopyright (C) 2004-2008 Norbert Schirmer \nSome rights reserved, TU Muenchen\n\nThis library is free software; you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation; either version 2.1 of the\nLicense, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307\nUSA\n*)\n\nsection \\User Guide \\label{sec:UserGuide}\\\n(*<*)\ntheory UserGuide \nimports HeapList Vcg\n \"~~/src/HOL/Statespace/StateSpaceSyntax\" \"~~/src/HOL/Library/LaTeXsugar\"\nbegin \n(*>*)\n\n(*<*)\nsyntax\n \"_statespace_updates\" :: \"('a \\ 'b) \\ updbinds \\ ('a \\ 'b)\" (\"_\\_\\\" [900,0] 900)\n(*>*)\n\n\n\ntext \\\nWe introduce the verification environment with a couple\nof examples that illustrate how to use the different\nbits and pieces to verify programs. \n\\\n\n\nsubsection \\Basics\\\n\ntext \\\n\nFirst of all we have to decide how to represent the state space. There\nare currently two implementations. One is based on records the other\none on the concept called `statespace' that was introduced with\nIsabelle 2007 (see \\texttt{HOL/Statespace}) . In contrast to records a \n'satespace' does not define a new type, but provides a notion of state, \nbased on locales. Logically\nthe state is modelled as a function from (abstract) names to\n(abstract) values and the statespace infrastructure organises\ndistinctness of names an projection/injection of concrete values into\nthe abstract one. Towards the user the interface of records and\nstatespaces is quite similar. However, statespaces offer more\nflexibility, inherited from the locale infrastructure, in\nparticular multiple inheritance and renaming of components.\n\nIn this user guide we prefer statespaces, but give some comments on\nthe usage of records in Section \\ref{sec:records}. \n\n\n\\\n\nhoarestate vars = \n A :: nat\n I :: nat\n M :: nat\n N :: nat\n R :: nat\n S :: nat\n\ntext (in vars) \\The command \\isacommand{hoarestate} is a simple preprocessor\nfor the command \\isacommand{statespaces} which decorates the state\ncomponents with the suffix \\_'\\, to avoid cluttering the\nnamespace. Also note that underscores are printed as hyphens in this\ndocumentation. So what you see as @{term \"A_'\"} in this document is\nactually \\texttt{A\\_'}. Every component name becomes a fixed variable in\nthe locale \\vars\\ and can no longer be used for logical\nvariables. \n\nLookup of a component @{term \"A_'\"} in a state @{term \"s\"} is written as\n@{term \"s\\A_'\"}, and update with a value @{term \"term v\"} as @{term \"s\\A_' := v\\\"}.\n\nTo deal with local and global variables in the context of procedures the\nprogram state is organised as a record containing the two componets @{const \"locals\"} \nand @{const \"globals\"}. The variables defined in hoarestate \\vars\\ reside\nin the @{const \"locals\"} part.\n\n\\\n\ntext \\\n Here is a first example.\n\\\n\nlemma (in vars) \"\\\\ \\\\N = 5\\ \\N :== 2 * \\N \\\\N = 10\\\"\n apply vcg\n txt \\@{subgoals}\\\n apply simp\n txt \\@{subgoals}\\\n done\n\ntext \\We enable the locale of statespace \\vars\\ by the\n\\texttt{in vars} directive. The verification condition generator is\ninvoked via the \\vcg\\ method and leaves us with the expected\nsubgoal that can be proved by simplification.\\\n\ntext (in vars) \\\n If we refer to components (variables) of the state-space of the program\n we always mark these with \\\\\\ (in assertions and also in the\n program itself). It is the acute-symbol and is present on\n most keyboards. The assertions of the Hoare tuple are\n ordinary Isabelle sets. As we usually want to refer to the state space\n in the assertions, we provide special brackets for them. They can be written \n as {\\verb+{| |}+} in ASCII or \\\\ \\\\ with symbols. Internally,\n marking variables has two effects. First of all we refer to the implicit\n state and secondary we get rid of the suffix \\_'\\.\n So the assertion @{term \"{|\\N = 5|}\"} internally gets expanded to \n \\{s. locals s \\N_' = 5}\\ written in ordinary set comprehension notation of\n Isabelle. It describes the set of states where the \\N_'\\ component\n is equal to \\5\\. \n An empty context and an empty postcondition for abrupt termination can be\n omitted. The lemma above is a shorthand for \n \\\\,{}\\ \\\\N = 5\\ \\N :== 2 * \\N \\\\N = 10\\,{}\\.\n\\\n\ntext \\We can step through verification condition generation by the\nmethod \\vcg_step\\.\n\\\n\nlemma (in vars) \"\\,{}\\ \\\\N = 5\\ \\N :== 2 * \\N \\\\N = 10\\\"\n apply vcg_step\n txt \\@{subgoals}\\\n txt \\The last step of verification condition generation, \n transforms the inclusion of state sets to the corresponding \n predicate on components of the state space. \n\\\n apply vcg_step\n txt \\@{subgoals}\\\n by simp\n\ntext \\\nAlthough our assertions work semantically on the state space, stepping\nthrough verification condition generation ``feels'' like the expected\nsyntactic substitutions of traditional Hoare logic. This is achieved\nby light simplification on the assertions calculated by the Hoare rules.\n\\\n\nlemma (in vars) \"\\\\ \\\\N = 5\\ \\N :== 2 * \\N \\\\N = 10\\\"\n apply (rule HoarePartial.Basic)\n txt \\@{subgoals}\\\n apply (simp only: mem_Collect_eq)\n txt \\@{subgoals}\\\n apply (tactic \n \\Hoare.BasicSimpTac @{context} Hoare.Function false\n [] (K all_tac) 1\\)\n txt \\@{subgoals}\\\n by simp\n\n\ntext \\The next example shows how we deal with the while loop. Note the\ninvariant annotation.\n\\\n\nlemma (in vars) \n \"\\,{}\\ \\\\M = 0 \\ \\S = 0\\\n WHILE \\M \\ a\n INV \\\\S = \\M * b\\\n DO \\S :== \\S + b;; \\M :== \\M + 1 OD\n \\\\S = a * b\\\"\n apply vcg\n txt \\@{subgoals [display]}\\\n txt \\The verification condition generator gives us three proof obligations,\n stemming from the path from the precondition to the invariant,\n from the invariant together with loop condition through the\n loop body to the invariant, and finally from the invariant together\n with the negated loop condition to the postcondition.\\\n apply auto\n done\n\nsubsection \\Procedures\\\n\nsubsubsection \\Declaration\\\n\ntext \\\nOur first procedure is a simple square procedure. We provide the\ncommand \\isacommand{procedures}, to declare and define a\nprocedure.\n\\\n\nprocedures\n Square (N::nat|R::nat) \n where I::nat in\n \"\\R :== \\N * \\N\"\n \n\n\ntext \\A procedure is given by the signature of the procedure\nfollowed by the procedure body. The signature consists of the name of\nthe procedure and a list of parameters together with their types. The\nparameters in front of the pipe \\|\\ are value parameters and\nbehind the pipe are the result parameters. Value parameters model call\nby value semantics. The value of a result parameter at the end of the\nprocedure is passed back to the caller. Local variables follow the\n\\where\\. If there are no local variables the \\where \\\nin\\ can be omitted. The variable @{term \"I\"} is actually unused in\nthe body, but is used in the examples below.\\\n\n\ntext \\\nThe procedures command provides convenient syntax\nfor procedure calls (that creates the proper @{term init}, @{term return} and\n@{term result} functions on the fly) and creates locales and statespaces to \nreason about the procedure. The purpose of locales is to set up logical contexts\nto support modular reasoning. Locales can be seen as freeze-dried proof contexts that\nget alive as you setup a new lemma or theorem (\\cite{Ballarin-04-locales}).\nThe locale the user deals with is named \\Square_impl\\.\n It defines the procedure name (internally @{term \"Square_'proc\"}), the procedure body \n(named \\Square_body\\) and the statespaces for parameters and local and\nglobal variables.\nMoreover it contains the \nassumption @{term \"\\ Square_'proc = Some Square_body\"}, which states \nthat the procedure is properly defined in the procedure context. \n\nThe purpose of the locale is to give us easy means to setup the context \nin which we prove programs correct. \nIn this locale the procedure context @{term \"\\\"} is fixed. \nSo we always use this letter for the procedure\nspecification. This is crucial, if we prove programs under the\nassumption of some procedure specifications.\n\\\n\n(*<*)\ncontext Square_impl\nbegin\n(*>*)\ntext \\The procedures command generates syntax, so that we can \neither write \\CALL Square(\\I,\\R)\\ or @{term \"\\I :== CALL\nSquare(\\R)\"} for the procedure call. The internal term is the\nfollowing: \n\\ \n\n(*<*) declare [[hoare_use_call_tr' = false]] (*>*) \ntext \\\\small @{term [display] \"CALL Square(\\I,\\R)\"}\\ \n(*<*) declare [[hoare_use_call_tr' = true]] (*>*)\n\ntext \\Note the\n additional decoration (with the procedure name) of the parameter and\n local variable names.\\\n(*<*)\nend \n(*>*)\n\ntext \\The abstract syntax for the\nprocedure call is @{term \"call init p return result\"}. The @{term\n\"init\"} function copies the values of the actual parameters to the\nformal parameters, the @{term return} function copies the global\nvariables back (in our case there are no global variables), and the\n@{term \"result\"} function additionally copies the values of the formal\nresult parameters to the actual locations. Actual value parameters can\nbe all kind of expressions, since we only need their value. But result\nparameters must be proper ``lvalues'': variables (including\ndereferenced pointers) or array locations, since we have to assign\nvalues to them. \n\\\n\nsubsubsection \\Verification\\\n\ntext (in Square_impl) \\\nA procedure specification is an ordinary Hoare tuple. \nWe use the parameterless\ncall for the specification; \\\\R :== PROC Square(\\N)\\ is syntactic sugar\nfor \\Call Square_'proc\\. This emphasises that the specification \ndescribes the internal behaviour of the procedure, whereas parameter passing\ncorresponds to the procedure call.\nThe following precondition fixes the current value \\\\N\\ to the logical \nvariable @{term n}. \nUniversal quantification of @{term \"n\"} enables us to adapt \nthe specification to an actual parameter. The specification is\nused in the rule for procedure call when we come upon a call to @{term Square}. \nThus @{term \"n\"} plays the role of the auxiliary variable @{term \"Z\"}.\n\\\n\n\ntext \\To verify the procedure we need to verify the body. We use\na derived variant of the general recursion rule, tailored for non recursive procedures:\n@{thm [source] HoarePartial.ProcNoRec1}:\n\\begin{center}\n@{thm [mode=Rule,mode=ParenStmt] HoarePartial.ProcNoRec1 [no_vars]}\n\\end{center}\nThe naming convention for the rule \nis the following: The \\1\\ expresses that we look at one\n procedure, and \\NoRec\\ that the procedure is non\nrecursive. \n\\ \n\n\nlemma (in Square_impl)\nshows \"\\n. \\\\\\\\N = n\\ \\R :== PROC Square(\\N) \\\\R = n * n\\\"\ntxt \\The directive \\in\\ has the effect that\nthe context of the locale @{term \"Square_impl\"} is included to the current\nlemma, and that the lemma is added as a fact to the locale, after it is proven. The\nnext time locale @{term \"Square_impl\"} is invoked this lemma is immediately available\nas fact, which the verification condition generator can use.\n\\\napply (hoare_rule HoarePartial.ProcNoRec1)\n txt \"@{subgoals[display]}\"\n txt \\The method \\hoare_rule\\, like \\rule\\ applies a \n single rule, but additionally does some ``obvious'' steps:\n It solves the canonical side-conditions of various Hoare-rules and it \n automatically expands the\n procedure body: With @{thm [source] Square_impl}: @{thm [names_short] Square_impl [no_vars]} we\n get the procedure body out of the procedure context @{term \"\\\"}; \n with @{thm [source] Square_body_def}: @{thm [names_short] Square_body_def [no_vars]} we\n can unfold the definition of the body.\n\n The proof is finished by the vcg and simp.\n\\\ntxt \"@{subgoals[display]}\"\nby vcg simp\n\ntext \\If the procedure is non recursive and there is no specification given, the\nverification condition generator automatically expands the body.\\\n\nlemma (in Square_impl) Square_spec: \nshows \"\\n. \\\\\\\\N = n\\ \\R :== PROC Square(\\N) \\\\R = n * n\\\"\n by vcg simp\n\ntext \\An important naming convention is to name the specification as\n\\_spec\\. The verification condition generator refers to\nthis name in order to search for a specification in the theorem database.\n\\\n\nsubsubsection \\Usage\\\n\n\ntext\\Let us see how we can use procedure specifications.\\\n(* FIXME: maybe don't show this at all *)\nlemma (in Square_impl)\n shows \"\\\\\\\\I = 2\\ \\R :== CALL Square(\\I) \\\\R = 4\\\"\n txt \\Remember that we have already proven @{thm [source] \"Square_spec\"} in the locale\n \\Square_impl\\. This is crucial for \n verification condition generation. When reaching a procedure call,\n it looks for the specification (by its name) and applies the\n rule @{thm [source,mode=ParenStmt] HoarePartial.ProcSpec} \ninstantiated with the specification\n (as last premise). \n Before we apply the verification condition generator, let us\n take some time to think of what we can expect.\n Let's look at the specification @{thm [source] Square_spec} again:\n @{thm [display] Square_spec [no_vars]}\n The specification talks about the formal parameters @{term \"N\"} and \n @{term R}. The precondition @{term \"\\\\N = n\\\"} just fixes the initial\n value of \\N\\.\n The actual parameters are @{term \"I\"} and @{term \"R\"}. We \n have to adapt the specification to this calling context.\n @{term \"\\n. \\\\ \\\\I = n\\ \\R :== CALL Square(\\I) \\\\R = n * n\\\"}.\n From the postcondition @{term \"\\\\R = n * n\\\"} we \n have to derive the actual postcondition @{term \"\\\\R = 4\\\"}. So\n we gain something like: @{term \"\\n * n = (4::nat)\\\"}.\n The precondition is @{term \"\\\\I = 2\\\"} and the specification \n tells us @{term \"\\\\I = n\\\"} for the pre-state. So the value of @{term n}\n is the value of @{term I} in the pre-state. So we arrive at\n @{term \"\\\\I = 2\\ \\ \\\\I * \\I = 4\\\"}.\n\\\n apply vcg_step\n txt \"@{subgoals[display]}\"\n txt \\\n The second set looks slightly more involved:\n @{term \"\\\\t. \\<^bsup>t\\<^esup>R = \\I * \\I \\ \\I * \\I = 4\\\"}, this is an artefact from the\n procedure call rule. Originally \\\\I * \\I = 4\\ was \\\\<^bsup>t\\<^esup>R = 4\\. Where\n @{term \"t\"} denotes the final state of the procedure and the superscript notation\n allows to select a component from a particular state. \n\\\n apply vcg_step\n txt \"@{subgoals[display]}\"\n by simp\n \ntext \\\nThe adaption of the procedure specification to the actual calling \ncontext is done due to the @{term init}, @{term return} and @{term result} functions \nin the rule @{thm [source] HoarePartial.ProcSpec} (or in the variant \n@{thm [source] HoarePartial.ProcSpecNoAbrupt} which already\nincorporates the fact that the postcondition for abrupt termination\nis the empty set). For the readers interested in the internals, \nhere a version without vcg.\n\\\nlemma (in Square_impl)\n shows \"\\\\\\\\I = 2\\ \\R :== CALL Square(\\I) \\\\R = 4\\\"\n apply (rule HoarePartial.ProcSpecNoAbrupt [OF _ _ Square_spec])\n txt \"@{subgoals[display]}\"\n txt \\This is the raw verification condition, \n It is interesting to see how the auxiliary variable @{term \"Z\"} is\n actually used. It is unified with @{term n} of the specification and\n fixes the state after parameter passing. \n\\\n apply simp\n txt \"@{subgoals[display]}\"\n prefer 2\n apply vcg_step\n txt \"@{subgoals[display]}\"\n apply (auto intro: ext)\n done\n\n\n\nsubsubsection \\Recursion\\\n\ntext \\We want to define a procedure for the factorial. We first\ndefine a HOL function that calculates it, to specify the procedure later on.\n\\\n\nprimrec fac:: \"nat \\ nat\"\nwhere\n\"fac 0 = 1\" |\n\"fac (Suc n) = (Suc n) * fac n\"\n\n(*<*)\nlemma fac_simp [simp]: \"0 < i \\ fac i = i * fac (i - 1)\"\n by (cases i) simp_all\n(*>*)\n\ntext \\Now we define the procedure.\\\nprocedures\n Fac (N::nat | R::nat) \n \"IF \\N = 0 THEN \\R :== 1\n ELSE \\R :== CALL Fac(\\N - 1);;\n \\R :== \\N * \\R\n FI\"\n \ntext \\\nNow let us prove that our implementation of @{term \"Fac\"} meets its specification. \n\\\n\nlemma (in Fac_impl)\nshows \"\\n. \\\\ \\\\N = n\\ \\R :== PROC Fac(\\N) \\\\R = fac n\\\"\napply (hoare_rule HoarePartial.ProcRec1)\ntxt \"@{subgoals[display]}\"\napply vcg\ntxt \"@{subgoals[display]}\"\napply simp\ndone\n\ntext \\\nSince the factorial is implemented recursively,\nthe main ingredient of this proof is, to assume that the specification holds for \nthe recursive call of @{term Fac} and prove the body correct.\nThe assumption for recursive calls is added to the context by\nthe rule @{thm [source] HoarePartial.ProcRec1} \n(also derived from the general rule for mutually recursive procedures):\n\\begin{center}\n@{thm [mode=Rule,mode=ParenStmt] HoarePartial.ProcRec1 [no_vars]}\n\\end{center}\nThe verification condition generator infers the specification out of the\ncontext @{term \"\\\"} when it encounters a recursive call of the factorial.\n\\\n\nsubsection \\Global Variables and Heap \\label{sec:VcgHeap}\\\n\ntext \\\nNow we define and verify some procedures on heap-lists. We consider\nlist structures consisting of two fields, a content element @{term \"cont\"} and\na reference to the next list element @{term \"next\"}. We model this by the \nfollowing state space where every field has its own heap.\n\\\n\nhoarestate globals_heap =\n \"next\" :: \"ref \\ ref\"\n cont :: \"ref \\ nat\"\n\ntext \\It is mandatory to start the state name with `globals'. This is exploited\nby the syntax translations to store the components in the @{const globals} part\nof the state.\n\\\n\ntext \\Updates to global components inside a procedure are\nalways propagated to the caller. This is implicitly done by the\nparameter passing syntax translations. \n\\\n\ntext \\We first define an append function on lists. It takes two \nreferences as parameters. It appends the list referred to by the first\nparameter with the list referred to by the second parameter. The statespace\nof the global variables has to be imported.\n\\\n\nprocedures (imports globals_heap)\n append(p :: ref, q::ref | p::ref) \n \"IF \\p=Null THEN \\p :== \\q \n ELSE \\p\\\\next :== CALL append(\\p\\\\next,\\q) FI\"\n\n(*<*)\ncontext append_impl\nbegin\n(*>*)\ntext \\\nThe difference of a global and a local variable is that global\nvariables are automatically copied back to the procedure caller.\nWe can study this effect on the translation of @{term \"\\p :== CALL append(\\p,\\q)\"}:\n\\\n(*<*)\ndeclare [[hoare_use_call_tr' = false]]\n(*>*)\ntext \\\n@{term [display] \"\\p :== CALL append(\\p,\\q)\"}\n\\\n(*<*)\ndeclare [[hoare_use_call_tr' = true]]\nend\n(*>*)\n\ntext \\Below we give two specifications this time.\nOne captures the functional behaviour and focuses on the\nentities that are potentially modified by the procedure, the second one\nis a pure frame condition. \n\\\n\n\n\ntext \\\nThe functional specification below introduces two logical variables besides the\nstate space variable @{term \"\\\"}, namely @{term \"Ps\"} and @{term \"Qs\"}.\nThey are universally quantified and range over both the pre-and the postcondition, so \nthat we are able to properly instantiate the specification\nduring the proofs. The syntax \\\\\\. \\\\\\ is a shorthand to fix the current \nstate: \\{s. \\ = s \\}\\. Moreover \\\\<^bsup>\\\\<^esup>x\\ abbreviates \nthe lookup of variable \\x\\ in the state \n\\\\\\. \n\nThe approach to specify procedures on lists\nbasically follows \\cite{MehtaN-CADE03}. From the pointer structure\nin the heap we (relationally) abstract to HOL lists of references. Then\nwe can specify further properties on the level of HOL lists, rather then \non the heap. The basic abstractions are: \n\n@{thm [display] Path.simps [no_vars]}\n\n@{term [show_types] \"Path x h y ps\"}: @{term ps} is a list of references that we can obtain\nout of the heap @{term h} by starting with the reference @{term x}, following\nthe references in @{term h} up to the reference @{term y}. \n\n\n@{thm [display] List_def [no_vars]}\n\nA list @{term \"List p h ps\"} is a path starting in @{term p} and ending up\nin @{term Null}.\n\\\n\n\nlemma (in append_impl) append_spec1: \nshows \"\\\\ Ps Qs. \n \\\\ \\\\. List \\p \\next Ps \\ List \\q \\next Qs \\ set Ps \\ set Qs = {}\\ \n \\p :== PROC append(\\p,\\q) \n \\List \\p \\next (Ps@Qs) \\ (\\x. x\\set Ps \\ \\next x = \\<^bsup>\\\\<^esup>next x)\\\"\napply (hoare_rule HoarePartial.ProcRec1)\ntxt \\@{subgoals [margin=80,display]} \nNote that @{term \"hoare_rule\"} takes care of multiple auxiliary variables! \n@{thm [source] HoarePartial.ProcRec1} has only one auxiliary variable, namely @{term Z}. \nBut the type of @{term Z} can be instantiated arbitrarily. So \\hoare_rule\\ \ninstantiates @{term Z} with the tuple @{term \"(\\,Ps,Qs)\"} and derives a proper variant\nof the rule. Therefore \\hoare_rule\\ depends on the proper quantification of\nauxiliary variables!\n\\\napply vcg\ntxt \\@{subgoals [display]} \nFor each branch of the \\IF\\ statement we have one conjunct to prove. The\n\\THEN\\ branch starts with \\p = Null \\ \\\\ and the \\ELSE\\ branch\nwith \\p \\ Null \\ \\\\. Let us focus on the \\ELSE\\ branch, were the\nrecursive call to append occurs. First of all we have to prove that the precondition for\nthe recursive call is fulfilled. That means we have to provide some witnesses for\nthe lists @{term Psa} and @{term Qsa} which are referenced by \\p\\next\\ (now\nwritten as @{term \"next p\"}) and @{term q}. Then we have to show that we can \nderive the overall postcondition from the postcondition of the recursive call. The\nstate components that have changed by the recursive call are the ones with the suffix\n\\a\\, like \\nexta\\ and \\pa\\.\n\\\napply fastforce\ndone\n\n\ntext \\If the verification condition generator works on a procedure\ncall it checks whether it can find a modifies clause in the\ncontext. If one is present the procedure call is simplified before the\nHoare rule @{thm [source] HoarePartial.ProcSpec} is\napplied. Simplification of the procedure call means that the ``copy\nback'' of the global components is simplified. Only those components\nthat occur in the modifies clause are actually copied back. This\nsimplification is justified by the rule @{thm [source]\nHoarePartial.ProcModifyReturn}. \nSo after this simplification all global\ncomponents that do not appear in the modifies clause are treated\nas local variables.\\\n\ntext \\We study the effect of the modifies clause on the following \nexamples, where we want to prove that @{term \"append\"} does not change\nthe @{term \"cont\"} part of the heap.\n\\\nlemma (in append_impl)\nshows \"\\\\ \\\\cont=c\\ \\p :== CALL append(Null,Null) \\\\cont=c\\\" \nproof -\n note append_spec = append_spec1\n show ?thesis\n apply vcg\n txt \\@{subgoals [display]}\\\n txt \\Only focus on the very last line: @{term conta} is the heap component \n after the procedure call,\n and @{term cont} the heap component before the procedure call. Since\n we have not added the modified clause we do not know that they have\n to be equal. \n\\\n oops\n\ntext \\\nWe now add the frame condition.\nThe list in the modifies clause names all global state components that\nmay be changed by the procedure. Note that we know from the modifies clause\nthat the @{term cont} parts are not changed. Also a small\nside note on the syntax. We use ordinary brackets in the postcondition\nof the modifies clause, and also the state components do not carry the\nacute, because we explicitly note the state @{term t} here.\n\\\n\n\nlemma (in append_impl) append_modifies:\n shows \"\\\\. \\\\\\<^bsub>/UNIV\\<^esub> {\\} \\p :== PROC append(\\p,\\q) \n {t. t may_only_modify_globals \\ in [next]}\"\n apply (hoare_rule HoarePartial.ProcRec1)\n apply (vcg spec=modifies)\n done\n\ntext \\We tell the verification condition generator to use only the\nmodifies clauses and not to search for functional specifications by \nthe parameter \\spec=modifies\\. It also tries to solve the \nverification conditions automatically. Again it is crucial to name \nthe lemma with this naming scheme, since the verfication condition \ngenerator searches for these names. \n\\\n\ntext \\The modifies clause is equal to a state update specification\nof the following form. \n\\\n\nlemma (in append_impl) shows \"{t. t may_only_modify_globals Z in [next]} \n = \n {t. \\next. globals t=update id id next_' (K_statefun next) (globals Z)}\"\n apply (unfold mex_def meq_def)\n apply simp\n done\n\ntext \\Now that we have proven the frame-condition, it is available within\nthe locale \\append_impl\\ and the \\vcg\\ exploits it.\\\n\nlemma (in append_impl) \nshows \"\\\\ \\\\cont=c\\ \\p :== CALL append(Null,Null) \\\\cont=c\\\"\nproof -\n note append_spec = append_spec1\n show ?thesis\n apply vcg\n txt \\@{subgoals [display]}\\\n txt \\With a modifies clause present we know that no change to @{term cont}\n has occurred. \n\\\n by simp\nqed\n \n\ntext \\\nOf course we could add the modifies clause to the functional specification as \nwell. But separating both has the advantage that we split up the verification\nwork. We can make use of the modifies clause before we apply the\nfunctional specification in a fully automatic fashion.\n\\\n \n\ntext \\\nTo prove that a procedure respects the modifies clause, we only need\nthe modifies clauses of the procedures called in the body. We do not need\nthe functional specifications. So we can always prove the modifies\nclause without functional specifications, but we may need the modifies\nclause to prove the functional specifications. So usually the modifies clause is\nproved before the proof of the functional specification, so that it can already be used\nby the verification condition generator.\n\\\n\n\n \nsubsection \\Total Correctness\\\n\ntext \\When proving total correctness the additional proof burden to\nthe user is to come up with a well-founded relation and to prove that\ncertain states get smaller according to this relation. Proving that a\nrelation is well-founded can be quite hard. But fortunately there are\nways to construct and stick together relations so that they are\nwell-founded by construction. This infrastructure is already present\nin Isabelle/HOL. For example, @{term \"measure f\"} is always well-founded;\nthe lexicographic product of two well-founded relations is again\nwell-founded and the inverse image construction @{term \"inv_image\"} of\na well-founded relation is again well-founded. The constructions are\nbest explained by some equations:\n\n@{thm in_measure_iff [no_vars]}\\\\\n@{thm in_lex_iff [no_vars]}\\\\\n@{thm in_inv_image_iff [no_vars]}\n\nAnother useful construction is \\<*mlex*>\\ which is a combination\nof a measure and a lexicographic product:\n\n@{thm in_mlex_iff [no_vars]}\\\\\nIn contrast to the lexicographic product it does not construct a product type.\nThe state may either decrease according to the measure function @{term f} or the\nmeasure stays the same and the state decreases because of the relation @{term r}.\n\nLets look at a loop:\n\\\n\nlemma (in vars) \n \"\\\\\\<^sub>t \\\\M = 0 \\ \\S = 0\\\n WHILE \\M \\ a\n INV \\\\S = \\M * b \\ \\M \\ a\\\n VAR MEASURE a - \\M\n DO \\S :== \\S + b;; \\M :== \\M + 1 OD\n \\\\S = a * b\\\"\napply vcg\ntxt \\@{subgoals [display]} \nThe first conjunct of the second subgoal is the proof obligation that the\nvariant decreases in the loop body. \n\\\nby auto\n\n\n\ntext \\The variant annotation is preceded by \\VAR\\. The capital \\MEASURE\\\nis a shorthand for \\measure (\\s. a - \\<^bsup>s\\<^esup>M)\\. Analogous there is a capital \n\\<*MLEX*>\\.\n\\\n\nlemma (in Fac_impl) Fac_spec': \nshows \"\\\\. \\\\\\<^sub>t {\\} \\R :== PROC Fac(\\N) \\\\R = fac \\<^bsup>\\\\<^esup>N\\\"\napply (hoare_rule HoareTotal.ProcRec1 [where r=\"measure (\\(s,p). \\<^bsup>s\\<^esup>N)\"])\ntxt \\In case of the factorial the parameter @{term N} decreases in every call. This\nis easily expressed by the measure function. Note that the well-founded relation for\nrecursive procedures is formally defined on tuples\ncontaining the state space and the procedure name.\n\\\ntxt \\@{subgoals [display]} \nThe initial call to the factorial is in state @{term \"\\\"}. Note that in the \nprecondition @{term \"{\\} \\ {\\'}\"}, @{term \"\\'\"} stems from the lemma we want to prove\nand @{term \"\\\"} stems from the recursion rule for total correctness. Both are\nsynonym for the initial state. To use the assumption in the Hoare context we\nhave to show that the call to the factorial is invoked on a smaller @{term N} compared\nto the initial \\\\<^bsup>\\\\<^esup>N\\.\n\\\napply vcg\ntxt \\@{subgoals [display]} \nThe tribute to termination is that we have to show \\N - 1 < N\\ in case of\nthe recursive call.\n\\\nby simp\n\nlemma (in append_impl) append_spec2:\nshows \"\\\\ Ps Qs. \\\\\\<^sub>t \n \\\\. List \\p \\next Ps \\ List \\q \\next Qs \\ set Ps \\ set Qs = {}\\ \n \\p :== PROC append(\\p,\\q) \n \\List \\p \\next (Ps@Qs) \\ (\\x. x\\set Ps \\ \\next x = \\<^bsup>\\\\<^esup>next x)\\\"\napply (hoare_rule HoareTotal.ProcRec1\n [where r=\"measure (\\(s,p). length (list \\<^bsup>s\\<^esup>p \\<^bsup>s\\<^esup>next))\"])\ntxt \\In case of the append function the length of the list referenced by @{term p}\ndecreases in every recursive call.\n\\\ntxt \\@{subgoals [margin=80,display]}\\\napply vcg\napply (fastforce simp add: List_list)\ndone\n\ntext \\\nIn case of the lists above, we have used a relational list abstraction @{term List}\nto construct the HOL lists @{term Ps} and @{term Qs} for the pre- and postcondition.\nTo supply a proper measure function we use a functional abstraction @{term list}.\nThe functional abstraction can be defined by means of the relational list abstraction,\nsince the lists are already uniquely determined by the relational abstraction:\n\n@{thm islist_def [no_vars]}\\\\\n@{thm list_def [no_vars]}\n\n\\isacommand{lemma} @{thm List_conv_islist_list [no_vars]}\n\\\n\ntext \\\nThe next contrived example is taken from \\cite{Homeier-95-vcg}, to illustrate\na more complex termination criterion for mutually recursive procedures. The procedures\ndo not calculate anything useful.\n\n\\\n\n\nprocedures \n pedal(N::nat,M::nat) \n \"IF 0 < \\N THEN\n IF 0 < \\M THEN \n CALL coast(\\N- 1,\\M- 1) FI;;\n CALL pedal(\\N- 1,\\M)\n FI\"\n and\n \n coast(N::nat,M::nat) \n \"CALL pedal(\\N,\\M);;\n IF 0 < \\M THEN CALL coast(\\N,\\M- 1) FI\"\n\n\ntext \\\nIn the recursive calls in procedure \\pedal\\ the first argument always decreases.\nIn the body of \\coast\\ in the recursive call of \\coast\\ the second\nargument decreases, but in the call to \\pedal\\ no argument decreases. \nTherefore an relation only on the state space is insufficient. We have to\ntake the procedure names into account, too.\nWe consider the procedure \\coast\\ to be ``bigger'' than \\pedal\\\nwhen we construct a well-founded relation on the product of state space and procedure\nnames.\n\\\n\nML \\ML_Thms.bind_thm (\"HoareTotal_ProcRec2\", Hoare.gen_proc_rec @{context} Hoare.Total 2)\\\n\n\ntext \\\n We provide the ML function {\\tt gen\\_proc\\_rec} to\nautomatically derive a convenient rule for recursion for a given number of mutually\nrecursive procedures.\n\\\n\n \nlemma (in pedal_coast_clique)\nshows \"(\\\\. \\\\\\<^sub>t {\\} PROC pedal(\\N,\\M) UNIV) \\\n (\\\\. \\\\\\<^sub>t {\\} PROC coast(\\N,\\M) UNIV)\"\napply (hoare_rule HoareTotal_ProcRec2 \n [where r= \"((\\(s,p). \\<^bsup>s\\<^esup>N) <*mlex*>\n (\\(s,p). \\<^bsup>s\\<^esup>M) <*mlex*>\n measure (\\(s,p). if p = coast_'proc then 1 else 0))\"])\n txt \\We can directly express the termination condition described above with\n the \\<*mlex*>\\ construction. Either state component \\N\\ decreases,\n or it stays the same and \\M\\ decreases or this also stays the same, but\n then the procedure name has to decrease.\\\n txt \\@{subgoals [margin=80,display]}\\\napply simp_all\n txt \\@{subgoals [margin=75,display]}\\\nby (vcg,simp)+\n\ntext \\We can achieve the same effect without \\<*mlex*>\\ by using\n the ordinary lexicographic product \\<*lex*>\\, \\inv_image\\ and\n \\measure\\ \n\\\n \nlemma (in pedal_coast_clique)\nshows \"(\\\\. \\\\\\<^sub>t {\\} PROC pedal(\\N,\\M) UNIV) \\\n (\\\\. \\\\\\<^sub>t {\\} PROC coast(\\N,\\M) UNIV)\"\napply (hoare_rule HoareTotal_ProcRec2\n [where r= \"inv_image (measure (\\m. m) <*lex*>\n measure (\\m. m) <*lex*> \n measure (\\p. if p = coast_'proc then 1 else 0))\n (\\(s,p). (\\<^bsup>s\\<^esup>N,\\<^bsup>s\\<^esup>M,p))\"])\n txt \\With the lexicographic product we construct a well-founded relation on\n triples of type @{typ \"(nat\\nat\\string)\"}. With @{term inv_image} we project\n the components out of the state-space and the procedure names to this\n triple.\n\\\n txt \\@{subgoals [margin=75,display]}\\\napply simp_all\nby (vcg,simp)+\n\ntext \\By doing some arithmetic we can express the termination condition with a single\nmeasure function.\n\\\n\nlemma (in pedal_coast_clique) \nshows \"(\\\\. \\\\\\<^sub>t {\\} PROC pedal(\\N,\\M) UNIV) \\\n (\\\\. \\\\\\<^sub>t {\\} PROC coast(\\N,\\M) UNIV)\"\napply(hoare_rule HoareTotal_ProcRec2\n [where r= \"measure (\\(s,p). \\<^bsup>s\\<^esup>N + \\<^bsup>s\\<^esup>M + (if p = coast_'proc then 1 else 0))\"])\napply simp_all\ntxt \\@{subgoals [margin=75,display]}\\\nby (vcg,simp,arith?)+\n\n\nsubsection \\Guards\\\n\ntext (in vars) \\The purpose of a guard is to guard the {\\bf (sub-) expressions} of a\nstatement against runtime faults. Typical runtime faults are array bound violations,\ndereferencing null pointers or arithmetical overflow. Guards make the potential\nruntime faults explicit, since the expressions themselves never ``fail'' because \nthey are ordinary HOL expressions. To relieve the user from typing in lots of standard\nguards for every subexpression, we supply some input syntax for the common\nlanguage constructs that automatically generate the guards.\nFor example the guarded assignment \\\\M :==\\<^sub>g (\\M + 1) div \\N\\ gets expanded to \nguarded command @{term \"\\M :==\\<^sub>g (\\M + 1) div \\N\"}. Here @{term \"in_range\"} is\nuninterpreted by now. \n\\\n\nlemma (in vars) \"\\\\\\True\\ \\M :==\\<^sub>g (\\M + 1) div \\N \\True\\\"\napply vcg\ntxt \\@{subgoals}\\\noops\n\ntext \\\nThe user can supply on (overloaded) definition of \\in_range\\\nto fit to his needs.\n\nCurrently guards are generated for:\n\n\\begin{itemize}\n\\item overflow and underflow of numbers (\\in_range\\). For subtraction of\n natural numbers \\a - b\\ the guard \\b \\ a\\ is generated instead\n of \\in_range\\ to guard against underflows.\n\\item division by \\0\\\n\\item dereferencing of @{term Null} pointers\n\\item array bound violations\n\\end{itemize}\n\nFollowing (input) variants of guarded statements are available:\n\n\\begin{itemize}\n\\item Assignment: \\\\ :==\\<^sub>g \\\\\n\\item If: \\IF\\<^sub>g \\\\\n\\item While: \\WHILE\\<^sub>g \\\\\n\\item Call: \\CALL\\<^sub>g \\\\ or \\\\ :== CALL\\<^sub>g \\\\\n\\end{itemize}\n\\\n\nsubsection \\Miscellaneous Techniques\\\n\n\n\nsubsubsection \\Modifies Clause\\\n\ntext \\We look at some issues regarding the modifies clause with the example\nof insertion sort for heap lists.\n\\\n\nprimrec sorted:: \"('a \\ 'a \\ bool) \\ 'a list \\ bool\"\nwhere\n\"sorted le [] = True\" |\n\"sorted le (x#xs) = ((\\y\\set xs. le x y) \\ sorted le xs)\"\n\nprocedures (imports globals_heap)\n insert(r::ref,p::ref | p::ref) \n \"IF \\r=Null THEN SKIP\n ELSE IF \\p=Null THEN \\p :== \\r;; \\p\\\\next :== Null\n ELSE IF \\r\\\\cont \\ \\p\\\\cont \n THEN \\r\\\\next :== \\p;; \\p:==\\r\n ELSE \\p\\\\next :== CALL insert(\\r,\\p\\\\next)\n FI\n FI\n FI\"\n\nlemma (in insert_impl) insert_modifies:\n \"\\\\. \\\\\\<^bsub>/UNIV\\<^esub> {\\} \\p :== PROC insert(\\r,\\p) \n {t. t may_only_modify_globals \\ in [next]}\"\n by (hoare_rule HoarePartial.ProcRec1) (vcg spec=modifies)\n\nlemma (in insert_impl) insert_spec:\n \"\\\\ Ps . \\\\ \n \\\\. List \\p \\next Ps \\ sorted (op \\) (map \\cont Ps) \\ \n \\r \\ Null \\ \\r \\ set Ps\\\n \\p :== PROC insert(\\r,\\p) \n \\\\Qs. List \\p \\next Qs \\ sorted (op \\) (map \\<^bsup>\\\\<^esup>cont Qs) \\\n set Qs = insert \\<^bsup>\\\\<^esup>r (set Ps) \\\n (\\x. x \\ set Qs \\ \\next x = \\<^bsup>\\\\<^esup>next x)\\\"\n (*<*)\n apply (hoare_rule HoarePartial.ProcRec1)\n apply vcg\n apply (intro conjI impI)\n apply fastforce\n apply fastforce\n apply fastforce\n apply (clarsimp) \n apply force\n done\n (*>*)\n\ntext \\\nIn the postcondition of the functional specification there is a small but \nimportant subtlety. Whenever we talk about the @{term \"cont\"} part we refer to \nthe one of the pre-state.\nThe reason is that we have separated out the information that @{term \"cont\"} is not \nmodified by the procedure, to the modifies clause. So whenever we talk about unmodified\nparts in the postcondition we have to use the pre-state part, or explicitly\nstate an equality in the postcondition.\nThe reason is simple. If the postcondition would talk about \\\\cont\\\ninstead of \\mbox{\\\\<^bsup>\\\\<^esup>cont\\}, we get a new instance of \\cont\\ during\nverification and the postcondition would only state something about this\nnew instance. But as the verification condition generator uses the\nmodifies clause the caller of @{term \"insert\"} instead still has the\nold \\cont\\ after the call. Thats the sense of the modifies clause.\nSo the caller and the specification simply talk about two different things,\nwithout being able to relate them (unless an explicit equality is added to\nthe specification). \n\\\n\n\nsubsubsection \\Annotations\\\n\ntext \\\nAnnotations (like loop invariants)\nare mere syntactic sugar of statements that are used by the \\vcg\\. \nLogically a statement with an annotation is\nequal to the statement without it. Hence annotations can be introduced by the user\nwhile building a proof:\n\n@{thm [source] HoarePartial.annotateI}: @{thm [mode=Rule] HoarePartial.annotateI [no_vars]} \n\nWhen introducing annotations it can easily happen that these mess around with the \nnesting of sequential composition. Then after stripping the annotations the resulting statement\nis no longer syntactically identical to original one, only equivalent modulo associativity of sequential composition. The following rule also deals with this case:\n\n@{thm [source] HoarePartial.annotate_normI}: @{thm [mode=Rule] HoarePartial.annotate_normI [no_vars]} \n\\\n\ntext_raw \\\\paragraph{Loop Annotations} \n\\mbox{}\n\\medskip\n\n\\mbox{}\n\\\n\nprocedures (imports globals_heap)\n insertSort(p::ref| p::ref) \n where r::ref q::ref in\n \"\\r:==Null;;\n WHILE (\\p \\ Null) DO\n \\q :== \\p;;\n \\p :== \\p\\\\next;;\n \\r :== CALL insert(\\q,\\r)\n OD;;\n \\p:==\\r\"\n\nlemma (in insertSort_impl) insertSort_modifies: \n shows\n \"\\\\. \\\\\\<^bsub>/UNIV\\<^esub> {\\} \\p :== PROC insertSort(\\p) \n {t. t may_only_modify_globals \\ in [next]}\"\napply (hoare_rule HoarePartial.ProcRec1)\napply (vcg spec=modifies)\ndone\n\n\n\n\ntext \\Insertion sort is not implemented recursively here, but with a \nloop. Note that the while loop is not annotated with an invariant in the\nprocedure definition. The invariant only comes into play during verification.\nTherefore we annotate the loop first, before we run the \\vcg\\. \n\\\n\nlemma (in insertSort_impl) insertSort_spec:\nshows \"\\\\ Ps. \n \\\\ \\\\. List \\p \\next Ps \\ \n \\p :== PROC insertSort(\\p)\n \\\\Qs. List \\p \\next Qs \\ sorted (op \\) (map \\<^bsup>\\\\<^esup>cont Qs) \\\n set Qs = set Ps\\\"\napply (hoare_rule HoarePartial.ProcRec1) \napply (hoare_rule anno= \n \"\\r :== Null;;\n WHILE \\p \\ Null\n INV \\\\Qs Rs. List \\p \\next Qs \\ List \\r \\next Rs \\ \n set Qs \\ set Rs = {} \\\n sorted (op \\) (map \\cont Rs) \\ set Qs \\ set Rs = set Ps \\\n \\cont = \\<^bsup>\\\\<^esup>cont \\\n DO \\q :== \\p;; \\p :== \\p\\\\next;; \\r :== CALL insert(\\q,\\r) OD;;\n \\p :== \\r\" in HoarePartial.annotateI)\napply vcg\ntxt \\\\\\\\\\\n(*<*)\n \n apply fastforce\n prefer 2\n apply fastforce\n apply (clarsimp)\n apply (rule_tac x=ps in exI)\n apply (intro conjI)\n apply (rule heap_eq_ListI1)\n apply assumption\n apply clarsimp\n apply (subgoal_tac \"x\\p \\ x \\ set Rs\")\n apply auto\n done\n(*>*)\n\ntext \\The method \\hoare_rule\\ automatically solves the side-condition \n that the annotated\n program is the same as the original one after stripping the annotations.\\\n\ntext_raw \\\\paragraph{Specification Annotations} \n\\mbox{}\n\\medskip\n\n\\mbox{}\n\\\n\n\n\ntext \\\nWhen verifying a larger block of program text, it might be useful to split up\nthe block and to prove the parts in isolation. This is especially useful to\nisolate loops. On the level of the Hoare calculus\nthe parts can then be combined with the consequence rule. To automate this\nprocess we introduce the derived command @{term specAnno}, which allows to introduce\na Hoare tuple (inclusive auxiliary variables) in the program text:\n\n@{thm specAnno_def [no_vars]}\n\nThe whole annotation reduces to the body @{term \"c undefined\"}. The\ntype of the assertions @{term \"P\"}, @{term \"Q\"} and @{term \"A\"} is\n@{typ \"'a \\ 's set\"} and the type of command @{term c} is @{typ \"'a \\ ('s,'p,'f) com\"}.\nAll entities formally depend on an auxiliary (logical) variable of type @{typ \"'a\"}.\nThe body @{term \"c\"} formally also depends on this variable, since a nested annotation\nor loop invariant may also depend on this logical variable. But the raw body without\nannotations does not depend on the logical variable. The logical variable is only\nused by the verification condition generator. We express this by defining the\nwhole @{term specAnno} to be equivalent with the body applied to an arbitrary\nvariable.\n\nThe Hoare rule for \\specAnno\\ is mainly an instance of the consequence rule:\n\n@{thm [mode=Rule,mode=ParenStmt] HoarePartial.SpecAnno [no_vars]}\n\nThe side-condition @{term \"\\Z. c Z = c undefined\"} expresses the intention of body @{term c}\nexplained above: The raw body is independent of the auxiliary variable. This\nside-condition is solved automatically by the \\vcg\\. The concrete syntax for \nthis specification annotation is shown in the following example: \n\\\n\nlemma (in vars) \"\\\\ {\\} \n \\I :== \\M;; \n ANNO \\. \\\\. \\I = \\<^bsup>\\\\<^esup>M\\\n \\M :== \\N;; \\N :== \\I \n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>I\\\n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>M\\\"\ntxt \\With the annotation we can name an intermediate state @{term \\}. Since the\n postcondition refers to @{term \"\\\"} we have to link the information about\n the equivalence of \\\\<^bsup>\\\\<^esup>I\\ and \\\\<^bsup>\\\\<^esup>M\\ in the specification in order\n to be able to derive the postcondition.\n\\\napply vcg_step\napply vcg_step\ntxt \\@{subgoals [display]}\\\ntxt \\The first subgoal is the isolated Hoare tuple. The second one is the\n side-condition of the consequence rule that allows us to derive the outermost\n pre/post condition from our inserted specification.\n \\\\I = \\<^bsup>\\\\<^esup>M\\ is the precondition of the specification, \n The second conjunct is a simplified version of\n \\\\t. \\<^bsup>t\\<^esup>M = \\N \\ \\<^bsup>t\\<^esup>N = \\I \\ \\<^bsup>t\\<^esup>M = \\<^bsup>\\\\<^esup>N \\ \\<^bsup>t\\<^esup>N = \\<^bsup>\\\\<^esup>M\\ expressing that the\n postcondition of the specification implies the outermost postcondition.\n\\\napply vcg\ntxt \\@{subgoals [display]}\\\napply simp\napply vcg\ntxt \\@{subgoals [display]}\\\nby simp\n\n\nlemma (in vars) \n \"\\\\ {\\} \n \\I :== \\M;; \n ANNO \\. \\\\. \\I = \\<^bsup>\\\\<^esup>M\\\n \\M :== \\N;; \\N :== \\I \n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>I\\\n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>M\\\"\napply vcg\ntxt \\@{subgoals [display]}\\\nby simp_all\n\ntext \\Note that \\vcg_step\\ changes the order of sequential composition, to \nallow the user to decompose sequences by repeated calls to \\vcg_step\\, whereas\n\\vcg\\ preserves the order.\n\nThe above example illustrates how we can introduce a new logical state variable \n@{term \"\\\"}. You can introduce multiple variables by using a tuple:\n\n\n\n\\\n\n\nlemma (in vars) \n \"\\\\ {\\} \n \\I :== \\M;; \n ANNO (n,i,m). \\\\I = \\<^bsup>\\\\<^esup>M \\ \\N=n \\ \\I=i \\ \\M=m\\\n \\M :== \\N;; \\N :== \\I \n \\\\M = n \\ \\N = i\\\n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>M\\\"\napply vcg\ntxt \\@{subgoals [display]}\\\nby simp_all\n\ntext_raw \\\\paragraph{Lemma Annotations} \n\\mbox{}\n\\medskip\n\n\\mbox{}\n\n\\\n\ntext \\\nThe specification annotations described before split the verification\ninto several Hoare triples which result in several subgoals. If we\ninstead want to proof the Hoare triples independently as\nseparate lemmas we can use the \\LEMMA\\ annotation to plug together the\nlemmas. It\ninserts the lemma in the same fashion as the specification annotation.\n\\\nlemma (in vars) foo_lemma: \n \"\\n m. \\\\ \\\\N = n \\ \\M = m\\ \\N :== \\N + 1;; \\M :== \\M + 1 \n \\\\N = n + 1 \\ \\M = m + 1\\\"\n apply vcg\n apply simp\n done\n\nlemma (in vars) \n \"\\\\ \\\\N = n \\ \\M = m\\ \n LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END;; \n \\N :== \\N + 1 \n \\\\N = n + 2 \\ \\M = m + 1\\\"\n apply vcg\n apply simp\n done\n\nlemma (in vars)\n \"\\\\ \\\\N = n \\ \\M = m\\ \n LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END;;\n LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END\n \\\\N = n + 2 \\ \\M = m + 2\\\"\n apply vcg\n apply simp\n done\n\nlemma (in vars) \n \"\\\\ \\\\N = n \\ \\M = m\\ \n \\N :== \\N + 1;; \\M :== \\M + 1;;\n \\N :== \\N + 1;; \\M :== \\M + 1\n \\\\N = n + 2 \\ \\M = m + 2\\\"\n apply (hoare_rule anno= \n \"LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END;;\n LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END\"\n in HoarePartial.annotate_normI)\n apply vcg\n apply simp\n done\n\n\nsubsubsection \\Total Correctness of Nested Loops\\\n\ntext \\\nWhen proving termination of nested loops it is sometimes necessary to express that\nthe loop variable of the outer loop is not modified in the inner loop. To express this\none has to fix the value of the outer loop variable before the inner loop and use this value\nin the invariant of the inner loop. This can be achieved by surrounding the inner while loop\nwith an \\ANNO\\ specification as explained previously. However, this\nleads to repeating the invariant of the inner loop three times: in the invariant itself and\nin the the pre- and postcondition of the \\ANNO\\ specification. Moreover one has\nto deal with the additional subgoal introduced by \\ANNO\\ that expresses how\nthe pre- and postcondition is connected to the invariant. To avoid this extra specification\nand verification work, we introduce an variant of the annotated while-loop, where one can\nintroduce logical variables by \\FIX\\. As for the \\ANNO\\ specification\nmultiple logical variables can be introduced via a tuple (\\FIX (a,b,c).\\).\n\nThe Hoare logic rule for the augmented while-loop is a mixture of the invariant rule for\nloops and the consequence rule for \\ANNO\\:\n\n\\begin{center}\n@{thm [mode=Rule,mode=ParenStmt] HoareTotal.WhileAnnoFix' [no_vars]}\n\\end{center}\n\nThe first premise expresses that the precondition implies the invariant and that\nthe invariant together with the negated loop condition implies the postcondition. Since\nboth implications may depend on the choice of the auxiliary variable @{term \"Z\"} these two\nimplications are expressed in a single premise and not in two of them as for the usual while\nrule. The second premise is the preservation of the invariant by the loop body. And the third\npremise is the side-condition that the computational part of the body does not depend on\nthe auxiliary variable. Finally the last premise is the well-foundedness of the variant.\nThe last two premises are usually discharged automatically by the verification condition\ngenerator. Hence usually two subgoals remain for the user, stemming from the first two\npremises.\n\nThe following example illustrates the usage of this rule. The outer loop increments the\nloop variable @{term \"M\"} while the inner loop increments @{term \"N\"}. To discharge the\nproof obligation for the termination of the outer loop, we need to know that the inner loop\ndoes not mess around with @{term \"M\"}. This is expressed by introducing the logical variable\n@{term \"m\"} and fixing the value of @{term \"M\"} to it.\n\\\n\n\nlemma (in vars) \n \"\\\\\\<^sub>t \\\\M=0 \\ \\N=0\\ \n WHILE (\\M < i) \n INV \\\\M \\ i \\ (\\M \\ 0 \\ \\N = j) \\ \\N \\ j\\\n VAR MEASURE (i - \\M)\n DO\n \\N :== 0;;\n WHILE (\\N < j)\n FIX m. \n INV \\\\M=m \\ \\N \\ j\\\n VAR MEASURE (j - \\N)\n DO\n \\N :== \\N + 1\n OD;;\n \\M :== \\M + 1\n OD\n \\\\M=i \\ (\\M\\0 \\ \\N=j)\\\"\napply vcg\ntxt \\@{subgoals [display]} \n\nThe first subgoal is from the precondition to the invariant of the outer loop.\nThe fourth subgoal is from the invariant together with the negated loop condition \nof the outer loop to the postcondition. The subgoals two and three are from the body\nof the outer while loop which is mainly the inner while loop. Because we introduce the\nlogical variable @{term \"m\"} here, the while Rule described above is used instead of the\nordinary while Rule. That is why we end up with two subgoals for the inner loop. Subgoal\ntwo is from the invariant and the loop condition of the outer loop to the invariant\nof the inner loop. And at the same time from the invariant of the inner loop to the\ninvariant of the outer loop (together with the proof obligation that the measure of the\nouter loop decreases). The universal quantified variables @{term \"Ma\"} and @{term \"N\"} are\nthe ``fresh'' state variables introduced for the final state of the inner loop. \nThe equality @{term \"Ma=M\"} is the result of the equality \\\\M=m\\ in the inner \ninvariant. Subgoal three is the preservation of the invariant by the\ninner loop body (together with the proof obligation that the measure of\nthe inner loop decreases).\n\\\n(*<*)\napply (simp)\napply (simp,arith)\napply (simp,arith)\ndone\n(*>*)\n\nsubsection \\Functional Correctness, Termination and Runtime Faults\\\n\ntext \\\nTotal correctness of a program with guards conceptually leads to three verification \ntasks.\n\\begin{itemize}\n\\item functional (partial) correctness \n\\item absence of runtime faults\n\\item termination\n\\end{itemize}\n\nIn case of a modifies specification the functional correctness part\ncan be solved automatically. But the absence of runtime faults and\ntermination may be non trivial. Fortunately the modifies clause is\nusually just a helpful companion of another specification that\nexpresses the ``real'' functional behaviour. Therefor the task to\nprove the absence of runtime faults and termination can be dealt with\nduring the proof of this functional specification. In most cases the\nabsence of runtime faults and termination heavily build on the\nfunctional specification parts. So after all there is no reason why\nwe should again prove the absence of runtime faults and termination\nfor the modifies clause. Therefor it suffices to have partial\ncorrectness of the modifies clause for a program were all guards are\nignored. This leads to the following pattern:\\\n\n\n\nprocedures foo (N::nat|M::nat) \n \"\\M :== \\M \n (* think of body with guards instead *)\"\n\n foo_spec: \"\\\\. \\\\\\<^sub>t (P \\) \\M :== PROC foo(\\N) (Q \\)\"\n foo_modifies: \"\\\\. \\\\\\<^bsub>/UNIV\\<^esub> {\\} \\M :== PROC foo(\\N) \n {t. t may_only_modify_globals \\ in []}\"\n\ntext \\\nThe verification condition generator can solve those modifies clauses automatically\nand can use them to simplify calls to \\foo\\ even in the context of total\ncorrectness.\n\\\n\nsubsection \\Procedures and Locales \\label{sec:Locales}\\\n\n\n\ntext \\\nVerification of a larger program is organised on the granularity of procedures. \nWe proof the procedures in a bottom up fashion. Of course you can also always use Isabelle's\ndummy proof \\sorry\\ to prototype your formalisation. So you can write the\ntheory in a bottom up fashion but actually prove the lemmas in any other order.\n \nHere are some explanations of handling of locales. In the examples below, consider\n\\proc\\<^sub>1\\ and \\proc\\<^sub>2\\ to be ``leaf'' procedures, which do not call any \nother procedure.\nProcedure \\proc\\ directly calls \\proc\\<^sub>1\\ and \\proc\\<^sub>2\\.\n\n\\isacommand{lemma} (\\isacommand{in} \\proc\\<^sub>1_impl\\) \\proc\\<^sub>1_modifies\\:\\\\\n\\isacommand{shows} \\\\\\ \n\nAfter the proof of \\proc\\<^sub>1_modifies\\, the \\isacommand{in} directive \nstores the lemma in the\nlocale \\proc\\<^sub>1_impl\\. When we later on include \\proc\\<^sub>1_impl\\ or prove \nanother theorem in locale \\proc\\<^sub>1_impl\\ the lemma \\proc\\<^sub>1_modifies\\\nwill already be available as fact.\n\n\\isacommand{lemma} (\\isacommand{in} \\proc\\<^sub>1_impl\\) \\proc\\<^sub>1_spec\\:\\\\\n\\isacommand{shows} \\\\\\ \n\n\\isacommand{lemma} (\\isacommand{in} \\proc\\<^sub>2_impl\\) \\proc\\<^sub>2_modifies\\:\\\\\n\\isacommand{shows} \\\\\\ \n\n\\isacommand{lemma} (\\isacommand{in} \\proc\\<^sub>2_impl\\) \\proc\\<^sub>2_spec\\:\\\\\n\\isacommand{shows} \\\\\\ \n\n\n\\isacommand{lemma} (\\isacommand{in} \\proc_impl\\) \\proc_modifies\\:\\\\\n\\isacommand{shows} \\\\\\ \n\nNote that we do not explicitly include anything about \\proc\\<^sub>1\\ or \n\\proc\\<^sub>2\\ here. This is handled automatically. When defining\nan \\impl\\-locale it imports all \\impl\\-locales of procedures that are\ncalled in the body. In case of \\proc_impl\\ this means, that \\proc\\<^sub>1_impl\\\nand \\proc\\<^sub>2_impl\\ are imported. This has the neat effect that all theorems that\nare proven in \\proc\\<^sub>1_impl\\ and \\proc\\<^sub>2_impl\\ are also present\nin \\proc_impl\\.\n\n\\isacommand{lemma} (\\isacommand{in} \\proc_impl\\) \\proc_spec\\:\\\\\n\\isacommand{shows} \\\\\\ \n\nAs we have seen in this example you only have to prove a procedure in its own\n\\impl\\ locale. You do not have to include any other locale. \n\\\n\nsubsection \\Records \\label{sec:records}\\\n\ntext \\\nBefore @{term \"statespaces\"} where introduced the state was represented as a @{term \"record\"}.\nThis is still supported. Compared to the flexibility of statespaces there are some drawbacks\nin particular with respect to modularity. Even names of local variables and \nparameters are globally visible and records can only be extended in a linear fashion, whereas\nstatespaces also allow multiple inheritance. The usage of records is quite similar to the usage of statespaces. \nWe repeat the example of an append function for heap lists.\nFirst we define the global components. \nAgain the appearance of the prefix `globals' is mandatory. This is the way the syntax layer distinguishes local and global variables. \n\\\nrecord globals_list = \n next_' :: \"ref \\ ref\"\n cont_' :: \"ref \\ nat\"\n\n\ntext \\The local variables also have to be defined as a record before the actual definition\nof the procedure. The parent record \\state\\ defines a generic @{term \"globals\"}\nfield as a place-holder for the record of global components. In contrast to the\nstatespace approach there is no single @{term \"locals\"} slot. The local components are\njust added to the record.\n\\\nrecord 'g list_vars = \"'g state\" +\n p_' :: \"ref\"\n q_' :: \"ref\"\n r_' :: \"ref\"\n root_' :: \"ref\"\n tmp_' :: \"ref\"\n\ntext \\Since the parameters and local variables are determined by the record, there are\nno type annotations or definitions of local variables while defining a procedure.\n\\\n\nprocedures\n append'(p,q|p) = \n \"IF \\p=Null THEN \\p :== \\q \n ELSE \\p \\\\next:== CALL append'(\\p\\\\next,\\q) FI\"\n\ntext \\As in the statespace approach, a locale called \\append'_impl\\ is created.\nNote that we do not give any explicit information which global or local state-record to use.\nSince the records are already defined we rely on Isabelle's type inference. \nDealing with the locale is analogous to the case with statespaces.\n\\\n\nlemma (in append'_impl) append'_modifies: \n shows\n \"\\\\. \\\\ {\\} \\p :== PROC append'(\\p,\\q)\n {t. t may_only_modify_globals \\ in [next]}\"\n apply (hoare_rule HoarePartial.ProcRec1)\n apply (vcg spec=modifies)\n done\n\nlemma (in append'_impl) append'_spec:\n shows \"\\\\ Ps Qs. \\\\ \n \\\\. List \\p \\next Ps \\ List \\q \\next Qs \\ set Ps \\ set Qs = {}\\\n \\p :== PROC append'(\\p,\\q) \n \\List \\p \\next (Ps@Qs) \\ (\\x. x\\set Ps \\ \\next x = \\<^bsup>\\\\<^esup>next x)\\\"\n apply (hoare_rule HoarePartial.ProcRec1)\n apply vcg\n apply fastforce\n done\n\n\ntext \\\nHowever, in some corner cases the inferred state type in a procedure definition \ncan be too general which raises problems when attempting to proof a suitable \nspecifications in the locale.\nConsider for example the simple procedure body @{term \"\\p :== NULL\"} for a procedure\n\\init\\. \n\\\n\nprocedures init (|p) = \n \"\\p:== Null\"\n\n\ntext \\\nHere Isabelle can only\ninfer the local variable record. Since no reference to any global variable is\nmade the type fixed for the global variables (in the locale \\init'_impl\\) is a \ntype variable say @{typ \"'g\"} and not a @{term \"globals_list\"} record. Any specification\nmentioning @{term \"next\"} or @{term \"cont\"} restricts the state type and cannot be\nadded to the locale \\init_impl\\. Hence we have to restrict the body\n@{term \"\\p :== NULL\"} in the first place by adding a typing annotation:\n\\\n\nprocedures init' (|p) = \n \"\\p:== Null::(('a globals_list_scheme, 'b) list_vars_scheme, char list, 'c) com\"\n\n\nsubsubsection \\Extending State Spaces\\\ntext \\\nThe records in Isabelle are\nextensible \\cite{Nipkow-02-hol,NaraschewskiW-TPHOLs98}. In principle this can be exploited \nduring verification. The state space can be extended while we we add procedures.\nBut there is one major drawback:\n\\begin{itemize}\n \\item records can only be extended in a linear fashion (there is no multiple inheritance)\n\\end{itemize}\n\nYou can extend both the main state record as well as the record for the global variables.\n\\\n\nsubsubsection \\Mapping Variables to Record Fields\\\n\ntext \\\nGenerally the state space (global and local variables) is flat and all components\nare accessible from everywhere. Locality or globality of variables is achieved by\nthe proper \\init\\ and \\return\\/\\result\\ functions in procedure\ncalls. What is the best way to map programming language variables to the state records?\nOne way is to disambiguate all names, by using the procedure names as prefix or the\nstructure names for heap components. This leads to long names and lots of \nrecord components. But for local variables this is not necessary, since\nvariable @{term i} of procedure @{term A} and variable @{term \"i\"} of procedure @{term B}\ncan be mapped to the same record component, without any harm, provided they have the\nsame logical type. Therefor for local variables it is preferable to map them per type. You\nonly have to distinguish a variable with the same name if they have a different type.\nNote that all pointers just have logical type \\ref\\. So you even do not\nhave to distinguish between a pointer \\p\\ to a integer and a pointer \\p\\ to\na list.\nFor global components (global variables and heap structures) you have to disambiguate the\nname. But hopefully the field names of structures have different names anyway.\nAlso note that there is no notion of hiding of a global component by a local one in\nthe logic. You have to disambiguate global and local names!\nAs the names of the components show up in the specifications and the\nproof obligations, names are even more important as for programming. Try to\nfind meaningful and short names, to avoid cluttering up your reasoning.\n\\\n\n(*<*)\ntext \\\nin locales, includes, spec or impl?\nNames: per type not per procedure\\\ndowngrading total to partial\\\n\\\n(*>*)\ntext \\\\\n(*<*)\nend\n(*>*)\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/l4v/tools/c-parser/Simpl/UserGuide.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.11920293140927592, "lm_q1q2_score": 0.05634525604188353}} {"text": "(* \nThis file is a part of IsarMathLib - \na library of formalized mathematics for Isabelle/Isar.\n\nCopyright (C) 2005, 2006 Slawomir Kolodynski\n\nThis program is free software; Redistribution and use in source and binary forms, \nwith or without modification, are permitted provided that the \nfollowing conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, \n this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright notice, \n this list of conditions and the following disclaimer in the documentation and/or \n other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products \n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED \nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF \nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. \nIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; \nOR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \nWHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \nOTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, \nEVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*)\n\nsection \\Abelian Group\\\n\ntheory AbelianGroup_ZF imports Group_ZF\n\nbegin\n\ntext\\A group is called ``abelian`` if its operation is commutative, i.e.\n $P\\langle a,b \\rangle = P\\langle a,b \\rangle$ for all group \n elements $a,b$, where $P$ is the group operation. It is customary\n to use the additive notation for abelian groups, so this condition\n is typically written as $a+b = b+a$. We will be using multiplicative \n notation though (in which the commutativity condition \n of the operation is written as $a\\cdot b = b\\cdot a$), just to avoid\n the hassle of changing the notation we used for general groups. \n\\\n\nsubsection\\Rearrangement formulae\\\n\ntext\\This section is not interesting and should not be read.\n Here we will prove formulas is which right hand side uses the same\n factors as the left hand side, just in different order. These facts\n are obvious in informal math sense, but Isabelle prover is not able\n to derive them automatically, so we have to prove them by hand. \n\\\n\ntext\\Proving the facts about associative and commutative operations is \n quite tedious in formalized mathematics. To a human the thing is simple:\n we can arrange the elements in any order and put parantheses wherever we \n want, it is all the same. However, formalizing this statement would be \n rather difficult (I think). The next lemma attempts a quasi-algorithmic\n approach to this type of problem. To prove that two expressions are equal, \n we first strip one from parantheses, then rearrange the elements in proper \n order, then put the parantheses where we want them to be. The algorithm for \n rearrangement is easy to describe: we keep putting the first element \n (from the right) that is in the wrong place at the left-most position\n until we get the proper arrangement. \n As far removing parantheses is concerned Isabelle does its job \n automatically.\\\n\nlemma (in group0) group0_4_L2:\n assumes A1:\"P {is commutative on} G\"\n and A2:\"a\\G\" \"b\\G\" \"c\\G\" \"d\\G\" \"E\\G\" \"F\\G\"\n shows \"(a\\b)\\(c\\d)\\(E\\F) = (a\\(d\\F))\\(b\\(c\\E))\"\nproof -\n from A2 have \"(a\\b)\\(c\\d)\\(E\\F) = a\\b\\c\\d\\E\\F\"\n using group_op_closed group_oper_assoc\n by simp\n also have \"a\\b\\c\\d\\E\\F = a\\d\\F\\b\\c\\E\"\n proof -\n from A1 A2 have \"a\\b\\c\\d\\E\\F = F\\(a\\b\\c\\d\\E)\"\n using IsCommutative_def group_op_closed \n by simp\n also from A2 have \"F\\(a\\b\\c\\d\\E) = F\\a\\b\\c\\d\\E\"\n using group_op_closed group_oper_assoc\n by simp\n also from A1 A2 have \"F\\a\\b\\c\\d\\E = d\\(F\\a\\b\\c)\\E\"\n using IsCommutative_def group_op_closed\n by simp\n also from A2 have \"d\\(F\\a\\b\\c)\\E = d\\F\\a\\b\\c\\E\"\n using group_op_closed group_oper_assoc\n by simp\n also from A1 A2 have \" d\\F\\a\\b\\c\\E = a\\(d\\F)\\b\\c\\E\"\n using IsCommutative_def group_op_closed\n by simp\n also from A2 have \"a\\(d\\F)\\b\\c\\E = a\\d\\F\\b\\c\\E\" \n using group_op_closed group_oper_assoc\n by simp\n finally show ?thesis by simp\n qed\n also from A2 have \"a\\d\\F\\b\\c\\E = (a\\(d\\F))\\(b\\(c\\E))\"\n using group_op_closed group_oper_assoc\n by simp\n finally show ?thesis by simp\nqed\n \ntext\\Another useful rearrangement.\\\n\nlemma (in group0) group0_4_L3:\n assumes A1:\"P {is commutative on} G\" \n and A2: \"a\\G\" \"b\\G\" and A3: \"c\\G\" \"d\\G\" \"E\\G\" \"F\\G\"\n shows \"a\\b\\((c\\d)\\\\(E\\F)\\) = (a\\(E\\c)\\)\\(b\\(F\\d)\\)\"\nproof -\n from A3 have T1:\n \"c\\\\G\" \"d\\\\G\" \"E\\\\G\" \"F\\\\G\" \"(c\\d)\\\\G\" \"(E\\F)\\\\G\"\n using inverse_in_group group_op_closed \n by auto\n from A2 T1 have \n \"a\\b\\((c\\d)\\\\(E\\F)\\) = a\\b\\(c\\d)\\\\(E\\F)\\\"\n using group_op_closed group_oper_assoc\n by simp\n also from A2 A3 have \n \"a\\b\\(c\\d)\\\\(E\\F)\\ = (a\\b)\\(d\\\\c\\)\\(F\\\\E\\)\"\n using group_inv_of_two by simp\n also from A1 A2 T1 have \n \"(a\\b)\\(d\\\\c\\)\\(F\\\\E\\) = (a\\(c\\\\E\\))\\(b\\(d\\\\F\\))\"\n using group0_4_L2 by simp\n also from A2 A3 have \n \"(a\\(c\\\\E\\))\\(b\\(d\\\\F\\)) = (a\\(E\\c)\\)\\(b\\(F\\d)\\)\"\n using group_inv_of_two by simp\n finally show ?thesis by simp\nqed\n\ntext\\Some useful rearrangements for two elements of a group.\\\n\nlemma (in group0) group0_4_L4:\n assumes A1:\"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\"\n shows \n \"b\\\\a\\ = a\\\\b\\\" \n \"(a\\b)\\ = a\\\\b\\\" \n \"(a\\b\\)\\ = a\\\\b\"\nproof -\n from A2 have T1: \"b\\\\G\" \"a\\\\G\" using inverse_in_group by auto\n with A1 show \"b\\\\a\\ = a\\\\b\\\" using IsCommutative_def by simp\n with A2 show \"(a\\b)\\ = a\\\\b\\\" using group_inv_of_two by simp\n from A2 T1 have \"(a\\b\\)\\ = (b\\)\\\\a\\\" using group_inv_of_two by simp\n with A1 A2 T1 show \"(a\\b\\)\\ = a\\\\b\" \n using group_inv_of_inv IsCommutative_def by simp\nqed\n \ntext\\Another bunch of useful rearrangements with three elements.\\\n\nlemma (in group0) group0_4_L4A: \n assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\"\n shows \n \"a\\b\\c = c\\a\\b\" \n \"a\\\\(b\\\\c\\)\\ = (a\\(b\\c)\\)\\\" \n \"a\\(b\\c)\\ = a\\b\\\\c\\\" \n \"a\\(b\\c\\)\\ = a\\b\\\\c\" \n \"a\\b\\\\c\\ = a\\c\\\\b\\\"\nproof -\n from A1 A2 have \"a\\b\\c = c\\(a\\b)\"\n using IsCommutative_def group_op_closed\n by simp\n with A2 show \"a\\b\\c = c\\a\\b\" using\n group_op_closed group_oper_assoc\n by simp\n from A2 have T: \n \"b\\\\G\" \"c\\\\G\" \"b\\\\c\\ \\ G\" \"a\\b \\ G\"\n using inverse_in_group group_op_closed\n by auto\n with A1 A2 show \"a\\\\(b\\\\c\\)\\ = (a\\(b\\c)\\)\\\"\n using group_inv_of_two IsCommutative_def \n by simp\n from A1 A2 T have \"a\\(b\\c)\\ = a\\(b\\\\c\\)\"\n using group_inv_of_two IsCommutative_def by simp\n with A2 T show \"a\\(b\\c)\\ = a\\b\\\\c\\\"\n using group_oper_assoc by simp\n from A1 A2 T have \"a\\(b\\c\\)\\ = a\\(b\\\\(c\\)\\)\"\n using group_inv_of_two IsCommutative_def by simp\n with A2 T show \"a\\(b\\c\\)\\ = a\\b\\\\c\"\n using group_oper_assoc group_inv_of_inv by simp\n from A1 A2 T have \"a\\b\\\\c\\ = a\\(c\\\\b\\)\"\n using group_oper_assoc IsCommutative_def by simp\n with A2 T show \"a\\b\\\\c\\ = a\\c\\\\b\\\"\n using group_oper_assoc by simp\nqed\n\ntext\\Another useful rearrangement.\\\n\nlemma (in group0) group0_4_L4B: \n assumes \"P {is commutative on} G\"\n and \"a\\G\" \"b\\G\" \"c\\G\"\n shows \"a\\b\\\\(b\\c\\) = a\\c\\\" \n using assms inverse_in_group group_op_closed \n group0_4_L4 group_oper_assoc inv_cancel_two by simp\n\ntext\\A couple of permutations of order for three alements.\\\n\nlemma (in group0) group0_4_L4C: \n assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\"\n shows\n \"a\\b\\c = c\\a\\b\"\n \"a\\b\\c = a\\(c\\b)\"\n \"a\\b\\c = c\\(a\\b)\"\n \"a\\b\\c = c\\b\\a\"\nproof -\n from A1 A2 show I: \"a\\b\\c = c\\a\\b\"\n using group0_4_L4A by simp\n also from A1 A2 have \"c\\a\\b = a\\c\\b\"\n using IsCommutative_def by simp\n also from A2 have \"a\\c\\b = a\\(c\\b)\"\n using group_oper_assoc by simp\n finally show \"a\\b\\c = a\\(c\\b)\" by simp\n from A2 I show \"a\\b\\c = c\\(a\\b)\"\n using group_oper_assoc by simp\n also from A1 A2 have \"c\\(a\\b) = c\\(b\\a)\"\n using IsCommutative_def by simp\n also from A2 have \"c\\(b\\a) = c\\b\\a\"\n using group_oper_assoc by simp\n finally show \"a\\b\\c = c\\b\\a\" by simp\nqed\n\ntext\\Some rearangement with three elements and inverse.\\\n\nlemma (in group0) group0_4_L4D:\n assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\"\n shows \n \"a\\\\b\\\\c = c\\a\\\\b\\\"\n \"b\\\\a\\\\c = c\\a\\\\b\\\"\n \"(a\\\\b\\c)\\ = a\\b\\\\c\\\"\nproof -\n from A2 have T: \n \"a\\ \\ G\" \"b\\ \\ G\" \"c\\\\G\"\n using inverse_in_group by auto\n with A1 A2 show \n \"a\\\\b\\\\c = c\\a\\\\b\\\"\n \"b\\\\a\\\\c = c\\a\\\\b\\\"\n using group0_4_L4A by auto\n from A1 A2 T show \"(a\\\\b\\c)\\ = a\\b\\\\c\\\"\n using group_inv_of_three group_inv_of_inv group0_4_L4C\n by simp\nqed\n\ntext\\Another rearrangement lemma with three elements and equation.\\\n\nlemma (in group0) group0_4_L5: assumes A1:\"P {is commutative on} G\" \n and A2: \"a\\G\" \"b\\G\" \"c\\G\"\n and A3: \"c = a\\b\\\"\n shows \"a = b\\c\"\nproof - \n from A2 A3 have \"c\\(b\\)\\ = a\"\n using inverse_in_group group0_2_L18\n by simp\n with A1 A2 show ?thesis using \n group_inv_of_inv IsCommutative_def by simp\nqed\n\ntext\\In abelian groups we can cancel an element with its inverse\n even if separated by another element.\\\n\nlemma (in group0) group0_4_L6A: assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\"\n shows \n \"a\\b\\a\\ = b\"\n \"a\\\\b\\a = b\"\n \"a\\\\(b\\a) = b\"\n \"a\\(b\\a\\) = b\"\nproof -\n from A1 A2 have \n \"a\\b\\a\\ = a\\\\a\\b\"\n using inverse_in_group group0_4_L4A by blast\n also from A2 have \"\\ = b\"\n using group0_2_L6 group0_2_L2 by simp\n finally show \"a\\b\\a\\ = b\" by simp\n from A1 A2 have \n \"a\\\\b\\a = a\\a\\\\b\"\n using inverse_in_group group0_4_L4A by blast\n also from A2 have \"\\ = b\"\n using group0_2_L6 group0_2_L2 by simp\n finally show \"a\\\\b\\a = b\" by simp\n moreover from A2 have \"a\\\\b\\a = a\\\\(b\\a)\"\n using inverse_in_group group_oper_assoc by simp\n ultimately show \"a\\\\(b\\a) = b\" by simp\n from A1 A2 show \"a\\(b\\a\\) = b\"\n using inverse_in_group IsCommutative_def inv_cancel_two\n by simp\nqed\n\ntext\\Another lemma about cancelling with two elements.\\\n\nlemma (in group0) group0_4_L6AA: \n assumes A1: \"P {is commutative on} G\" and A2: \"a\\G\" \"b\\G\"\n shows \"a\\b\\\\a\\ = b\\\"\n using assms inverse_in_group group0_4_L6A\n by auto\n\ntext\\Another lemma about cancelling with two elements.\\\n\nlemma (in group0) group0_4_L6AB: \n assumes A1: \"P {is commutative on} G\" and A2: \"a\\G\" \"b\\G\"\n shows \n \"a\\(a\\b)\\ = b\\\"\n \"a\\(b\\a\\) = b\"\nproof -\n from A2 have \"a\\(a\\b)\\ = a\\(b\\\\a\\)\"\n using group_inv_of_two by simp\n also from A2 have \"\\ = a\\b\\\\a\\\"\n using inverse_in_group group_oper_assoc by simp\n also from A1 A2 have \"\\ = b\\\"\n using group0_4_L6AA by simp\n finally show \"a\\(a\\b)\\ = b\\\" by simp\n from A1 A2 have \"a\\(b\\a\\) = a\\(a\\\\b)\"\n using inverse_in_group IsCommutative_def by simp\n also from A2 have \"\\ = b\"\n using inverse_in_group group_oper_assoc group0_2_L6 group0_2_L2\n by simp\n finally show \"a\\(b\\a\\) = b\" by simp\nqed\n\ntext\\Another lemma about cancelling with two elements.\\\n\nlemma (in group0) group0_4_L6AC: \n assumes \"P {is commutative on} G\" and \"a\\G\" \"b\\G\"\n shows \"a\\(a\\b\\)\\ = b\"\n using assms inverse_in_group group0_4_L6AB group_inv_of_inv\n by simp\n\n\ntext\\In abelian groups we can cancel an element with its inverse\n even if separated by two other elements.\\\n\nlemma (in group0) group0_4_L6B: assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\" \n shows \n \"a\\b\\c\\a\\ = b\\c\"\n \"a\\\\b\\c\\a = b\\c\"\nproof -\n from A2 have \n \"a\\b\\c\\a\\ = a\\(b\\c)\\a\\\"\n \"a\\\\b\\c\\a = a\\\\(b\\c)\\a\"\n using group_op_closed group_oper_assoc inverse_in_group\n by auto\n with A1 A2 show\n \"a\\b\\c\\a\\ = b\\c\"\n \"a\\\\b\\c\\a = b\\c\"\n using group_op_closed group0_4_L6A\n by auto\nqed\n\ntext\\In abelian groups we can cancel an element with its inverse\n even if separated by three other elements.\\\n\nlemma (in group0) group0_4_L6C: assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\" \"d\\G\"\n shows \"a\\b\\c\\d\\a\\ = b\\c\\d\" \nproof -\n from A2 have \"a\\b\\c\\d\\a\\ = a\\(b\\c\\d)\\a\\\"\n using group_op_closed group_oper_assoc\n by simp\n with A1 A2 show ?thesis \n using group_op_closed group0_4_L6A \n by simp\nqed\n\ntext\\Another couple of useful rearrangements of three elements\n and cancelling.\\\n\nlemma (in group0) group0_4_L6D: \n assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\"\n shows \n \"a\\b\\\\(a\\c\\)\\ = c\\b\\\"\n \"(a\\c)\\\\(b\\c) = a\\\\b\"\n \"a\\(b\\(c\\a\\\\b\\)) = c\"\n \"a\\b\\c\\\\(c\\a\\) = b\"\nproof -\n from A2 have T: \n \"a\\ \\ G\" \"b\\ \\ G\" \"c\\ \\ G\" \n \"a\\b \\ G\" \"a\\b\\ \\ G\" \"c\\\\a\\ \\ G\" \"c\\a\\ \\ G\"\n using inverse_in_group group_op_closed by auto\n with A1 A2 show \"a\\b\\\\(a\\c\\)\\ = c\\b\\\"\n using group0_2_L12 group_oper_assoc group0_4_L6B\n IsCommutative_def by simp\n from A2 T have \"(a\\c)\\\\(b\\c) = c\\\\a\\\\b\\c\"\n using group_inv_of_two group_oper_assoc by simp\n also from A1 A2 T have \"\\ = a\\\\b\"\n using group0_4_L6B by simp\n finally show \"(a\\c)\\\\(b\\c) = a\\\\b\"\n by simp\n from A1 A2 T show \"a\\(b\\(c\\a\\\\b\\)) = c\"\n using group_oper_assoc group0_4_L6B group0_4_L6A\n by simp\n from T have \"a\\b\\c\\\\(c\\a\\) = a\\b\\(c\\\\(c\\a\\))\"\n using group_oper_assoc by simp\n also from A1 A2 T have \"\\ = b\"\n using group_oper_assoc group0_2_L6 group0_2_L2 group0_4_L6A\n by simp\n finally show \"a\\b\\c\\\\(c\\a\\) = b\" by simp\nqed\n\ntext\\Another useful rearrangement of three elements\n and cancelling.\\\n\nlemma (in group0) group0_4_L6E: \n assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\"\n shows \n \"a\\b\\(a\\c)\\ = b\\c\\\"\nproof -\n from A2 have T: \"b\\ \\ G\" \"c\\ \\ G\"\n using inverse_in_group by auto\n with A1 A2 have\n \"a\\(b\\)\\\\(a\\(c\\)\\)\\ = c\\\\(b\\)\\\"\n using group0_4_L6D by simp\n with A1 A2 T show \"a\\b\\(a\\c)\\ = b\\c\\\"\n using group_inv_of_inv IsCommutative_def\n by simp\nqed\n\ntext\\A rearrangement with two elements and canceelling,\n special case of \\group0_4_L6D\\ when $c=b^{-1}$.\\\n\nlemma (in group0) group0_4_L6F: \n assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\"\n shows \"a\\b\\\\(a\\b)\\ = b\\\\b\\\"\nproof -\n from A2 have \"b\\ \\ G\" \n using inverse_in_group by simp\n with A1 A2 have \"a\\b\\\\(a\\(b\\)\\)\\ = b\\\\b\\\"\n using group0_4_L6D by simp\n with A2 show \"a\\b\\\\(a\\b)\\ = b\\\\b\\\"\n using group_inv_of_inv by simp\nqed\n\ntext\\Some other rearrangements with four elements.\n The algorithm for proof as in \\group0_4_L2\\\n works very well here.\\\n\nlemma (in group0) rearr_ab_gr_4_elemA:\n assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\" \"d\\G\"\n shows \n \"a\\b\\c\\d = a\\d\\b\\c\"\n \"a\\b\\c\\d = a\\c\\(b\\d)\"\nproof -\n from A1 A2 have \"a\\b\\c\\d = d\\(a\\b\\c)\"\n using IsCommutative_def group_op_closed\n by simp\n also from A2 have \"\\ = d\\a\\b\\c\"\n using group_op_closed group_oper_assoc\n by simp\n also from A1 A2 have \"\\ = a\\d\\b\\c\"\n using IsCommutative_def group_op_closed\n by simp\n finally show \"a\\b\\c\\d = a\\d\\b\\c\"\n by simp\n from A1 A2 have \"a\\b\\c\\d = c\\(a\\b)\\d\"\n using IsCommutative_def group_op_closed\n by simp\n also from A2 have \"\\ = c\\a\\b\\d\"\n using group_op_closed group_oper_assoc\n by simp\n also from A1 A2 have \"\\ = a\\c\\b\\d\"\n using IsCommutative_def group_op_closed\n by simp\n also from A2 have \"\\ = a\\c\\(b\\d)\"\n using group_op_closed group_oper_assoc\n by simp\n finally show \"a\\b\\c\\d = a\\c\\(b\\d)\"\n by simp\nqed\n\ntext\\Some rearrangements with four elements and inverse\n that are applications of \\rearr_ab_gr_4_elem\\ \n\\\n\nlemma (in group0) rearr_ab_gr_4_elemB:\n assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\" \"d\\G\"\n shows \n \"a\\b\\\\c\\\\d\\ = a\\d\\\\b\\\\c\\\"\n \"a\\b\\c\\d\\ = a\\d\\\\b\\c\"\n \"a\\b\\c\\\\d\\ = a\\c\\\\(b\\d\\)\"\nproof -\n from A2 have T: \"b\\ \\ G\" \"c\\ \\ G\" \"d\\ \\ G\"\n using inverse_in_group by auto\n with A1 A2 show \n \"a\\b\\\\c\\\\d\\ = a\\d\\\\b\\\\c\\\"\n \"a\\b\\c\\d\\ = a\\d\\\\b\\c\"\n \"a\\b\\c\\\\d\\ = a\\c\\\\(b\\d\\)\"\n using rearr_ab_gr_4_elemA by auto\nqed\n \ntext\\Some rearrangement lemmas with four elements.\\\n \nlemma (in group0) group0_4_L7: \n assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\" \"d\\G\"\n shows \n \"a\\b\\c\\d\\ = a\\d\\\\ b\\c\" \n \"a\\d\\(b\\d\\(c\\d))\\ = a\\(b\\c)\\\\d\\\"\n \"a\\(b\\c)\\d = a\\b\\d\\c\"\nproof -\n from A2 have T:\n \"b\\c \\ G\" \"d\\ \\ G\" \"b\\\\G\" \"c\\\\G\" \n \"d\\\\b \\ G\" \"c\\\\d \\ G\" \"(b\\c)\\ \\ G\"\n \"b\\d \\ G\" \"b\\d\\c \\ G\" \"(b\\d\\c)\\ \\ G\"\n \"a\\d \\ G\" \"b\\c \\ G\"\n using group_op_closed inverse_in_group \n by auto\n with A1 A2 have \"a\\b\\c\\d\\ = a\\(d\\\\b\\c)\"\n using group_oper_assoc group0_4_L4A by simp\n also from A2 T have \"a\\(d\\\\b\\c) = a\\d\\\\b\\c\"\n using group_oper_assoc by simp \n finally show \"a\\b\\c\\d\\ = a\\d\\\\ b\\c\" by simp\n from A2 T have \"a\\d\\(b\\d\\(c\\d))\\ = a\\d\\(d\\\\(b\\d\\c)\\)\"\n using group_oper_assoc group_inv_of_two by simp\n also from A2 T have \"\\ = a\\(b\\d\\c)\\\"\n using group_oper_assoc inv_cancel_two by simp\n also from A1 A2 have \"\\ = a\\(d\\(b\\c))\\\"\n using IsCommutative_def group_oper_assoc by simp\n also from A2 T have \"\\ = a\\((b\\c)\\\\d\\)\"\n using group_inv_of_two by simp\n also from A2 T have \"\\ = a\\(b\\c)\\\\d\\\"\n using group_oper_assoc by simp\n finally show \"a\\d\\(b\\d\\(c\\d))\\ = a\\(b\\c)\\\\d\\\"\n by simp\n from A2 have \"a\\(b\\c)\\d = a\\(b\\(c\\d))\"\n using group_op_closed group_oper_assoc by simp\n also from A1 A2 have \"\\ = a\\(b\\(d\\c))\"\n using IsCommutative_def group_op_closed by simp\n also from A2 have \"\\ = a\\b\\d\\c\"\n using group_op_closed group_oper_assoc by simp\n finally show \"a\\(b\\c)\\d = a\\b\\d\\c\" by simp\nqed\n\ntext\\Some other rearrangements with four elements.\\\n\nlemma (in group0) group0_4_L8: \n assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\" \"d\\G\"\n shows \n \"a\\(b\\c)\\ = (a\\d\\\\c\\)\\(d\\b\\)\"\n \"a\\b\\(c\\d) = c\\a\\(b\\d)\"\n \"a\\b\\(c\\d) = a\\c\\(b\\d)\"\n \"a\\(b\\c\\)\\d = a\\b\\d\\c\\\"\n \"(a\\b)\\(c\\d)\\\\(b\\d\\)\\ = a\\c\\\"\nproof -\n from A2 have T:\n \"b\\c \\ G\" \"a\\b \\ G\" \"d\\ \\ G\" \"b\\\\G\" \"c\\\\G\" \n \"d\\\\b \\ G\" \"c\\\\d \\ G\" \"(b\\c)\\ \\ G\"\n \"a\\b \\ G\" \"(c\\d)\\ \\ G\" \"(b\\d\\)\\ \\ G\" \"d\\b\\ \\ G\"\n using group_op_closed inverse_in_group \n by auto\n from A2 have \"a\\(b\\c)\\ = a\\c\\\\b\\\" using group0_2_L14A by blast\n moreover from A2 have \"a\\c\\ = (a\\d\\)\\(d\\c\\)\" using group0_2_L14A\n by blast\n ultimately have \"a\\(b\\c)\\ = (a\\d\\)\\(d\\c\\)\\b\\\" by simp\n with A1 A2 T have \"a\\(b\\c)\\= a\\d\\\\(c\\\\d)\\b\\\"\n using IsCommutative_def by simp\n with A2 T show \"a\\(b\\c)\\ = (a\\d\\\\c\\)\\(d\\b\\)\"\n using group_op_closed group_oper_assoc by simp\n from A2 T have \"a\\b\\(c\\d) = a\\b\\c\\d\"\n using group_oper_assoc by simp\n also have \"a\\b\\c\\d = c\\a\\b\\d\"\n proof -\n from A1 A2 have \"a\\b\\c\\d = c\\(a\\b)\\d\"\n using IsCommutative_def group_op_closed\n by simp\n also from A2 have \"\\ = c\\a\\b\\d\"\n using group_op_closed group_oper_assoc\n by simp\n finally show ?thesis by simp\n qed\n also from A2 have \"c\\a\\b\\d = c\\a\\(b\\d)\"\n using group_op_closed group_oper_assoc\n by simp\n finally show \"a\\b\\(c\\d) = c\\a\\(b\\d)\" by simp\n with A1 A2 show \"a\\b\\(c\\d) = a\\c\\(b\\d)\"\n using IsCommutative_def by simp\n from A1 A2 T show \"a\\(b\\c\\)\\d = a\\b\\d\\c\\\"\n using group0_4_L7 by simp\n from T have \"(a\\b)\\(c\\d)\\\\(b\\d\\)\\ = (a\\b)\\((c\\d)\\\\(b\\d\\)\\)\"\n using group_oper_assoc by simp\n also from A1 A2 T have \"\\ = (a\\b)\\(c\\\\d\\\\(d\\b\\))\"\n using group_inv_of_two group0_2_L12 IsCommutative_def\n by simp\n also from T have \"\\ = (a\\b)\\(c\\\\(d\\\\(d\\b\\)))\"\n using group_oper_assoc by simp\n also from A1 A2 T have \"\\ = a\\c\\\"\n using group_oper_assoc group0_2_L6 group0_2_L2 IsCommutative_def\n inv_cancel_two by simp\n finally show \"(a\\b)\\(c\\d)\\\\(b\\d\\)\\ = a\\c\\\"\n by simp\nqed\n\n\ntext\\Some other rearrangements with four elements.\\\n\nlemma (in group0) group0_4_L8A: \n assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\" \"d\\G\"\n shows \n \"a\\b\\\\(c\\d\\) = a\\c\\(b\\\\d\\)\"\n \"a\\b\\\\(c\\d\\) = a\\c\\b\\\\d\\\"\nproof -\n from A2 have \n T: \"a\\G\" \"b\\ \\ G\" \"c\\G\" \"d\\ \\ G\"\n using inverse_in_group by auto\n with A1 show \"a\\b\\\\(c\\d\\) = a\\c\\(b\\\\d\\)\"\n by (rule group0_4_L8)\n with A2 T show \"a\\b\\\\(c\\d\\) = a\\c\\b\\\\d\\\"\n using group_op_closed group_oper_assoc\n by simp\nqed\n\ntext\\Some rearrangements with an equation.\\\n\nlemma (in group0) group0_4_L9:\n assumes A1: \"P {is commutative on} G\"\n and A2: \"a\\G\" \"b\\G\" \"c\\G\" \"d\\G\"\n and A3: \"a = b\\c\\\\d\\\"\n shows \n \"d = b\\a\\\\c\\\"\n \"d = a\\\\b\\c\\\"\n \"b = a\\d\\c\"\nproof -\n from A2 have T: \n \"a\\ \\ G\" \"c\\ \\ G\" \"d\\ \\ G\" \"b\\c\\ \\ G\"\n using group_op_closed inverse_in_group \n by auto\n with A2 A3 have \"a\\(d\\)\\ = b\\c\\\"\n using group0_2_L18 by simp\n with A2 have \"b\\c\\ = a\\d\"\n using group_inv_of_inv by simp\n with A2 T have I: \"a\\\\(b\\c\\) = d\"\n using group0_2_L18 by simp\n with A1 A2 T show \n \"d = b\\a\\\\c\\\"\n \"d = a\\\\b\\c\\\"\n using group_oper_assoc IsCommutative_def by auto\n from A3 have \"a\\d\\c = (b\\c\\\\d\\)\\d\\c\" by simp\n also from A2 T have \"\\ = b\\c\\\\(d\\\\d)\\c\"\n using group_oper_assoc by simp\n also from A2 T have \"\\ = b\\c\\\\c\"\n using group0_2_L6 group0_2_L2 by simp\n also from A2 T have \"\\ = b\\(c\\\\c)\"\n using group_oper_assoc by simp\n also from A2 have \"\\ = b\"\n using group0_2_L6 group0_2_L2 by simp\n finally have \"a\\d\\c = b\" by simp\n thus \"b = a\\d\\c\" by simp\nqed\n\nend\n", "meta": {"author": "SKolodynski", "repo": "IsarMathLib", "sha": "879c6b779ca00364879aa0232b0aa9f18bafa85a", "save_path": "github-repos/isabelle/SKolodynski-IsarMathLib", "path": "github-repos/isabelle/SKolodynski-IsarMathLib/IsarMathLib-879c6b779ca00364879aa0232b0aa9f18bafa85a/IsarMathLib/AbelianGroup_ZF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.13117323564948066, "lm_q1q2_score": 0.055921982721693825}} {"text": "(* Author: Norbert Schirmer\n Maintainer: Norbert Schirmer, norbert.schirmer at web de\n License: LGPL\n*)\n\n(* Title: UserGuide.thy\n Author: Norbert Schirmer, TU Muenchen\n\nCopyright (C) 2004-2008 Norbert Schirmer \nSome rights reserved, TU Muenchen\n\nThis library is free software; you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation; either version 2.1 of the\nLicense, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307\nUSA\n*)\n\nsection \\User Guide \\label{sec:UserGuide}\\\n(*<*)\ntheory UserGuide \nimports HeapList Vcg\n \"HOL-Statespace.StateSpaceSyntax\" \"HOL-Library.LaTeXsugar\"\nbegin \n(*>*)\n\n(*<*)\nsyntax\n \"_statespace_updates\" :: \"('a \\ 'b) \\ updbinds \\ ('a \\ 'b)\" (\"_\\_\\\" [900,0] 900)\n(*>*)\n\n\n\ntext \\\nWe introduce the verification environment with a couple\nof examples that illustrate how to use the different\nbits and pieces to verify programs. \n\\\n\n\nsubsection \\Basics\\\n\ntext \\\n\nFirst of all we have to decide how to represent the state space. There\nare currently two implementations. One is based on records the other\none on the concept called `statespace' that was introduced with\nIsabelle 2007 (see \\texttt{HOL/Statespace}) . In contrast to records a \n'satespace' does not define a new type, but provides a notion of state, \nbased on locales. Logically\nthe state is modelled as a function from (abstract) names to\n(abstract) values and the statespace infrastructure organises\ndistinctness of names an projection/injection of concrete values into\nthe abstract one. Towards the user the interface of records and\nstatespaces is quite similar. However, statespaces offer more\nflexibility, inherited from the locale infrastructure, in\nparticular multiple inheritance and renaming of components.\n\nIn this user guide we prefer statespaces, but give some comments on\nthe usage of records in Section \\ref{sec:records}. \n\n\n\\\n\nhoarestate vars = \n A :: nat\n I :: nat\n M :: nat\n N :: nat\n R :: nat\n S :: nat\n\ntext (in vars) \\The command \\isacommand{hoarestate} is a simple preprocessor\nfor the command \\isacommand{statespaces} which decorates the state\ncomponents with the suffix \\_'\\, to avoid cluttering the\nnamespace. Also note that underscores are printed as hyphens in this\ndocumentation. So what you see as @{term \"A_'\"} in this document is\nactually \\texttt{A\\_'}. Every component name becomes a fixed variable in\nthe locale \\vars\\ and can no longer be used for logical\nvariables. \n\nLookup of a component @{term \"A_'\"} in a state @{term \"s\"} is written as\n@{term \"s\\A_'\"}, and update with a value @{term \"term v\"} as @{term \"s\\A_' := v\\\"}.\n\nTo deal with local and global variables in the context of procedures the\nprogram state is organised as a record containing the two componets @{const \"locals\"} \nand @{const \"globals\"}. The variables defined in hoarestate \\vars\\ reside\nin the @{const \"locals\"} part.\n\n\\\n\ntext \\\n Here is a first example.\n\\\n\nlemma (in vars) \"\\\\ \\\\N = 5\\ \\N :== 2 * \\N \\\\N = 10\\\"\n apply vcg\n txt \\@{subgoals}\\\n apply simp\n txt \\@{subgoals}\\\n done\n\ntext \\We enable the locale of statespace \\vars\\ by the\n\\texttt{in vars} directive. The verification condition generator is\ninvoked via the \\vcg\\ method and leaves us with the expected\nsubgoal that can be proved by simplification.\\\n\ntext (in vars) \\\n If we refer to components (variables) of the state-space of the program\n we always mark these with \\\\\\ (in assertions and also in the\n program itself). It is the acute-symbol and is present on\n most keyboards. The assertions of the Hoare tuple are\n ordinary Isabelle sets. As we usually want to refer to the state space\n in the assertions, we provide special brackets for them. They can be written \n as {\\verb+{| |}+} in ASCII or \\\\ \\\\ with symbols. Internally,\n marking variables has two effects. First of all we refer to the implicit\n state and secondary we get rid of the suffix \\_'\\.\n So the assertion @{term \"{|\\N = 5|}\"} internally gets expanded to \n \\{s. locals s \\N_' = 5}\\ written in ordinary set comprehension notation of\n Isabelle. It describes the set of states where the \\N_'\\ component\n is equal to \\5\\. \n An empty context and an empty postcondition for abrupt termination can be\n omitted. The lemma above is a shorthand for \n \\\\,{}\\ \\\\N = 5\\ \\N :== 2 * \\N \\\\N = 10\\,{}\\.\n\\\n\ntext \\We can step through verification condition generation by the\nmethod \\vcg_step\\.\n\\\n\nlemma (in vars) \"\\,{}\\ \\\\N = 5\\ \\N :== 2 * \\N \\\\N = 10\\\"\n apply vcg_step\n txt \\@{subgoals}\\\n txt \\The last step of verification condition generation, \n transforms the inclusion of state sets to the corresponding \n predicate on components of the state space. \n\\\n apply vcg_step\n txt \\@{subgoals}\\\n by simp\n\ntext \\\nAlthough our assertions work semantically on the state space, stepping\nthrough verification condition generation ``feels'' like the expected\nsyntactic substitutions of traditional Hoare logic. This is achieved\nby light simplification on the assertions calculated by the Hoare rules.\n\\\n\nlemma (in vars) \"\\\\ \\\\N = 5\\ \\N :== 2 * \\N \\\\N = 10\\\"\n apply (rule HoarePartial.Basic)\n txt \\@{subgoals}\\\n apply (simp only: mem_Collect_eq)\n txt \\@{subgoals}\\\n apply (tactic \n \\Hoare.BasicSimpTac @{context} Hoare.Function false\n [] (K all_tac) 1\\)\n txt \\@{subgoals}\\\n by simp\n\n\ntext \\The next example shows how we deal with the while loop. Note the\ninvariant annotation.\n\\\n\nlemma (in vars) \n \"\\,{}\\ \\\\M = 0 \\ \\S = 0\\\n WHILE \\M \\ a\n INV \\\\S = \\M * b\\\n DO \\S :== \\S + b;; \\M :== \\M + 1 OD\n \\\\S = a * b\\\"\n apply vcg\n txt \\@{subgoals [display]}\\\n txt \\The verification condition generator gives us three proof obligations,\n stemming from the path from the precondition to the invariant,\n from the invariant together with loop condition through the\n loop body to the invariant, and finally from the invariant together\n with the negated loop condition to the postcondition.\\\n apply auto\n done\n\nsubsection \\Procedures\\\n\nsubsubsection \\Declaration\\\n\ntext \\\nOur first procedure is a simple square procedure. We provide the\ncommand \\isacommand{procedures}, to declare and define a\nprocedure.\n\\\n\nprocedures\n Square (N::nat|R::nat) \n where I::nat in\n \"\\R :== \\N * \\N\"\n \n\n\ntext \\A procedure is given by the signature of the procedure\nfollowed by the procedure body. The signature consists of the name of\nthe procedure and a list of parameters together with their types. The\nparameters in front of the pipe \\|\\ are value parameters and\nbehind the pipe are the result parameters. Value parameters model call\nby value semantics. The value of a result parameter at the end of the\nprocedure is passed back to the caller. Local variables follow the\n\\where\\. If there are no local variables the \\where \\\nin\\ can be omitted. The variable @{term \"I\"} is actually unused in\nthe body, but is used in the examples below.\\\n\n\ntext \\\nThe procedures command provides convenient syntax\nfor procedure calls (that creates the proper @{term init}, @{term return} and\n@{term result} functions on the fly) and creates locales and statespaces to \nreason about the procedure. The purpose of locales is to set up logical contexts\nto support modular reasoning. Locales can be seen as freeze-dried proof contexts that\nget alive as you setup a new lemma or theorem (\\cite{Ballarin-04-locales}).\nThe locale the user deals with is named \\Square_impl\\.\n It defines the procedure name (internally @{term \"Square_'proc\"}), the procedure body \n(named \\Square_body\\) and the statespaces for parameters and local and\nglobal variables.\nMoreover it contains the \nassumption @{term \"\\ Square_'proc = Some Square_body\"}, which states \nthat the procedure is properly defined in the procedure context. \n\nThe purpose of the locale is to give us easy means to setup the context \nin which we prove programs correct. \nIn this locale the procedure context @{term \"\\\"} is fixed. \nSo we always use this letter for the procedure\nspecification. This is crucial, if we prove programs under the\nassumption of some procedure specifications.\n\\\n\n(*<*)\ncontext Square_impl\nbegin\n(*>*)\ntext \\The procedures command generates syntax, so that we can \neither write \\CALL Square(\\I,\\R)\\ or @{term \"\\I :== CALL\nSquare(\\R)\"} for the procedure call. The internal term is the\nfollowing: \n\\ \n\n(*<*) declare [[hoare_use_call_tr' = false]] (*>*) \ntext \\\\small @{term [display] \"CALL Square(\\I,\\R)\"}\\ \n(*<*) declare [[hoare_use_call_tr' = true]] (*>*)\n\ntext \\Note the\n additional decoration (with the procedure name) of the parameter and\n local variable names.\\\n(*<*)\nend \n(*>*)\n\ntext \\The abstract syntax for the\nprocedure call is @{term \"call init p return result\"}. The @{term\n\"init\"} function copies the values of the actual parameters to the\nformal parameters, the @{term return} function copies the global\nvariables back (in our case there are no global variables), and the\n@{term \"result\"} function additionally copies the values of the formal\nresult parameters to the actual locations. Actual value parameters can\nbe all kind of expressions, since we only need their value. But result\nparameters must be proper ``lvalues'': variables (including\ndereferenced pointers) or array locations, since we have to assign\nvalues to them. \n\\\n\nsubsubsection \\Verification\\\n\ntext (in Square_impl) \\\nA procedure specification is an ordinary Hoare tuple. \nWe use the parameterless\ncall for the specification; \\\\R :== PROC Square(\\N)\\ is syntactic sugar\nfor \\Call Square_'proc\\. This emphasises that the specification \ndescribes the internal behaviour of the procedure, whereas parameter passing\ncorresponds to the procedure call.\nThe following precondition fixes the current value \\\\N\\ to the logical \nvariable @{term n}. \nUniversal quantification of @{term \"n\"} enables us to adapt \nthe specification to an actual parameter. The specification is\nused in the rule for procedure call when we come upon a call to @{term Square}. \nThus @{term \"n\"} plays the role of the auxiliary variable @{term \"Z\"}.\n\\\n\n\ntext \\To verify the procedure we need to verify the body. We use\na derived variant of the general recursion rule, tailored for non recursive procedures:\n@{thm [source] HoarePartial.ProcNoRec1}:\n\\begin{center}\n@{thm [mode=Rule,mode=ParenStmt] HoarePartial.ProcNoRec1 [no_vars]}\n\\end{center}\nThe naming convention for the rule \nis the following: The \\1\\ expresses that we look at one\n procedure, and \\NoRec\\ that the procedure is non\nrecursive. \n\\ \n\n\nlemma (in Square_impl)\nshows \"\\n. \\\\\\\\N = n\\ \\R :== PROC Square(\\N) \\\\R = n * n\\\"\ntxt \\The directive \\in\\ has the effect that\nthe context of the locale @{term \"Square_impl\"} is included to the current\nlemma, and that the lemma is added as a fact to the locale, after it is proven. The\nnext time locale @{term \"Square_impl\"} is invoked this lemma is immediately available\nas fact, which the verification condition generator can use.\n\\\napply (hoare_rule HoarePartial.ProcNoRec1)\n txt \"@{subgoals[display]}\"\n txt \\The method \\hoare_rule\\, like \\rule\\ applies a \n single rule, but additionally does some ``obvious'' steps:\n It solves the canonical side-conditions of various Hoare-rules and it \n automatically expands the\n procedure body: With @{thm [source] Square_impl}: @{thm [names_short] Square_impl [no_vars]} we\n get the procedure body out of the procedure context @{term \"\\\"}; \n with @{thm [source] Square_body_def}: @{thm [names_short] Square_body_def [no_vars]} we\n can unfold the definition of the body.\n\n The proof is finished by the vcg and simp.\n\\\ntxt \"@{subgoals[display]}\"\nby vcg simp\n\ntext \\If the procedure is non recursive and there is no specification given, the\nverification condition generator automatically expands the body.\\\n\nlemma (in Square_impl) Square_spec: \nshows \"\\n. \\\\\\\\N = n\\ \\R :== PROC Square(\\N) \\\\R = n * n\\\"\n by vcg simp\n\ntext \\An important naming convention is to name the specification as\n\\_spec\\. The verification condition generator refers to\nthis name in order to search for a specification in the theorem database.\n\\\n\nsubsubsection \\Usage\\\n\n\ntext\\Let us see how we can use procedure specifications.\\\n(* FIXME: maybe don't show this at all *)\nlemma (in Square_impl)\n shows \"\\\\\\\\I = 2\\ \\R :== CALL Square(\\I) \\\\R = 4\\\"\n txt \\Remember that we have already proven @{thm [source] \"Square_spec\"} in the locale\n \\Square_impl\\. This is crucial for \n verification condition generation. When reaching a procedure call,\n it looks for the specification (by its name) and applies the\n rule @{thm [source,mode=ParenStmt] HoarePartial.ProcSpec} \ninstantiated with the specification\n (as last premise). \n Before we apply the verification condition generator, let us\n take some time to think of what we can expect.\n Let's look at the specification @{thm [source] Square_spec} again:\n @{thm [display] Square_spec [no_vars]}\n The specification talks about the formal parameters @{term \"N\"} and \n @{term R}. The precondition @{term \"\\\\N = n\\\"} just fixes the initial\n value of \\N\\.\n The actual parameters are @{term \"I\"} and @{term \"R\"}. We \n have to adapt the specification to this calling context.\n @{term \"\\n. \\\\ \\\\I = n\\ \\R :== CALL Square(\\I) \\\\R = n * n\\\"}.\n From the postcondition @{term \"\\\\R = n * n\\\"} we \n have to derive the actual postcondition @{term \"\\\\R = 4\\\"}. So\n we gain something like: @{term \"\\n * n = (4::nat)\\\"}.\n The precondition is @{term \"\\\\I = 2\\\"} and the specification \n tells us @{term \"\\\\I = n\\\"} for the pre-state. So the value of @{term n}\n is the value of @{term I} in the pre-state. So we arrive at\n @{term \"\\\\I = 2\\ \\ \\\\I * \\I = 4\\\"}.\n\\\n apply vcg_step\n txt \"@{subgoals[display]}\"\n txt \\\n The second set looks slightly more involved:\n @{term \"\\\\t. \\<^bsup>t\\<^esup>R = \\I * \\I \\ \\I * \\I = 4\\\"}, this is an artefact from the\n procedure call rule. Originally \\\\I * \\I = 4\\ was \\\\<^bsup>t\\<^esup>R = 4\\. Where\n @{term \"t\"} denotes the final state of the procedure and the superscript notation\n allows to select a component from a particular state. \n\\\n apply vcg_step\n txt \"@{subgoals[display]}\"\n by simp\n \ntext \\\nThe adaption of the procedure specification to the actual calling \ncontext is done due to the @{term init}, @{term return} and @{term result} functions \nin the rule @{thm [source] HoarePartial.ProcSpec} (or in the variant \n@{thm [source] HoarePartial.ProcSpecNoAbrupt} which already\nincorporates the fact that the postcondition for abrupt termination\nis the empty set). For the readers interested in the internals, \nhere a version without vcg.\n\\\nlemma (in Square_impl)\n shows \"\\\\\\\\I = 2\\ \\R :== CALL Square(\\I) \\\\R = 4\\\"\n apply (rule HoarePartial.ProcSpecNoAbrupt [OF _ _ Square_spec])\n txt \"@{subgoals[display]}\"\n txt \\This is the raw verification condition, \n It is interesting to see how the auxiliary variable @{term \"Z\"} is\n actually used. It is unified with @{term n} of the specification and\n fixes the state after parameter passing. \n\\\n apply simp\n txt \"@{subgoals[display]}\"\n prefer 2\n apply vcg_step\n txt \"@{subgoals[display]}\"\n apply (auto intro: ext)\n done\n\n\n\nsubsubsection \\Recursion\\\n\ntext \\We want to define a procedure for the factorial. We first\ndefine a HOL function that calculates it, to specify the procedure later on.\n\\\n\nprimrec fac:: \"nat \\ nat\"\nwhere\n\"fac 0 = 1\" |\n\"fac (Suc n) = (Suc n) * fac n\"\n\n(*<*)\nlemma fac_simp [simp]: \"0 < i \\ fac i = i * fac (i - 1)\"\n by (cases i) simp_all\n(*>*)\n\ntext \\Now we define the procedure.\\\nprocedures\n Fac (N::nat | R::nat) \n \"IF \\N = 0 THEN \\R :== 1\n ELSE \\R :== CALL Fac(\\N - 1);;\n \\R :== \\N * \\R\n FI\"\n \ntext \\\nNow let us prove that our implementation of @{term \"Fac\"} meets its specification. \n\\\n\nlemma (in Fac_impl)\nshows \"\\n. \\\\ \\\\N = n\\ \\R :== PROC Fac(\\N) \\\\R = fac n\\\"\napply (hoare_rule HoarePartial.ProcRec1)\ntxt \"@{subgoals[display]}\"\napply vcg\ntxt \"@{subgoals[display]}\"\napply simp\ndone\n\ntext \\\nSince the factorial is implemented recursively,\nthe main ingredient of this proof is, to assume that the specification holds for \nthe recursive call of @{term Fac} and prove the body correct.\nThe assumption for recursive calls is added to the context by\nthe rule @{thm [source] HoarePartial.ProcRec1} \n(also derived from the general rule for mutually recursive procedures):\n\\begin{center}\n@{thm [mode=Rule,mode=ParenStmt] HoarePartial.ProcRec1 [no_vars]}\n\\end{center}\nThe verification condition generator infers the specification out of the\ncontext @{term \"\\\"} when it encounters a recursive call of the factorial.\n\\\n\nsubsection \\Global Variables and Heap \\label{sec:VcgHeap}\\\n\ntext \\\nNow we define and verify some procedures on heap-lists. We consider\nlist structures consisting of two fields, a content element @{term \"cont\"} and\na reference to the next list element @{term \"next\"}. We model this by the \nfollowing state space where every field has its own heap.\n\\\n\nhoarestate globals_heap =\n \"next\" :: \"ref \\ ref\"\n cont :: \"ref \\ nat\"\n\ntext \\It is mandatory to start the state name with `globals'. This is exploited\nby the syntax translations to store the components in the @{const globals} part\nof the state.\n\\\n\ntext \\Updates to global components inside a procedure are\nalways propagated to the caller. This is implicitly done by the\nparameter passing syntax translations. \n\\\n\ntext \\We first define an append function on lists. It takes two \nreferences as parameters. It appends the list referred to by the first\nparameter with the list referred to by the second parameter. The statespace\nof the global variables has to be imported.\n\\\n\nprocedures (imports globals_heap)\n append(p :: ref, q::ref | p::ref) \n \"IF \\p=Null THEN \\p :== \\q \n ELSE \\p\\\\next :== CALL append(\\p\\\\next,\\q) FI\"\n\n(*<*)\ncontext append_impl\nbegin\n(*>*)\ntext \\\nThe difference of a global and a local variable is that global\nvariables are automatically copied back to the procedure caller.\nWe can study this effect on the translation of @{term \"\\p :== CALL append(\\p,\\q)\"}:\n\\\n(*<*)\ndeclare [[hoare_use_call_tr' = false]]\n(*>*)\ntext \\\n@{term [display] \"\\p :== CALL append(\\p,\\q)\"}\n\\\n(*<*)\ndeclare [[hoare_use_call_tr' = true]]\nend\n(*>*)\n\ntext \\Below we give two specifications this time.\nOne captures the functional behaviour and focuses on the\nentities that are potentially modified by the procedure, the second one\nis a pure frame condition. \n\\\n\n\n\ntext \\\nThe functional specification below introduces two logical variables besides the\nstate space variable @{term \"\\\"}, namely @{term \"Ps\"} and @{term \"Qs\"}.\nThey are universally quantified and range over both the pre-and the postcondition, so \nthat we are able to properly instantiate the specification\nduring the proofs. The syntax \\\\\\. \\\\\\ is a shorthand to fix the current \nstate: \\{s. \\ = s \\}\\. Moreover \\\\<^bsup>\\\\<^esup>x\\ abbreviates \nthe lookup of variable \\x\\ in the state \n\\\\\\. \n\nThe approach to specify procedures on lists\nbasically follows \\cite{MehtaN-CADE03}. From the pointer structure\nin the heap we (relationally) abstract to HOL lists of references. Then\nwe can specify further properties on the level of HOL lists, rather then \non the heap. The basic abstractions are: \n\n@{thm [display] Path.simps [no_vars]}\n\n@{term [show_types] \"Path x h y ps\"}: @{term ps} is a list of references that we can obtain\nout of the heap @{term h} by starting with the reference @{term x}, following\nthe references in @{term h} up to the reference @{term y}. \n\n\n@{thm [display] List_def [no_vars]}\n\nA list @{term \"List p h ps\"} is a path starting in @{term p} and ending up\nin @{term Null}.\n\\\n\n\nlemma (in append_impl) append_spec1: \nshows \"\\\\ Ps Qs. \n \\\\ \\\\. List \\p \\next Ps \\ List \\q \\next Qs \\ set Ps \\ set Qs = {}\\ \n \\p :== PROC append(\\p,\\q) \n \\List \\p \\next (Ps@Qs) \\ (\\x. x\\set Ps \\ \\next x = \\<^bsup>\\\\<^esup>next x)\\\"\napply (hoare_rule HoarePartial.ProcRec1)\ntxt \\@{subgoals [margin=80,display]} \nNote that @{term \"hoare_rule\"} takes care of multiple auxiliary variables! \n@{thm [source] HoarePartial.ProcRec1} has only one auxiliary variable, namely @{term Z}. \nBut the type of @{term Z} can be instantiated arbitrarily. So \\hoare_rule\\ \ninstantiates @{term Z} with the tuple @{term \"(\\,Ps,Qs)\"} and derives a proper variant\nof the rule. Therefore \\hoare_rule\\ depends on the proper quantification of\nauxiliary variables!\n\\\napply vcg\ntxt \\@{subgoals [display]} \nFor each branch of the \\IF\\ statement we have one conjunct to prove. The\n\\THEN\\ branch starts with \\p = Null \\ \\\\ and the \\ELSE\\ branch\nwith \\p \\ Null \\ \\\\. Let us focus on the \\ELSE\\ branch, were the\nrecursive call to append occurs. First of all we have to prove that the precondition for\nthe recursive call is fulfilled. That means we have to provide some witnesses for\nthe lists @{term Psa} and @{term Qsa} which are referenced by \\p\\next\\ (now\nwritten as @{term \"next p\"}) and @{term q}. Then we have to show that we can \nderive the overall postcondition from the postcondition of the recursive call. The\nstate components that have changed by the recursive call are the ones with the suffix\n\\a\\, like \\nexta\\ and \\pa\\.\n\\\napply fastforce\ndone\n\n\ntext \\If the verification condition generator works on a procedure\ncall it checks whether it can find a modifies clause in the\ncontext. If one is present the procedure call is simplified before the\nHoare rule @{thm [source] HoarePartial.ProcSpec} is\napplied. Simplification of the procedure call means that the ``copy\nback'' of the global components is simplified. Only those components\nthat occur in the modifies clause are actually copied back. This\nsimplification is justified by the rule @{thm [source]\nHoarePartial.ProcModifyReturn}. \nSo after this simplification all global\ncomponents that do not appear in the modifies clause are treated\nas local variables.\\\n\ntext \\We study the effect of the modifies clause on the following \nexamples, where we want to prove that @{term \"append\"} does not change\nthe @{term \"cont\"} part of the heap.\n\\\nlemma (in append_impl)\nshows \"\\\\ \\\\cont=c\\ \\p :== CALL append(Null,Null) \\\\cont=c\\\" \nproof -\n note append_spec = append_spec1\n show ?thesis\n apply vcg\n txt \\@{subgoals [display]}\\\n txt \\Only focus on the very last line: @{term conta} is the heap component \n after the procedure call,\n and @{term cont} the heap component before the procedure call. Since\n we have not added the modified clause we do not know that they have\n to be equal. \n\\\n oops\n\ntext \\\nWe now add the frame condition.\nThe list in the modifies clause names all global state components that\nmay be changed by the procedure. Note that we know from the modifies clause\nthat the @{term cont} parts are not changed. Also a small\nside note on the syntax. We use ordinary brackets in the postcondition\nof the modifies clause, and also the state components do not carry the\nacute, because we explicitly note the state @{term t} here.\n\\\n\n\nlemma (in append_impl) append_modifies:\n shows \"\\\\. \\\\\\<^bsub>/UNIV\\<^esub> {\\} \\p :== PROC append(\\p,\\q) \n {t. t may_only_modify_globals \\ in [next]}\"\n apply (hoare_rule HoarePartial.ProcRec1)\n apply (vcg spec=modifies)\n done\n\ntext \\We tell the verification condition generator to use only the\nmodifies clauses and not to search for functional specifications by \nthe parameter \\spec=modifies\\. It also tries to solve the \nverification conditions automatically. Again it is crucial to name \nthe lemma with this naming scheme, since the verfication condition \ngenerator searches for these names. \n\\\n\ntext \\The modifies clause is equal to a state update specification\nof the following form. \n\\\n\nlemma (in append_impl) shows \"{t. t may_only_modify_globals Z in [next]} \n = \n {t. \\next. globals t=update id id next_' (K_statefun next) (globals Z)}\"\n apply (unfold mex_def meq_def)\n apply simp\n done\n\ntext \\Now that we have proven the frame-condition, it is available within\nthe locale \\append_impl\\ and the \\vcg\\ exploits it.\\\n\nlemma (in append_impl) \nshows \"\\\\ \\\\cont=c\\ \\p :== CALL append(Null,Null) \\\\cont=c\\\"\nproof -\n note append_spec = append_spec1\n show ?thesis\n apply vcg\n txt \\@{subgoals [display]}\\\n txt \\With a modifies clause present we know that no change to @{term cont}\n has occurred. \n\\\n by simp\nqed\n \n\ntext \\\nOf course we could add the modifies clause to the functional specification as \nwell. But separating both has the advantage that we split up the verification\nwork. We can make use of the modifies clause before we apply the\nfunctional specification in a fully automatic fashion.\n\\\n \n\ntext \\\nTo prove that a procedure respects the modifies clause, we only need\nthe modifies clauses of the procedures called in the body. We do not need\nthe functional specifications. So we can always prove the modifies\nclause without functional specifications, but we may need the modifies\nclause to prove the functional specifications. So usually the modifies clause is\nproved before the proof of the functional specification, so that it can already be used\nby the verification condition generator.\n\\\n\n\n \nsubsection \\Total Correctness\\\n\ntext \\When proving total correctness the additional proof burden to\nthe user is to come up with a well-founded relation and to prove that\ncertain states get smaller according to this relation. Proving that a\nrelation is well-founded can be quite hard. But fortunately there are\nways to construct and stick together relations so that they are\nwell-founded by construction. This infrastructure is already present\nin Isabelle/HOL. For example, @{term \"measure f\"} is always well-founded;\nthe lexicographic product of two well-founded relations is again\nwell-founded and the inverse image construction @{term \"inv_image\"} of\na well-founded relation is again well-founded. The constructions are\nbest explained by some equations:\n\n@{thm in_measure_iff [no_vars]}\\\\\n@{thm in_lex_iff [no_vars]}\\\\\n@{thm in_inv_image_iff [no_vars]}\n\nAnother useful construction is \\<*mlex*>\\ which is a combination\nof a measure and a lexicographic product:\n\n@{thm in_mlex_iff [no_vars]}\\\\\nIn contrast to the lexicographic product it does not construct a product type.\nThe state may either decrease according to the measure function @{term f} or the\nmeasure stays the same and the state decreases because of the relation @{term r}.\n\nLets look at a loop:\n\\\n\nlemma (in vars) \n \"\\\\\\<^sub>t \\\\M = 0 \\ \\S = 0\\\n WHILE \\M \\ a\n INV \\\\S = \\M * b \\ \\M \\ a\\\n VAR MEASURE a - \\M\n DO \\S :== \\S + b;; \\M :== \\M + 1 OD\n \\\\S = a * b\\\"\napply vcg\ntxt \\@{subgoals [display]} \nThe first conjunct of the second subgoal is the proof obligation that the\nvariant decreases in the loop body. \n\\\nby auto\n\n\n\ntext \\The variant annotation is preceded by \\VAR\\. The capital \\MEASURE\\\nis a shorthand for \\measure (\\s. a - \\<^bsup>s\\<^esup>M)\\. Analogous there is a capital \n\\<*MLEX*>\\.\n\\\n\nlemma (in Fac_impl) Fac_spec': \nshows \"\\\\. \\\\\\<^sub>t {\\} \\R :== PROC Fac(\\N) \\\\R = fac \\<^bsup>\\\\<^esup>N\\\"\napply (hoare_rule HoareTotal.ProcRec1 [where r=\"measure (\\(s,p). \\<^bsup>s\\<^esup>N)\"])\ntxt \\In case of the factorial the parameter @{term N} decreases in every call. This\nis easily expressed by the measure function. Note that the well-founded relation for\nrecursive procedures is formally defined on tuples\ncontaining the state space and the procedure name.\n\\\ntxt \\@{subgoals [display]} \nThe initial call to the factorial is in state @{term \"\\\"}. Note that in the \nprecondition @{term \"{\\} \\ {\\'}\"}, @{term \"\\'\"} stems from the lemma we want to prove\nand @{term \"\\\"} stems from the recursion rule for total correctness. Both are\nsynonym for the initial state. To use the assumption in the Hoare context we\nhave to show that the call to the factorial is invoked on a smaller @{term N} compared\nto the initial \\\\<^bsup>\\\\<^esup>N\\.\n\\\napply vcg\ntxt \\@{subgoals [display]} \nThe tribute to termination is that we have to show \\N - 1 < N\\ in case of\nthe recursive call.\n\\\nby simp\n\nlemma (in append_impl) append_spec2:\nshows \"\\\\ Ps Qs. \\\\\\<^sub>t \n \\\\. List \\p \\next Ps \\ List \\q \\next Qs \\ set Ps \\ set Qs = {}\\ \n \\p :== PROC append(\\p,\\q) \n \\List \\p \\next (Ps@Qs) \\ (\\x. x\\set Ps \\ \\next x = \\<^bsup>\\\\<^esup>next x)\\\"\napply (hoare_rule HoareTotal.ProcRec1\n [where r=\"measure (\\(s,p). length (list \\<^bsup>s\\<^esup>p \\<^bsup>s\\<^esup>next))\"])\ntxt \\In case of the append function the length of the list referenced by @{term p}\ndecreases in every recursive call.\n\\\ntxt \\@{subgoals [margin=80,display]}\\\napply vcg\napply (fastforce simp add: List_list)\ndone\n\ntext \\\nIn case of the lists above, we have used a relational list abstraction @{term List}\nto construct the HOL lists @{term Ps} and @{term Qs} for the pre- and postcondition.\nTo supply a proper measure function we use a functional abstraction @{term list}.\nThe functional abstraction can be defined by means of the relational list abstraction,\nsince the lists are already uniquely determined by the relational abstraction:\n\n@{thm islist_def [no_vars]}\\\\\n@{thm list_def [no_vars]}\n\n\\isacommand{lemma} @{thm List_conv_islist_list [no_vars]}\n\\\n\ntext \\\nThe next contrived example is taken from \\cite{Homeier-95-vcg}, to illustrate\na more complex termination criterion for mutually recursive procedures. The procedures\ndo not calculate anything useful.\n\n\\\n\n\nprocedures \n pedal(N::nat,M::nat) \n \"IF 0 < \\N THEN\n IF 0 < \\M THEN \n CALL coast(\\N- 1,\\M- 1) FI;;\n CALL pedal(\\N- 1,\\M)\n FI\"\n and\n \n coast(N::nat,M::nat) \n \"CALL pedal(\\N,\\M);;\n IF 0 < \\M THEN CALL coast(\\N,\\M- 1) FI\"\n\n\ntext \\\nIn the recursive calls in procedure \\pedal\\ the first argument always decreases.\nIn the body of \\coast\\ in the recursive call of \\coast\\ the second\nargument decreases, but in the call to \\pedal\\ no argument decreases. \nTherefore an relation only on the state space is insufficient. We have to\ntake the procedure names into account, too.\nWe consider the procedure \\coast\\ to be ``bigger'' than \\pedal\\\nwhen we construct a well-founded relation on the product of state space and procedure\nnames.\n\\\n\nML \\ML_Thms.bind_thm (\"HoareTotal_ProcRec2\", Hoare.gen_proc_rec @{context} Hoare.Total 2)\\\n\n\ntext \\\n We provide the ML function {\\tt gen\\_proc\\_rec} to\nautomatically derive a convenient rule for recursion for a given number of mutually\nrecursive procedures.\n\\\n\n \nlemma (in pedal_coast_clique)\nshows \"(\\\\. \\\\\\<^sub>t {\\} PROC pedal(\\N,\\M) UNIV) \\\n (\\\\. \\\\\\<^sub>t {\\} PROC coast(\\N,\\M) UNIV)\"\napply (hoare_rule HoareTotal_ProcRec2 \n [where r= \"((\\(s,p). \\<^bsup>s\\<^esup>N) <*mlex*>\n (\\(s,p). \\<^bsup>s\\<^esup>M) <*mlex*>\n measure (\\(s,p). if p = coast_'proc then 1 else 0))\"])\n txt \\We can directly express the termination condition described above with\n the \\<*mlex*>\\ construction. Either state component \\N\\ decreases,\n or it stays the same and \\M\\ decreases or this also stays the same, but\n then the procedure name has to decrease.\\\n txt \\@{subgoals [margin=80,display]}\\\napply simp_all\n txt \\@{subgoals [margin=75,display]}\\\nby (vcg,simp)+\n\ntext \\We can achieve the same effect without \\<*mlex*>\\ by using\n the ordinary lexicographic product \\<*lex*>\\, \\inv_image\\ and\n \\measure\\ \n\\\n \nlemma (in pedal_coast_clique)\nshows \"(\\\\. \\\\\\<^sub>t {\\} PROC pedal(\\N,\\M) UNIV) \\\n (\\\\. \\\\\\<^sub>t {\\} PROC coast(\\N,\\M) UNIV)\"\napply (hoare_rule HoareTotal_ProcRec2\n [where r= \"inv_image (measure (\\m. m) <*lex*>\n measure (\\m. m) <*lex*> \n measure (\\p. if p = coast_'proc then 1 else 0))\n (\\(s,p). (\\<^bsup>s\\<^esup>N,\\<^bsup>s\\<^esup>M,p))\"])\n txt \\With the lexicographic product we construct a well-founded relation on\n triples of type @{typ \"(nat\\nat\\string)\"}. With @{term inv_image} we project\n the components out of the state-space and the procedure names to this\n triple.\n\\\n txt \\@{subgoals [margin=75,display]}\\\napply simp_all\nby (vcg,simp)+\n\ntext \\By doing some arithmetic we can express the termination condition with a single\nmeasure function.\n\\\n\nlemma (in pedal_coast_clique) \nshows \"(\\\\. \\\\\\<^sub>t {\\} PROC pedal(\\N,\\M) UNIV) \\\n (\\\\. \\\\\\<^sub>t {\\} PROC coast(\\N,\\M) UNIV)\"\napply(hoare_rule HoareTotal_ProcRec2\n [where r= \"measure (\\(s,p). \\<^bsup>s\\<^esup>N + \\<^bsup>s\\<^esup>M + (if p = coast_'proc then 1 else 0))\"])\napply simp_all\ntxt \\@{subgoals [margin=75,display]}\\\nby (vcg,simp,arith?)+\n\n\nsubsection \\Guards\\\n\ntext (in vars) \\The purpose of a guard is to guard the {\\bf (sub-) expressions} of a\nstatement against runtime faults. Typical runtime faults are array bound violations,\ndereferencing null pointers or arithmetical overflow. Guards make the potential\nruntime faults explicit, since the expressions themselves never ``fail'' because \nthey are ordinary HOL expressions. To relieve the user from typing in lots of standard\nguards for every subexpression, we supply some input syntax for the common\nlanguage constructs that automatically generate the guards.\nFor example the guarded assignment \\\\M :==\\<^sub>g (\\M + 1) div \\N\\ gets expanded to \nguarded command @{term \"\\M :==\\<^sub>g (\\M + 1) div \\N\"}. Here @{term \"in_range\"} is\nuninterpreted by now. \n\\\n\nlemma (in vars) \"\\\\\\True\\ \\M :==\\<^sub>g (\\M + 1) div \\N \\True\\\"\napply vcg\ntxt \\@{subgoals}\\\noops\n\ntext \\\nThe user can supply on (overloaded) definition of \\in_range\\\nto fit to his needs.\n\nCurrently guards are generated for:\n\n\\begin{itemize}\n\\item overflow and underflow of numbers (\\in_range\\). For subtraction of\n natural numbers \\a - b\\ the guard \\b \\ a\\ is generated instead\n of \\in_range\\ to guard against underflows.\n\\item division by \\0\\\n\\item dereferencing of @{term Null} pointers\n\\item array bound violations\n\\end{itemize}\n\nFollowing (input) variants of guarded statements are available:\n\n\\begin{itemize}\n\\item Assignment: \\\\ :==\\<^sub>g \\\\\n\\item If: \\IF\\<^sub>g \\\\\n\\item While: \\WHILE\\<^sub>g \\\\\n\\item Call: \\CALL\\<^sub>g \\\\ or \\\\ :== CALL\\<^sub>g \\\\\n\\end{itemize}\n\\\n\nsubsection \\Miscellaneous Techniques\\\n\n\n\nsubsubsection \\Modifies Clause\\\n\ntext \\We look at some issues regarding the modifies clause with the example\nof insertion sort for heap lists.\n\\\n\nprimrec sorted:: \"('a \\ 'a \\ bool) \\ 'a list \\ bool\"\nwhere\n\"sorted le [] = True\" |\n\"sorted le (x#xs) = ((\\y\\set xs. le x y) \\ sorted le xs)\"\n\nprocedures (imports globals_heap)\n insert(r::ref,p::ref | p::ref) \n \"IF \\r=Null THEN SKIP\n ELSE IF \\p=Null THEN \\p :== \\r;; \\p\\\\next :== Null\n ELSE IF \\r\\\\cont \\ \\p\\\\cont \n THEN \\r\\\\next :== \\p;; \\p:==\\r\n ELSE \\p\\\\next :== CALL insert(\\r,\\p\\\\next)\n FI\n FI\n FI\"\n\nlemma (in insert_impl) insert_modifies:\n \"\\\\. \\\\\\<^bsub>/UNIV\\<^esub> {\\} \\p :== PROC insert(\\r,\\p) \n {t. t may_only_modify_globals \\ in [next]}\"\n by (hoare_rule HoarePartial.ProcRec1) (vcg spec=modifies)\n\nlemma (in insert_impl) insert_spec:\n \"\\\\ Ps . \\\\ \n \\\\. List \\p \\next Ps \\ sorted (op \\) (map \\cont Ps) \\ \n \\r \\ Null \\ \\r \\ set Ps\\\n \\p :== PROC insert(\\r,\\p) \n \\\\Qs. List \\p \\next Qs \\ sorted (op \\) (map \\<^bsup>\\\\<^esup>cont Qs) \\\n set Qs = insert \\<^bsup>\\\\<^esup>r (set Ps) \\\n (\\x. x \\ set Qs \\ \\next x = \\<^bsup>\\\\<^esup>next x)\\\"\n (*<*)\n apply (hoare_rule HoarePartial.ProcRec1)\n apply vcg\n apply (intro conjI impI)\n apply fastforce\n apply fastforce\n apply fastforce\n apply (clarsimp) \n apply force\n done\n (*>*)\n\ntext \\\nIn the postcondition of the functional specification there is a small but \nimportant subtlety. Whenever we talk about the @{term \"cont\"} part we refer to \nthe one of the pre-state.\nThe reason is that we have separated out the information that @{term \"cont\"} is not \nmodified by the procedure, to the modifies clause. So whenever we talk about unmodified\nparts in the postcondition we have to use the pre-state part, or explicitly\nstate an equality in the postcondition.\nThe reason is simple. If the postcondition would talk about \\\\cont\\\ninstead of \\mbox{\\\\<^bsup>\\\\<^esup>cont\\}, we get a new instance of \\cont\\ during\nverification and the postcondition would only state something about this\nnew instance. But as the verification condition generator uses the\nmodifies clause the caller of @{term \"insert\"} instead still has the\nold \\cont\\ after the call. Thats the sense of the modifies clause.\nSo the caller and the specification simply talk about two different things,\nwithout being able to relate them (unless an explicit equality is added to\nthe specification). \n\\\n\n\nsubsubsection \\Annotations\\\n\ntext \\\nAnnotations (like loop invariants)\nare mere syntactic sugar of statements that are used by the \\vcg\\. \nLogically a statement with an annotation is\nequal to the statement without it. Hence annotations can be introduced by the user\nwhile building a proof:\n\n@{thm [source] HoarePartial.annotateI}: @{thm [mode=Rule] HoarePartial.annotateI [no_vars]} \n\nWhen introducing annotations it can easily happen that these mess around with the \nnesting of sequential composition. Then after stripping the annotations the resulting statement\nis no longer syntactically identical to original one, only equivalent modulo associativity of sequential composition. The following rule also deals with this case:\n\n@{thm [source] HoarePartial.annotate_normI}: @{thm [mode=Rule] HoarePartial.annotate_normI [no_vars]} \n\\\n\ntext_raw \\\\paragraph{Loop Annotations} \n\\mbox{}\n\\medskip\n\n\\mbox{}\n\\\n\nprocedures (imports globals_heap)\n insertSort(p::ref| p::ref) \n where r::ref q::ref in\n \"\\r:==Null;;\n WHILE (\\p \\ Null) DO\n \\q :== \\p;;\n \\p :== \\p\\\\next;;\n \\r :== CALL insert(\\q,\\r)\n OD;;\n \\p:==\\r\"\n\nlemma (in insertSort_impl) insertSort_modifies: \n shows\n \"\\\\. \\\\\\<^bsub>/UNIV\\<^esub> {\\} \\p :== PROC insertSort(\\p) \n {t. t may_only_modify_globals \\ in [next]}\"\napply (hoare_rule HoarePartial.ProcRec1)\napply (vcg spec=modifies)\ndone\n\n\n\n\ntext \\Insertion sort is not implemented recursively here, but with a \nloop. Note that the while loop is not annotated with an invariant in the\nprocedure definition. The invariant only comes into play during verification.\nTherefore we annotate the loop first, before we run the \\vcg\\. \n\\\n\nlemma (in insertSort_impl) insertSort_spec:\nshows \"\\\\ Ps. \n \\\\ \\\\. List \\p \\next Ps \\ \n \\p :== PROC insertSort(\\p)\n \\\\Qs. List \\p \\next Qs \\ sorted (op \\) (map \\<^bsup>\\\\<^esup>cont Qs) \\\n set Qs = set Ps\\\"\napply (hoare_rule HoarePartial.ProcRec1) \napply (hoare_rule anno= \n \"\\r :== Null;;\n WHILE \\p \\ Null\n INV \\\\Qs Rs. List \\p \\next Qs \\ List \\r \\next Rs \\ \n set Qs \\ set Rs = {} \\\n sorted (op \\) (map \\cont Rs) \\ set Qs \\ set Rs = set Ps \\\n \\cont = \\<^bsup>\\\\<^esup>cont \\\n DO \\q :== \\p;; \\p :== \\p\\\\next;; \\r :== CALL insert(\\q,\\r) OD;;\n \\p :== \\r\" in HoarePartial.annotateI)\napply vcg\ntxt \\\\\\\\\\\n(*<*)\n \n apply fastforce\n prefer 2\n apply fastforce\n apply (clarsimp)\n apply (rule_tac x=ps in exI)\n apply (intro conjI)\n apply (rule heap_eq_ListI1)\n apply assumption\n apply clarsimp\n apply (subgoal_tac \"x\\p \\ x \\ set Rs\")\n apply auto\n done\n(*>*)\n\ntext \\The method \\hoare_rule\\ automatically solves the side-condition \n that the annotated\n program is the same as the original one after stripping the annotations.\\\n\ntext_raw \\\\paragraph{Specification Annotations} \n\\mbox{}\n\\medskip\n\n\\mbox{}\n\\\n\n\n\ntext \\\nWhen verifying a larger block of program text, it might be useful to split up\nthe block and to prove the parts in isolation. This is especially useful to\nisolate loops. On the level of the Hoare calculus\nthe parts can then be combined with the consequence rule. To automate this\nprocess we introduce the derived command @{term specAnno}, which allows to introduce\na Hoare tuple (inclusive auxiliary variables) in the program text:\n\n@{thm specAnno_def [no_vars]}\n\nThe whole annotation reduces to the body @{term \"c undefined\"}. The\ntype of the assertions @{term \"P\"}, @{term \"Q\"} and @{term \"A\"} is\n@{typ \"'a \\ 's set\"} and the type of command @{term c} is @{typ \"'a \\ ('s,'p,'f) com\"}.\nAll entities formally depend on an auxiliary (logical) variable of type @{typ \"'a\"}.\nThe body @{term \"c\"} formally also depends on this variable, since a nested annotation\nor loop invariant may also depend on this logical variable. But the raw body without\nannotations does not depend on the logical variable. The logical variable is only\nused by the verification condition generator. We express this by defining the\nwhole @{term specAnno} to be equivalent with the body applied to an arbitrary\nvariable.\n\nThe Hoare rule for \\specAnno\\ is mainly an instance of the consequence rule:\n\n@{thm [mode=Rule,mode=ParenStmt] HoarePartial.SpecAnno [no_vars]}\n\nThe side-condition @{term \"\\Z. c Z = c undefined\"} expresses the intention of body @{term c}\nexplained above: The raw body is independent of the auxiliary variable. This\nside-condition is solved automatically by the \\vcg\\. The concrete syntax for \nthis specification annotation is shown in the following example: \n\\\n\nlemma (in vars) \"\\\\ {\\} \n \\I :== \\M;; \n ANNO \\. \\\\. \\I = \\<^bsup>\\\\<^esup>M\\\n \\M :== \\N;; \\N :== \\I \n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>I\\\n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>M\\\"\ntxt \\With the annotation we can name an intermediate state @{term \\}. Since the\n postcondition refers to @{term \"\\\"} we have to link the information about\n the equivalence of \\\\<^bsup>\\\\<^esup>I\\ and \\\\<^bsup>\\\\<^esup>M\\ in the specification in order\n to be able to derive the postcondition.\n\\\napply vcg_step\napply vcg_step\ntxt \\@{subgoals [display]}\\\ntxt \\The first subgoal is the isolated Hoare tuple. The second one is the\n side-condition of the consequence rule that allows us to derive the outermost\n pre/post condition from our inserted specification.\n \\\\I = \\<^bsup>\\\\<^esup>M\\ is the precondition of the specification, \n The second conjunct is a simplified version of\n \\\\t. \\<^bsup>t\\<^esup>M = \\N \\ \\<^bsup>t\\<^esup>N = \\I \\ \\<^bsup>t\\<^esup>M = \\<^bsup>\\\\<^esup>N \\ \\<^bsup>t\\<^esup>N = \\<^bsup>\\\\<^esup>M\\ expressing that the\n postcondition of the specification implies the outermost postcondition.\n\\\napply vcg\ntxt \\@{subgoals [display]}\\\napply simp\napply vcg\ntxt \\@{subgoals [display]}\\\nby simp\n\n\nlemma (in vars) \n \"\\\\ {\\} \n \\I :== \\M;; \n ANNO \\. \\\\. \\I = \\<^bsup>\\\\<^esup>M\\\n \\M :== \\N;; \\N :== \\I \n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>I\\\n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>M\\\"\napply vcg\ntxt \\@{subgoals [display]}\\\nby simp_all\n\ntext \\Note that \\vcg_step\\ changes the order of sequential composition, to \nallow the user to decompose sequences by repeated calls to \\vcg_step\\, whereas\n\\vcg\\ preserves the order.\n\nThe above example illustrates how we can introduce a new logical state variable \n@{term \"\\\"}. You can introduce multiple variables by using a tuple:\n\n\n\n\\\n\n\nlemma (in vars) \n \"\\\\ {\\} \n \\I :== \\M;; \n ANNO (n,i,m). \\\\I = \\<^bsup>\\\\<^esup>M \\ \\N=n \\ \\I=i \\ \\M=m\\\n \\M :== \\N;; \\N :== \\I \n \\\\M = n \\ \\N = i\\\n \\\\M = \\<^bsup>\\\\<^esup>N \\ \\N = \\<^bsup>\\\\<^esup>M\\\"\napply vcg\ntxt \\@{subgoals [display]}\\\nby simp_all\n\ntext_raw \\\\paragraph{Lemma Annotations} \n\\mbox{}\n\\medskip\n\n\\mbox{}\n\n\\\n\ntext \\\nThe specification annotations described before split the verification\ninto several Hoare triples which result in several subgoals. If we\ninstead want to proof the Hoare triples independently as\nseparate lemmas we can use the \\LEMMA\\ annotation to plug together the\nlemmas. It\ninserts the lemma in the same fashion as the specification annotation.\n\\\nlemma (in vars) foo_lemma: \n \"\\n m. \\\\ \\\\N = n \\ \\M = m\\ \\N :== \\N + 1;; \\M :== \\M + 1 \n \\\\N = n + 1 \\ \\M = m + 1\\\"\n apply vcg\n apply simp\n done\n\nlemma (in vars) \n \"\\\\ \\\\N = n \\ \\M = m\\ \n LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END;; \n \\N :== \\N + 1 \n \\\\N = n + 2 \\ \\M = m + 1\\\"\n apply vcg\n apply simp\n done\n\nlemma (in vars)\n \"\\\\ \\\\N = n \\ \\M = m\\ \n LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END;;\n LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END\n \\\\N = n + 2 \\ \\M = m + 2\\\"\n apply vcg\n apply simp\n done\n\nlemma (in vars) \n \"\\\\ \\\\N = n \\ \\M = m\\ \n \\N :== \\N + 1;; \\M :== \\M + 1;;\n \\N :== \\N + 1;; \\M :== \\M + 1\n \\\\N = n + 2 \\ \\M = m + 2\\\"\n apply (hoare_rule anno= \n \"LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END;;\n LEMMA foo_lemma \n \\N :== \\N + 1;; \\M :== \\M + 1\n END\"\n in HoarePartial.annotate_normI)\n apply vcg\n apply simp\n done\n\n\nsubsubsection \\Total Correctness of Nested Loops\\\n\ntext \\\nWhen proving termination of nested loops it is sometimes necessary to express that\nthe loop variable of the outer loop is not modified in the inner loop. To express this\none has to fix the value of the outer loop variable before the inner loop and use this value\nin the invariant of the inner loop. This can be achieved by surrounding the inner while loop\nwith an \\ANNO\\ specification as explained previously. However, this\nleads to repeating the invariant of the inner loop three times: in the invariant itself and\nin the the pre- and postcondition of the \\ANNO\\ specification. Moreover one has\nto deal with the additional subgoal introduced by \\ANNO\\ that expresses how\nthe pre- and postcondition is connected to the invariant. To avoid this extra specification\nand verification work, we introduce an variant of the annotated while-loop, where one can\nintroduce logical variables by \\FIX\\. As for the \\ANNO\\ specification\nmultiple logical variables can be introduced via a tuple (\\FIX (a,b,c).\\).\n\nThe Hoare logic rule for the augmented while-loop is a mixture of the invariant rule for\nloops and the consequence rule for \\ANNO\\:\n\n\\begin{center}\n@{thm [mode=Rule,mode=ParenStmt] HoareTotal.WhileAnnoFix' [no_vars]}\n\\end{center}\n\nThe first premise expresses that the precondition implies the invariant and that\nthe invariant together with the negated loop condition implies the postcondition. Since\nboth implications may depend on the choice of the auxiliary variable @{term \"Z\"} these two\nimplications are expressed in a single premise and not in two of them as for the usual while\nrule. The second premise is the preservation of the invariant by the loop body. And the third\npremise is the side-condition that the computational part of the body does not depend on\nthe auxiliary variable. Finally the last premise is the well-foundedness of the variant.\nThe last two premises are usually discharged automatically by the verification condition\ngenerator. Hence usually two subgoals remain for the user, stemming from the first two\npremises.\n\nThe following example illustrates the usage of this rule. The outer loop increments the\nloop variable @{term \"M\"} while the inner loop increments @{term \"N\"}. To discharge the\nproof obligation for the termination of the outer loop, we need to know that the inner loop\ndoes not mess around with @{term \"M\"}. This is expressed by introducing the logical variable\n@{term \"m\"} and fixing the value of @{term \"M\"} to it.\n\\\n\n\nlemma (in vars) \n \"\\\\\\<^sub>t \\\\M=0 \\ \\N=0\\ \n WHILE (\\M < i) \n INV \\\\M \\ i \\ (\\M \\ 0 \\ \\N = j) \\ \\N \\ j\\\n VAR MEASURE (i - \\M)\n DO\n \\N :== 0;;\n WHILE (\\N < j)\n FIX m. \n INV \\\\M=m \\ \\N \\ j\\\n VAR MEASURE (j - \\N)\n DO\n \\N :== \\N + 1\n OD;;\n \\M :== \\M + 1\n OD\n \\\\M=i \\ (\\M\\0 \\ \\N=j)\\\"\napply vcg\ntxt \\@{subgoals [display]} \n\nThe first subgoal is from the precondition to the invariant of the outer loop.\nThe fourth subgoal is from the invariant together with the negated loop condition \nof the outer loop to the postcondition. The subgoals two and three are from the body\nof the outer while loop which is mainly the inner while loop. Because we introduce the\nlogical variable @{term \"m\"} here, the while Rule described above is used instead of the\nordinary while Rule. That is why we end up with two subgoals for the inner loop. Subgoal\ntwo is from the invariant and the loop condition of the outer loop to the invariant\nof the inner loop. And at the same time from the invariant of the inner loop to the\ninvariant of the outer loop (together with the proof obligation that the measure of the\nouter loop decreases). The universal quantified variables @{term \"Ma\"} and @{term \"N\"} are\nthe ``fresh'' state variables introduced for the final state of the inner loop. \nThe equality @{term \"Ma=M\"} is the result of the equality \\\\M=m\\ in the inner \ninvariant. Subgoal three is the preservation of the invariant by the\ninner loop body (together with the proof obligation that the measure of\nthe inner loop decreases).\n\\\n(*<*)\napply (simp)\napply (simp,arith)\napply (simp,arith)\ndone\n(*>*)\n\nsubsection \\Functional Correctness, Termination and Runtime Faults\\\n\ntext \\\nTotal correctness of a program with guards conceptually leads to three verification \ntasks.\n\\begin{itemize}\n\\item functional (partial) correctness \n\\item absence of runtime faults\n\\item termination\n\\end{itemize}\n\nIn case of a modifies specification the functional correctness part\ncan be solved automatically. But the absence of runtime faults and\ntermination may be non trivial. Fortunately the modifies clause is\nusually just a helpful companion of another specification that\nexpresses the ``real'' functional behaviour. Therefor the task to\nprove the absence of runtime faults and termination can be dealt with\nduring the proof of this functional specification. In most cases the\nabsence of runtime faults and termination heavily build on the\nfunctional specification parts. So after all there is no reason why\nwe should again prove the absence of runtime faults and termination\nfor the modifies clause. Therefor it suffices to have partial\ncorrectness of the modifies clause for a program were all guards are\nignored. This leads to the following pattern:\\\n\n\n\nprocedures foo (N::nat|M::nat) \n \"\\M :== \\M \n (* think of body with guards instead *)\"\n\n foo_spec: \"\\\\. \\\\\\<^sub>t (P \\) \\M :== PROC foo(\\N) (Q \\)\"\n foo_modifies: \"\\\\. \\\\\\<^bsub>/UNIV\\<^esub> {\\} \\M :== PROC foo(\\N) \n {t. t may_only_modify_globals \\ in []}\"\n\ntext \\\nThe verification condition generator can solve those modifies clauses automatically\nand can use them to simplify calls to \\foo\\ even in the context of total\ncorrectness.\n\\\n\nsubsection \\Procedures and Locales \\label{sec:Locales}\\\n\n\n\ntext \\\nVerification of a larger program is organised on the granularity of procedures. \nWe proof the procedures in a bottom up fashion. Of course you can also always use Isabelle's\ndummy proof \\sorry\\ to prototype your formalisation. So you can write the\ntheory in a bottom up fashion but actually prove the lemmas in any other order.\n \nHere are some explanations of handling of locales. In the examples below, consider\n\\proc\\<^sub>1\\ and \\proc\\<^sub>2\\ to be ``leaf'' procedures, which do not call any \nother procedure.\nProcedure \\proc\\ directly calls \\proc\\<^sub>1\\ and \\proc\\<^sub>2\\.\n\n\\isacommand{lemma} (\\isacommand{in} \\proc\\<^sub>1_impl\\) \\proc\\<^sub>1_modifies\\:\\\\\n\\isacommand{shows} \\\\\\ \n\nAfter the proof of \\proc\\<^sub>1_modifies\\, the \\isacommand{in} directive \nstores the lemma in the\nlocale \\proc\\<^sub>1_impl\\. When we later on include \\proc\\<^sub>1_impl\\ or prove \nanother theorem in locale \\proc\\<^sub>1_impl\\ the lemma \\proc\\<^sub>1_modifies\\\nwill already be available as fact.\n\n\\isacommand{lemma} (\\isacommand{in} \\proc\\<^sub>1_impl\\) \\proc\\<^sub>1_spec\\:\\\\\n\\isacommand{shows} \\\\\\ \n\n\\isacommand{lemma} (\\isacommand{in} \\proc\\<^sub>2_impl\\) \\proc\\<^sub>2_modifies\\:\\\\\n\\isacommand{shows} \\\\\\ \n\n\\isacommand{lemma} (\\isacommand{in} \\proc\\<^sub>2_impl\\) \\proc\\<^sub>2_spec\\:\\\\\n\\isacommand{shows} \\\\\\ \n\n\n\\isacommand{lemma} (\\isacommand{in} \\proc_impl\\) \\proc_modifies\\:\\\\\n\\isacommand{shows} \\\\\\ \n\nNote that we do not explicitly include anything about \\proc\\<^sub>1\\ or \n\\proc\\<^sub>2\\ here. This is handled automatically. When defining\nan \\impl\\-locale it imports all \\impl\\-locales of procedures that are\ncalled in the body. In case of \\proc_impl\\ this means, that \\proc\\<^sub>1_impl\\\nand \\proc\\<^sub>2_impl\\ are imported. This has the neat effect that all theorems that\nare proven in \\proc\\<^sub>1_impl\\ and \\proc\\<^sub>2_impl\\ are also present\nin \\proc_impl\\.\n\n\\isacommand{lemma} (\\isacommand{in} \\proc_impl\\) \\proc_spec\\:\\\\\n\\isacommand{shows} \\\\\\ \n\nAs we have seen in this example you only have to prove a procedure in its own\n\\impl\\ locale. You do not have to include any other locale. \n\\\n\nsubsection \\Records \\label{sec:records}\\\n\ntext \\\nBefore @{term \"statespaces\"} where introduced the state was represented as a @{term \"record\"}.\nThis is still supported. Compared to the flexibility of statespaces there are some drawbacks\nin particular with respect to modularity. Even names of local variables and \nparameters are globally visible and records can only be extended in a linear fashion, whereas\nstatespaces also allow multiple inheritance. The usage of records is quite similar to the usage of statespaces. \nWe repeat the example of an append function for heap lists.\nFirst we define the global components. \nAgain the appearance of the prefix `globals' is mandatory. This is the way the syntax layer distinguishes local and global variables. \n\\\nrecord globals_list = \n next_' :: \"ref \\ ref\"\n cont_' :: \"ref \\ nat\"\n\n\ntext \\The local variables also have to be defined as a record before the actual definition\nof the procedure. The parent record \\state\\ defines a generic @{term \"globals\"}\nfield as a place-holder for the record of global components. In contrast to the\nstatespace approach there is no single @{term \"locals\"} slot. The local components are\njust added to the record.\n\\\nrecord 'g list_vars = \"'g state\" +\n p_' :: \"ref\"\n q_' :: \"ref\"\n r_' :: \"ref\"\n root_' :: \"ref\"\n tmp_' :: \"ref\"\n\ntext \\Since the parameters and local variables are determined by the record, there are\nno type annotations or definitions of local variables while defining a procedure.\n\\\n\nprocedures\n append'(p,q|p) = \n \"IF \\p=Null THEN \\p :== \\q \n ELSE \\p \\\\next:== CALL append'(\\p\\\\next,\\q) FI\"\n\ntext \\As in the statespace approach, a locale called \\append'_impl\\ is created.\nNote that we do not give any explicit information which global or local state-record to use.\nSince the records are already defined we rely on Isabelle's type inference. \nDealing with the locale is analogous to the case with statespaces.\n\\\n\nlemma (in append'_impl) append'_modifies: \n shows\n \"\\\\. \\\\ {\\} \\p :== PROC append'(\\p,\\q)\n {t. t may_only_modify_globals \\ in [next]}\"\n apply (hoare_rule HoarePartial.ProcRec1)\n apply (vcg spec=modifies)\n done\n\nlemma (in append'_impl) append'_spec:\n shows \"\\\\ Ps Qs. \\\\ \n \\\\. List \\p \\next Ps \\ List \\q \\next Qs \\ set Ps \\ set Qs = {}\\\n \\p :== PROC append'(\\p,\\q) \n \\List \\p \\next (Ps@Qs) \\ (\\x. x\\set Ps \\ \\next x = \\<^bsup>\\\\<^esup>next x)\\\"\n apply (hoare_rule HoarePartial.ProcRec1)\n apply vcg\n apply fastforce\n done\n\n\ntext \\\nHowever, in some corner cases the inferred state type in a procedure definition \ncan be too general which raises problems when attempting to proof a suitable \nspecifications in the locale.\nConsider for example the simple procedure body @{term \"\\p :== NULL\"} for a procedure\n\\init\\. \n\\\n\nprocedures init (|p) = \n \"\\p:== Null\"\n\n\ntext \\\nHere Isabelle can only\ninfer the local variable record. Since no reference to any global variable is\nmade the type fixed for the global variables (in the locale \\init'_impl\\) is a \ntype variable say @{typ \"'g\"} and not a @{term \"globals_list\"} record. Any specification\nmentioning @{term \"next\"} or @{term \"cont\"} restricts the state type and cannot be\nadded to the locale \\init_impl\\. Hence we have to restrict the body\n@{term \"\\p :== NULL\"} in the first place by adding a typing annotation:\n\\\n\nprocedures init' (|p) = \n \"\\p:== Null::(('a globals_list_scheme, 'b) list_vars_scheme, char list, 'c) com\"\n\n\nsubsubsection \\Extending State Spaces\\\ntext \\\nThe records in Isabelle are\nextensible \\cite{Nipkow-02-hol,NaraschewskiW-TPHOLs98}. In principle this can be exploited \nduring verification. The state space can be extended while we we add procedures.\nBut there is one major drawback:\n\\begin{itemize}\n \\item records can only be extended in a linear fashion (there is no multiple inheritance)\n\\end{itemize}\n\nYou can extend both the main state record as well as the record for the global variables.\n\\\n\nsubsubsection \\Mapping Variables to Record Fields\\\n\ntext \\\nGenerally the state space (global and local variables) is flat and all components\nare accessible from everywhere. Locality or globality of variables is achieved by\nthe proper \\init\\ and \\return\\/\\result\\ functions in procedure\ncalls. What is the best way to map programming language variables to the state records?\nOne way is to disambiguate all names, by using the procedure names as prefix or the\nstructure names for heap components. This leads to long names and lots of \nrecord components. But for local variables this is not necessary, since\nvariable @{term i} of procedure @{term A} and variable @{term \"i\"} of procedure @{term B}\ncan be mapped to the same record component, without any harm, provided they have the\nsame logical type. Therefor for local variables it is preferable to map them per type. You\nonly have to distinguish a variable with the same name if they have a different type.\nNote that all pointers just have logical type \\ref\\. So you even do not\nhave to distinguish between a pointer \\p\\ to a integer and a pointer \\p\\ to\na list.\nFor global components (global variables and heap structures) you have to disambiguate the\nname. But hopefully the field names of structures have different names anyway.\nAlso note that there is no notion of hiding of a global component by a local one in\nthe logic. You have to disambiguate global and local names!\nAs the names of the components show up in the specifications and the\nproof obligations, names are even more important as for programming. Try to\nfind meaningful and short names, to avoid cluttering up your reasoning.\n\\\n\n(*<*)\ntext \\\nin locales, includes, spec or impl?\nNames: per type not per procedure\\\ndowngrading total to partial\\\n\\\n(*>*)\ntext \\\\\n(*<*)\nend\n(*>*)\n", "meta": {"author": "LVPGroup", "repo": "TimSort", "sha": "16437b6b6e2df9f6d32b2a32be7d0d650d83f980", "save_path": "github-repos/isabelle/LVPGroup-TimSort", "path": "github-repos/isabelle/LVPGroup-TimSort/TimSort-16437b6b6e2df9f6d32b2a32be7d0d650d83f980/Simpl/UserGuide.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.11757212736159105, "lm_q1q2_score": 0.05465946676011584}} {"text": "(*\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n \n *)\n\ntheory Word_Additions\n imports SymbolicRewriting\n \"HOL-Word.WordBitwise\"\nbegin\n\nsection \"Extensions to the Word library\"\n\ntext {*\n The word library models two's complement representation of ints.\n Some of the available operations:\n*}\nfind_consts \"_ word \\ _ word \\ _ word\"\nfind_consts \"_ word \\ _ word\"\nfind_consts \"_ word \\ bool list\"\nfind_consts \"nat \\ _ word\"\nfind_consts \"_ word \\ nat\"\nfind_consts \"int \\ _ word\"\nfind_consts \"_ word \\ int\"\nfind_consts \"bool list \\ _ word\"\n\n\n\ntext {*\n Take the bits from $l$ to $h$ (both including) of the word.\n*}\ndefinition take_bits :: \"nat \\ nat \\ 'a::len0 word \\ 'b::len0 word\" (\"\\_,_\\_\" [51,51,72] 72)\n where \"take_bits h l w \\ of_bl (take (h + 1 - l) (drop (LENGTH('a) - h - 1) (to_bl w)))\"\n\n\nfun bv_cat :: \"'a::len0 word \\ nat \\ 'a::len0 word \\ nat \\ 'a::len0 word \\ nat\"\n where \"bv_cat (w0,s0) (w1,s1) = (if s1 = 0 then (w0,s0) else ((w0 << s1) OR \\s1-1,0\\ w1, s0 + s1))\"\ndeclare bv_cat.simps[simp del]\n\nfun sextend :: \"'a::len word \\ nat \\ nat \\ 'a::len word\"\n where \"sextend w s s' = (if w!!(s - 1) then ((\\s-1,0\\w) OR NOT mask s) AND mask s' else \\s-1,0\\w)\"\n\n\n\nsubsection \"Words to bytes\"\n\nfun word_to_bytes :: \"'a::len0 word \\ nat \\ 8 word list\"\n where \"word_to_bytes w s = (if s \\ 0 then [] else (\\s*8-1,s*8-8\\w)#(word_to_bytes w (s-1)))\"\ndeclare word_to_bytes.simps[simp del]\nlemmas word_to_bytes_simps[simp] =\n word_to_bytes.simps[of 0 s]\n word_to_bytes.simps[of 1 s]\n word_to_bytes.simps[of \"(numeral n)::'a::len0 word\" s]\n word_to_bytes.simps[of \"- ((numeral n)::'a::len0 word)\" s]\n for s n\n\ndefinition sublist :: \"nat \\ nat \\ 'a list \\ 'a list\"\n where \"sublist l h \\ take (h + 1 - l) \\ (drop l)\"\n\ndefinition bytes_of :: \"nat \\ nat \\ 'a::len0 word \\ 8 word list\" (\"\\_,_\\_\" [51,51,72] 72)\n where \"bytes_of h l w = (if h < l \\ LENGTH('a) div 8 \\ h then [] else sublist (LENGTH('a) div 8 - 1 - h) (LENGTH('a) div 8 - 1 - l) (word_to_bytes w (LENGTH('a) div 8)))\"\n\nabbreviation byte_of :: \"nat \\ 'a::len0 word \\ 8 word\" (\"\\_\\ _\" [51,72] 72)\n where \"byte_of n w \\ hd (\\n,n\\ w)\"\n\nprimrec cat_bytes :: \"8 word list \\ 'a::len0 word\"\n where \"cat_bytes [] = 0\"\n | \"cat_bytes (b#bs) = ((ucast b) << (length bs * 8)) OR cat_bytes bs\"\n\ntext {*\n Function @{term cat_bytes} takes a list of bytes (8 words) and converts them to a 64 word.\n This does essentially them same of @{term word_rcat}, but this version is tailored to bytes and\n makes proves/rewriting easier.\n*}\n\nvalue \"(cat_bytes [1,2::8 word])::64 word\"\nvalue \"(cat_bytes [0,0,0,21::8 word]) :: 64 word\"\nvalue \"(word_rcat [1,2::8 word])::16 word\"\n\n\n\n \n\n\n\nsubsection \"Additional rewrite rules for words\"\n\ntext {*\n Additional word rewriting.\n*}\nlemma le_numeral_zero[simp]:\n \"((numeral bin0::'a::len word) \\ (0::'a::len word)) = (uint (numeral bin0::'a::len word) = 0)\"\n apply (simp add: word_le_def)\n by (smt bintr_ge0)\nlemma le_numeral_one[simp]:\n \"((numeral bin0::'a::len word) \\ (1::'a::len word)) = (uint (numeral bin0::'a::len word) \\ 1)\"\n unfolding word_le_def word_le_def\n by simp\n\nlemma le_minus_numeral[simp]:\n \"(\n (word_sless::('a::len word \\ 'a::len word \\ bool))\n ((- (numeral bin0::'a::len word)))\n (numeral bin1::'a::len word)\n ) = (sint (- numeral bin0::'a::len word) < sint (numeral bin1::'a::len word))\"\n unfolding word_sless_def word_sle_def\n by (smt word_sint.Rep_inject)\n\nlemma le_zero_numeral[simp]:\n \"(\n (word_sless::('a::len word \\ 'a::len word \\ bool))\n 0 (numeral bin1::'a::len word)\n ) = (0 < sint (numeral bin1::'a::len word))\"\n unfolding word_sless_def word_sle_def\n using word_sint.Rep_inject by fastforce\n\nlemma rewrite_le_minus[simp]:\n shows \"((a::'a::len word) - n \\ a - m) = (if a \\ m then m \\ n \\ a \\ n else (a-n \\ (max_word::'a::len word) - m + a + 1))\"\nproof(cases \"a\\m\")\n case True\n thus ?thesis\n apply (auto simp add: uint_minus_simple_alt)\n by (smt uint_sub_ge)+\nnext\n case False\n have 1: \"(max_word::'a::len word) - m + a + 1 = (a - m)\"\n apply auto\n by (metis add.left_inverse max_word_wrap)\n show ?thesis\n using False\n apply (auto)\n apply (subst 1,simp)\n by (simp add: \"1\")\nqed\n\nlemma rewrite_le_minus_0[simp]:\n shows \"((a::'a::len word) \\ a - m) = (a \\ m \\ m = 0)\" \n using rewrite_le_minus[of a 0 m]\n apply auto\n by (meson less_imp_le not_le word_sub_le_iff)\n\nlemma plus_less_left_cancel_nowrap: \"x \\ x + y' \\ x \\ x + y \\ x + y' \\ x + y \\ y' \\ y\"\n for x y y' :: \"'a::len0 word\"\n by uint_arith\n\nlemma word_not_gr_zero[simp]:\n fixes w :: \"'a::len0 word\"\n shows \"\\ 0 < w \\ w = 0\"\n apply unat_arith\n by (simp add: unat_eq_zero)\n\n\nlemma mask_numeral[simp]:\n shows \"mask (numeral n) = (1 << (numeral n)) - 1\"\n by (auto simp add: mask_def)\n\nlemma unfold_test_bit:\nfixes w :: \"'a::len word\"\nshows \"w !! n = (if n < LENGTH('a) then to_bl w ! (LENGTH('a) - 1 - n) else False)\"\n using to_bl_nth[of \"LENGTH('a) - 1 - n\" w,symmetric] test_bit_bin\n by (auto simp add: word_size)\n\nlemma is_zero_bitOR[simp]:\n fixes a b :: \"'a::len0 word\"\n shows \"((a OR b) = 0) = (a = 0 \\ b = 0)\"\n by (metis word_bw_lcs(2) word_bw_same(2) word_log_esimps(3))\n\nlemma is_zero_all_bits:\n fixes a :: \"'a::len0 word\"\n shows \"(a = 0) = (\\ n < LENGTH ('a) . \\a !! n)\"\n by (auto simp add: word_eq_iff)\n\nlemma is_zero_shiftl:\n fixes a :: \"'a::len0 word\"\n shows \"((a << n) = 0) = (n \\ LENGTH('a) \\ (\\ i < LENGTH('a) - n . \\a!!i))\"\n using less_diff_conv \n by (auto simp add: is_zero_all_bits nth_shiftl)\n\nlemma twos_complement_subtraction[simp]:\n fixes a b :: \"'a::len0 word\"\n shows \"1 + (a + NOT b) = a - b\"\n by (auto simp add: word_succ_p1 twos_complement)\n\nlemma twos_complement_subtraction_r[simp]:\n fixes a b :: \"'a::len0 word\"\n shows \"1 + (NOT b + a) = a - b\"\n by (auto simp add: word_succ_p1 twos_complement)\n\n\nprimrec enum_le :: \"nat \\ nat list\"\n where \"enum_le 0 = []\"\n | \"enum_le (Suc n) = n#(enum_le n)\"\n\nlemma spec_of_enum_le:\n shows \"x \\ List.set (enum_le n) = (x < n)\"\n by(induct n,auto)\n\n\nlemma bitNOT_nth:\n \"(NOT x) !! n \\ n < LENGTH('a) \\ \\x !! n\"\n for x :: \"'a::len0 word\"\n using test_bit_size[of \"NOT x\" n]\n by (auto simp add: word_size word_ops_nth_size)\n\n\n\ndeclare plus_less_left_cancel_nowrap[simp add]\nlemma x_less_x_plus_y[simp]:\n fixes x y :: \"'a::len word\"\n assumes \"x \\ max_word - y\"\n shows \"x \\ x + y\"\n apply (rule plus_minus_no_overflow_ab[of x \"max_word::'a::len word\" y,OF assms])\n by auto\nlemma plus_minus_no_overflow_ab_l: \"x \\ ab - c \\ c \\ ab \\ x \\ c + x\"\n for x ab c :: \"'a::len0 word\"\n by uint_arith\nlemma x_less_x_plus_y_l[simp]:\n fixes x y :: \"'a::len word\"\n assumes \"x \\ max_word - y\"\n shows \"x \\ y + x\"\n apply (rule plus_minus_no_overflow_ab_l[of x \"max_word::'a::len word\" y,OF assms])\n by auto\nlemma x_minus_le_plus_x[simp]:\n fixes x y w z :: \"'a::len word\"\n assumes \"x \\ w\"\n and \"x \\ max_word - z\"\n shows \"x - w \\ z + x\"\n using assms\nproof-\n have \"x - w \\ x\"\n using assms(1)\n by unat_arith\n also have \"x \\ z + x\"\n using assms(2)\n by simp\n finally\n show ?thesis\n by simp\nqed\nlemma x_plus_y_less_x[simp]:\n fixes x y :: \\'a::len word\\\n assumes \\x \\ max_word - y\\\n and \\y > 0\\\n shows \\x + y \\ x \\ False\\\n using assms x_less_x_plus_y\n by fastforce\nlemma less_max_word_minus[simp]:\n fixes x y z :: \"'a::len word\"\n assumes \"x \\ max_word - y\"\n and \"y \\ z\"\n shows \"x \\ max_word - z\"\n apply (rule order_trans[OF assms(1)])\n using assms\n by simp\nlemma plus_lt_left_cancel_nowrap[simp]: \"x \\ x + y' \\ x \\ x + y \\ x + y' < x + y \\ y' < y\"\n for x y y' :: \"'a::len0 word\"\n by uint_arith\nlemma plus_lt_right_cancel_nowrap[simp]: \"x \\ x + y' \\ x \\ x + y \\ y' + x < y + x \\ y' < y\"\n for x y y' :: \"'a::len0 word\"\n by uint_arith\nlemma x_lt_x_plus_y[simp]:\n fixes x y :: \"'a::len word\"\n assumes \"x \\ max_word - y\"\n shows \"x < x + y \\ y > 0\"\nproof-\n have \"x \\ x + y\"\n apply (rule plus_minus_no_overflow_ab[of x \"max_word::'a::len word\" y,OF assms(1)])\n by auto\n thus ?thesis\n apply (auto simp add: word_le_less_eq)\n by uint_arith\nqed\n\n\n\nlemma gt_zero_is_le_one:\n fixes w :: \\'a::len word\\\n assumes \\0 < w\\\n shows \\1 \\ w\\\n using assms word_le_sub1\n by force\n\nlemma a_minus_b_lt[simp]:\n fixes a :: \"'a::len0 word\"\n assumes \"a \\ b\"\n shows \"(a - b < a) = (b > 0)\"\n using assms\n by unat_arith\n\nlemma a_minus_b_le[simp]:\n fixes a :: \"'a::len0 word\"\n assumes \"a \\ b\"\n shows \"(a - b \\ a)\"\n using assms\n by unat_arith\n\nlemma unat_ucast[OF refl]:\n assumes \"uc = ucast\"\n and \"is_up uc\"\n shows \"unat (uc a) = unat a\"\n using assms\n by (auto simp add: unat_def uint_up_ucast)\n\nlemma ucast_minus:\n fixes a b :: \"'a::len0 word\"\n shows \"ucast (a - b) = (if uint b \\ uint a then ucast a - ucast b else ucast a - ucast b + word_of_int (2 ^ LENGTH('a)))\"\n apply (auto simp add: ucast_def)\n apply (subst uint_sub_if')\n apply (auto simp add: wi_hom_syms(2))\n apply (subst uint_sub_if')\n by (auto simp add: wi_hom_syms ucast_def[symmetric])\n\nlemma ucast_plus:\n fixes a b :: \"'a::len0 word\"\n shows \"ucast (a + b) = (if uint a + uint b < 2 ^ LENGTH('a) then ucast a + ucast b else ucast a + ucast b - word_of_int (2 ^ LENGTH('a)))\"\n apply (auto simp add: ucast_def)\n apply (subst uint_plus_if_size)\n apply (auto simp add: word_size wi_hom_syms ucast_def[symmetric])\n apply (auto simp add: ucast_def)\n apply (subst uint_plus_if_size)\n by (auto simp add: word_size wi_hom_syms ucast_def[symmetric])\n\nlemma msb_is_gt_2p:\n fixes a :: \"'a::len word\"\n shows \"msb a \\ a \\ 2 ^ (LENGTH('a) - 1)\"\nproof-\n {\n assume 1: \"a !! (LENGTH('a) - 1)\"\n hence \"a \\ 2 ^ (LENGTH('a) - 1)\"\n using bang_is_le\n by (auto simp add: word_size)\n }\n moreover\n {\n assume 1: \"\\a!! (LENGTH('a) - 1)\"\n {\n fix i :: nat\n assume \"i < LENGTH('a)\"\n hence \"(a AND mask (LENGTH('a) - 1)) !! i = a !! i\"\n using 1\n by (cases \"i=LENGTH('a) - 1\",auto simp add: word_ao_nth word_size)\n }\n hence \"a AND mask (LENGTH('a) - 1) = a\"\n apply (intro word_eqI)\n by (auto simp add: word_size)\n hence \"a < 2 ^ (LENGTH('a) - 1)\"\n using mask_eq_iff_w2p[of \"LENGTH('a) - 1\" a]\n by (auto simp add: word_size)\n }\n ultimately\n show ?thesis\n unfolding msb_nth\n using linorder_not_le\n by blast\nqed\n\nlemma zero_le_2p:\n assumes \"n < LENGTH('a)\"\n shows \"(0::'a::len word) < 2 ^ n\"\n using assms\nproof(induct n)\n case 0\n thus ?case\n by auto\nnext\n case (Suc n)\n thus ?case\n using shiftl_1[symmetric,of \"n+1\",where 'a='a]\n using is_zero_shiftl[of \"1::'a word\" \"n+1\"]\n apply (auto simp del: shiftl_1)\n by fastforce\nqed\n\n\n\nlemma of_nat_unat_is_ucast[simp]:\n fixes a :: \"'a::len word\"\n assumes \"LENGTH('a) < LENGTH('b)\"\n shows \"of_nat (unat a) = (ucast a :: 'b::len word)\"\n apply (rule word_unat.Rep_eqD)\n apply (subst unat_of_nat)\n apply (subst unat_ucast)\n apply (subst is_up)\n using assms apply simp\n using unat_lt2p[of a] assms\n by (metis assms int_ops(3) lt2p_lem mod_less of_nat_less_iff of_nat_power order_less_imp_le uint_nat)\n\nlemma sextend_remove:\n fixes a :: \"'a::len word\"\n assumes \"a < 2^(s-1)\"\n shows \"sextend a s s' = \\s - Suc 0,0\\a\"\n using assms\n unfolding sextend.simps\n apply auto\n apply (frule bang_is_le)\n by auto\n\nend", "meta": {"author": "ssrg-vt", "repo": "Luce-src", "sha": "f7f1ef0fd07bba48bcb3d5e32404db6013a5f1bc", "save_path": "github-repos/isabelle/ssrg-vt-Luce-src", "path": "github-repos/isabelle/ssrg-vt-Luce-src/Luce-src-f7f1ef0fd07bba48bcb3d5e32404db6013a5f1bc/tacas2020_artifact/isabelle/Word_Additions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.11279539882690352, "lm_q1q2_score": 0.05375599181451385}} {"text": "(* Title: Miscellaneous Definitions and Lemmas\n Author: Peter Lammich \n Maintainer: Peter Lammich \n Thomas Tuerk \n*)\n\n(*\n CHANGELOG:\n 2010-05-09: Removed AC, AI locales, they are superseeded by concepts\n from OrderedGroups\n 2010-09-22: Merges with ext/Aux\n 2017-06-12: Added a bunch of lemmas from various other projects\n\n*)\n\nsection \\Miscellaneous Definitions and Lemmas\\\n\ntheory Misc\nimports Main\n \"HOL-Library.Multiset\"\n \"HOL-ex.Quicksort\"\n \"HOL-Library.Option_ord\"\n \"HOL-Library.Infinite_Set\"\n \"HOL-Eisbach.Eisbach\"\nbegin\ntext_raw \\\\label{thy:Misc}\\\n\n \nsubsection \\Isabelle Distribution Move Proposals\\ \n\nsubsubsection \\Pure\\\nlemma TERMI: \"TERM x\" unfolding Pure.term_def .\n \n \nsubsubsection \\HOL\\ \n(* Stronger disjunction elimination rules. *)\nlemma disjE1: \"\\ P \\ Q; P \\ R; \\\\P;Q\\ \\ R \\ \\ R\"\n by metis\nlemma disjE2: \"\\ P \\ Q; \\P; \\Q\\ \\ R; Q \\ R \\ \\ R\"\n by blast\n\nlemma imp_mp_iff[simp]: \n \"a \\ (a \\ b) \\ a \\ b\" \n \"(a \\ b) \\ a \\ a \\ b\" (* is Inductive.imp_conj_iff, but not in simpset by default *)\n by blast+\n \nlemma atomize_Trueprop_eq[atomize]: \"(Trueprop x \\ Trueprop y) \\ Trueprop (x=y)\"\n apply rule\n apply (rule)\n apply (erule equal_elim_rule1)\n apply assumption\n apply (erule equal_elim_rule2)\n apply assumption\n apply simp\n done\n \nsubsubsection \\Set\\ \nlemma inter_compl_diff_conv[simp]: \"A \\ -B = A - B\" by auto\nlemma pair_set_inverse[simp]: \"{(a,b). P a b}\\ = {(b,a). P a b}\"\n by auto\n\nlemma card_doubleton_eq_2_iff[simp]: \"card {a,b} = 2 \\ a\\b\" by auto\n\n \nsubsubsection \\List\\ \n(* TODO: Move, analogous to List.length_greater_0_conv *) \nthm List.length_greater_0_conv \nlemma length_ge_1_conv[iff]: \"Suc 0 \\ length l \\ l\\[]\"\n by (cases l) auto\n \n\\ \\Obtains a list from the pointwise characterization of its elements\\\nlemma obtain_list_from_elements:\n assumes A: \"\\ili. P li i)\"\n obtains l where\n \"length l = n\"\n \"\\il. length l=n \\ (\\iii l!j\"\n by (simp add: sorted_iff_nth_mono)\n also from nth_eq_iff_index_eq[OF D] B have \"l!i \\ l!j\"\n by auto\n finally show ?thesis .\nqed\n\nlemma distinct_sorted_strict_mono_iff:\n assumes \"distinct l\" \"sorted l\"\n assumes \"i il!j \\ i\\j\"\n by (metis assms distinct_sorted_strict_mono_iff leD le_less_linear)\n \n \n(* List.thy has:\n declare map_eq_Cons_D [dest!] Cons_eq_map_D [dest!] \n\n We could, analogously, declare rules for \"map _ _ = _@_\" as dest!,\n or use elim!, or declare the _conv-rule as simp\n*) \n \nlemma map_eq_appendE: \n assumes \"map f ls = fl@fl'\"\n obtains l l' where \"ls=l@l'\" and \"map f l=fl\" and \"map f l' = fl'\"\n using assms \nproof (induction fl arbitrary: ls thesis)\n case (Cons x xs)\n then obtain l ls' where [simp]: \"ls = l#ls'\" \"f l = x\" by force\n with Cons.prems(2) have \"map f ls' = xs @ fl'\" by simp\n from Cons.IH[OF _ this] guess ll ll' .\n with Cons.prems(1)[of \"l#ll\" ll'] show thesis by simp\nqed simp\n\nlemma map_eq_append_conv: \"map f ls = fl@fl' \\ (\\l l'. ls = l@l' \\ map f l = fl \\ map f l' = fl')\"\n by (auto elim!: map_eq_appendE)\n \nlemmas append_eq_mapE = map_eq_appendE[OF sym]\n \nlemma append_eq_map_conv: \"fl@fl' = map f ls \\ (\\l l'. ls = l@l' \\ map f l = fl \\ map f l' = fl')\"\n by (auto elim!: append_eq_mapE)\n \n \nlemma distinct_mapI: \"distinct (map f l) \\ distinct l\"\n by (induct l) auto\n \nlemma map_distinct_upd_conv: \n \"\\i \\ (map f l)[i := x] = map (f(l!i := x)) l\"\n \\ \\Updating a mapped distinct list is equal to updating the \n mapping function\\\n by (auto simp: nth_eq_iff_index_eq intro: nth_equalityI)\n\n \nlemma zip_inj: \"\\length a = length b; length a' = length b'; zip a b = zip a' b'\\ \\ a=a' \\ b=b'\"\nproof (induct a b arbitrary: a' b' rule: list_induct2)\n case Nil\n then show ?case by (cases a'; cases b'; auto)\nnext\n case (Cons x xs y ys)\n then show ?case by (cases a'; cases b'; auto)\nqed\n\nlemma zip_eq_zip_same_len[simp]:\n \"\\ length a = length b; length a' = length b' \\ \\\n zip a b = zip a' b' \\ a=a' \\ b=b'\"\n by (auto dest: zip_inj)\n \n \nlemma upt_merge[simp]: \"i\\j \\ j\\k \\ [i.. (ys \\ [] \\ butlast ys = xs \\ last ys = x)\"\n by auto\n\n(* Case distinction how two elements of a list can be related to each other *)\nlemma list_match_lel_lel:\n assumes \"c1 @ qs # c2 = c1' @ qs' # c2'\"\n obtains\n (left) c21' where \"c1 = c1' @ qs' # c21'\" \"c2' = c21' @ qs # c2\"\n | (center) \"c1' = c1\" \"qs' = qs\" \"c2' = c2\"\n | (right) c21 where \"c1' = c1 @ qs # c21\" \"c2 = c21 @ qs' # c2'\"\n using assms \n apply (clarsimp simp: append_eq_append_conv2) \n subgoal for us by (cases us) auto\n done \n \nlemma xy_in_set_cases[consumes 2, case_names EQ XY YX]:\n assumes A: \"x\\set l\" \"y\\set l\"\n and C:\n \"!!l1 l2. \\ x=y; l=l1@y#l2 \\ \\ P\"\n \"!!l1 l2 l3. \\ x\\y; l=l1@x#l2@y#l3 \\ \\ P\"\n \"!!l1 l2 l3. \\ x\\y; l=l1@y#l2@x#l3 \\ \\ P\"\n shows P\nproof (cases \"x=y\")\n case True with A(1) obtain l1 l2 where \"l=l1@y#l2\" by (blast dest: split_list)\n with C(1) True show ?thesis by blast\nnext\n case False\n from A(1) obtain l1 l2 where S1: \"l=l1@x#l2\" by (blast dest: split_list)\n from A(2) obtain l1' l2' where S2: \"l=l1'@y#l2'\" by (blast dest: split_list)\n from S1 S2 have M: \"l1@x#l2 = l1'@y#l2'\" by simp\n thus P proof (cases rule: list_match_lel_lel[consumes 1, case_names 1 2 3])\n case (1 c) with S1 have \"l=l1'@y#c@x#l2\" by simp\n with C(3) False show ?thesis by blast\n next\n case 2 with False have False by blast\n thus ?thesis ..\n next\n case (3 c) with S1 have \"l=l1@x#c@y#l2'\" by simp\n with C(2) False show ?thesis by blast\n qed\nqed\n \n \nlemma list_e_eq_lel[simp]:\n \"[e] = l1@e'#l2 \\ l1=[] \\ e'=e \\ l2=[]\"\n \"l1@e'#l2 = [e] \\ l1=[] \\ e'=e \\ l2=[]\"\n apply (cases l1, auto) []\n apply (cases l1, auto) []\n done\n\nlemma list_ee_eq_leel[simp]:\n \"([e1,e2] = l1@e1'#e2'#l2) \\ (l1=[] \\ e1=e1' \\ e2=e2' \\ l2=[])\"\n \"(l1@e1'#e2'#l2 = [e1,e2]) \\ (l1=[] \\ e1=e1' \\ e2=e2' \\ l2=[])\"\n apply (cases l1, auto) []\n apply (cases l1, auto) []\n done\n\n\nsubsubsection \\Transitive Closure\\\n\ntext \\A point-free induction rule for elements reachable from an initial set\\\nlemma rtrancl_reachable_induct[consumes 0, case_names base step]:\n assumes I0: \"I \\ INV\"\n assumes IS: \"E``INV \\ INV\"\n shows \"E\\<^sup>*``I \\ INV\"\n by (metis I0 IS Image_closed_trancl Image_mono subset_refl)\n \n\nlemma acyclic_empty[simp, intro!]: \"acyclic {}\" by (unfold acyclic_def) auto\n\nlemma acyclic_union:\n \"acyclic (A\\B) \\ acyclic A\"\n \"acyclic (A\\B) \\ acyclic B\"\n by (metis Un_upper1 Un_upper2 acyclic_subset)+\n \n \n \nsubsubsection \\Lattice Syntax\\ \n(* Providing the syntax in a locale makes it more usable, without polluting the global namespace*) \nlocale Lattice_Syntax begin\n notation\n bot (\"\\\") and\n top (\"\\\") and\n inf (infixl \"\\\" 70) and\n sup (infixl \"\\\" 65) and\n Inf (\"\\_\" [900] 900) and\n Sup (\"\\_\" [900] 900)\n\nend\n \n \n \ntext \\Here we provide a collection of miscellaneous definitions and helper lemmas\\\n\nsubsection \"Miscellaneous (1)\"\n\ntext \\This stuff is used in this theory itself, and thus occurs in first place or is simply not sorted into any other section of this theory.\\\n\nlemma IdD: \"(a,b)\\Id \\ a=b\" by simp\n\ntext \\Conversion Tag\\ \ndefinition [simp]: \"CNV x y \\ x=y\"\nlemma CNV_I: \"CNV x x\" by simp\nlemma CNV_eqD: \"CNV x y \\ x=y\" by simp\nlemma CNV_meqD: \"CNV x y \\ x\\y\" by simp\n \n(* TODO: Move. Shouldn't this be detected by simproc? *)\nlemma ex_b_b_and_simp[simp]: \"(\\b. b \\ Q b) \\ Q True\" by auto\nlemma ex_b_not_b_and_simp[simp]: \"(\\b. \\b \\ Q b) \\ Q False\" by auto\n \nmethod repeat_all_new methods m = m;(repeat_all_new \\m\\)?\n \n \nsubsubsection \"AC-operators\"\n\ntext \\Locale to declare AC-laws as simplification rules\\\nlocale Assoc =\n fixes f\n assumes assoc[simp]: \"f (f x y) z = f x (f y z)\"\n\nlocale AC = Assoc +\n assumes commute[simp]: \"f x y = f y x\"\n\nlemma (in AC) left_commute[simp]: \"f x (f y z) = f y (f x z)\"\n by (simp only: assoc[symmetric]) simp\n\nlemmas (in AC) AC_simps = commute assoc left_commute\n\ntext \\Locale to define functions from surjective, unique relations\\\nlocale su_rel_fun =\n fixes F and f\n assumes unique: \"\\(A,B)\\F; (A,B')\\F\\ \\ B=B'\"\n assumes surjective: \"\\!!B. (A,B)\\F \\ P\\ \\ P\"\n assumes f_def: \"f A == THE B. (A,B)\\F\"\n\nlemma (in su_rel_fun) repr1: \"(A,f A)\\F\" proof (unfold f_def)\n obtain B where \"(A,B)\\F\" by (rule surjective)\n with theI[where P=\"\\B. (A,B)\\F\", OF this] show \"(A, THE x. (A, x) \\ F) \\ F\" by (blast intro: unique)\nqed\n\nlemma (in su_rel_fun) repr2: \"(A,B)\\F \\ B=f A\" using repr1\n by (blast intro: unique)\n\nlemma (in su_rel_fun) repr: \"(f A = B) = ((A,B)\\F)\" using repr1 repr2\n by (blast)\n\n \\ \\Contract quantification over two variables to pair\\\nlemma Ex_prod_contract: \"(\\a b. P a b) \\ (\\z. P (fst z) (snd z))\"\n by auto\n\nlemma All_prod_contract: \"(\\a b. P a b) \\ (\\z. P (fst z) (snd z))\"\n by auto\n\n\nlemma nat_geq_1_eq_neqz: \"x\\1 \\ x\\(0::nat)\"\n by auto\n\nlemma nat_in_between_eq:\n \"(a b\\Suc a) \\ b = Suc a\"\n \"(a\\b \\ b b = a\"\n by auto\n\nlemma Suc_n_minus_m_eq: \"\\ n\\m; m>1 \\ \\ Suc (n - m) = n - (m - 1)\"\n by simp\n\nlemma Suc_to_right: \"Suc n = m \\ n = m - Suc 0\" by simp\nlemma Suc_diff[simp]: \"\\n m. n\\m \\ m\\1 \\ Suc (n - m) = n - (m - 1)\"\n by simp\n\nlemma if_not_swap[simp]: \"(if \\c then a else b) = (if c then b else a)\" by auto\nlemma all_to_meta: \"Trueprop (\\a. P a) \\ (\\a. P a)\"\n apply rule\n by auto\n\nlemma imp_to_meta: \"Trueprop (P\\Q) \\ (P\\Q)\"\n apply rule\n by auto\n\n\n(* for some reason, there is no such rule in HOL *)\nlemma iffI2: \"\\P \\ Q; \\ P \\ \\ Q\\ \\ P \\ Q\"\nby metis\n\nlemma iffExI:\n \"\\ \\x. P x \\ Q x; \\x. Q x \\ P x \\ \\ (\\x. P x) \\ (\\x. Q x)\"\nby metis\n\nlemma bex2I[intro?]: \"\\ (a,b)\\S; (a,b)\\S \\ P a b \\ \\ \\a b. (a,b)\\S \\ P a b\"\n by blast\n\n \n(* TODO: Move lemma to HOL! *) \nlemma cnv_conj_to_meta: \"(P \\ Q \\ PROP X) \\ (\\P;Q\\ \\ PROP X)\"\n by (rule BNF_Fixpoint_Base.conj_imp_eq_imp_imp)\n \n \n\nsubsection \\Sets\\\n lemma remove_subset: \"x\\S \\ S-{x} \\ S\" by auto\n\n lemma subset_minus_empty: \"A\\B \\ A-B = {}\" by auto\n\n lemma insert_minus_eq: \"x\\y \\ insert x A - {y} = insert x (A - {y})\" by auto\n \n lemma set_notEmptyE: \"\\S\\{}; !!x. x\\S \\ P\\ \\ P\"\n by (metis equals0I)\n\n lemma subset_Collect_conv: \"S \\ Collect P \\ (\\x\\S. P x)\"\n by auto\n\n lemma memb_imp_not_empty: \"x\\S \\ S\\{}\"\n by auto\n\n lemma disjoint_mono: \"\\ a\\a'; b\\b'; a'\\b'={} \\ \\ a\\b={}\" by auto\n\n lemma disjoint_alt_simp1: \"A-B = A \\ A\\B = {}\" by auto\n lemma disjoint_alt_simp2: \"A-B \\ A \\ A\\B \\ {}\" by auto\n lemma disjoint_alt_simp3: \"A-B \\ A \\ A\\B \\ {}\" by auto\n\n lemma disjointI[intro?]: \"\\ \\x. \\x\\a; x\\b\\ \\ False \\ \\ a\\b={}\"\n by auto\n\n\n lemmas set_simps = subset_minus_empty disjoint_alt_simp1 disjoint_alt_simp2 disjoint_alt_simp3 Un_absorb1 Un_absorb2\n\n lemma set_minus_singleton_eq: \"x\\X \\ X-{x} = X\"\n by auto\n\n lemma set_diff_diff_left: \"A-B-C = A-(B\\C)\"\n by auto\n\n\n lemma image_update[simp]: \"x\\A \\ f(x:=n)`A = f`A\"\n by auto\n\n lemma eq_or_mem_image_simp[simp]: \"{f l |l. l = a \\ l\\B} = insert (f a) {f l|l. l\\B}\" by blast\n \n lemma set_union_code [code_unfold]:\n \"set xs \\ set ys = set (xs @ ys)\"\n by auto\n\n lemma in_fst_imageE:\n assumes \"x \\ fst`S\"\n obtains y where \"(x,y)\\S\"\n using assms by auto\n\n lemma in_snd_imageE:\n assumes \"y \\ snd`S\"\n obtains x where \"(x,y)\\S\"\n using assms by auto\n\n lemma fst_image_mp: \"\\fst`A \\ B; (x,y)\\A \\ \\ x\\B\"\n by (metis Domain.DomainI fst_eq_Domain in_mono)\n\n lemma snd_image_mp: \"\\snd`A \\ B; (x,y)\\A \\ \\ y\\B\"\n by (metis Range.intros rev_subsetD snd_eq_Range)\n\n lemma inter_eq_subsetI: \"\\ S\\S'; A\\S' = B\\S' \\ \\ A\\S = B\\S\"\n by auto\n\ntext \\\n Decompose general union over sum types.\n\\\nlemma Union_plus:\n \"(\\ x \\ A <+> B. f x) = (\\ a \\ A. f (Inl a)) \\ (\\b \\ B. f (Inr b))\"\nby auto\n\nlemma Union_sum:\n \"(\\x. f (x::'a+'b)) = (\\l. f (Inl l)) \\ (\\r. f (Inr r))\"\n (is \"?lhs = ?rhs\")\nproof -\n have \"?lhs = (\\x \\ UNIV <+> UNIV. f x)\"\n by simp\n thus ?thesis\n by (simp only: Union_plus)\nqed\n\n \n\n\n subsubsection \\Finite Sets\\\n\n lemma card_1_singletonI: \"\\finite S; card S = 1; x\\S\\ \\ S={x}\"\n proof (safe, rule ccontr, goal_cases)\n case prems: (1 x')\n hence \"finite (S-{x})\" \"S-{x} \\ {}\" by auto\n hence \"card (S-{x}) \\ 0\" by auto\n moreover from prems(1-3) have \"card (S-{x}) = 0\" by auto\n ultimately have False by simp\n thus ?case ..\n qed\n\n lemma card_insert_disjoint': \"\\finite A; x \\ A\\ \\ card (insert x A) - Suc 0 = card A\"\n by (drule (1) card_insert_disjoint) auto\n\n lemma card_eq_UNIV[simp]: \"card (S::'a::finite set) = card (UNIV::'a set) \\ S=UNIV\"\n proof (auto)\n fix x\n assume A: \"card S = card (UNIV::'a set)\"\n show \"x\\S\" proof (rule ccontr)\n assume \"x\\S\" hence \"S\\UNIV\" by auto\n with psubset_card_mono[of UNIV S] have \"card S < card (UNIV::'a set)\" by auto\n with A show False by simp\n qed\n qed\n\n lemma card_eq_UNIV2[simp]: \"card (UNIV::'a set) = card (S::'a::finite set) \\ S=UNIV\"\n using card_eq_UNIV[of S] by metis\n\n lemma card_ge_UNIV[simp]: \"card (UNIV::'a::finite set) \\ card (S::'a set) \\ S=UNIV\"\n using card_mono[of \"UNIV::'a::finite set\" S, simplified]\n by auto\n\n lemmas length_remdups_card = length_remdups_concat[of \"[l]\", simplified] for l\n\n lemma fs_contract: \"fst ` { p | p. f (fst p) (snd p) \\ S } = { a . \\b. f a b \\ S }\"\n by (simp add: image_Collect)\n\nlemma finite_Collect: \"finite S \\ inj f \\ finite {a. f a : S}\"\nby(simp add: finite_vimageI vimage_def[symmetric])\n\n \\ \\Finite sets have an injective mapping to an initial segments of the\n natural numbers\\\n (* This lemma is also in the standard library (from Isabelle2009-1 on)\n as @{thm [source] Finite_Set.finite_imp_inj_to_nat_seg}. However, it is formulated with HOL's\n \\ there rather then with the meta-logic obtain *)\n lemma finite_imp_inj_to_nat_seg':\n fixes A :: \"'a set\"\n assumes A: \"finite A\"\n obtains f::\"'a \\ nat\" and n::\"nat\" where\n \"f`A = {i. i finite (lists P \\ { l. n = length l })\"\n proof -\n assume A: \"finite P\"\n have S: \"{ l. n = length l } = { l. length l = n }\" by auto\n have \"finite (lists P \\ { l. n = length l })\n \\ finite (lists P \\ { l. length l = n })\"\n by (subst S) simp\n\n thus ?thesis using lists_of_len_fin1[OF A] by auto\n qed\n\n lemmas lists_of_len_fin = lists_of_len_fin1 lists_of_len_fin2\n\n\n (* Try (simp only: cset_fin_simps, fastforce intro: cset_fin_intros) when reasoning about finiteness of collected sets *)\n lemmas cset_fin_simps = Ex_prod_contract fs_contract[symmetric] image_Collect[symmetric]\n lemmas cset_fin_intros = finite_imageI finite_Collect inj_onI\n\n\nlemma Un_interval:\n fixes b1 :: \"'a::linorder\"\n assumes \"b1\\b2\" and \"b2\\b3\"\n shows \"{ f i | i. b1\\i \\ i { f i | i. b2\\i \\ ii \\ i\n The standard library proves that a generalized union is finite\n if the index set is finite and if for every index the component\n set is itself finite. Conversely, we show that every component\n set must be finite when the union is finite.\n\\\nlemma finite_UNION_then_finite:\n \"finite (\\(B ` A)) \\ a \\ A \\ finite (B a)\"\nby (metis Set.set_insert UN_insert Un_infinite)\n\nlemma finite_if_eq_beyond_finite: \"finite S \\ finite {s. s - S = s' - S}\"\nproof (rule finite_subset[where B=\"(\\s. s \\ (s' - S)) ` Pow S\"], clarsimp)\n fix s\n have \"s = (s \\ S) \\ (s - S)\"\n by auto\n also assume \"s - S = s' - S\"\n finally show \"s \\ (\\s. s \\ (s' - S)) ` Pow S\" by blast\nqed blast\n\nlemma distinct_finite_subset:\n assumes \"finite x\"\n shows \"finite {ys. set ys \\ x \\ distinct ys}\" (is \"finite ?S\")\nproof (rule finite_subset)\n from assms show \"?S \\ {ys. set ys \\ x \\ length ys \\ card x}\"\n by clarsimp (metis distinct_card card_mono)\n from assms show \"finite ...\" by (rule finite_lists_length_le)\nqed\n\nlemma distinct_finite_set:\n shows \"finite {ys. set ys = x \\ distinct ys}\" (is \"finite ?S\")\nproof (cases \"finite x\")\n case False hence \"{ys. set ys = x} = {}\" by auto\n thus ?thesis by simp\nnext\n case True show ?thesis\n proof (rule finite_subset)\n show \"?S \\ {ys. set ys \\ x \\ length ys \\ card x}\"\n using distinct_card by force\n from True show \"finite ...\" by (rule finite_lists_length_le)\n qed\nqed\n\nlemma finite_set_image:\n assumes f: \"finite (set ` A)\"\n and dist: \"\\xs. xs \\ A \\ distinct xs\"\n shows \"finite A\"\nproof (rule finite_subset)\n from f show \"finite (set -` (set ` A) \\ {xs. distinct xs})\"\n proof (induct rule: finite_induct)\n case (insert x F)\n have \"finite (set -` {x} \\ {xs. distinct xs})\"\n apply (simp add: vimage_def)\n by (metis Collect_conj_eq distinct_finite_set)\n with insert show ?case\n apply (subst vimage_insert)\n apply (subst Int_Un_distrib2)\n apply (rule finite_UnI)\n apply simp_all\n done\n qed simp\n moreover from dist show \"A \\ ...\"\n by (auto simp add: vimage_image_eq)\nqed\n\n\nsubsubsection \\Infinite Set\\\nlemma INFM_nat_inductI:\n assumes P0: \"P (0::nat)\"\n assumes PS: \"\\i. P i \\ \\j>i. P j \\ Q j\"\n shows \"\\\\<^sub>\\i. Q i\"\nproof -\n have \"\\i. \\j>i. P j \\ Q j\" proof\n fix i\n show \"\\j>i. P j \\ Q j\"\n apply (induction i)\n using PS[OF P0] apply auto []\n by (metis PS Suc_lessI)\n qed\n thus ?thesis unfolding INFM_nat by blast\nqed\n\nsubsection \\Functions\\\n\nlemma fun_neq_ext_iff: \"m\\m' \\ (\\x. m x \\ m' x)\" by auto \n\ndefinition \"inv_on f A x == SOME y. y\\A \\ f y = x\"\n\nlemma inv_on_f_f[simp]: \"\\inj_on f A; x\\A\\ \\ inv_on f A (f x) = x\"\n by (auto simp add: inv_on_def inj_on_def)\n\nlemma f_inv_on_f: \"\\ y\\f`A \\ \\ f (inv_on f A y) = y\"\n by (auto simp add: inv_on_def intro: someI2)\n\nlemma inv_on_f_range: \"\\ y \\ f`A \\ \\ inv_on f A y \\ A\"\n by (auto simp add: inv_on_def intro: someI2)\n\nlemma inj_on_map_inv_f [simp]: \"\\set l \\ A; inj_on f A\\ \\ map (inv_on f A) (map f l) = l\"\n apply (simp)\n apply (induct l)\n apply auto\n done\n\nlemma comp_cong_right: \"x = y \\ f o x = f o y\" by (simp)\nlemma comp_cong_left: \"x = y \\ x o f = y o f\" by (simp)\n\nlemma fun_comp_eq_conv: \"f o g = fg \\ (\\x. f (g x) = fg x)\"\n by auto\n\nabbreviation comp2 (infixl \"oo\" 55) where \"f oo g \\ \\x. f o (g x)\"\nabbreviation comp3 (infixl \"ooo\" 55) where \"f ooo g \\ \\x. f oo (g x)\"\n\nnotation\n comp2 (infixl \"\\\\\" 55) and\n comp3 (infixl \"\\\\\\\" 55)\n\ndefinition [code_unfold, simp]: \"swap_args2 f x y \\ f y x\"\n \n\nsubsection \\Multisets\\\n\n(*\n The following is a syntax extension for multisets. Unfortunately, it depends on a change in the Library/Multiset.thy, so it is commented out here, until it will be incorporated\n into Library/Multiset.thy by its maintainers.\n\n The required change in Library/Multiset.thy is removing the syntax for single:\n - single :: \"'a => 'a multiset\" (\"{#_#}\")\n + single :: \"'a => 'a multiset\"\n\n And adding the following translations instead:\n\n + syntax\n + \"_multiset\" :: \"args \\ 'a multiset\" (\"{#(_)#}\")\n\n + translations\n + \"{#x, xs#}\" == \"{#x#} + {#xs#}\"\n + \"{# x #}\" == \"single x\"\n\n This translates \"{# \\ #}\" into a sum of singletons, that is parenthesized to the right. ?? Can we also achieve left-parenthesizing ??\n\n*)\n\n\n (* Let's try what happens if declaring AC-rules for multiset union as simp-rules *)\n(*declare union_ac[simp] -- don't do it !*)\n\n\nlemma count_mset_set_finite_iff:\n \"finite S \\ count (mset_set S) a = (if a \\ S then 1 else 0)\"\n by simp\n\nlemma ex_Melem_conv: \"(\\x. x \\# A) = (A \\ {#})\"\n by (simp add: ex_in_conv)\n\nsubsubsection \\Count\\\n lemma count_ne_remove: \"\\ x ~= t\\ \\ count S x = count (S-{#t#}) x\"\n by (auto)\n lemma mset_empty_count[simp]: \"(\\p. count M p = 0) = (M={#})\"\n by (auto simp add: multiset_eq_iff)\n\nsubsubsection \\Union, difference and intersection\\\n\n lemma size_diff_se: \"t \\# S \\ size S = size (S - {#t#}) + 1\" proof (unfold size_multiset_overloaded_eq)\n let ?SIZE = \"sum (count S) (set_mset S)\"\n assume A: \"t \\# S\"\n from A have SPLITPRE: \"finite (set_mset S) & {t}\\(set_mset S)\" by auto\n hence \"?SIZE = sum (count S) (set_mset S - {t}) + sum (count S) {t}\" by (blast dest: sum.subset_diff)\n hence \"?SIZE = sum (count S) (set_mset S - {t}) + count (S) t\" by auto\n moreover with A have \"count S t = count (S-{#t#}) t + 1\" by auto\n ultimately have D: \"?SIZE = sum (count S) (set_mset S - {t}) + count (S-{#t#}) t + 1\" by (arith)\n moreover have \"sum (count S) (set_mset S - {t}) = sum (count (S-{#t#})) (set_mset S - {t})\" proof -\n have \"\\x\\(set_mset S - {t}). count S x = count (S-{#t#}) x\" by (auto iff add: count_ne_remove)\n thus ?thesis by simp\n qed\n ultimately have D: \"?SIZE = sum (count (S-{#t#})) (set_mset S - {t}) + count (S-{#t#}) t + 1\" by (simp)\n moreover\n { assume CASE: \"t \\# S - {#t#}\"\n from CASE have \"set_mset S - {t} = set_mset (S - {#t#})\"\n by (auto simp add: in_diff_count split: if_splits)\n with CASE D have \"?SIZE = sum (count (S-{#t#})) (set_mset (S - {#t#})) + 1\"\n by (simp add: not_in_iff)\n }\n moreover\n { assume CASE: \"t \\# S - {#t#}\"\n from CASE have \"t \\# S\" by (rule in_diffD)\n with CASE have 1: \"set_mset S = set_mset (S-{#t#})\"\n by (auto simp add: in_diff_count split: if_splits)\n moreover from D have \"?SIZE = sum (count (S-{#t#})) (set_mset S - {t}) + sum (count (S-{#t#})) {t} + 1\" by simp\n moreover from SPLITPRE sum.subset_diff have \"sum (count (S-{#t#})) (set_mset S) = sum (count (S-{#t#})) (set_mset S - {t}) + sum (count (S-{#t#})) {t}\" by (blast)\n ultimately have \"?SIZE = sum (count (S-{#t#})) (set_mset (S-{#t#})) + 1\" by simp\n }\n ultimately show \"?SIZE = sum (count (S-{#t#})) (set_mset (S - {#t#})) + 1\" by blast\n qed\n\n (* TODO: Check whether this proof can be done simpler *)\n lemma mset_union_diff_comm: \"t \\# S \\ T + (S - {#t#}) = (T + S) - {#t#}\" proof -\n assume \"t \\# S\"\n then obtain S' where S: \"S = add_mset t S'\"\n by (metis insert_DiffM)\n then show ?thesis\n by auto\n qed\n\n(* lemma mset_diff_diff_left: \"A-B-C = A-((B::'a multiset)+C)\" proof -\n have \"\\e . count (A-B-C) e = count (A-(B+C)) e\" by auto\n thus ?thesis by (simp add: multiset_eq_conv_count_eq)\n qed\n\n lemma mset_diff_commute: \"A-B-C = A-C-(B::'a multiset)\" proof -\n have \"A-B-C = A-(B+C)\" by (simp add: mset_diff_diff_left)\n also have \"\\ = A-(C+B)\" by (simp add: union_commute)\n thus ?thesis by (simp add: mset_diff_diff_left)\n qed\n\n lemma mset_diff_same_empty[simp]: \"(S::'a multiset) - S = {#}\"\n proof -\n have \"\\e . count (S-S) e = 0\" by auto\n hence \"\\e . ~ (e : set_mset (S-S))\" by auto\n hence \"set_mset (S-S) = {}\" by blast\n thus ?thesis by (auto)\n qed\n*)\n \n lemma mset_right_cancel_union: \"\\a \\# A+B; ~(a \\# B)\\ \\ a\\#A\"\n by (simp)\n lemma mset_left_cancel_union: \"\\a \\# A+B; ~(a \\# A)\\ \\ a\\#B\"\n by (simp)\n\n lemmas mset_cancel_union = mset_right_cancel_union mset_left_cancel_union\n\n lemma mset_right_cancel_elem: \"\\a \\# A+{#b#}; a~=b\\ \\ a\\#A\"\n by simp\n\n lemma mset_left_cancel_elem: \"\\a \\# {#b#}+A; a~=b\\ \\ a\\#A\"\n by simp\n\n lemmas mset_cancel_elem = mset_right_cancel_elem mset_left_cancel_elem\n\n lemma mset_diff_cancel1elem[simp]: \"~(a \\# B) \\ {#a#}-B = {#a#}\"\n by (auto simp add: not_in_iff intro!: multiset_eqI)\n\n(* lemma diff_union_inverse[simp]: \"A + B - B = (A::'a multiset)\"\n by (auto iff add: multiset_eq_conv_count_eq)\n\n lemma diff_union_inverse2[simp]: \"B + A - B = (A::'a multiset)\"\n by (auto iff add: multiset_eq_conv_count_eq)\n*)\n (*lemma union_diff_assoc_se2: \"t \\# A \\ (A+B)-{#t#} = (A-{#t#}) + B\"\n by (auto iff add: multiset_eq_conv_count_eq)\n lemmas union_diff_assoc_se = union_diff_assoc_se1 union_diff_assoc_se2*)\n\n lemma union_diff_assoc: \"C-B={#} \\ (A+B)-C = A + (B-C)\"\n by (simp add: multiset_eq_iff)\n\n lemmas mset_neutral_cancel1 = union_left_cancel[where N=\"{#}\", simplified] union_right_cancel[where N=\"{#}\", simplified]\n declare mset_neutral_cancel1[simp]\n\n lemma mset_union_2_elem: \"{#a, b#} = add_mset c M \\ {#a#}=M & b=c | a=c & {#b#}=M\"\n by (auto simp: add_eq_conv_diff)\n\n lemma mset_un_cases[cases set, case_names left right]:\n \"\\a \\# A + B; a \\# A \\ P; a \\# B \\ P\\ \\ P\"\n by (auto)\n\n lemma mset_unplusm_dist_cases[cases set, case_names left right]:\n assumes A: \"{#s#}+A = B+C\"\n assumes L: \"\\B={#s#}+(B-{#s#}); A=(B-{#s#})+C\\ \\ P\"\n assumes R: \"\\C={#s#}+(C-{#s#}); A=B+(C-{#s#})\\ \\ P\"\n shows P\n proof -\n from A[symmetric] have \"s \\# B+C\" by simp\n thus ?thesis proof (cases rule: mset_un_cases)\n case left hence 1: \"B={#s#}+(B-{#s#})\" by simp\n with A have \"{#s#}+A = {#s#}+((B-{#s#})+C)\" by (simp add: union_ac)\n hence 2: \"A = (B-{#s#})+C\" by (simp)\n from L[OF 1 2] show ?thesis .\n next\n case right hence 1: \"C={#s#}+(C-{#s#})\" by simp\n with A have \"{#s#}+A = {#s#}+(B+(C-{#s#}))\" by (simp add: union_ac)\n hence 2: \"A = B+(C-{#s#})\" by (simp)\n from R[OF 1 2] show ?thesis .\n qed\n qed\n\n lemma mset_unplusm_dist_cases2[cases set, case_names left right]:\n assumes A: \"B+C = {#s#}+A\"\n assumes L: \"\\B={#s#}+(B-{#s#}); A=(B-{#s#})+C\\ \\ P\"\n assumes R: \"\\C={#s#}+(C-{#s#}); A=B+(C-{#s#})\\ \\ P\"\n shows P\n using mset_unplusm_dist_cases[OF A[symmetric]] L R by blast\n\n lemma mset_single_cases[cases set, case_names loc env]:\n assumes A: \"add_mset s c = add_mset r' c'\"\n assumes CASES: \"\\s=r'; c=c'\\ \\ P\" \"\\c'={#s#}+(c'-{#s#}); c={#r'#}+(c-{#r'#}); c-{#r'#} = c'-{#s#} \\ \\ P\"\n shows \"P\"\n proof -\n { assume CASE: \"s=r'\"\n with A have \"c=c'\" by simp\n with CASE CASES have ?thesis by auto\n } moreover {\n assume CASE: \"s\\r'\"\n have \"s \\# {#s#}+c\" by simp\n with A have \"s \\# {#r'#}+c'\" by simp\n with CASE have \"s \\# c'\" by simp\n hence 1: \"c' = {#s#} + (c' - {#s#})\" by simp\n with A have \"{#s#}+c = {#s#}+({#r'#}+(c' - {#s#}))\" by (auto simp add: union_ac)\n hence 2: \"c={#r'#}+(c' - {#s#})\" by (auto)\n hence 3: \"c-{#r'#} = (c' - {#s#})\" by auto\n from 1 2 3 CASES have ?thesis by auto\n } ultimately show ?thesis by blast\n qed\n\n lemma mset_single_cases'[cases set, case_names loc env]:\n assumes A: \"add_mset s c = add_mset r' c'\"\n assumes CASES: \"\\s=r'; c=c'\\ \\ P\" \"!!cc. \\c'={#s#}+cc; c={#r'#}+cc; c'-{#s#}=cc; c-{#r'#}=cc\\ \\ P\"\n shows \"P\"\n using A CASES by (auto elim!: mset_single_cases)\n\n lemma mset_single_cases2[cases set, case_names loc env]:\n assumes A: \"add_mset s c = add_mset r' c'\"\n assumes CASES: \"\\s=r'; c=c'\\ \\ P\" \"\\c'=(c'-{#s#})+{#s#}; c=(c-{#r'#})+{#r'#}; c-{#r'#} = c'-{#s#} \\ \\ P\"\n shows \"P\"\n proof -\n from A have \"add_mset s c = add_mset r' c'\" by (simp add: union_ac)\n thus ?thesis using CASES by (cases rule: mset_single_cases) simp_all\n qed\n\n lemma mset_single_cases2'[cases set, case_names loc env]:\n assumes A: \"add_mset s c = add_mset r' c'\"\n assumes CASES: \"\\s=r'; c=c'\\ \\ P\" \"!!cc. \\c'=cc+{#s#}; c=cc+{#r'#}; c'-{#s#}=cc; c-{#r'#}=cc\\ \\ P\"\n shows \"P\"\n using A CASES by (auto elim!: mset_single_cases2)\n\n lemma mset_un_single_un_cases [consumes 1, case_names left right]:\n assumes A: \"add_mset a A = B + C\"\n and CASES: \"a \\# B \\ A = (B - {#a#}) + C \\ P\"\n \"a \\# C \\ A = B + (C - {#a#}) \\ P\" shows \"P\"\n proof -\n have \"a \\# A+{#a#}\" by simp\n with A have \"a \\# B+C\" by auto\n thus ?thesis proof (cases rule: mset_un_cases)\n case left hence \"B=B-{#a#}+{#a#}\" by auto\n with A have \"A+{#a#} = (B-{#a#})+C+{#a#}\" by (auto simp add: union_ac)\n hence \"A=(B-{#a#})+C\" by simp\n with CASES(1)[OF left] show ?thesis by blast\n next\n case right hence \"C=C-{#a#}+{#a#}\" by auto\n with A have \"A+{#a#} = B+(C-{#a#})+{#a#}\" by (auto simp add: union_ac)\n hence \"A=B+(C-{#a#})\" by simp\n with CASES(2)[OF right] show ?thesis by blast\n qed\n qed\n\n (* TODO: Can this proof be done more automatically ? *)\n lemma mset_distrib[consumes 1, case_names dist]: assumes A: \"(A::'a multiset)+B = M+N\" \"!!Am An Bm Bn. \\A=Am+An; B=Bm+Bn; M=Am+Bm; N=An+Bn\\ \\ P\" shows \"P\"\n proof -\n have BN_MA: \"B - N = M - A\"\n by (metis (no_types) add_diff_cancel_right assms(1) union_commute)\n have H: \"A = A\\# C + (A - C) \\# D\" if \"A + B = C + D\" for A B C D :: \"'a multiset\"\n by (metis add.commute diff_intersect_left_idem mset_subset_eq_add_left subset_eq_diff_conv\n subset_mset.add_diff_inverse subset_mset.inf_absorb1 subset_mset.inf_le1 that)\n have A': \"A = A\\# M + (A - M) \\# N\"\n using A(1) H by blast\n moreover have B': \"B = (B - N) \\# M + B\\# N\"\n using A(1) H[of B A N M] by (auto simp: ac_simps)\n moreover have \"M = A \\# M + (B - N) \\# M\"\n using H[of M N A B] BN_MA[symmetric] A(1) by (metis (no_types) diff_intersect_left_idem\n diff_union_cancelR multiset_inter_commute subset_mset.diff_add subset_mset.inf.cobounded1\n union_commute)\n moreover have \"N = (A - M) \\# N + B \\# N\"\n by (metis A' assms(1) diff_union_cancelL inter_union_distrib_left inter_union_distrib_right\n mset_subset_eq_multiset_union_diff_commute subset_mset.inf.cobounded1 subset_mset.inf.commute)\n ultimately show P\n using A(2) by blast\n qed\n\n\nsubsubsection \\Singleton multisets\\\n\nlemma mset_size_le1_cases[case_names empty singleton,consumes 1]: \"\\ size M \\ Suc 0; M={#} \\ P; !!m. M={#m#} \\ P \\ \\ P\"\n by (cases M) auto\n\nlemma diff_union_single_conv2: \"a \\# J \\ J + I - {#a#} = (J - {#a#}) + I\"\n by simp\n\nlemmas diff_union_single_convs = diff_union_single_conv diff_union_single_conv2\n\nlemma mset_contains_eq: \"(m \\# M) = ({#m#}+(M-{#m#})=M)\"\n using diff_single_trivial by fastforce\n\n\nsubsubsection \\Pointwise ordering\\\n\n\n (*declare mset_le_trans[trans] Seems to be in there now. Why is this not done in Multiset.thy or order-class ? *)\n\n lemma mset_le_incr_right1: \"a\\#(b::'a multiset) \\ a\\#b+c\" using mset_subset_eq_mono_add[of a b \"{#}\" c, simplified] .\n lemma mset_le_incr_right2: \"a\\#(b::'a multiset) \\ a\\#c+b\" using mset_le_incr_right1\n by (auto simp add: union_commute)\n lemmas mset_le_incr_right = mset_le_incr_right1 mset_le_incr_right2\n\n lemma mset_le_decr_left1: \"a+c\\#(b::'a multiset) \\ a\\#b\" using mset_le_incr_right1 mset_subset_eq_mono_add_right_cancel\n by blast\n lemma mset_le_decr_left2: \"c+a\\#(b::'a multiset) \\ a\\#b\" using mset_le_decr_left1\n by (auto simp add: union_ac)\n lemma mset_le_add_mset_decr_left1: \"add_mset c a\\#(b::'a multiset) \\ a\\#b\"\n by (simp add: mset_subset_eq_insertD subset_mset.dual_order.strict_implies_order)\n lemma mset_le_add_mset_decr_left2: \"add_mset c a\\#(b::'a multiset) \\ {#c#}\\#b\"\n by (simp add: mset_subset_eq_insertD subset_mset.dual_order.strict_implies_order)\n\n lemmas mset_le_decr_left = mset_le_decr_left1 mset_le_decr_left2 mset_le_add_mset_decr_left1\n mset_le_add_mset_decr_left2\n\n \n\n lemma mset_union_subset: \"A+B \\# C \\ A\\#C \\ B\\#(C::'a multiset)\"\n by (auto dest: mset_le_decr_left)\n\n lemma mset_le_add_mset: \"add_mset x B \\# C \\ {#x#}\\#C \\ B\\#(C::'a multiset)\"\n by (auto dest: mset_le_decr_left)\n\n lemma mset_le_subtract_left: \"A+B \\# (X::'a multiset) \\ B \\# X-A \\ A\\#X\"\n by (auto dest: mset_le_subtract[of \"A+B\" \"X\" \"A\"] mset_union_subset)\n lemma mset_le_subtract_right: \"A+B \\# (X::'a multiset) \\ A \\# X-B \\ B\\#X\"\n by (auto dest: mset_le_subtract[of \"A+B\" \"X\" \"B\"] mset_union_subset)\n\n lemma mset_le_subtract_add_mset_left: \"add_mset x B \\# (X::'a multiset) \\ B \\# X-{#x#} \\ {#x#}\\#X\"\n by (auto dest: mset_le_subtract[of \"add_mset x B\" \"X\" \"{#x#}\"] mset_le_add_mset)\n\n lemma mset_le_subtract_add_mset_right: \"add_mset x B \\# (X::'a multiset) \\ {#x#} \\# X-B \\ B\\#X\"\n by (auto dest: mset_le_subtract[of \"add_mset x B\" \"X\" \"B\"] mset_le_add_mset)\n\n lemma mset_le_addE: \"\\ xs \\# (ys::'a multiset); !!zs. ys=xs+zs \\ P \\ \\ P\" using mset_subset_eq_exists_conv\n by blast\n\n declare subset_mset.diff_add[simp, intro]\n\n lemma mset_2dist2_cases:\n assumes A: \"{#a#}+{#b#} \\# A+B\"\n assumes CASES: \"{#a#}+{#b#} \\# A \\ P\" \"{#a#}+{#b#} \\# B \\ P\" \"\\a \\# A; b \\# B\\ \\ P\" \"\\a \\# B; b \\# A\\ \\ P\"\n shows \"P\"\n proof -\n { assume C: \"a \\# A\" \"b \\# A-{#a#}\"\n with mset_subset_eq_mono_add[of \"{#a#}\" \"{#a#}\" \"{#b#}\" \"A-{#a#}\"] have \"{#a#}+{#b#} \\# A\" by auto\n } moreover {\n assume C: \"a \\# A\" \"\\ (b \\# A-{#a#})\"\n with A have \"b \\# B\"\n by (metis diff_union_single_conv2 mset_le_subtract_left mset_subset_eq_insertD mset_un_cases)\n } moreover {\n assume C: \"\\ (a \\# A)\" \"b \\# B-{#a#}\"\n with A have \"a \\# B\"\n by (auto dest: mset_subset_eqD)\n with C mset_subset_eq_mono_add[of \"{#a#}\" \"{#a#}\" \"{#b#}\" \"B-{#a#}\"] have \"{#a#}+{#b#} \\# B\" by auto\n } moreover {\n assume C: \"\\ (a \\# A)\" \"\\ (b \\# B-{#a#})\"\n with A have \"a \\# B \\ b \\# A\"\n apply (intro conjI)\n apply (auto dest!: mset_subset_eq_insertD simp: insert_union_subset_iff; fail)[]\n by (metis mset_diff_cancel1elem mset_le_subtract_left multiset_diff_union_assoc\n single_subset_iff subset_eq_diff_conv)\n } ultimately show P using CASES by blast\n qed\n\n\n lemma mset_union_subset_s: \"{#a#}+B \\# C \\ a \\# C \\ B \\# C\"\n by (drule mset_union_subset) simp\n\n (* TODO: Check which of these lemmas are already introduced by order-classes ! *)\n\n\n lemma mset_le_single_cases[consumes 1, case_names empty singleton]: \"\\M\\#{#a#}; M={#} \\ P; M={#a#} \\ P\\ \\ P\"\n by (induct M) auto\n\n \n\nlemma mset_le_mono_add_single: \"\\a \\# ys; b \\# ws\\ \\ {#a#} + {#b#} \\# ys + ws\"\n by (meson mset_subset_eq_mono_add single_subset_iff)\n\n lemma mset_size1elem: \"\\size P \\ 1; q \\# P\\ \\ P={#q#}\"\n by (auto elim: mset_size_le1_cases)\n lemma mset_size2elem: \"\\size P \\ 2; {#q#}+{#q'#} \\# P\\ \\ P={#q#}+{#q'#}\"\n by (auto elim: mset_le_addE)\n\n\nsubsubsection \\Image under function\\\n\nnotation image_mset (infixr \"`#\" 90)\n\nlemma mset_map_split_orig: \"!!M1 M2. \\f `# P = M1+M2; !!P1 P2. \\P=P1+P2; f `# P1 = M1; f `# P2 = M2\\ \\ Q \\ \\ Q\"\n by (induct P) (force elim!: mset_un_single_un_cases)+\n\nlemma mset_map_id: \"\\!!x. f (g x) = x\\ \\ f `# g `# X = X\"\n by (induct X) auto\n\ntext \\The following is a very specialized lemma. Intuitively, it splits the original multiset\n by a splitting of some pointwise supermultiset of its image.\n\n Application:\n This lemma came in handy when proving the correctness of a constraint system that collects at most k sized submultisets of the sets of spawned threads.\n\\\nlemma mset_map_split_orig_le: assumes A: \"f `# P \\# M1+M2\" and EX: \"!!P1 P2. \\P=P1+P2; f `# P1 \\# M1; f `# P2 \\# M2\\ \\ Q\" shows \"Q\"\n using A EX by (auto elim: mset_le_distrib mset_map_split_orig)\n\n\nsubsection \\Lists\\\n\n\nlemma len_greater_imp_nonempty[simp]: \"length l > x \\ l\\[]\"\n by auto\n\nlemma list_take_induct_tl2:\n \"\\length xs = length ys; \\n\n \\ \\n < length (tl xs). P ((tl ys) ! n) ((tl xs) ! n)\"\nby (induct xs ys rule: list_induct2) auto\n\nlemma not_distinct_split_distinct:\n assumes \"\\ distinct xs\"\n obtains y ys zs where \"distinct ys\" \"y \\ set ys\" \"xs = ys@[y]@zs\"\nusing assms\nproof (induct xs rule: rev_induct)\n case Nil thus ?case by simp\nnext\n case (snoc x xs) thus ?case by (cases \"distinct xs\") auto\nqed\n\nlemma distinct_length_le:\n assumes d: \"distinct ys\"\n and eq: \"set ys = set xs\"\n shows \"length ys \\ length xs\"\nproof -\n from d have \"length ys = card (set ys)\" by (simp add: distinct_card)\n also from eq List.card_set have \"card (set ys) = length (remdups xs)\" by simp\n also have \"... \\ length xs\" by simp\n finally show ?thesis .\nqed\n\nlemma find_SomeD:\n \"List.find P xs = Some x \\ P x\"\n \"List.find P xs = Some x \\ x\\set xs\"\n by (auto simp add: find_Some_iff)\n\nlemma in_hd_or_tl_conv[simp]: \"l\\[] \\ x=hd l \\ x\\set (tl l) \\ x\\set l\"\n by (cases l) auto\n\nlemma length_dropWhile_takeWhile:\n assumes \"x < length (dropWhile P xs)\"\n shows \"x + length (takeWhile P xs) < length xs\"\n using assms\n by (induct xs) auto\n\ntext \\Elim-version of @{thm neq_Nil_conv}.\\ \nlemma neq_NilE: \n assumes \"l\\[]\"\n obtains x xs where \"l=x#xs\" \n using assms by (metis list.exhaust)\n\n \nlemma length_Suc_rev_conv: \"length xs = Suc n \\ (\\ys y. xs=ys@[y] \\ length ys = n)\"\n by (cases xs rule: rev_cases) auto\n\n \nsubsubsection \\List Destructors\\\nlemma not_hd_in_tl:\n \"x \\ hd xs \\ x \\ set xs \\ x \\ set (tl xs)\"\nby (induct xs) simp_all\n\nlemma distinct_hd_tl:\n \"distinct xs \\ x = hd xs \\ x \\ set (tl (xs))\"\nby (induct xs) simp_all\n\nlemma in_set_tlD: \"x \\ set (tl xs) \\ x \\ set xs\"\nby (induct xs) simp_all\n\nlemma nth_tl: \"xs \\ [] \\ tl xs ! n = xs ! Suc n\"\nby (induct xs) simp_all\n\nlemma tl_subset:\n \"xs \\ [] \\ set xs \\ A \\ set (tl xs) \\ A\"\nby (metis in_set_tlD rev_subsetD subsetI)\n\nlemma tl_last:\n \"tl xs \\ [] \\ last xs = last (tl xs)\"\nby (induct xs) simp_all\n\nlemma tl_obtain_elem:\n assumes \"xs \\ []\" \"tl xs = []\"\n obtains e where \"xs = [e]\"\nusing assms\nby (induct xs rule: list_nonempty_induct) simp_all\n\nlemma butlast_subset:\n \"xs \\ [] \\ set xs \\ A \\ set (butlast xs) \\ A\"\nby (metis in_set_butlastD rev_subsetD subsetI)\n\nlemma butlast_rev_tl:\n \"xs \\ [] \\ butlast (rev xs) = rev (tl xs)\"\nby (induct xs rule: rev_induct) simp_all\n\nlemma hd_butlast:\n \"length xs > 1 \\ hd (butlast xs) = hd xs\"\nby (induct xs) simp_all\n\nlemma butlast_upd_last_eq[simp]: \"length l \\ 2 \\\n (butlast l) [ length l - 2 := x ] = take (length l - 2) l @ [x]\"\n apply (case_tac l rule: rev_cases)\n apply simp\n apply simp\n apply (case_tac ys rule: rev_cases)\n apply simp\n apply simp\n done\n\nlemma distinct_butlast_swap[simp]: \n \"distinct pq \\ distinct (butlast (pq[i := last pq]))\"\n apply (cases pq rule: rev_cases)\n apply (auto simp: list_update_append distinct_list_update split: nat.split)\n done\n\nsubsubsection \\Splitting list according to structure of other list\\\ncontext begin\nprivate definition \"SPLIT_ACCORDING m l \\ length l = length m\"\n\nprivate lemma SPLIT_ACCORDINGE: \n assumes \"length m = length l\"\n obtains \"SPLIT_ACCORDING m l\"\n unfolding SPLIT_ACCORDING_def using assms by auto\n\nprivate lemma SPLIT_ACCORDING_simp:\n \"SPLIT_ACCORDING m (l1@l2) \\ (\\m1 m2. m=m1@m2 \\ SPLIT_ACCORDING m1 l1 \\ SPLIT_ACCORDING m2 l2)\"\n \"SPLIT_ACCORDING m (x#l') \\ (\\y m'. m=y#m' \\ SPLIT_ACCORDING m' l')\"\n apply (fastforce simp: SPLIT_ACCORDING_def intro: exI[where x = \"take (length l1) m\"] exI[where x = \"drop (length l1) m\"])\n apply (cases m;auto simp: SPLIT_ACCORDING_def)\n done\n\ntext \\Split structure of list @{term m} according to structure of list @{term l}.\\\nmethod split_list_according for m :: \"'a list\" and l :: \"'b list\" =\n (rule SPLIT_ACCORDINGE[of m l],\n (simp; fail),\n ( simp only: SPLIT_ACCORDING_simp,\n elim exE conjE, \n simp only: SPLIT_ACCORDING_def\n )\n ) \nend\n \n \n \nsubsubsection \\\\list_all2\\\\\nlemma list_all2_induct[consumes 1, case_names Nil Cons]:\n assumes \"list_all2 P l l'\"\n assumes \"Q [] []\"\n assumes \"\\x x' ls ls'. \\ P x x'; list_all2 P ls ls'; Q ls ls' \\\n \\ Q (x#ls) (x'#ls')\"\n shows \"Q l l'\"\n using list_all2_lengthD[OF assms(1)] assms\n apply (induct rule: list_induct2)\n apply auto\n done\n\n\nsubsubsection \\Indexing\\ \n\nlemma ran_nth_set_encoding_conv[simp]: \n \"ran (\\i. if ii l[j:=x]!i = l!i\" \n apply (induction l arbitrary: i j)\n apply (auto split: nat.splits)\n done\n\nlemma nth_list_update': \"l[i:=x]!j = (if i=j \\ i length l \\ n\\0 \\ last (take n l) = l!(n - 1)\"\n apply (induction l arbitrary: n)\n apply (auto simp: take_Cons split: nat.split)\n done\n\nlemma nth_append_first[simp]: \"i (l@l')!i = l!i\"\n by (simp add: nth_append) \n \nlemma in_set_image_conv_nth: \"f x \\ f`set l \\ (\\ii. i f (l!i) = f (l'!i)\" \n shows \"f`set l = f`set l'\"\n using assms\n by (fastforce simp: in_set_conv_nth in_set_image_conv_nth)\n \nlemma insert_swap_set_eq: \"i insert (l!i) (set (l[i:=x])) = insert x (set l)\"\n by (auto simp: in_set_conv_nth nth_list_update split: if_split_asm)\n \n \nsubsubsection \\Reverse lists\\\n lemma neq_Nil_revE: \n assumes \"l\\[]\" \n obtains ll e where \"l = ll@[e]\"\n using assms by (cases l rule: rev_cases) auto\n \n \n\n text \\Caution: Same order of case variables in snoc-case as @{thm [source] rev_exhaust}, the other way round than @{thm [source] rev_induct} !\\\n lemma length_compl_rev_induct[case_names Nil snoc]: \"\\P []; !! l e . \\!! ll . length ll <= length l \\ P ll\\ \\ P (l@[e])\\ \\ P l\"\n apply(induct_tac l rule: length_induct)\n apply(case_tac \"xs\" rule: rev_cases)\n apply(auto)\n done\n\n lemma list_append_eq_Cons_cases[consumes 1]: \"\\ys@zs = x#xs; \\ys=[]; zs=x#xs\\ \\ P; !!ys'. \\ ys=x#ys'; ys'@zs=xs \\ \\ P \\ \\ P\"\n by (auto iff add: append_eq_Cons_conv)\n lemma list_Cons_eq_append_cases[consumes 1]: \"\\x#xs = ys@zs; \\ys=[]; zs=x#xs\\ \\ P; !!ys'. \\ ys=x#ys'; ys'@zs=xs \\ \\ P \\ \\ P\"\n by (auto iff add: Cons_eq_append_conv)\n\nlemma map_of_rev_distinct[simp]:\n \"distinct (map fst m) \\ map_of (rev m) = map_of m\"\n apply (induct m)\n apply simp\n\n apply simp\n apply (subst map_add_comm)\n apply force\n apply simp\n done\n\n\n\\ \\Tail-recursive, generalized @{const rev}. May also be used for\n tail-recursively getting a list with all elements of the two\n operands, if the order does not matter, e.g. when implementing\n sets by lists.\\\nfun revg where\n \"revg [] b = b\" |\n \"revg (a#as) b = revg as (a#b)\"\n\nlemma revg_fun[simp]: \"revg a b = rev a @ b\"\n by (induct a arbitrary: b)\n auto\n\nlemma rev_split_conv[simp]:\n \"l \\ [] \\ rev (tl l) @ [hd l] = rev l\"\nby (induct l) simp_all\n\nlemma rev_butlast_is_tl_rev: \"rev (butlast l) = tl (rev l)\"\n by (induct l) auto\n\nlemma hd_last_singletonI:\n \"\\xs \\ []; hd xs = last xs; distinct xs\\ \\ xs = [hd xs]\"\n by (induct xs rule: list_nonempty_induct) auto\n\nlemma last_filter:\n \"\\xs \\ []; P (last xs)\\ \\ last (filter P xs) = last xs\"\n by (induct xs rule: rev_nonempty_induct) simp_all\n\n(* As the following two rules are similar in nature to list_induct2',\n they are named accordingly. *)\nlemma rev_induct2' [case_names empty snocl snocr snoclr]:\n assumes empty: \"P [] []\"\n and snocl: \"\\x xs. P (xs@[x]) []\"\n and snocr: \"\\y ys. P [] (ys@[y])\"\n and snoclr: \"\\x xs y ys. P xs ys \\ P (xs@[x]) (ys@[y])\"\n shows \"P xs ys\"\nproof (induct xs arbitrary: ys rule: rev_induct)\n case Nil thus ?case using empty snocr\n by (cases ys rule: rev_exhaust) simp_all\nnext\n case snoc thus ?case using snocl snoclr\n by (cases ys rule: rev_exhaust) simp_all\nqed\n\n\n\n\nsubsubsection \"Folding\"\n\ntext \"Ugly lemma about foldl over associative operator with left and right neutral element\"\nlemma foldl_A1_eq: \"!!i. \\ !! e. f n e = e; !! e. f e n = e; !!a b c. f a (f b c) = f (f a b) c \\ \\ foldl f i ww = f i (foldl f n ww)\"\nproof (induct ww)\n case Nil thus ?case by simp\nnext\n case (Cons a ww i) note IHP[simplified]=this\n have \"foldl f i (a # ww) = foldl f (f i a) ww\" by simp\n also from IHP have \"\\ = f (f i a) (foldl f n ww)\" by blast\n also from IHP(4) have \"\\ = f i (f a (foldl f n ww))\" by simp\n also from IHP(1)[OF IHP(2,3,4), where i=a] have \"\\ = f i (foldl f a ww)\" by simp\n also from IHP(2)[of a] have \"\\ = f i (foldl f (f n a) ww)\" by simp\n also have \"\\ = f i (foldl f n (a#ww))\" by simp\n finally show ?case .\nqed\n\n\nlemmas foldl_conc_empty_eq = foldl_A1_eq[of \"(@)\" \"[]\", simplified]\nlemmas foldl_un_empty_eq = foldl_A1_eq[of \"(\\)\" \"{}\", simplified, OF Un_assoc[symmetric]]\n\nlemma foldl_set: \"foldl (\\) {} l = \\{x. x\\set l}\"\n apply (induct l)\n apply simp_all\n apply (subst foldl_un_empty_eq)\n apply auto\n done\n\nlemma (in monoid_mult) foldl_absorb1: \"x*foldl (*) 1 zs = foldl (*) x zs\"\n apply (rule sym)\n apply (rule foldl_A1_eq)\n apply (auto simp add: mult.assoc)\ndone\n\ntext \\Towards an invariant rule for foldl\\\nlemma foldl_rule_aux:\n fixes I :: \"'\\ \\ 'a list \\ bool\"\n assumes initial: \"I \\0 l0\"\n assumes step: \"!!l1 l2 x \\. \\ l0=l1@x#l2; I \\ (x#l2) \\ \\ I (f \\ x) l2\"\n shows \"I (foldl f \\0 l0) []\"\n using initial step\n apply (induct l0 arbitrary: \\0)\n apply auto\n done\n\nlemma foldl_rule_aux_P:\n fixes I :: \"'\\ \\ 'a list \\ bool\"\n assumes initial: \"I \\0 l0\"\n assumes step: \"!!l1 l2 x \\. \\ l0=l1@x#l2; I \\ (x#l2) \\ \\ I (f \\ x) l2\"\n assumes final: \"!!\\. I \\ [] \\ P \\\"\n shows \"P (foldl f \\0 l0)\"\nusing foldl_rule_aux[of I \\0 l0, OF initial, OF step] final\nby simp\n\n\nlemma foldl_rule:\n fixes I :: \"'\\ \\ 'a list \\ 'a list \\ bool\"\n assumes initial: \"I \\0 [] l0\"\n assumes step: \"!!l1 l2 x \\. \\ l0=l1@x#l2; I \\ l1 (x#l2) \\ \\ I (f \\ x) (l1@[x]) l2\"\n shows \"I (foldl f \\0 l0) l0 []\"\n using initial step\n apply (rule_tac I=\"\\\\ lr. \\ll. l0=ll@lr \\ I \\ ll lr\" in foldl_rule_aux_P)\n apply auto\n done\n\ntext \\\n Invariant rule for foldl. The invariant is parameterized with\n the state, the list of items that have already been processed and\n the list of items that still have to be processed.\n\\\nlemma foldl_rule_P:\n fixes I :: \"'\\ \\ 'a list \\ 'a list \\ bool\"\n \\ \\The invariant holds for the initial state, no items processed yet and all items to be processed:\\\n assumes initial: \"I \\0 [] l0\"\n \\ \\The invariant remains valid if one item from the list is processed\\\n assumes step: \"!!l1 l2 x \\. \\ l0=l1@x#l2; I \\ l1 (x#l2) \\ \\ I (f \\ x) (l1@[x]) l2\"\n \\ \\The proposition follows from the invariant in the final state, i.e. all items processed and nothing to be processed\\\n assumes final: \"!!\\. I \\ l0 [] \\ P \\\"\n shows \"P (foldl f \\0 l0)\"\n using foldl_rule[of I, OF initial step] by (simp add: final)\n\n\ntext \\Invariant reasoning over @{const foldl} for distinct lists. Invariant rule makes no\n assumptions about ordering.\\\nlemma distinct_foldl_invar:\n \"\\ distinct S; I (set S) \\0;\n \\x it \\. \\x \\ it; it \\ set S; I it \\\\ \\ I (it - {x}) (f \\ x)\n \\ \\ I {} (foldl f \\0 S)\"\nproof (induct S arbitrary: \\0)\n case Nil thus ?case by auto\nnext\n case (Cons x S)\n\n note [simp] = Cons.prems(1)[simplified]\n\n show ?case\n apply simp\n apply (rule Cons.hyps)\n proof -\n from Cons.prems(1) show \"distinct S\" by simp\n from Cons.prems(3)[of x \"set (x#S)\", simplified,\n OF Cons.prems(2)[simplified]]\n show \"I (set S) (f \\0 x)\" .\n fix xx it \\\n assume A: \"xx\\it\" \"it \\ set S\" \"I it \\\"\n show \"I (it - {xx}) (f \\ xx)\" using A(2)\n apply (rule_tac Cons.prems(3))\n apply (simp_all add: A(1,3))\n apply blast\n done\n qed\nqed\n\nlemma foldl_length_aux: \"foldl (\\i x. Suc i) a l = a + length l\"\n by (induct l arbitrary: a) auto\n\nlemmas foldl_length[simp] = foldl_length_aux[where a=0, simplified]\n\nlemma foldr_length_aux: \"foldr (\\x i. Suc i) l a = a + length l\"\n by (induct l arbitrary: a rule: rev_induct) auto\n\nlemmas foldr_length[simp] = foldr_length_aux[where a=0, simplified]\n\ncontext comp_fun_commute begin\n\nlemma foldl_f_commute: \"f a (foldl (\\a b. f b a) b xs) = foldl (\\a b. f b a) (f a b) xs\"\nby(induct xs arbitrary: b)(simp_all add: fun_left_comm)\n\nlemma foldr_conv_foldl: \"foldr f xs a = foldl (\\a b. f b a) a xs\"\nby(induct xs arbitrary: a)(simp_all add: foldl_f_commute)\n\nend\n\nlemma filter_conv_foldr:\n \"filter P xs = foldr (\\x xs. if P x then x # xs else xs) xs []\"\nby(induct xs) simp_all\n\nlemma foldr_Cons: \"foldr Cons xs [] = xs\"\nby(induct xs) simp_all\n\nlemma foldr_snd_zip:\n \"length xs \\ length ys \\ foldr (\\(x, y). f y) (zip xs ys) b = foldr f ys b\"\nproof(induct ys arbitrary: xs)\n case (Cons y ys) thus ?case by(cases xs) simp_all\nqed simp\n\nlemma foldl_snd_zip:\n \"length xs \\ length ys \\ foldl (\\b (x, y). f b y) b (zip xs ys) = foldl f b ys\"\nproof(induct ys arbitrary: xs b)\n case (Cons y ys) thus ?case by(cases xs) simp_all\nqed simp\n\n\n\nlemma foldl_foldl_conv_concat: \"foldl (foldl f) a xs = foldl f a (concat xs)\"\nby(induct xs arbitrary: a) simp_all\n\nlemma foldl_list_update:\n \"n < length xs \\ foldl f a (xs[n := x]) = foldl f (f (foldl f a (take n xs)) x) (drop (Suc n) xs)\"\nby(simp add: upd_conv_take_nth_drop)\n\nlemma map_by_foldl:\n fixes l :: \"'a list\" and f :: \"'a \\ 'b\"\n shows \"foldl (\\l x. l@[f x]) [] l = map f l\"\nproof -\n {\n fix l'\n have \"foldl (\\l x. l@[f x]) l' l = l'@map f l\"\n by (induct l arbitrary: l') auto\n } thus ?thesis by simp\nqed\n\n\nsubsubsection \\Sorting\\\n\nlemma sorted_in_between:\n assumes A: \"0\\i\" \"i x\" \"xk\" and \"kx\" and \"xk. i\\k \\ k l!k\\x \\ x x\")\n case True\n from True Suc.hyps have \"d = j - (i + 1)\" by simp\n moreover from True have \"i+1 < j\"\n by (metis Suc.prems Suc_eq_plus1 Suc_lessI not_less)\n moreover from True have \"0\\i+1\" by simp\n ultimately obtain k where\n \"i+1\\k\" \"k x\" \"xk\" \"k x\" \"xsorted l; l\\[]\\ \\ hd l \\ last l\"\nby (metis eq_iff hd_Cons_tl last_in_set not_hd_in_tl sorted.simps(2))\n\nlemma (in linorder) sorted_hd_min:\n \"\\xs \\ []; sorted xs\\ \\ \\x \\ set xs. hd xs \\ x\"\nby (induct xs, auto)\n\nlemma sorted_append_bigger:\n \"\\sorted xs; \\x \\ set xs. x \\ y\\ \\ sorted (xs @ [y])\"\nproof (induct xs)\n case Nil\n then show ?case by simp\nnext\n case (Cons x xs)\n then have s: \"sorted xs\" by (cases xs) simp_all\n from Cons have a: \"\\x\\set xs. x \\ y\" by simp\n from Cons(1)[OF s a] Cons(2-) show ?case by (cases xs) simp_all\nqed\n\nlemma sorted_filter':\n \"sorted l \\ sorted (filter P l)\"\n using sorted_filter[where f=id, simplified] .\n\nsubsubsection \\Map\\\n(* List.thy has:\n declare map_eq_Cons_D [dest!] Cons_eq_map_D [dest!] *) \nlemma map_eq_consE: \"\\map f ls = fa#fl; !!a l. \\ ls=a#l; f a=fa; map f l = fl \\ \\ P\\ \\ P\"\n by auto\n\nlemma map_fst_mk_snd[simp]: \"map fst (map (\\x. (x,k)) l) = l\" by (induct l) auto\nlemma map_snd_mk_fst[simp]: \"map snd (map (\\x. (k,x)) l) = l\" by (induct l) auto\nlemma map_fst_mk_fst[simp]: \"map fst (map (\\x. (k,x)) l) = replicate (length l) k\" by (induct l) auto\nlemma map_snd_mk_snd[simp]: \"map snd (map (\\x. (x,k)) l) = replicate (length l) k\" by (induct l) auto\n\nlemma map_zip1: \"map (\\x. (x,k)) l = zip l (replicate (length l) k)\" by (induct l) auto\nlemma map_zip2: \"map (\\x. (k,x)) l = zip (replicate (length l) k) l\" by (induct l) auto\nlemmas map_zip=map_zip1 map_zip2\n\n(* TODO/FIXME: hope nobody changes nth to be underdefined! *)\nlemma map_eq_nth_eq:\n assumes A: \"map f l = map f l'\"\n shows \"f (l!i) = f (l'!i)\"\nproof -\n from A have \"length l = length l'\"\n by (metis length_map)\n thus ?thesis using A\n apply (induct arbitrary: i rule: list_induct2)\n apply simp\n apply (simp add: nth_def split: nat.split)\n done\nqed\n\nlemma map_upd_eq:\n \"\\i f (l!i) = f x\\ \\ map f (l[i:=x]) = map f l\"\n by (metis list_update_beyond list_update_id map_update not_le_imp_less)\n\n\n\n\nlemma inj_map_inv_f [simp]: \"inj f \\ map (inv f) (map f l) = l\"\n by (simp)\n\nlemma inj_on_map_the: \"\\D \\ dom m; inj_on m D\\ \\ inj_on (the\\m) D\"\n apply (rule inj_onI)\n apply simp\n apply (case_tac \"m x\")\n apply (case_tac \"m y\")\n apply (auto intro: inj_onD) [1]\n apply (auto intro: inj_onD) [1]\n apply (case_tac \"m y\")\n apply (auto intro: inj_onD) [1]\n apply simp\n apply (rule inj_onD)\n apply assumption\n apply auto\n done\n\n \n\nlemma map_consI:\n \"w=map f ww \\ f a#w = map f (a#ww)\"\n \"w@l=map f ww@l \\ f a#w@l = map f (a#ww)@l\"\n by auto\n\n\nlemma restrict_map_subset_eq:\n fixes R\n shows \"\\m |` R = m'; R'\\R\\ \\ m|` R' = m' |` R'\"\n by (auto simp add: Int_absorb1)\n\nlemma restrict_map_self[simp]: \"m |` dom m = m\"\n apply (rule ext)\n apply (case_tac \"m x\")\n apply (auto simp add: restrict_map_def)\n done\n\nlemma restrict_map_UNIV[simp]: \"f |` UNIV = f\"\n by (auto simp add: restrict_map_def)\n\nlemma restrict_map_inv[simp]: \"f |` (- dom f) = Map.empty\"\n by (auto simp add: restrict_map_def intro: ext)\n\nlemma restrict_map_upd: \"(f |` S)(k \\ v) = f(k\\v) |` (insert k S)\"\n by (auto simp add: restrict_map_def intro: ext)\n\nlemma map_upd_eq_restrict: \"m (x:=None) = m |` (-{x})\"\n by (auto intro: ext)\n\ndeclare Map.finite_dom_map_of [simp, intro!]\n\n\n\nlemma restrict_map_eq :\n \"((m |` A) k = None) \\ (k \\ dom m \\ A)\"\n \"((m |` A) k = Some v) \\ (m k = Some v \\ k \\ A)\"\nunfolding restrict_map_def\nby (simp_all add: dom_def)\n\n\ndefinition \"rel_of m P == {(k,v). m k = Some v \\ P (k, v)}\"\nlemma rel_of_empty[simp]: \"rel_of Map.empty P = {}\"\n by (auto simp add: rel_of_def)\n\nlemma remove1_tl: \"xs \\ [] \\ remove1 (hd xs) xs = tl xs\"\n by (cases xs) auto\n\nlemma set_oo_map_alt: \"(set \\\\ map) f = (\\l. f ` set l)\" by auto\n \nsubsubsection \"Filter and Revert\"\nprimrec filter_rev_aux where\n \"filter_rev_aux a P [] = a\"\n| \"filter_rev_aux a P (x#xs) = (\n if P x then filter_rev_aux (x#a) P xs else filter_rev_aux a P xs)\"\n\nlemma filter_rev_aux_alt: \"filter_rev_aux a P l = filter P (rev l) @ a\"\n by (induct l arbitrary: a) auto\n\ndefinition \"filter_rev == filter_rev_aux []\"\nlemma filter_rev_alt: \"filter_rev P l = filter P (rev l)\"\n unfolding filter_rev_def by (simp add: filter_rev_aux_alt)\n\ndefinition \"remove_rev x == filter_rev (Not o (=) x)\"\nlemma remove_rev_alt_def :\n \"remove_rev x xs = (filter (\\y. y \\ x) (rev xs))\"\n unfolding remove_rev_def\n apply (simp add: filter_rev_alt comp_def)\n by metis\n\nsubsubsection \"zip\"\n\ndeclare zip_map_fst_snd[simp] \n\nlemma pair_list_split: \"\\ !!l1 l2. \\ l = zip l1 l2; length l1=length l2; length l=length l2 \\ \\ P \\ \\ P\"\nproof (induct l arbitrary: P)\n case Nil thus ?case by auto\nnext\n case (Cons a l) from Cons.hyps obtain l1 l2 where IHAPP: \"l=zip l1 l2\" \"length l1 = length l2\" \"length l=length l2\" .\n obtain a1 a2 where [simp]: \"a=(a1,a2)\" by (cases a) auto\n from IHAPP have \"a#l = zip (a1#l1) (a2#l2)\" \"length (a1#l1) = length (a2#l2)\" \"length (a#l) = length (a2#l2)\"\n by (simp_all only:) (simp_all (no_asm_use))\n with Cons.prems show ?case by blast\nqed\n\nlemma set_zip_cart: \"x\\set (zip l l') \\ x\\set l \\ set l'\"\n by (auto simp add: set_zip)\n\n\nlemma map_prod_fun_zip: \"map (\\(x, y). (f x, g y)) (zip xs ys) = zip (map f xs) (map g ys)\"\nproof(induct xs arbitrary: ys)\n case Nil thus ?case by simp\nnext\n case (Cons x xs) thus ?case by(cases ys) simp_all\nqed\n\n\nsubsubsection \\Generalized Zip\\\ntext \\Zip two lists element-wise, where the combination of two elements is specified by a function. Note that this function is underdefined for lists of different length.\\\nfun zipf :: \"('a\\'b\\'c) \\ 'a list \\ 'b list \\ 'c list\" where\n \"zipf f [] [] = []\" |\n \"zipf f (a#as) (b#bs) = f a b # zipf f as bs\"\n\n\nlemma zipf_zip: \"\\length l1 = length l2\\ \\ zipf Pair l1 l2 = zip l1 l2\"\n apply (induct l1 arbitrary: l2)\n apply auto\n apply (case_tac l2)\n apply auto\n done\n\n \\ \\All quantification over zipped lists\\\nfun list_all_zip where\n \"list_all_zip P [] [] \\ True\" |\n \"list_all_zip P (a#as) (b#bs) \\ P a b \\ list_all_zip P as bs\" |\n \"list_all_zip P _ _ \\ False\"\n\nlemma list_all_zip_alt: \"list_all_zip P as bs \\ length as = length bs \\ (\\iP as bs rule: list_all_zip.induct)\n apply auto\n apply (case_tac i)\n apply auto\n done\n\nlemma list_all_zip_map1: \"list_all_zip P (List.map f as) bs \\ list_all_zip (\\a b. P (f a) b) as bs\"\n apply (induct as arbitrary: bs)\n apply (case_tac bs)\n apply auto [2]\n apply (case_tac bs)\n apply auto [2]\n done\n\nlemma list_all_zip_map2: \"list_all_zip P as (List.map f bs) \\ list_all_zip (\\a b. P a (f b)) as bs\"\n apply (induct as arbitrary: bs)\n apply (case_tac bs)\n apply auto [2]\n apply (case_tac bs)\n apply auto [2]\n done\n\ndeclare list_all_zip_alt[mono]\n\nlemma lazI[intro?]: \"\\ length a = length b; !!i. i P (a!i) (b!i) \\\n \\ list_all_zip P a b\"\n by (auto simp add: list_all_zip_alt)\n\nlemma laz_conj[simp]: \"list_all_zip (\\x y. P x y \\ Q x y) a b\n \\ list_all_zip P a b \\ list_all_zip Q a b\"\n by (auto simp add: list_all_zip_alt)\n\nlemma laz_len: \"list_all_zip P a b \\ length a = length b\"\n by (simp add: list_all_zip_alt)\n\nlemma laz_eq: \"list_all_zip (=) a b \\ a=b\"\n apply (induct a arbitrary: b)\n apply (case_tac b)\n apply simp\n apply simp\n apply (case_tac b)\n apply simp\n apply simp\n done\n\n\nlemma laz_swap_ex:\n assumes A: \"list_all_zip (\\a b. \\c. P a b c) A B\"\n obtains C where\n \"list_all_zip (\\a c. \\b. P a b c) A C\"\n \"list_all_zip (\\b c. \\a. P a b c) B C\"\nproof -\n from A have\n [simp]: \"length A = length B\" and\n IC: \"\\ici. P (A!i) (B!i) ci\"\n by (auto simp add: list_all_zip_alt)\n from obtain_list_from_elements[OF IC] obtain C where\n \"length C = length B\"\n \"\\ia b. P a) A B \\ (length A = length B) \\ (\\a\\set A. P a)\"\n by (auto simp add: list_all_zip_alt set_conv_nth)\n\nlemma laz_weak_Pb[simp]:\n \"list_all_zip (\\a b. P b) A B \\ (length A = length B) \\ (\\b\\set B. P b)\"\n by (force simp add: list_all_zip_alt set_conv_nth)\n\n\n\nsubsubsection \"Collecting Sets over Lists\"\n\ndefinition \"list_collect_set f l == \\{ f a | a. a\\set l }\"\nlemma list_collect_set_simps[simp]:\n \"list_collect_set f [] = {}\"\n \"list_collect_set f [a] = f a\"\n \"list_collect_set f (a#l) = f a \\ list_collect_set f l\"\n \"list_collect_set f (l@l') = list_collect_set f l \\ list_collect_set f l'\"\nby (unfold list_collect_set_def) auto\n\nlemma list_collect_set_map_simps[simp]:\n \"list_collect_set f (map x []) = {}\"\n \"list_collect_set f (map x [a]) = f (x a)\"\n \"list_collect_set f (map x (a#l)) = f (x a) \\ list_collect_set f (map x l)\"\n \"list_collect_set f (map x (l@l')) = list_collect_set f (map x l) \\ list_collect_set f (map x l')\"\nby simp_all\n\nlemma list_collect_set_alt: \"list_collect_set f l = \\{ f (l!i) | i. i(set (map f l))\"\n by (unfold list_collect_set_def) auto\n\nsubsubsection \\Sorted List with arbitrary Relations\\\n\nlemma (in linorder) sorted_wrt_rev_linord [simp] :\n \"sorted_wrt (\\) l \\ sorted (rev l)\"\nby (simp add: sorted_sorted_wrt sorted_wrt_rev)\n\nlemma (in linorder) sorted_wrt_map_linord [simp] :\n \"sorted_wrt (\\(x::'a \\ 'b) y. fst x \\ fst y) l\n \\ sorted (map fst l)\"\nby (simp add: sorted_sorted_wrt sorted_wrt_map)\n\nlemma (in linorder) sorted_wrt_map_rev_linord [simp] :\n \"sorted_wrt (\\(x::'a \\ 'b) y. fst x \\ fst y) l\n \\ sorted (rev (map fst l))\"\nby (induct l) (auto simp add: sorted_append)\n\n \nsubsubsection \\Take and Drop\\\n lemma take_update[simp]: \"take n (l[i:=x]) = (take n l)[i:=x]\"\n apply (induct l arbitrary: n i)\n apply (auto split: nat.split)\n apply (case_tac n)\n apply simp_all\n apply (case_tac n)\n apply simp_all\n done\n\n lemma take_update_last: \"length list>n \\ (take (Suc n) list) [n:=x] = take n list @ [x]\"\n by (induct list arbitrary: n)\n (auto split: nat.split)\n\n lemma drop_upd_irrelevant: \"m < n \\ drop n (l[m:=x]) = drop n l\"\n apply (induct n arbitrary: l m)\n apply simp\n apply (case_tac l)\n apply (auto split: nat.split)\n done\n\nlemma set_drop_conv:\n \"set (drop n l) = { l!i | i. n\\i \\ i < length l }\" (is \"?L=?R\")\nproof (intro equalityI subsetI)\n fix x\n assume \"x\\?L\"\n then obtain i where L: \"i = l!(n+i)\" using L by simp\n finally show \"x\\?R\" using L by auto\nnext\n fix x\n assume \"x\\?R\"\n then obtain i where L: \"n\\i\" \"i?L\"\n by (auto simp add: in_set_conv_nth)\nqed\n\n\n\nlemma in_set_drop_conv_nth: \"x\\set (drop n l) \\ (\\i. n\\i \\ i x = l!i)\"\n apply (clarsimp simp: in_set_conv_nth)\n apply safe\n apply simp\n apply (metis le_add2 less_diff_conv add.commute)\n apply (rule_tac x=\"i-n\" in exI)\n apply auto []\n done\n\nlemma Union_take_drop_id: \"\\(set (drop n l)) \\ \\(set (take n l)) = \\(set l)\"\n by (metis Union_Un_distrib append_take_drop_id set_union_code sup_commute)\n\n\nlemma Un_set_drop_extend: \"\\j\\Suc 0; j < length l\\\n \\ l ! (j - Suc 0) \\ \\(set (drop j l)) = \\(set (drop (j - Suc 0) l))\"\n apply safe\n apply simp_all\n apply (metis diff_Suc_Suc diff_zero gr0_implies_Suc in_set_drop_conv_nth\n le_refl less_eq_Suc_le order.strict_iff_order)\n apply (metis Nat.diff_le_self set_drop_subset_set_drop subset_code(1))\n by (metis diff_Suc_Suc gr0_implies_Suc in_set_drop_conv_nth\n less_eq_Suc_le order.strict_iff_order minus_nat.diff_0)\n\nlemma drop_take_drop_unsplit:\n \"i\\j \\ drop i (take j l) @ drop j l = drop i l\"\nproof -\n assume \"i \\ j\"\n then obtain skf where \"i + skf = j\"\n by (metis le_iff_add)\n thus \"drop i (take j l) @ drop j l = drop i l\"\n by (metis append_take_drop_id diff_add_inverse drop_drop drop_take\n add.commute)\nqed\n\nlemma drop_last_conv[simp]: \"l\\[] \\ drop (length l - Suc 0) l = [last l]\"\n by (cases l rule: rev_cases) auto\n\nlemma take_butlast_conv[simp]: \"take (length l - Suc 0) l = butlast l\"\n by (cases l rule: rev_cases) auto\n\n lemma drop_takeWhile:\n assumes \"i\\length (takeWhile P l)\"\n shows \"drop i (takeWhile P l) = takeWhile P (drop i l)\" \n using assms\n proof (induction l arbitrary: i)\n case Nil thus ?case by auto\n next\n case (Cons x l) thus ?case \n by (cases i) auto\n qed \n \nlemma less_length_takeWhile_conv: \"i < length (takeWhile P l) \\ (i (\\j\\i. P (l!j)))\" \n apply safe\n subgoal using length_takeWhile_le less_le_trans by blast\n subgoal by (metis dual_order.strict_trans2 nth_mem set_takeWhileD takeWhile_nth)\n subgoal by (meson less_le_trans not_le_imp_less nth_length_takeWhile)\n done\n \nlemma eq_len_takeWhile_conv: \"i=length (takeWhile P l) \n \\ i\\length l \\ (\\j (i \\P (l!i))\" \n apply safe\n subgoal using length_takeWhile_le less_le_trans by blast\n subgoal by (auto simp: less_length_takeWhile_conv)\n subgoal using nth_length_takeWhile by blast \n subgoal by (metis length_takeWhile_le nth_length_takeWhile order.order_iff_strict) \n subgoal by (metis dual_order.strict_trans2 leI less_length_takeWhile_conv linorder_neqE_nat nth_length_takeWhile) \n done\n \n \nsubsubsection \\Up-to\\\n\nlemma upt_eq_append_conv: \"i\\j \\ [i.. (\\k. i\\k \\ k\\j \\ [i.. [k..j\"\n thus \"\\k\\i. k \\ j \\ [i.. [k.. length l \\ map (nth l) [M.. is1 = [l.. is2 = [Suc i.. l\\i \\ ii. i + ofs) [a..Last and butlast\\\nlemma butlast_upt: \"butlast [m.. butlast [n..length l \\ take (n - Suc 0) l = butlast (take n l)\"\n by (simp add: butlast_take)\n\nlemma butlast_eq_cons_conv: \"butlast l = x#xs \\ (\\xl. l=x#xs@[xl])\"\n by (metis Cons_eq_appendI append_butlast_last_id butlast.simps\n butlast_snoc eq_Nil_appendI)\n\nlemma butlast_eq_consE:\n assumes \"butlast l = x#xs\"\n obtains xl where \"l=x#xs@[xl]\"\n using assms\n by (auto simp: butlast_eq_cons_conv)\n\nlemma drop_eq_ConsD: \"drop n xs = x # xs' \\ drop (Suc n) xs = xs'\"\nby(induct xs arbitrary: n)(simp_all add: drop_Cons split: nat.split_asm)\n\nsubsubsection \\List Slices\\ \n text \\Based on Lars Hupel's code.\\ \ndefinition slice :: \"nat \\ nat \\ 'a list \\ 'a list\" where\n\"slice from to list = take (to - from) (drop from list)\"\n\nlemma slice_len[simp]: \"\\ from \\ to; to \\ length xs \\ \\ length (slice from to xs) = to - from\"\nunfolding slice_def\nby simp\n\nlemma slice_head: \"\\ from < to; to \\ length xs \\ \\ hd (slice from to xs) = xs ! from\"\nunfolding slice_def\nproof -\n assume a1: \"from < to\"\n assume \"to \\ length xs\"\n then have \"\\n. to - (to - n) \\ length (take to xs)\"\n by (metis (no_types) slice_def diff_le_self drop_take length_drop slice_len)\n then show \"hd (take (to - from) (drop from xs)) = xs ! from\"\n using a1 by (metis diff_diff_cancel drop_take hd_drop_conv_nth leI le_antisym less_or_eq_imp_le nth_take)\nqed\n\nlemma slice_eq_bounds_empty[simp]: \"slice i i xs = []\"\nunfolding slice_def by auto\n\nlemma slice_nth: \"\\ from < to; to \\ length xs; i < to - from \\ \\ slice from to xs ! i = xs ! (from + i)\"\nunfolding slice_def\nby (induction \"to - from\" arbitrary: \"from\" to i) simp+\n\nlemma slice_prepend: \"\\ i \\ k; k \\ length xs \\ \\ let p = length ys in slice i k xs = slice (i + p) (k + p) (ys @ xs)\"\nunfolding slice_def Let_def\nby force\n\nlemma slice_Nil[simp]: \"slice begin end [] = []\" \n unfolding slice_def by auto\n \nlemma slice_Cons: \"slice begin end (x#xs) \n = (if begin=0 \\ end>0 then x#slice begin (end-1) xs else slice (begin - 1) (end - 1) xs)\"\n unfolding slice_def\n by (auto simp: take_Cons' drop_Cons')\n\nlemma slice_complete[simp]: \"slice 0 (length xs) xs = xs\"\n unfolding slice_def\n by simp\n\n \n \nsubsubsection \\Miscellaneous\\\n lemma length_compl_induct[case_names Nil Cons]: \"\\P []; !! e l . \\!! ll . length ll <= length l \\ P ll\\ \\ P (e#l)\\ \\ P l\"\n apply(induct_tac l rule: length_induct)\n apply(case_tac \"xs\")\n apply(auto)\n done\n\n lemma in_set_list_format: \"\\ e\\set l; !!l1 l2. l=l1@e#l2 \\ P \\ \\ P\"\n proof (induct l arbitrary: P)\n case Nil thus ?case by auto\n next\n case (Cons a l) show ?case proof (cases \"a=e\")\n case True with Cons show ?thesis by force\n next\n case False with Cons.prems(1) have \"e\\set l\" by auto\n with Cons.hyps obtain l1 l2 where \"l=l1@e#l2\" by blast\n hence \"a#l = (a#l1)@e#l2\" by simp\n with Cons.prems(2) show P by blast\n qed\n qed\n\nlemma in_set_upd_cases:\n assumes \"x\\set (l[i:=y])\"\n obtains \"iset l\"\n by (metis assms in_set_conv_nth length_list_update nth_list_update_eq\n nth_list_update_neq)\n\nlemma in_set_upd_eq_aux:\n assumes \"iset (l[i:=y]) \\ x=y \\ (\\y. x\\set (l[i:=y]))\"\n by (metis in_set_upd_cases assms list_update_overwrite\n set_update_memI)\n\nlemma in_set_upd_eq:\n assumes \"iset (l[i:=y]) \\ x=y \\ (x\\set l \\ (\\y. x\\set (l[i:=y])))\"\n by (metis in_set_upd_cases in_set_upd_eq_aux assms)\n\n\n text \\Simultaneous induction over two lists, prepending an element to one of the lists in each step\\\n lemma list_2pre_induct[case_names base left right]: assumes BASE: \"P [] []\" and LEFT: \"!!e w1' w2. P w1' w2 \\ P (e#w1') w2\" and RIGHT: \"!!e w1 w2'. P w1 w2' \\ P w1 (e#w2')\" shows \"P w1 w2\"\n proof -\n { \\ \\The proof is done by induction over the sum of the lengths of the lists\\\n fix n\n have \"!!w1 w2. \\length w1 + length w2 = n; P [] []; !!e w1' w2. P w1' w2 \\ P (e#w1') w2; !!e w1 w2'. P w1 w2' \\ P w1 (e#w2') \\ \\ P w1 w2 \"\n apply (induct n)\n apply simp\n apply (case_tac w1)\n apply auto\n apply (case_tac w2)\n apply auto\n done\n } from this[OF _ BASE LEFT RIGHT] show ?thesis by blast\n qed\n\n\n lemma list_decomp_1: \"length l=1 \\ \\a. l=[a]\"\n by (case_tac l, auto)\n\n lemma list_decomp_2: \"length l=2 \\ \\a b. l=[a,b]\"\n by (case_tac l, auto simp add: list_decomp_1)\n\n\n\n lemma list_rest_coinc: \"\\length s2 \\ length s1; s1@r1 = s2@r2\\ \\ \\r1p. r2=r1p@r1\"\n by (metis append_eq_append_conv_if)\n\n lemma list_tail_coinc: \"n1#r1 = n2#r2 \\ n1=n2 & r1=r2\"\n by (auto)\n\n\n lemma last_in_set[intro]: \"\\l\\[]\\ \\ last l \\ set l\"\n by (induct l) auto\n\n lemma empty_append_eq_id[simp]: \"(@) [] = (\\x. x)\" by auto\n \n lemma op_conc_empty_img_id[simp]: \"((@) [] ` L) = L\" by auto\n\n\n lemma distinct_match: \"\\ distinct (al@e#bl) \\ \\ (al@e#bl = al'@e#bl') \\ (al=al' \\ bl=bl')\"\n proof (rule iffI, induct al arbitrary: al')\n case Nil thus ?case by (cases al') auto\n next\n case (Cons a al) note Cprems=Cons.prems note Chyps=Cons.hyps\n show ?case proof (cases al')\n case Nil with Cprems have False by auto\n thus ?thesis ..\n next\n case [simp]: (Cons a' all')\n with Cprems have [simp]: \"a=a'\" and P: \"al@e#bl = all'@e#bl'\" by auto\n from Cprems(1) have D: \"distinct (al@e#bl)\" by auto\n from Chyps[OF D P] have [simp]: \"al=all'\" \"bl=bl'\" by auto\n show ?thesis by simp\n qed\n qed simp\n\n\n lemma prop_match: \"\\ list_all P al; \\P e; \\P e'; list_all P bl \\ \\ (al@e#bl = al'@e'#bl') \\ (al=al' \\ e=e' \\ bl=bl')\"\n apply (rule iffI, induct al arbitrary: al')\n apply (case_tac al', fastforce, fastforce)+\n done\n\n lemmas prop_matchD = rev_iffD1[OF _ prop_match[where P=P]] for P\n\n declare distinct_tl[simp]\n\n\nlemma list_se_match[simp]:\n \"l1 \\ [] \\ l1@l2 = [a] \\ l1 = [a] \\ l2 = []\"\n \"l2 \\ [] \\ l1@l2 = [a] \\ l1 = [] \\ l2 = [a]\"\n \"l1 \\ [] \\ [a] = l1@l2 \\ l1 = [a] \\ l2 = []\"\n \"l2 \\ [] \\ [a] = l1@l2 \\ l1 = [] \\ l2 = [a]\"\n apply (cases l1, simp_all)\n apply (cases l1, simp_all)\n apply (cases l1, auto) []\n apply (cases l1, auto) []\n done\n\n\n\n\n\n (* Placed here because it depends on xy_in_set_cases *)\nlemma distinct_map_eq: \"\\ distinct (List.map f l); f x = f y; x\\set l; y\\set l \\ \\ x=y\"\n by (erule (2) xy_in_set_cases) auto\n\n\n\nlemma upt_append:\n assumes \"iu'\"\n assumes NP: \"\\i. u\\i \\ i \\P i\"\n shows \"[i\\[0..[0..[0..[0..[u..[u..[0.. P (l!i)\"\nproof\n assume A: \"P (l!i)\"\n have \"[0..i\n by (simp add: upt_append)\n also have \"[i..i\n by (auto simp: upt_conv_Cons)\n finally\n have \"[k\\[0..[Suc i..P (l!i)\\ by simp\n hence \"j = last (i#[k\\[Suc i.. \\ i\"\n proof -\n have \"sorted (i#[k\\[Suc i.. last ?l\"\n by (rule sorted_hd_last) simp\n thus ?thesis by simp\n qed\n finally have \"i\\j\" . thus False using \\j by simp\nqed\n\nlemma all_set_conv_nth: \"(\\x\\set l. P x) \\ (\\i\n*) \nlemma upt_0_eq_Nil_conv[simp]: \"[0.. j=0\"\n by auto\n\nlemma filter_eq_snocD: \"filter P l = l'@[x] \\ x\\set l \\ P x\"\nproof -\n assume A: \"filter P l = l'@[x]\"\n hence \"x\\set (filter P l)\" by simp\n thus ?thesis by simp\nqed\n\nlemma lists_image_witness:\n assumes A: \"x\\lists (f`Q)\"\n obtains xo where \"xo\\lists Q\" \"x=map f xo\"\nproof -\n have \"\\ x\\lists (f`Q) \\ \\ \\xo\\lists Q. x=map f xo\"\n proof (induct x)\n case Nil thus ?case by auto\n next\n case (Cons x xs)\n then obtain xos where \"xos\\lists Q\" \"xs=map f xos\" by force\n moreover from Cons.prems have \"x\\f`Q\" by auto\n then obtain xo where \"xo\\Q\" \"x=f xo\" by auto\n ultimately show ?case\n by (rule_tac x=\"xo#xos\" in bexI) auto\n qed\n thus ?thesis\n apply (simp_all add: A)\n apply (erule_tac bexE)\n apply (rule_tac that)\n apply assumption+\n done\nqed\n\n\nlemma map_of_None_filterD:\n \"map_of xs x = None \\ map_of (filter P xs) x = None\"\nby(induct xs) auto\n\nlemma map_of_concat: \"map_of (concat xss) = foldr (\\xs f. f ++ map_of xs) xss Map.empty\"\nby(induct xss) simp_all\n\nlemma map_of_Some_split:\n \"map_of xs k = Some v \\ \\ys zs. xs = ys @ (k, v) # zs \\ map_of ys k = None\"\nproof(induct xs)\n case (Cons x xs)\n obtain k' v' where x: \"x = (k', v')\" by(cases x)\n show ?case\n proof(cases \"k' = k\")\n case True\n with \\map_of (x # xs) k = Some v\\ x have \"x # xs = [] @ (k, v) # xs\" \"map_of [] k = None\" by simp_all\n thus ?thesis by blast\n next\n case False\n with \\map_of (x # xs) k = Some v\\ x\n have \"map_of xs k = Some v\" by simp\n from \\map_of xs k = Some v \\ \\ys zs. xs = ys @ (k, v) # zs \\ map_of ys k = None\\[OF this]\n obtain ys zs where \"xs = ys @ (k, v) # zs\" \"map_of ys k = None\" by blast\n with False x have \"x # xs = (x # ys) @ (k, v) # zs\" \"map_of (x # ys) k = None\" by simp_all\n thus ?thesis by blast\n qed\nqed simp\n\nlemma map_add_find_left:\n \"g k = None \\ (f ++ g) k = f k\"\nby(simp add: map_add_def)\n\nlemma map_add_left_None:\n \"f k = None \\ (f ++ g) k = g k\"\nby(simp add: map_add_def split: option.split)\n\nlemma map_of_Some_filter_not_in:\n \"\\ map_of xs k = Some v; \\ P (k, v); distinct (map fst xs) \\ \\ map_of (filter P xs) k = None\"\napply(induct xs)\napply(auto)\napply(auto simp add: map_of_eq_None_iff)\ndone\n\nlemma distinct_map_fst_filterI: \"distinct (map fst xs) \\ distinct (map fst (filter P xs))\"\nby(induct xs) auto\n\nlemma distinct_map_fstD: \"\\ distinct (map fst xs); (x, y) \\ set xs; (x, z) \\ set xs \\ \\ y = z\"\nby(induct xs)(fastforce elim: notE rev_image_eqI)+\n\n\n\nlemma concat_filter_neq_Nil:\n \"concat [ys\\xs. ys \\ Nil] = concat xs\"\nby(induct xs) simp_all\n\nlemma distinct_concat':\n \"\\distinct [ys\\xs. ys \\ Nil]; \\ys. ys \\ set xs \\ distinct ys;\n \\ys zs. \\ys \\ set xs; zs \\ set xs; ys \\ zs\\ \\ set ys \\ set zs = {}\\\n \\ distinct (concat xs)\"\nby(erule distinct_concat[of \"[ys\\xs. ys \\ Nil]\", unfolded concat_filter_neq_Nil]) auto\n\nlemma distinct_idx:\n assumes \"distinct (map f l)\"\n assumes \"im. n \\ m \\ m < length xs \\ filter P xs ! n = xs ! m \\ filter P (take m xs) = take n (filter P xs)\"\nusing assms\nproof(induct xs rule: rev_induct)\n case Nil thus ?case by simp\nnext\n case (snoc x xs)\n show ?case\n proof(cases \"P x\")\n case [simp]: False\n from \\n < length (filter P (xs @ [x]))\\ have \"n < length (filter P xs)\" by simp\n hence \"\\m\\n. m < length xs \\ filter P xs ! n = xs ! m \\ filter P (take m xs) = take n (filter P xs)\" by(rule snoc)\n thus ?thesis by(auto simp add: nth_append)\n next\n case [simp]: True\n show ?thesis\n proof(cases \"n = length (filter P xs)\")\n case False\n with \\n < length (filter P (xs @ [x]))\\ have \"n < length (filter P xs)\" by simp\n moreover hence \"\\m\\n. m < length xs \\ filter P xs ! n = xs ! m \\ filter P (take m xs) = take n (filter P xs)\"\n by(rule snoc)\n ultimately show ?thesis by(auto simp add: nth_append)\n next\n case [simp]: True\n hence \"filter P (xs @ [x]) ! n = (xs @ [x]) ! length xs\" by simp\n moreover have \"length xs < length (xs @ [x])\" by simp\n moreover have \"length xs \\ n\" by simp\n moreover have \"filter P (take (length xs) (xs @ [x])) = take n (filter P (xs @ [x]))\" by simp\n ultimately show ?thesis by blast\n qed\n qed\nqed\n\nlemma set_map_filter:\n \"set (List.map_filter g xs) = {y. \\x. x \\ set xs \\ g x = Some y}\"\n by (induct xs) (auto simp add: List.map_filter_def set_eq_iff)\n\n \n \n \n \n\nsubsection \\Quicksort by Relation\\\n\ntext \\A functional implementation of quicksort on lists. It it similar to the\none in Isabelle/HOL's example directory. However, it uses tail-recursion for append and arbitrary\nrelations.\\\n\nfun partition_rev :: \"('a \\ bool) \\ ('a list \\ 'a list) \\ 'a list \\ ('a list \\ 'a list)\" where\n \"partition_rev P (yes, no) [] = (yes, no)\"\n | \"partition_rev P (yes, no) (x # xs) =\n partition_rev P (if P x then (x # yes, no) else (yes, x # no)) xs\"\n\nlemma partition_rev_filter_conv :\n \"partition_rev P (yes, no) xs = (rev (filter P xs) @ yes, rev (filter (Not \\ P) xs) @ no)\"\nby (induct xs arbitrary: yes no) (simp_all)\n\nfunction quicksort_by_rel :: \"('a \\ 'a \\ bool) \\ 'a list \\ 'a list \\ 'a list\" where\n \"quicksort_by_rel R sl [] = sl\"\n| \"quicksort_by_rel R sl (x#xs) =\n (let (xs_s, xs_b) = partition_rev (\\y. R y x) ([],[]) xs in\n quicksort_by_rel R (x # (quicksort_by_rel R sl xs_b)) xs_s)\"\nby pat_completeness simp_all\ntermination\nby (relation \"measure (\\(_, _, xs). length xs)\")\n (simp_all add: partition_rev_filter_conv less_Suc_eq_le)\n\nlemma quicksort_by_rel_remove_acc :\n \"quicksort_by_rel R sl xs = (quicksort_by_rel R [] xs @ sl)\"\nproof (induct xs arbitrary: sl rule: measure_induct_rule[of \"length\"])\n case (less xs)\n note ind_hyp = this\n\n show ?case\n proof (cases xs)\n case Nil thus ?thesis by simp\n next\n case (Cons x xs') note xs_eq[simp] = this\n\n obtain xs1 xs2 where part_rev_eq[simp]: \"partition_rev (\\y. R y x) ([], []) xs' = (xs1, xs2)\"\n by (rule prod.exhaust)\n\n from part_rev_eq[symmetric]\n have length_le: \"length xs1 < length xs\" \"length xs2 < length xs\"\n unfolding partition_rev_filter_conv by (simp_all add: less_Suc_eq_le)\n\n note ind_hyp1a = ind_hyp[OF length_le(1), of \"x # quicksort_by_rel R [] xs2\"]\n note ind_hyp1b = ind_hyp[OF length_le(1), of \"x # quicksort_by_rel R [] xs2 @ sl\"]\n note ind_hyp2 = ind_hyp[OF length_le(2), of sl]\n\n show ?thesis by (simp add: ind_hyp1a ind_hyp1b ind_hyp2)\n qed\nqed\n\nlemma quicksort_by_rel_remove_acc_guared :\n \"sl \\ [] \\ quicksort_by_rel R sl xs = (quicksort_by_rel R [] xs @ sl)\"\nby (metis quicksort_by_rel_remove_acc)\n\nlemma quicksort_by_rel_permutes [simp]:\n \"mset (quicksort_by_rel R sl xs) = mset (xs @ sl)\"\nproof (induct xs arbitrary: sl rule: measure_induct_rule[of \"length\"])\n case (less xs)\n note ind_hyp = this\n\n show ?case\n proof (cases xs)\n case Nil thus ?thesis by simp\n next\n case (Cons x xs') note xs_eq[simp] = this\n\n obtain xs1 xs2 where part_rev_eq[simp]: \"partition_rev (\\y. R y x) ([], []) xs' = (xs1, xs2)\"\n by (rule prod.exhaust)\n\n from part_rev_eq[symmetric] have xs'_multi_eq : \"mset xs' = mset xs1 + mset xs2\"\n unfolding partition_rev_filter_conv\n by (simp add: mset_filter)\n\n from part_rev_eq[symmetric]\n have length_le: \"length xs1 < length xs\" \"length xs2 < length xs\"\n unfolding partition_rev_filter_conv by (simp_all add: less_Suc_eq_le)\n\n note ind_hyp[OF length_le(1)] ind_hyp[OF length_le(2)]\n thus ?thesis by (simp add: xs'_multi_eq union_assoc)\n qed\nqed\n\n\n\n\n\n show ?case\n proof (cases xs)\n case Nil thus ?thesis by simp\n next\n case (Cons x xs') note xs_eq[simp] = this\n\n obtain xs1 xs2 where part_rev_eq[simp]: \"partition_rev (\\y. R y x) ([], []) xs' = (xs1, xs2)\"\n by (rule prod.exhaust)\n\n from part_rev_eq[symmetric] have xs1_props: \"\\y. y \\ set xs1 \\ (R y x)\" and\n xs2_props: \"\\y. y \\ set xs2 \\ \\(R y x)\"\n unfolding partition_rev_filter_conv\n by simp_all\n\n from xs2_props lin have xs2_props': \"\\y. y \\ set xs2 \\ (R x y)\" by blast\n from xs2_props' xs1_props trans_R have xs1_props':\n \"\\y1 y2. y1 \\ set xs1 \\ y2 \\ set xs2 \\ (R y1 y2)\"\n by metis\n\n from part_rev_eq[symmetric]\n have length_le: \"length xs1 < length xs\" \"length xs2 < length xs\"\n unfolding partition_rev_filter_conv by (simp_all add: less_Suc_eq_le)\n\n note ind_hyps = ind_hyp[OF length_le(1)] ind_hyp[OF length_le(2)]\n thus ?thesis\n by (simp add: quicksort_by_rel_remove_acc_guared sorted_wrt_append Ball_def\n xs1_props xs2_props' xs1_props')\n qed\nqed\n\nlemma sorted_quicksort_by_rel:\n \"sorted (quicksort_by_rel (\\) [] xs)\"\nunfolding sorted_sorted_wrt\nby (rule sorted_wrt_quicksort_by_rel) auto\n\nlemma sort_quicksort_by_rel:\n \"sort = quicksort_by_rel (\\) []\"\n apply (rule ext, rule properties_for_sort)\n apply(simp_all add: sorted_quicksort_by_rel)\ndone\n\n\n\nsubsection \\Mergesort by Relation\\\n\ntext \\A functional implementation of mergesort on lists. It it similar to the\none in Isabelle/HOL's example directory. However, it uses tail-recursion for append and arbitrary\nrelations.\\\n\nfun mergesort_by_rel_split :: \"('a list \\ 'a list) \\ 'a list \\ ('a list \\ 'a list)\" where\n \"mergesort_by_rel_split (xs1, xs2) [] = (xs1, xs2)\"\n | \"mergesort_by_rel_split (xs1, xs2) [x] = (x # xs1, xs2)\"\n | \"mergesort_by_rel_split (xs1, xs2) (x1 # x2 # xs) =\n mergesort_by_rel_split (x1 # xs1, x2 # xs2) xs\"\n\n\n\n show ?case\n proof (cases xs)\n case Nil thus ?thesis using assms(1) by simp\n next\n case (Cons x1 xs') note xs_eq[simp] = this\n thus ?thesis\n proof (cases xs')\n case Nil thus ?thesis using assms(2) by simp\n next\n case (Cons x2 xs'') note xs'_eq[simp] = this\n show ?thesis\n by (simp add: ind_hyp assms(3))\n qed\n qed\nqed\n\nlemma mergesort_by_rel_split_length :\n \"length (fst (mergesort_by_rel_split (xs1, xs2) xs)) = length xs1 + (length xs div 2) + (length xs mod 2) \\\n length (snd (mergesort_by_rel_split (xs1, xs2) xs)) = length xs2 + (length xs div 2)\"\nby (induct xs arbitrary: xs1 xs2 rule: list_induct_first2)\n (simp_all)\n\nlemma mset_mergesort_by_rel_split [simp]:\n \"mset (fst (mergesort_by_rel_split (xs1, xs2) xs)) +\n mset (snd (mergesort_by_rel_split (xs1, xs2) xs)) =\n mset xs + mset xs1 + mset xs2\"\n apply (induct xs arbitrary: xs1 xs2 rule: list_induct_first2)\n apply (simp_all add: ac_simps)\ndone\n\nfun mergesort_by_rel_merge :: \"('a \\ 'a \\ bool) \\ 'a list \\ 'a list \\ 'a list\"\nwhere\n \"mergesort_by_rel_merge R (x#xs) (y#ys) =\n (if R x y then x # mergesort_by_rel_merge R xs (y#ys) else y # mergesort_by_rel_merge R (x#xs) ys)\"\n| \"mergesort_by_rel_merge R xs [] = xs\"\n| \"mergesort_by_rel_merge R [] ys = ys\"\n\ndeclare mergesort_by_rel_merge.simps [simp del]\n\nlemma mergesort_by_rel_merge_simps[simp] :\n \"mergesort_by_rel_merge R (x#xs) (y#ys) =\n (if R x y then x # mergesort_by_rel_merge R xs (y#ys) else y # mergesort_by_rel_merge R (x#xs) ys)\"\n \"mergesort_by_rel_merge R xs [] = xs\"\n \"mergesort_by_rel_merge R [] ys = ys\"\n apply (simp_all add: mergesort_by_rel_merge.simps)\n apply (cases ys)\n apply (simp_all add: mergesort_by_rel_merge.simps)\ndone\n\nlemma mergesort_by_rel_merge_induct [consumes 0, case_names Nil1 Nil2 Cons1 Cons2]:\nassumes \"\\xs::'a list. P xs []\" \"\\ys::'b list. P [] ys\"\n \"\\x xs y ys. R x y \\ P xs (y # ys) \\ P (x # xs) (y # ys)\"\n \"\\x xs y ys. \\(R x y) \\ P (x # xs) ys \\ P (x # xs) (y # ys)\"\nshows \"P xs ys\"\nproof (induct xs arbitrary: ys)\n case Nil thus ?case using assms(2) by simp\nnext\n case (Cons x xs) note P_xs = this\n show ?case\n proof (induct ys)\n case Nil thus ?case using assms(1) by simp\n next\n case (Cons y ys) note P_x_xs_ys = this\n show ?case using assms(3,4)[of x y xs ys] P_x_xs_ys P_xs by metis\n qed\nqed\n\nlemma mset_mergesort_by_rel_merge [simp]:\n \"mset (mergesort_by_rel_merge R xs ys) = mset xs + mset ys\"\nby (induct R xs ys rule: mergesort_by_rel_merge.induct) (simp_all add: ac_simps)\n\n\n\nlemma sorted_wrt_mergesort_by_rel_merge [simp]:\n assumes lin : \"\\x y. (R x y) \\ (R y x)\"\n and trans_R: \"\\x y z. R x y \\ R y z \\ R x z\"\n shows \"sorted_wrt R (mergesort_by_rel_merge R xs ys) \\\n sorted_wrt R xs \\ sorted_wrt R ys\"\nproof (induct xs ys rule: mergesort_by_rel_merge_induct[where R = R])\n case Nil1 thus ?case by simp\nnext\n case Nil2 thus ?case by simp\nnext\n case (Cons1 x xs y ys) thus ?case\n by (simp add: Ball_def) (metis trans_R)\nnext\n case (Cons2 x xs y ys) thus ?case\n apply (auto simp add: Ball_def)\n apply (metis lin)\n apply (metis lin trans_R)\n done\nqed\n\nfunction mergesort_by_rel :: \"('a \\ 'a \\ bool) \\ 'a list \\ 'a list\"\nwhere\n \"mergesort_by_rel R xs =\n (if length xs < 2 then xs else\n (mergesort_by_rel_merge R\n (mergesort_by_rel R (fst (mergesort_by_rel_split ([], []) xs)))\n (mergesort_by_rel R (snd (mergesort_by_rel_split ([], []) xs)))))\"\nby auto\ntermination\nby (relation \"measure (\\(_, xs). length xs)\")\n (simp_all add: mergesort_by_rel_split_length not_less minus_div_mult_eq_mod [symmetric])\n\ndeclare mergesort_by_rel.simps [simp del]\n\nlemma mergesort_by_rel_simps [simp, code] :\n \"mergesort_by_rel R [] = []\"\n \"mergesort_by_rel R [x] = [x]\"\n \"mergesort_by_rel R (x1 # x2 # xs) =\n (let (xs1, xs2) = (mergesort_by_rel_split ([x1], [x2]) xs) in\n mergesort_by_rel_merge R (mergesort_by_rel R xs1) (mergesort_by_rel R xs2))\"\napply (simp add: mergesort_by_rel.simps)\napply (simp add: mergesort_by_rel.simps)\napply (simp add: mergesort_by_rel.simps[of _ \"x1 # x2 # xs\"] split: prod.splits)\ndone\n\nlemma mergesort_by_rel_permutes [simp]:\n \"mset (mergesort_by_rel R xs) = mset xs\"\nproof (induct xs rule: length_induct)\n case (1 xs) note ind_hyp = this\n\n show ?case\n proof (cases xs)\n case Nil thus ?thesis by simp\n next\n case (Cons x1 xs') note xs_eq[simp] = this\n show ?thesis\n proof (cases xs')\n case Nil thus ?thesis by simp\n next\n case (Cons x2 xs'') note xs'_eq[simp] = this\n\n have \"length (fst (mergesort_by_rel_split ([], []) xs)) < length xs\"\n \"length (snd (mergesort_by_rel_split ([], []) xs)) < length xs\"\n by (simp_all add: mergesort_by_rel_split_length)\n with ind_hyp show ?thesis\n unfolding mergesort_by_rel.simps[of _ xs]\n by (simp add: ac_simps)\n qed\n qed\nqed\n\nlemma set_mergesort_by_rel [simp]: \"set (mergesort_by_rel R xs) = set xs\"\n unfolding set_mset_comp_mset [symmetric] o_apply by simp\n\nlemma sorted_wrt_mergesort_by_rel:\n fixes R:: \"'x \\ 'x \\ bool\"\n assumes lin : \"\\x y. (R x y) \\ (R y x)\"\n and trans_R: \"\\x y z. R x y \\ R y z \\ R x z\"\n shows \"sorted_wrt R (mergesort_by_rel R xs)\"\nproof (induct xs rule: measure_induct_rule[of \"length\"])\n case (less xs)\n note ind_hyp = this\n\n show ?case\n proof (cases xs)\n case Nil thus ?thesis by simp\n next\n case (Cons x xs') note xs_eq[simp] = this\n thus ?thesis\n proof (cases xs')\n case Nil thus ?thesis by simp\n next\n case (Cons x2 xs'') note xs'_eq[simp] = this\n\n have \"length (fst (mergesort_by_rel_split ([], []) xs)) < length xs\"\n \"length (snd (mergesort_by_rel_split ([], []) xs)) < length xs\"\n by (simp_all add: mergesort_by_rel_split_length)\n with ind_hyp show ?thesis\n unfolding mergesort_by_rel.simps[of _ xs]\n by (simp add: sorted_wrt_mergesort_by_rel_merge[OF lin trans_R])\n qed\n qed\nqed\n\nlemma sorted_mergesort_by_rel:\n \"sorted (mergesort_by_rel (\\) xs)\"\nunfolding sorted_sorted_wrt\nby (rule sorted_wrt_mergesort_by_rel) auto\n\nlemma sort_mergesort_by_rel:\n \"sort = mergesort_by_rel (\\)\"\n apply (rule ext, rule properties_for_sort)\n apply(simp_all add: sorted_mergesort_by_rel)\ndone\n\ndefinition \"mergesort = mergesort_by_rel (\\)\"\n\nlemma sort_mergesort: \"sort = mergesort\"\n unfolding mergesort_def by (rule sort_mergesort_by_rel)\n\nsubsubsection \\Mergesort with Remdup\\\nterm merge\n\nfun merge :: \"'a::{linorder} list \\ 'a list \\ 'a list\" where\n \"merge [] l2 = l2\"\n | \"merge l1 [] = l1\"\n | \"merge (x1 # l1) (x2 # l2) =\n (if (x1 < x2) then x1 # (merge l1 (x2 # l2)) else\n (if (x1 = x2) then x1 # (merge l1 l2) else x2 # (merge (x1 # l1) l2)))\"\n\nlemma merge_correct :\nassumes l1_OK: \"distinct l1 \\ sorted l1\"\nassumes l2_OK: \"distinct l2 \\ sorted l2\"\nshows \"distinct (merge l1 l2) \\ sorted (merge l1 l2) \\ set (merge l1 l2) = set l1 \\ set l2\"\nusing assms\nproof (induct l1 arbitrary: l2)\n case Nil thus ?case by simp\nnext\n case (Cons x1 l1 l2)\n note x1_l1_props = Cons(2)\n note l2_props = Cons(3)\n\n from x1_l1_props have l1_props: \"distinct l1 \\ sorted l1\"\n and x1_nin_l1: \"x1 \\ set l1\"\n and x1_le: \"\\x. x \\ set l1 \\ x1 \\ x\"\n by (simp_all add: Ball_def)\n\n note ind_hyp_l1 = Cons(1)[OF l1_props]\n\n show ?case\n using l2_props\n proof (induct l2)\n case Nil with x1_l1_props show ?case by simp\n next\n case (Cons x2 l2)\n note x2_l2_props = Cons(2)\n from x2_l2_props have l2_props: \"distinct l2 \\ sorted l2\"\n and x2_nin_l2: \"x2 \\ set l2\"\n and x2_le: \"\\x. x \\ set l2 \\ x2 \\ x\"\n by (simp_all add: Ball_def)\n\n note ind_hyp_l2 = Cons(1)[OF l2_props]\n show ?case\n proof (cases \"x1 < x2\")\n case True note x1_less_x2 = this\n\n from ind_hyp_l1[OF x2_l2_props] x1_less_x2 x1_nin_l1 x1_le x2_le\n show ?thesis\n apply (auto simp add: Ball_def)\n apply (metis linorder_not_le)\n apply (metis linorder_not_less xt1(6) xt1(9))\n done\n next\n case False note x2_le_x1 = this\n\n show ?thesis\n proof (cases \"x1 = x2\")\n case True note x1_eq_x2 = this\n\n from ind_hyp_l1[OF l2_props] x1_le x2_le x2_nin_l2 x1_eq_x2 x1_nin_l1\n show ?thesis by (simp add: x1_eq_x2 Ball_def)\n next\n case False note x1_neq_x2 = this\n with x2_le_x1 have x2_less_x1 : \"x2 < x1\" by auto\n\n from ind_hyp_l2 x2_le_x1 x1_neq_x2 x2_le x2_nin_l2 x1_le\n show ?thesis\n apply (simp add: x2_less_x1 Ball_def)\n apply (metis linorder_not_le x2_less_x1 xt1(7))\n done\n qed\n qed\n qed\nqed\n\nfunction merge_list :: \"'a::{linorder} list list \\ 'a list list \\ 'a list\" where\n \"merge_list [] [] = []\"\n | \"merge_list [] [l] = l\"\n | \"merge_list (la # acc2) [] = merge_list [] (la # acc2)\"\n | \"merge_list (la # acc2) [l] = merge_list [] (l # la # acc2)\"\n | \"merge_list acc2 (l1 # l2 # ls) =\n merge_list ((merge l1 l2) # acc2) ls\"\nby pat_completeness simp_all\ntermination\nby (relation \"measure (\\(acc, ls). 3 * length acc + 2 * length ls)\") (simp_all)\n\nlemma merge_list_correct :\nassumes ls_OK: \"\\l. l \\ set ls \\ distinct l \\ sorted l\"\nassumes as_OK: \"\\l. l \\ set as \\ distinct l \\ sorted l\"\nshows \"distinct (merge_list as ls) \\ sorted (merge_list as ls) \\\n set (merge_list as ls) = set (concat (as @ ls))\"\nusing assms\nproof (induct as ls rule: merge_list.induct)\n case 1 thus ?case by simp\nnext\n case 2 thus ?case by simp\nnext\n case 3 thus ?case by simp\nnext\n case 4 thus ?case by auto\nnext\n case (5 acc l1 l2 ls)\n note ind_hyp = 5(1)\n note l12_l_OK = 5(2)\n note acc_OK = 5(3)\n\n from l12_l_OK acc_OK merge_correct[of l1 l2]\n have set_merge_eq: \"set (merge l1 l2) = set l1 \\ set l2\" by auto\n\n from l12_l_OK acc_OK merge_correct[of l1 l2]\n have \"distinct (merge_list (merge l1 l2 # acc) ls) \\\n sorted (merge_list (merge l1 l2 # acc) ls) \\\n set (merge_list (merge l1 l2 # acc) ls) =\n set (concat ((merge l1 l2 # acc) @ ls))\"\n by (rule_tac ind_hyp) auto\n with set_merge_eq show ?case by auto\nqed\n\n\ndefinition mergesort_remdups where\n \"mergesort_remdups xs = merge_list [] (map (\\x. [x]) xs)\"\n\nlemma mergesort_remdups_correct :\n \"distinct (mergesort_remdups l)\n \\ sorted (mergesort_remdups l)\n \\ (set (mergesort_remdups l) = set l)\"\nproof -\n let ?l' = \"map (\\x. [x]) l\"\n\n { fix xs\n assume \"xs \\ set ?l'\"\n then obtain x where xs_eq: \"xs = [x]\" by auto\n hence \"distinct xs \\ sorted xs\" by simp\n } note l'_OK = this\n\n from merge_list_correct[of \"?l'\" \"[]\", OF l'_OK]\n show ?thesis unfolding mergesort_remdups_def by simp\nqed\n\n(* TODO: Move *)\nlemma ex1_eqI: \"\\\\!x. P x; P a; P b\\ \\ a=b\"\n by blast\n\nlemma remdup_sort_mergesort_remdups:\n \"remdups o sort = mergesort_remdups\" (is \"?lhs=?rhs\")\nproof\n fix l\n have \"set (?lhs l) = set l\" and \"sorted (?lhs l)\" and \"distinct (?lhs l)\"\n by simp_all\n moreover note mergesort_remdups_correct\n ultimately show \"?lhs l = ?rhs l\"\n by (auto intro!: ex1_eqI[OF finite_sorted_distinct_unique[OF finite_set]])\nqed\n\nsubsection \\Native Integers\\ \nlemma int_of_integer_less_iff: \"int_of_integer x < int_of_integer y \\ x0 \\ y\\0 \\ nat_of_integer x < nat_of_integer y \\ xn' < n. \\ P n') \\ P (n::nat)\"\n shows \"\\n' \\ n. P n'\"\nproof (rule classical)\n assume contra: \"\\ (\\n'\\n. P n')\"\n hence \"\\n' < n. \\ P n'\" by auto\n hence \"P n\" by (rule hyp)\n thus \"\\n'\\n. P n'\" by auto\nqed\n\nsubsubsection \\Induction on nat\\\n lemma nat_compl_induct[case_names 0 Suc]: \"\\P 0; \\n . \\nn. nn \\ n \\ P nn \\ P (Suc n)\\ \\ P n\"\n apply(induct_tac n rule: nat_less_induct)\n apply(case_tac n)\n apply(auto)\n done\n\n lemma nat_compl_induct'[case_names 0 Suc]: \"\\P 0; !! n . \\!! nn . nn \\ n \\ P nn\\ \\ P (Suc n)\\ \\ P n\"\n apply(induct_tac n rule: nat_less_induct)\n apply(case_tac n)\n apply(auto)\n done\n\n lemma nz_le_conv_less: \"0 k \\ m \\ k - Suc 0 < m\"\n by auto\n \n lemma min_Suc_gt[simp]: \n \"a min (Suc a) b = Suc a\" \n \"a min b (Suc a) = Suc a\" \n by auto\n \n \nsubsection \\Integer\\\n\ntext \\Some setup from \\int\\ transferred to \\integer\\\\\n\nlemma atLeastLessThanPlusOne_atLeastAtMost_integer: \"{l.. u \\\n {(0::integer).. u\")\n apply (subst image_atLeastZeroLessThan_integer, assumption)\n apply (rule finite_imageI)\n apply auto\n done\n\nlemma finite_atLeastLessThan_integer [iff]: \"finite {l..Functions of type @{typ \"bool\\bool\"}\\\n lemma boolfun_cases_helper: \"g=(\\x. False) | g=(\\x. x) | g=(\\x. True) | g= (\\x. \\x)\"\n proof -\n { assume \"g False\" \"g True\"\n hence \"g = (\\x. True)\" by (rule_tac ext, case_tac x, auto)\n } moreover {\n assume \"g False\" \"\\g True\"\n hence \"g = (\\x. \\x)\" by (rule_tac ext, case_tac x, auto)\n } moreover {\n assume \"\\g False\" \"g True\"\n hence \"g = (\\x. x)\" by (rule_tac ext, case_tac x, auto)\n } moreover {\n assume \"\\g False\" \"\\g True\"\n hence \"g = (\\x. False)\" by (rule_tac ext, case_tac x, auto)\n } ultimately show ?thesis by fast\n qed\n\n lemma boolfun_cases[case_names False Id True Neg]: \"\\g=(\\x. False) \\ P; g=(\\x. x) \\ P; g=(\\x. True) \\ P; g=(\\x. \\x) \\ P\\ \\ P\"\n proof -\n note boolfun_cases_helper[of g]\n moreover assume \"g=(\\x. False) \\ P\" \"g=(\\x. x) \\ P\" \"g=(\\x. True) \\ P\" \"g=(\\x. \\x) \\ P\"\n ultimately show ?thesis by fast\n qed\n\n\nsubsection \\Definite and indefinite description\\\n text \"Combined definite and indefinite description for binary predicate\"\n lemma some_theI: assumes EX: \"\\a b . P a b\" and BUN: \"!! b1 b2 . \\\\a . P a b1; \\a . P a b2\\ \\ b1=b2\"\n shows \"P (SOME a . \\b . P a b) (THE b . \\a . P a b)\"\n proof -\n from EX have \"\\b. P (SOME a. \\b. P a b) b\" by (rule someI_ex)\n moreover from EX have \"\\b. \\a. P a b\" by blast\n with BUN theI'[of \"\\b. \\a. P a b\"] have \"\\a. P a (THE b. \\a. P a b)\" by (unfold Ex1_def, blast)\n moreover note BUN\n ultimately show ?thesis by (fast)\n qed\n\n lemma some_insert_self[simp]: \"S\\{} \\ insert (SOME x. x\\S) S = S\"\n by (auto intro: someI)\n\n lemma some_elem[simp]: \"S\\{} \\ (SOME x. x\\S) \\ S\"\n by (auto intro: someI)\n\nsubsubsection\\Hilbert Choice with option\\\n\ndefinition Eps_Opt where\n \"Eps_Opt P = (if (\\x. P x) then Some (SOME x. P x) else None)\"\n\nlemma some_opt_eq_trivial[simp] :\n \"Eps_Opt (\\y. y = x) = Some x\"\nunfolding Eps_Opt_def by simp\n\nlemma some_opt_sym_eq_trivial[simp] :\n \"Eps_Opt ((=) x) = Some x\"\nunfolding Eps_Opt_def by simp\n\nlemma some_opt_false_trivial[simp] :\n \"Eps_Opt (\\_. False) = None\"\nunfolding Eps_Opt_def by simp\n\nlemma Eps_Opt_eq_None[simp] :\n \"Eps_Opt P = None \\ \\(Ex P)\"\nunfolding Eps_Opt_def by simp\n\nlemma Eps_Opt_eq_Some_implies :\n \"Eps_Opt P = Some x \\ P x\"\nunfolding Eps_Opt_def\nby (metis option.inject option.simps(2) someI_ex)\n\nlemma Eps_Opt_eq_Some :\nassumes P_prop: \"\\x'. P x \\ P x' \\ x' = x\"\nshows \"Eps_Opt P = Some x \\ P x\"\nusing P_prop\nunfolding Eps_Opt_def\nby (metis option.inject option.simps(2) someI_ex)\n\nsubsection \\Product Type\\\n\nlemma nested_case_prod_simp: \"(\\(a,b) c. f a b c) x y =\n (case_prod (\\a b. f a b y) x)\"\n by (auto split: prod.split)\n\nlemma fn_fst_conv: \"(\\x. (f (fst x))) = (\\(a,_). f a)\"\n by auto\nlemma fn_snd_conv: \"(\\x. (f (snd x))) = (\\(_,b). f b)\"\n by auto\n\nfun pairself where\n \"pairself f (a,b) = (f a, f b)\"\n\nlemma pairself_image_eq[simp]:\n \"pairself f ` {(a,b). P a b} = {(f a, f b)| a b. P a b}\"\n by force\n\nlemma pairself_image_cart[simp]: \"pairself f ` (A\\B) = f`A \\ f`B\"\n by (auto simp: image_def)\n\nlemma in_prod_fst_sndI: \"fst x \\ A \\ snd x \\ B \\ x\\A\\B\"\n by (cases x) auto\n\nlemma inj_Pair[simp]:\n \"inj_on (\\x. (x,c x)) S\"\n \"inj_on (\\x. (c x,x)) S\"\n by (auto intro!: inj_onI)\n\ndeclare Product_Type.swap_inj_on[simp]\n\nlemma img_fst [intro]:\n assumes \"(a,b) \\ S\"\n shows \"a \\ fst ` S\"\nby (rule image_eqI[OF _ assms]) simp\n\nlemma img_snd [intro]:\n assumes \"(a,b) \\ S\"\n shows \"b \\ snd ` S\"\nby (rule image_eqI[OF _ assms]) simp\n\nlemma range_prod:\n \"range f \\ (range (fst \\ f)) \\ (range (snd \\ f))\"\nproof\n fix y\n assume \"y \\ range f\"\n then obtain x where y: \"y = f x\" by auto\n hence \"y = (fst(f x), snd(f x))\"\n by simp\n thus \"y \\ (range (fst \\ f)) \\ (range (snd \\ f))\"\n by (fastforce simp add: image_def)\nqed\n\nlemma finite_range_prod:\n assumes fst: \"finite (range (fst \\ f))\"\n and snd: \"finite (range (snd \\ f))\"\n shows \"finite (range f)\"\nproof -\n from fst snd have \"finite (range (fst \\ f) \\ range (snd \\ f))\"\n by (rule finite_SigmaI)\n thus ?thesis\n by (rule finite_subset[OF range_prod])\nqed\n\nlemma fstE:\n \"x = (a,b) \\ P (fst x) \\ P a\"\nby (metis fst_conv)\n\nlemma sndE:\n \"x = (a,b) \\ P (snd x) \\ P b\"\nby (metis snd_conv)\n\nsubsubsection \\Uncurrying\\\n\n(* TODO: Move to HOL/Product_Type? Lars H: \"It's equal to case_prod, should use an abbreviation\"*)\ndefinition uncurry :: \"('a \\ 'b \\ 'c) \\ 'a \\ 'b \\ 'c\" where\n \"uncurry f \\ \\(a,b). f a b\"\n\nlemma uncurry_apply[simp]: \"uncurry f (a,b) = f a b\"\n unfolding uncurry_def\n by simp\n\nlemma curry_uncurry_id[simp]: \"curry (uncurry f) = f\"\n unfolding uncurry_def\n by simp\n\nlemma uncurry_curry_id[simp]: \"uncurry (curry f) = f\"\n unfolding uncurry_def\n by simp\n\nlemma do_curry: \"f (a,b) = curry f a b\" by simp\nlemma do_uncurry: \"f a b = uncurry f (a,b)\" by simp\n \nsubsection \\Sum Type\\ \nlemma map_sum_Inr_conv: \"map_sum fl fr s = Inr y \\ (\\x. s=Inr x \\ y = fr x)\"\n by (cases s) auto\nlemma map_sum_Inl_conv: \"map_sum fl fr s = Inl y \\ (\\x. s=Inl x \\ y = fl x)\"\n by (cases s) auto\n \n \nsubsection \\Directed Graphs and Relations\\\n\n subsubsection \"Reflexive-Transitive Closure\"\n lemma r_le_rtrancl[simp]: \"S\\S\\<^sup>*\" by auto\n lemma rtrancl_mono_rightI: \"S\\S' \\ S\\S'\\<^sup>*\" by auto\n\n lemma trancl_sub:\n \"R \\ R\\<^sup>+\"\n by auto\n\n lemma trancl_single[simp]:\n \"{(a,b)}\\<^sup>+ = {(a,b)}\"\n by (auto simp: trancl_insert)\n\n\n text \\Pick first non-reflexive step\\\n lemma converse_rtranclE'[consumes 1, case_names base step]:\n assumes \"(u,v)\\R\\<^sup>*\"\n obtains \"u=v\"\n | vh where \"u\\vh\" and \"(u,vh)\\R\" and \"(vh,v)\\R\\<^sup>*\"\n using assms\n apply (induct rule: converse_rtrancl_induct)\n apply auto []\n apply (case_tac \"y=z\")\n apply auto\n done\n\n lemma in_rtrancl_insert: \"x\\R\\<^sup>* \\ x\\(insert r R)\\<^sup>*\"\n by (metis in_mono rtrancl_mono subset_insertI)\n\n\n lemma rtrancl_apply_insert: \"R\\<^sup>*``(insert x S) = insert x (R\\<^sup>*``(S\\R``{x}))\"\n apply (auto)\n apply (erule converse_rtranclE)\n apply auto [2]\n apply (erule converse_rtranclE)\n apply (auto intro: converse_rtrancl_into_rtrancl) [2]\n done\n\n\n\n\n text \\A path in a graph either does not use nodes from S at all, or it has a prefix leading to a node in S and a suffix that does not use nodes in S\\\n lemma rtrancl_last_visit[cases set, case_names no_visit last_visit_point]:\n shows\n \"\\ (q,q')\\R\\<^sup>*;\n (q,q')\\(R-UNIV\\S)\\<^sup>* \\ P;\n !!qt. \\ qt\\S; (q,qt)\\R\\<^sup>+; (qt,q')\\(R-UNIV\\S)\\<^sup>* \\ \\ P\n \\ \\ P\"\n proof (induct rule: converse_rtrancl_induct[case_names refl step])\n case refl thus ?case by auto\n next\n case (step q qh)\n show P proof (rule step.hyps(3))\n assume A: \"(qh,q')\\(R-UNIV\\S)\\<^sup>*\"\n show P proof (cases \"qh\\S\")\n case False\n with step.hyps(1) A have \"(q,q')\\(R-UNIV\\S)\\<^sup>*\"\n by (auto intro: converse_rtrancl_into_rtrancl)\n with step.prems(1) show P .\n next\n case True\n from step.hyps(1) have \"(q,qh)\\R\\<^sup>+\" by auto\n with step.prems(2) True A show P by blast\n qed\n next\n fix qt\n assume A: \"qt\\S\" \"(qh,qt)\\R\\<^sup>+\" \"(qt,q')\\(R-UNIV\\S)\\<^sup>*\"\n with step.hyps(1) have \"(q,qt)\\R\\<^sup>+\" by auto\n with step.prems(2) A(1,3) show P by blast\n qed\n qed\n\n text \\Less general version of \\rtrancl_last_visit\\, but there's a short automatic proof\\\n lemma rtrancl_last_visit': \"\\ (q,q')\\R\\<^sup>*; (q,q')\\(R-UNIV\\S)\\<^sup>* \\ P; !!qt. \\ qt\\S; (q,qt)\\R\\<^sup>*; (qt,q')\\(R-UNIV\\S)\\<^sup>* \\ \\ P \\ \\ P\"\n by (induct rule: converse_rtrancl_induct) (auto intro: converse_rtrancl_into_rtrancl)\n\n lemma rtrancl_last_visit_node:\n assumes \"(s,s')\\R\\<^sup>*\"\n shows \"s\\sh \\ (s,s')\\(R \\ (UNIV \\ (-{sh})))\\<^sup>* \\\n (s,sh)\\R\\<^sup>* \\ (sh,s')\\(R \\ (UNIV \\ (-{sh})))\\<^sup>*\"\n using assms\n proof (induct rule: converse_rtrancl_induct)\n case base thus ?case by auto\n next\n case (step s st)\n moreover {\n assume P: \"(st,s')\\ (R \\ UNIV \\ - {sh})\\<^sup>*\"\n {\n assume \"st=sh\" with step have ?case\n by auto\n } moreover {\n assume \"st\\sh\"\n with \\(s,st)\\R\\ have \"(s,st)\\(R \\ UNIV \\ - {sh})\\<^sup>*\" by auto\n also note P\n finally have ?case by blast\n } ultimately have ?case by blast\n } moreover {\n assume P: \"(st, sh) \\ R\\<^sup>* \\ (sh, s') \\ (R \\ UNIV \\ - {sh})\\<^sup>*\"\n with step(1) have ?case\n by (auto dest: converse_rtrancl_into_rtrancl)\n } ultimately show ?case by blast\n qed\n\n text \\Find last point where a path touches a set\\\n lemma rtrancl_last_touch: \"\\ (q,q')\\R\\<^sup>*; q\\S; !!qt. \\ qt\\S; (q,qt)\\R\\<^sup>*; (qt,q')\\(R-UNIV\\S)\\<^sup>* \\ \\ P \\ \\ P\"\n by (erule rtrancl_last_visit') auto\n\n text \\A path either goes over edge once, or not at all\\\n lemma trancl_over_edgeE:\n assumes \"(u,w)\\(insert (v1,v2) E)\\<^sup>+\"\n obtains \"(u,w)\\E\\<^sup>+\"\n | \"(u,v1)\\E\\<^sup>*\" and \"(v2,w)\\E\\<^sup>*\"\n using assms\n proof induct\n case (base z) thus ?thesis\n by (metis insertE prod.inject r_into_trancl' rtrancl_eq_or_trancl)\n next\n case (step y z) thus ?thesis\n by (metis (hide_lams, no_types)\n Pair_inject insertE rtrancl.simps trancl.simps trancl_into_rtrancl)\n qed\n\n lemma rtrancl_image_advance: \"\\q\\R\\<^sup>* `` Q0; (q,x)\\R\\ \\ x\\R\\<^sup>* `` Q0\"\n by (auto intro: rtrancl_into_rtrancl)\n\n lemma trancl_image_by_rtrancl: \"(E\\<^sup>+)``Vi \\ Vi = (E\\<^sup>*)``Vi\"\n by (metis Image_Id Un_Image rtrancl_trancl_reflcl)\n\n lemma reachable_mono: \"\\R\\R'; X\\X'\\ \\ R\\<^sup>*``X \\ R'\\<^sup>*``X'\"\n by (metis Image_mono rtrancl_mono)\n\n lemma finite_reachable_advance:\n \"\\ finite (E\\<^sup>*``{v0}); (v0,v)\\E\\<^sup>* \\ \\ finite (E\\<^sup>*``{v})\"\n by (erule finite_subset[rotated]) auto\n\nlemma rtrancl_mono_mp: \"U\\V \\ x\\U\\<^sup>* \\ x\\V\\<^sup>*\" by (metis in_mono rtrancl_mono)\nlemma trancl_mono_mp: \"U\\V \\ x\\U\\<^sup>+ \\ x\\V\\<^sup>+\" by (metis trancl_mono)\n\nlemma rtrancl_mapI: \"(a,b)\\E\\<^sup>* \\ (f a, f b)\\(pairself f `E)\\<^sup>*\"\n apply (induction rule: rtrancl_induct)\n apply (force intro: rtrancl.intros)+\n done\n\nlemma rtrancl_image_advance_rtrancl:\n assumes \"q \\ R\\<^sup>*``Q0\"\n assumes \"(q,x) \\ R\\<^sup>*\"\n shows \"x \\ R\\<^sup>*``Q0\"\n using assms\n by (metis rtrancl_idemp rtrancl_image_advance)\n\nlemma nth_step_trancl:\n \"\\n m. \\ \\ n. n < length xs - 1 \\ (xs ! Suc n, xs ! n) \\ R \\ \\ n < length xs \\ m < n \\ (xs ! n, xs ! m) \\ R\\<^sup>+\"\nproof (induction xs)\n case (Cons x xs)\n hence \"\\n. n < length xs - 1 \\ (xs ! Suc n, xs ! n) \\ R\"\n apply clarsimp\n by (metis One_nat_def diff_Suc_eq_diff_pred nth_Cons_Suc zero_less_diff)\n note IH = this[THEN Cons.IH]\n\n from Cons obtain n' where n': \"Suc n' = n\" by (cases n) blast+\n\n show ?case\n proof (cases m)\n case \"0\" with Cons have \"xs \\ []\" by auto\n with \"0\" Cons.prems(1)[of m] have \"(xs ! 0, x) \\ R\" by simp\n moreover from IH[where m = 0] have \"\\n. n < length xs \\ n > 0 \\ (xs ! n, xs ! 0) \\ R\\<^sup>+\" by simp\n ultimately have \"\\n. n < length xs \\ (xs ! n, x) \\ R\\<^sup>+\" by (metis trancl_into_trancl gr0I r_into_trancl')\n with Cons \"0\" show ?thesis by auto\n next\n case (Suc m') with Cons.prems n' have \"n' < length xs\" \"m' < n'\" by auto\n with IH have \"(xs ! n', xs ! m') \\ R\\<^sup>+\" by simp\n with Suc n' show ?thesis by auto\n qed\nqed simp\n\nlemma Image_empty_trancl_Image_empty:\n \"R `` {v} = {} \\ R\\<^sup>+ `` {v} = {}\"\n unfolding Image_def\n by (auto elim: converse_tranclE)\n\nlemma Image_empty_rtrancl_Image_id:\n \"R `` {v} = {} \\ R\\<^sup>* `` {v} = {v}\"\n unfolding Image_def\n by (auto elim: converse_rtranclE)\n\nlemma trans_rtrancl_eq_reflcl:\n \"trans A \\ A^* = A^=\"\n by (simp add: rtrancl_trancl_reflcl)\n\nlemma refl_on_reflcl_Image:\n \"refl_on B A \\ C \\ B \\ A^= `` C = A `` C\"\n by (auto simp add: Image_def dest: refl_onD)\n\nlemma Image_absorb_rtrancl:\n \"\\ trans A; refl_on B A; C \\ B \\ \\ A^* `` C = A `` C\"\n by (simp add: trans_rtrancl_eq_reflcl refl_on_reflcl_Image)\n\nlemma trancl_Image_unfold_left: \"E\\<^sup>+``S = E\\<^sup>*``E``S\"\n by (auto simp: trancl_unfold_left)\n\nlemma trancl_Image_unfold_right: \"E\\<^sup>+``S = E``E\\<^sup>*``S\"\n by (auto simp: trancl_unfold_right)\n\nlemma trancl_Image_advance_ss: \"(u,v)\\E \\ E\\<^sup>+``{v} \\ E\\<^sup>+``{u}\"\n by auto\n\nlemma rtrancl_Image_advance_ss: \"(u,v)\\E \\ E\\<^sup>*``{v} \\ E\\<^sup>*``{u}\"\n by auto\n\n(* FIXME: nicer name *)\nlemma trancl_union_outside:\n assumes \"(v,w) \\ (E\\U)\\<^sup>+\"\n and \"(v,w) \\ E\\<^sup>+\"\n shows \"\\x y. (v,x) \\ (E\\U)\\<^sup>* \\ (x,y) \\ U \\ (y,w) \\ (E\\U)\\<^sup>*\"\nusing assms\nproof (induction)\n case base thus ?case by auto\nnext\n case (step w x)\n show ?case\n proof (cases \"(v,w)\\E\\<^sup>+\")\n case True\n from step have \"(v,w)\\(E\\U)\\<^sup>*\" by simp\n moreover from True step have \"(w,x) \\ U\" by (metis Un_iff trancl.simps)\n moreover have \"(x,x) \\ (E\\U)\\<^sup>*\" by simp\n ultimately show ?thesis by blast\n next\n case False with step.IH obtain a b where \"(v,a) \\ (E\\U)\\<^sup>*\" \"(a,b) \\ U\" \"(b,w) \\ (E\\U)\\<^sup>*\" by blast\n moreover with step have \"(b,x) \\ (E\\U)\\<^sup>*\" by (metis rtrancl_into_rtrancl)\n ultimately show ?thesis by blast\n qed\nqed\n\nlemma trancl_restrict_reachable:\n assumes \"(u,v) \\ E\\<^sup>+\"\n assumes \"E``S \\ S\"\n assumes \"u\\S\"\n shows \"(u,v) \\ (E\\S\\S)\\<^sup>+\"\n using assms\n by (induction rule: converse_trancl_induct)\n (auto intro: trancl_into_trancl2)\n\nlemma rtrancl_image_unfold_right: \"E``E\\<^sup>*``V \\ E\\<^sup>*``V\"\n by (auto intro: rtrancl_into_rtrancl)\n\n\nlemma trancl_Image_in_Range:\n \"R\\<^sup>+ `` V \\ Range R\"\nby (auto elim: trancl.induct)\n\nlemma rtrancl_Image_in_Field:\n \"R\\<^sup>* `` V \\ Field R \\ V\"\nproof -\n from trancl_Image_in_Range have \"R\\<^sup>+ `` V \\ Field R\"\n unfolding Field_def by fast\n hence \"R\\<^sup>+ `` V \\ V \\ Field R \\ V\" by blast\n with trancl_image_by_rtrancl show ?thesis by metis\nqed\n\nlemma rtrancl_sub_insert_rtrancl:\n \"R\\<^sup>* \\ (insert x R)\\<^sup>*\"\nby (auto elim: rtrancl.induct rtrancl_into_rtrancl)\n\nlemma trancl_sub_insert_trancl:\n \"R\\<^sup>+ \\ (insert x R)\\<^sup>+\"\nby (auto elim: trancl.induct trancl_into_trancl)\n\nlemma Restr_rtrancl_mono:\n \"(v,w) \\ (Restr E U)\\<^sup>* \\ (v,w) \\ E\\<^sup>*\"\n by (metis inf_le1 rtrancl_mono subsetCE)\n\nlemma Restr_trancl_mono:\n \"(v,w) \\ (Restr E U)\\<^sup>+ \\ (v,w) \\ E\\<^sup>+\"\n by (metis inf_le1 trancl_mono)\n\n\n\n\n\n\n\n\n subsubsection \"Converse Relation\"\n\n lemmas converse_add_simps = converse_Times trancl_converse[symmetric] converse_Un converse_Int\n\n lemma dom_ran_disj_comp[simp]: \"Domain R \\ Range R = {} \\ R O R = {}\"\n by auto\n\n lemma below_Id_inv[simp]: \"R\\\\Id \\ R\\Id\" by (auto)\n \n \n subsubsection \"Cyclicity\"\n\n lemma cyclicE: \"\\\\acyclic g; !!x. (x,x)\\g\\<^sup>+ \\ P\\ \\ P\"\n by (unfold acyclic_def) blast\n\n lemma acyclic_insert_cyclic: \"\\acyclic g; \\acyclic (insert (x,y) g)\\ \\ (y,x)\\g\\<^sup>*\"\n by (unfold acyclic_def) (auto simp add: trancl_insert)\n\n\n text \\\n This lemma makes a case distinction about a path in a graph where a couple of edges with the same\n endpoint have been inserted: If there is a path from a to b, then there's such a path in the original graph, or\n there's a path that uses an inserted edge only once.\n\n Originally, this lemma was used to reason about the graph of an updated acquisition history. Any path in\n this graph is either already contained in the original graph, or passes via an\n inserted edge. Because all the inserted edges point to the same target node, in the\n second case, the path can be short-circuited to use exactly one inserted edge.\n\\\n lemma trancl_multi_insert[cases set, case_names orig via]:\n \"\\ (a,b)\\(r\\X\\{m})\\<^sup>+;\n (a,b)\\r\\<^sup>+ \\ P;\n !!x. \\ x\\X; (a,x)\\r\\<^sup>*; (m,b)\\r\\<^sup>* \\ \\ P\n \\ \\ P\"\n proof (induct arbitrary: P rule: trancl_induct)\n case (base b) thus ?case by auto\n next\n case (step b c) show ?case proof (rule step.hyps(3))\n assume A: \"(a,b)\\r\\<^sup>+\"\n note step.hyps(2)\n moreover {\n assume \"(b,c)\\r\"\n with A have \"(a,c)\\r\\<^sup>+\" by auto\n with step.prems have P by blast\n } moreover {\n assume \"b\\X\" \"c=m\"\n with A have P by (rule_tac step.prems(2)) simp+\n } ultimately show P by auto\n next\n fix x\n assume A: \"x \\ X\" \"(a, x) \\ r\\<^sup>*\" \"(m, b) \\ r\\<^sup>*\"\n note step.hyps(2)\n moreover {\n assume \"(b,c)\\r\"\n with A(3) have \"(m,c)\\r\\<^sup>*\" by auto\n with step.prems(2)[OF A(1,2)] have P by blast\n } moreover {\n assume \"b\\X\" \"c=m\"\n with A have P by (rule_tac step.prems(2)) simp+\n } ultimately show P by auto\n qed\n qed\n\n text \\\n Version of @{thm [source] trancl_multi_insert} for inserted edges with the same startpoint.\n\\\n lemma trancl_multi_insert2[cases set, case_names orig via]:\n \"\\(a,b)\\(r\\{m}\\X)\\<^sup>+; (a,b)\\r\\<^sup>+ \\ P; !!x. \\ x\\X; (a,m)\\r\\<^sup>*; (x,b)\\r\\<^sup>* \\ \\ P \\ \\ P\"\n proof goal_cases\n case prems: 1 from prems(1) have \"(b,a)\\((r\\{m}\\X)\\<^sup>+)\\\" by simp\n also have \"((r\\{m}\\X)\\<^sup>+)\\ = (r\\\\X\\{m})\\<^sup>+\" by (simp add: converse_add_simps)\n finally have \"(b, a) \\ (r\\ \\ X \\ {m})\\<^sup>+\" .\n thus ?case\n by (auto elim!: trancl_multi_insert\n intro: prems(2,3)\n simp add: trancl_converse rtrancl_converse\n )\n qed\n\nlemma cyclic_subset:\n \"\\ \\ acyclic R; R \\ S \\ \\ \\ acyclic S\"\n unfolding acyclic_def\n by (blast intro: trancl_mono)\n\n\n\n\n\n subsubsection \\Wellfoundedness\\\n lemma wf_min: assumes A: \"wf R\" \"R\\{}\" \"!!m. m\\Domain R - Range R \\ P\" shows P proof -\n have H: \"!!x. wf R \\ \\y. (x,y)\\R \\ x\\Domain R - Range R \\ (\\m. m\\Domain R - Range R)\"\n by (erule_tac wf_induct_rule[where P=\"\\x. \\y. (x,y)\\R \\ x\\Domain R - Range R \\ (\\m. m\\Domain R - Range R)\"]) auto\n from A(2) obtain x y where \"(x,y)\\R\" by auto\n with A(1,3) H show ?thesis by blast\n qed\n\n lemma finite_wf_eq_wf_converse: \"finite R \\ wf (R\\) \\ wf R\"\n by (metis acyclic_converse finite_acyclic_wf finite_acyclic_wf_converse wf_acyclic)\n\n \n\n \\ \\Useful lemma to show well-foundedness of some process approaching a finite upper bound\\\n lemma wf_bounded_supset: \"finite S \\ wf {(Q',Q). Q'\\Q \\ Q'\\ S}\"\n proof -\n assume [simp]: \"finite S\"\n hence [simp]: \"!!x. finite (S-x)\" by auto\n have \"{(Q',Q). Q\\Q' \\ Q'\\ S} \\ inv_image ({(s'::nat,s). s'Q. card (S-Q))\"\n proof (intro subsetI, case_tac x, simp)\n fix a b\n assume A: \"b\\a \\ a\\S\"\n hence \"S-a \\ S-b\" by blast\n thus \"card (S-a) < card (S-b)\" by (auto simp add: psubset_card_mono)\n qed\n moreover have \"wf ({(s'::nat,s). s' (fst a, fst b)\\r \\ \\ (a,b)\\r<*lex*>s\"\n apply (cases a, cases b)\n apply auto\n done\n\n lemma lex_prod_sndI: \"\\ fst a = fst b; (snd a, snd b)\\s \\ \\ (a,b)\\r<*lex*>s\"\n apply (cases a, cases b)\n apply auto\n done\n\n lemma wf_no_path: \"Domain R \\ Range R = {} \\ wf R\"\n apply (rule wf_no_loop)\n by simp\n\ntext \\Extend a wf-relation by a break-condition\\\ndefinition \"brk_rel R \\\n {((False,x),(False,y)) | x y. (x,y)\\R}\n \\ {((True,x),(False,y)) | x y. True}\"\n\nlemma brk_rel_wf[simp,intro!]:\n assumes WF[simp]: \"wf R\"\n shows \"wf (brk_rel R)\"\nproof -\n have \"wf {((False,x),(False,y)) | x y. (x,y)\\R}\"\n proof -\n have \"{((False,x),(False,y)) | x y. (x,y)\\R} \\ inv_image R snd\"\n by auto\n from wf_subset[OF wf_inv_image[OF WF] this] show ?thesis .\n qed\n moreover have \"wf {((True,x),(False,y)) | x y. True}\"\n by (rule wf_no_path) auto\n ultimately show ?thesis\n unfolding brk_rel_def\n apply (subst Un_commute)\n by (blast intro: wf_Un)\nqed\n\n\nsubsubsection \\Restrict Relation\\\ndefinition rel_restrict :: \"('a \\ 'a) set \\ 'a set \\ ('a \\ 'a) set\"\nwhere\n \"rel_restrict R A \\ {(v,w). (v,w) \\ R \\ v \\ A \\ w \\ A}\"\n\nlemma rel_restrict_alt_def:\n \"rel_restrict R A = R \\ (-A) \\ (-A)\"\nunfolding rel_restrict_def\nby auto\n\nlemma rel_restrict_empty[simp]:\n \"rel_restrict R {} = R\"\nby (simp add: rel_restrict_def)\n\nlemma rel_restrict_notR:\n assumes \"(x,y) \\ rel_restrict A R\"\n shows \"x \\ R\" and \"y \\ R\"\nusing assms\nunfolding rel_restrict_def\nby auto\n\nlemma rel_restrict_sub:\n \"rel_restrict R A \\ R\"\nunfolding rel_restrict_def\nby auto\n\nlemma rel_restrict_Int_empty:\n \"A \\ Field R = {} \\ rel_restrict R A = R\"\nunfolding rel_restrict_def Field_def\nby auto\n\nlemma Domain_rel_restrict:\n \"Domain (rel_restrict R A) \\ Domain R - A\"\nunfolding rel_restrict_def\nby auto\n\nlemma Range_rel_restrict:\n \"Range (rel_restrict R A) \\ Range R - A\"\nunfolding rel_restrict_def\nby auto\n\nlemma Field_rel_restrict:\n \"Field (rel_restrict R A) \\ Field R - A\"\nunfolding rel_restrict_def Field_def\nby auto\n\nlemma rel_restrict_compl:\n \"rel_restrict R A \\ rel_restrict R (-A) = {}\"\nunfolding rel_restrict_def\nby auto\n\nlemma finite_rel_restrict:\n \"finite R \\ finite (rel_restrict R A)\"\nby (metis finite_subset rel_restrict_sub)\n\nlemma R_subset_Field: \"R \\ Field R \\ Field R\"\n unfolding Field_def\n by auto\n\nlemma homo_rel_restrict_mono:\n \"R \\ B \\ B \\ rel_restrict R A \\ (B - A) \\ (B - A)\"\nproof -\n assume A: \"R \\ B \\ B\"\n hence \"Field R \\ B\" unfolding Field_def by auto\n with Field_rel_restrict have \"Field (rel_restrict R A) \\ B - A\"\n by (metis Diff_mono order_refl order_trans)\n with R_subset_Field show ?thesis by blast\nqed\n\nlemma rel_restrict_union:\n \"rel_restrict R (A \\ B) = rel_restrict (rel_restrict R A) B\"\nunfolding rel_restrict_def\nby auto\n\nlemma rel_restrictI:\n \"x \\ R \\ y \\ R \\ (x,y) \\ E \\ (x,y) \\ rel_restrict E R\"\nunfolding rel_restrict_def\nby auto\n\nlemma rel_restrict_lift:\n \"(x,y) \\ rel_restrict E R \\ (x,y) \\ E\"\nunfolding rel_restrict_def\nby simp\n\nlemma rel_restrict_trancl_mem:\n \"(a,b) \\ (rel_restrict A R)\\<^sup>+ \\ (a,b) \\ rel_restrict (A\\<^sup>+) R\"\nby (induction rule: trancl_induct) (auto simp add: rel_restrict_def)\n\nlemma rel_restrict_trancl_sub:\n \"(rel_restrict A R)\\<^sup>+ \\ rel_restrict (A\\<^sup>+) R\"\nby (metis subrelI rel_restrict_trancl_mem)\n\nlemma rel_restrict_mono:\n \"A \\ B \\ rel_restrict A R \\ rel_restrict B R\"\nunfolding rel_restrict_def by auto\n\nlemma rel_restrict_mono2:\n \"R \\ S \\ rel_restrict A S \\ rel_restrict A R\"\nunfolding rel_restrict_def by auto\n\n\n\n\nlemma finite_reachable_restrictedI:\n assumes F: \"finite Q\"\n assumes I: \"I\\Q\"\n assumes R: \"Range E \\ Q\"\n shows \"finite (E\\<^sup>*``I)\"\nproof -\n from I R have \"E\\<^sup>*``I \\ Q\"\n by (force elim: rtrancl.cases)\n also note F\n finally (finite_subset) show ?thesis .\nqed\n\ncontext begin\n private lemma rtrancl_restrictI_aux:\n assumes \"(u,v)\\(E-UNIV\\R)\\<^sup>*\"\n assumes \"u\\R\"\n shows \"(u,v)\\(rel_restrict E R)\\<^sup>* \\ v\\R\"\n using assms\n by (induction) (auto simp: rel_restrict_def intro: rtrancl.intros)\n\n corollary rtrancl_restrictI:\n assumes \"(u,v)\\(E-UNIV\\R)\\<^sup>*\"\n assumes \"u\\R\"\n shows \"(u,v)\\(rel_restrict E R)\\<^sup>*\"\n using rtrancl_restrictI_aux[OF assms] ..\nend\n\nlemma E_closed_restr_reach_cases:\n assumes P: \"(u,v)\\E\\<^sup>*\"\n assumes CL: \"E``R \\ R\"\n obtains \"v\\R\" | \"u\\R\" \"(u,v)\\(rel_restrict E R)\\<^sup>*\"\n using P\nproof (cases rule: rtrancl_last_visit[where S=R])\n case no_visit\n show ?thesis proof (cases \"u\\R\")\n case True with P have \"v\\R\"\n using rtrancl_reachable_induct[OF _ CL, where I=\"{u}\"]\n by auto\n thus ?thesis ..\n next\n case False with no_visit have \"(u,v)\\(rel_restrict E R)\\<^sup>*\"\n by (rule rtrancl_restrictI)\n with False show ?thesis ..\n qed\nnext\n case (last_visit_point x)\n from \\(x, v) \\ (E - UNIV \\ R)\\<^sup>*\\ have \"(x,v)\\E\\<^sup>*\"\n by (rule rtrancl_mono_mp[rotated]) auto\n with \\x\\R\\ have \"v\\R\"\n using rtrancl_reachable_induct[OF _ CL, where I=\"{x}\"]\n by auto\n thus ?thesis ..\nqed\n\nlemma rel_restrict_trancl_notR:\n assumes \"(v,w) \\ (rel_restrict E R)\\<^sup>+\"\n shows \"v \\ R\" and \"w \\ R\"\n using assms\n by (metis rel_restrict_trancl_mem rel_restrict_notR)+\n\nlemma rel_restrict_tranclI:\n assumes \"(x,y) \\ E\\<^sup>+\"\n and \"x \\ R\" \"y \\ R\"\n and \"E `` R \\ R\"\n shows \"(x,y) \\ (rel_restrict E R)\\<^sup>+\"\n using assms\n proof (induct)\n case base thus ?case by (metis r_into_trancl rel_restrictI)\n next\n case (step y z) hence \"y \\ R\" by auto\n with step show ?case by (metis trancl_into_trancl rel_restrictI)\n qed\n\n\nsubsubsection \\Single-Valued Relations\\\nlemma single_valued_inter1: \"single_valued R \\ single_valued (R\\S)\"\n by (auto intro: single_valuedI dest: single_valuedD)\n\n\n\nlemma single_valued_below_Id: \"R\\Id \\ single_valued R\"\n by (auto intro: single_valuedI)\n \n\nsubsubsection \\Bijective Relations\\\ndefinition \"bijective R \\\n (\\x y z. (x,y)\\R \\ (x,z)\\R \\ y=z) \\\n (\\x y z. (x,z)\\R \\ (y,z)\\R \\ x=y)\"\n\nlemma bijective_alt: \"bijective R \\ single_valued R \\ single_valued (R\\)\"\n unfolding bijective_def single_valued_def by blast\n\nlemma bijective_Id[simp, intro!]: \"bijective Id\"\n by (auto simp: bijective_def)\n\nlemma bijective_Empty[simp, intro!]: \"bijective {}\"\n by (auto simp: bijective_def)\n\nsubsubsection \\Miscellaneous\\\n\n lemma pair_vimage_is_Image[simp]: \"(Pair u -` E) = E``{u}\"\n by auto\n\nlemma fst_in_Field: \"fst ` R \\ Field R\"\n by (simp add: Field_def fst_eq_Domain)\n\nlemma snd_in_Field: \"snd ` R \\ Field R\"\n by (simp add: Field_def snd_eq_Range)\n\nlemma ran_map_of:\n \"ran (map_of xs) \\ snd ` set (xs)\"\nby (induct xs) (auto simp add: ran_def)\n\nlemma Image_subset_snd_image:\n \"A `` B \\ snd ` A\"\nunfolding Image_def image_def\nby force\n\nlemma finite_Image_subset:\n \"finite (A `` B) \\ C \\ A \\ finite (C `` B)\"\nby (metis Image_mono order_refl rev_finite_subset)\n\nlemma finite_Field_eq_finite[simp]: \"finite (Field R) \\ finite R\"\n by (metis finite_cartesian_product finite_subset R_subset_Field finite_Field)\n\n\n\ndefinition \"fun_of_rel R x \\ SOME y. (x,y)\\R\"\n\nlemma for_in_RI(*[intro]*): \"x\\Domain R \\ (x,fun_of_rel R x)\\R\"\n unfolding fun_of_rel_def\n by (auto intro: someI)\n\nlemma Field_not_elem:\n \"v \\ Field R \\ \\(x,y) \\ R. x \\ v \\ y \\ v\"\nunfolding Field_def by auto\n\nlemma Sigma_UNIV_cancel[simp]: \"(A \\ X - A \\ UNIV) = {}\" by auto\n\nlemma same_fst_trancl[simp]: \"(same_fst P R)\\<^sup>+ = same_fst P (\\x. (R x)\\<^sup>+)\"\nproof -\n {\n fix x y\n assume \"(x,y)\\(same_fst P R)\\<^sup>+\"\n hence \"(x,y)\\same_fst P (\\x. (R x)\\<^sup>+)\"\n by induction (auto simp: same_fst_def)\n } moreover {\n fix f f' x y\n assume \"((f,x),(f',y))\\same_fst P (\\x. (R x)\\<^sup>+)\"\n hence [simp]: \"f'=f\" \"P f\" and 1: \"(x,y)\\(R f)\\<^sup>+\" by (auto simp: same_fst_def)\n from 1 have \"((f,x),(f',y))\\(same_fst P R)\\<^sup>+\"\n apply induction\n subgoal by (rule r_into_trancl) auto\n subgoal by (erule trancl_into_trancl) auto\n done\n } ultimately show ?thesis by auto\nqed \n \n\nsubsection \\\\option\\ Datatype\\\n\n\n\nlemma not_Some_eq2[simp]: \"(\\x y. v \\ Some (x,y)) = (v = None)\"\n by (cases v) auto\n\n\nsubsection \"Maps\"\n primrec the_default where\n \"the_default _ (Some x) = x\"\n | \"the_default x None = x\"\n\n declare map_add_dom_app_simps[simp] \n declare map_add_upd_left[simp] \n\n lemma ran_add[simp]: \"dom f \\ dom g = {} \\ ran (f++g) = ran f \\ ran g\" by (fastforce simp add: ran_def map_add_def split: option.split_asm option.split)\n\n lemma nempty_dom: \"\\e\\Map.empty; !!m. m\\dom e \\ P \\ \\ P\"\n by (subgoal_tac \"dom e \\ {}\") (blast, auto)\n\n\n\n lemma le_map_dom_mono: \"m\\m' \\ dom m \\ dom m'\"\n apply (safe)\n apply (drule_tac x=x in le_funD)\n apply simp\n apply (erule le_some_optE)\n apply simp\n done\n\n lemma map_add_first_le: fixes m::\"'a\\('b::order)\" shows \"\\ m\\m' \\ \\ m++n \\ m'++n\"\n apply (rule le_funI)\n apply (auto simp add: map_add_def split: option.split elim: le_funE)\n done\n\n lemma map_add_distinct_le: shows \"\\ m\\m'; n\\n'; dom m' \\ dom n' = {} \\ \\ m++n \\ m'++n'\"\n apply (rule le_funI)\n apply (auto simp add: map_add_def split: option.split)\n apply (fastforce elim: le_funE)\n apply (drule le_map_dom_mono)\n apply (drule le_map_dom_mono)\n apply (case_tac \"m x\")\n apply simp\n apply (force)\n apply (fastforce dest!: le_map_dom_mono)\n apply (erule le_funE)\n apply (erule_tac x=x in le_funE)\n apply simp\n done\n\n lemma map_add_left_comm: assumes A: \"dom A \\ dom B = {}\" shows \"A ++ (B ++ C) = B ++ (A ++ C)\"\n proof -\n have \"A ++ (B ++ C) = (A++B)++C\" by simp\n also have \"\\ = (B++A)++C\" by (simp add: map_add_comm[OF A])\n also have \"\\ = B++(A++C)\" by simp\n finally show ?thesis .\n qed\n lemmas map_add_ac = map_add_assoc map_add_comm map_add_left_comm\n\n lemma le_map_restrict[simp]: fixes m :: \"'a \\ ('b::order)\" shows \"m |` X \\ m\"\n by (rule le_funI) (simp add: restrict_map_def)\n\nlemma map_of_distinct_upd:\n \"x \\ set (map fst xs) \\ [x \\ y] ++ map_of xs = (map_of xs) (x \\ y)\"\n by (induct xs) (auto simp add: fun_upd_twist)\n\nlemma map_of_distinct_upd2:\n assumes \"x \\ set(map fst xs)\"\n \"x \\ set (map fst ys)\"\n shows \"map_of (xs @ (x,y) # ys) = (map_of (xs @ ys))(x \\ y)\"\n apply(insert assms)\n apply(induct xs)\n apply (auto intro: ext)\n done\n\nlemma map_of_distinct_upd3:\n assumes \"x \\ set(map fst xs)\"\n \"x \\ set (map fst ys)\"\n shows \"map_of (xs @ (x,y) # ys) = (map_of (xs @ (x,y') # ys))(x \\ y)\"\n apply(insert assms)\n apply(induct xs)\n apply (auto intro: ext)\n done\n\nlemma map_of_distinct_upd4:\n assumes \"x \\ set(map fst xs)\"\n \"x \\ set (map fst ys)\"\n shows \"map_of (xs @ ys) = (map_of (xs @ (x,y) # ys))(x := None)\"\n using assms by (induct xs) (auto simp: map_of_eq_None_iff)\n\nlemma map_of_distinct_lookup:\n assumes \"x \\ set(map fst xs)\"\n \"x \\ set (map fst ys)\"\n shows \"map_of (xs @ (x,y) # ys) x = Some y\"\nproof -\n have \"map_of (xs @ (x,y) # ys) = (map_of (xs @ ys)) (x \\ y)\"\n using assms map_of_distinct_upd2 by simp\n thus ?thesis\n by simp\nqed\n\nlemma ran_distinct:\n assumes dist: \"distinct (map fst al)\"\n shows \"ran (map_of al) = snd ` set al\"\nusing assms proof (induct al)\n case Nil then show ?case by simp\nnext\n case (Cons kv al)\n then have \"ran (map_of al) = snd ` set al\" by simp\n moreover from Cons.prems have \"map_of al (fst kv) = None\"\n by (simp add: map_of_eq_None_iff)\n ultimately show ?case by (simp only: map_of.simps ran_map_upd) simp\nqed\n\nlemma ran_is_image:\n \"ran M = (the \\ M) ` (dom M)\"\nunfolding ran_def dom_def image_def\nby auto\n\nlemma map_card_eq_iff:\n assumes finite: \"finite (dom M)\"\n and card_eq: \"card (dom M) = card (ran M)\"\n and indom: \"x \\ dom M\"\n shows \"(M x = M y) \\ (x = y)\"\nproof -\n from ran_is_image finite card_eq have *: \"inj_on (the \\ M) (dom M)\" using eq_card_imp_inj_on by metis\n thus ?thesis\n proof (cases \"y \\ dom M\")\n case False with indom show ?thesis by auto\n next\n case True with indom have \"the (M x) = the (M y) \\ (x = y)\" using inj_on_eq_iff[OF *] by auto\n thus ?thesis by auto\n qed\nqed\n\nlemma map_dom_ran_finite:\n \"finite (dom M) \\ finite (ran M)\"\nby (simp add: ran_is_image)\n\nlemma map_update_eta_repair[simp]:\n (* An update operation may get simplified, if it happens to be eta-expanded.\n This lemma tries to repair some common expressions *)\n \"dom (\\x. if x=k then Some v else m x) = insert k (dom m)\"\n \"m k = None \\ ran (\\x. if x=k then Some v else m x) = insert v (ran m)\"\n apply auto []\n apply (force simp: ran_def)\n done\n\nlemma map_leI[intro?]: \"\\\\x v. m1 x = Some v \\ m2 x = Some v\\ \\ m1\\\\<^sub>mm2\"\n unfolding map_le_def by force\nlemma map_leD: \"m1\\\\<^sub>mm2 \\ m1 k = Some v \\ m2 k = Some v\"\n unfolding map_le_def by force\n \nlemma map_restrict_insert_none_simp: \"m x = None \\ m|`(-insert x s) = m|`(-s)\"\n by (auto intro!: ext simp:restrict_map_def)\n\n(* TODO: Move *)\nlemma eq_f_restr_conv: \"s\\dom (f A) \\ A = f A |` (-s) \\ A \\\\<^sub>m f A \\ s = dom (f A) - dom A\"\n apply auto\n subgoal by (metis map_leI restrict_map_eq(2))\n subgoal by (metis ComplD restrict_map_eq(2))\n subgoal by (metis Compl_iff restrict_in)\n subgoal by (force simp: map_le_def restrict_map_def)\n done\n \ncorollary eq_f_restr_ss_eq: \"\\ s\\dom (f A) \\ \\ A = f A |` (-s) \\ A \\\\<^sub>m f A \\ s = dom (f A) - dom A\"\n using eq_f_restr_conv by blast\n \n \n \n subsubsection \\Simultaneous Map Update\\\n definition \"map_mmupd m K v k \\ if k\\K then Some v else m k\"\n lemma map_mmupd_empty[simp]: \"map_mmupd m {} v = m\"\n by (auto simp: map_mmupd_def)\n\n lemma mmupd_in_upd[simp]: \"k\\K \\ map_mmupd m K v k = Some v\"\n by (auto simp: map_mmupd_def)\n\n lemma mmupd_notin_upd[simp]: \"k\\K \\ map_mmupd m K v k = m k\"\n by (auto simp: map_mmupd_def)\n\n lemma map_mmupdE:\n assumes \"map_mmupd m K v k = Some x\"\n obtains \"k\\K\" \"m k = Some x\"\n | \"k\\K\" \"x=v\"\n using assms by (auto simp: map_mmupd_def split: if_split_asm) \n\n lemma dom_mmupd[simp]: \"dom (map_mmupd m K v) = dom m \\ K\" \n by (auto simp: map_mmupd_def split: if_split_asm) \n\n lemma le_map_mmupd_not_dom[simp, intro!]: \"m \\\\<^sub>m map_mmupd m (K-dom m) v\" \n by (auto simp: map_le_def)\n\n lemma map_mmupd_update_less: \"K\\K' \\ map_mmupd m (K - dom m) v \\\\<^sub>m map_mmupd m (K'-dom m) v\"\n by (auto simp: map_le_def map_mmupd_def)\n\n \n\nsubsection\\Connection between Maps and Sets of Key-Value Pairs\\\n\ndefinition map_to_set where\n \"map_to_set m = {(k, v) . m k = Some v}\"\n\ndefinition set_to_map where\n \"set_to_map S k = Eps_Opt (\\v. (k, v) \\ S)\"\n\nlemma set_to_map_simp :\nassumes inj_on_fst: \"inj_on fst S\"\nshows \"(set_to_map S k = Some v) \\ (k, v) \\ S\"\nproof (cases \"\\v. (k, v) \\ S\")\n case True\n note kv_ex = this\n then obtain v' where kv'_in: \"(k, v') \\ S\" by blast\n\n with inj_on_fst have kv''_in: \"\\v''. (k, v'') \\ S \\ v' = v''\"\n unfolding inj_on_def Ball_def\n by auto\n\n show ?thesis\n unfolding set_to_map_def\n by (simp add: kv_ex kv''_in)\nnext\n case False\n hence kv''_nin: \"\\v''. (k, v'') \\ S\" by simp\n thus ?thesis\n by (simp add: set_to_map_def)\nqed\n\nlemma inj_on_fst_map_to_set :\n \"inj_on fst (map_to_set m)\"\nunfolding map_to_set_def inj_on_def by simp\n\nlemma map_to_set_inverse :\n \"set_to_map (map_to_set m) = m\"\nproof\n fix k\n show \"set_to_map (map_to_set m) k = m k\"\n proof (cases \"m k\")\n case None note mk_eq = this\n hence \"\\v. (k, v) \\ map_to_set m\"\n unfolding map_to_set_def by simp\n with set_to_map_simp [OF inj_on_fst_map_to_set, of m k]\n show ?thesis unfolding mk_eq by auto\n next\n case (Some v) note mk_eq = this\n hence \"(k, v) \\ map_to_set m\"\n unfolding map_to_set_def by simp\n with set_to_map_simp [OF inj_on_fst_map_to_set, of m k v]\n show ?thesis unfolding mk_eq by auto\n qed\nqed\n\nlemma set_to_map_inverse :\nassumes inj_on_fst_S: \"inj_on fst S\"\nshows \"map_to_set (set_to_map S) = S\"\nproof (rule set_eqI)\n fix kv\n from set_to_map_simp [OF inj_on_fst_S, of \"fst kv\" \"snd kv\"]\n show \"(kv \\ map_to_set (set_to_map S)) = (kv \\ S)\"\n unfolding map_to_set_def\n by auto\nqed\n\nlemma map_to_set_empty[simp]: \"map_to_set Map.empty = {}\"\n unfolding map_to_set_def by simp\n\n\n\nlemma map_to_set_empty_iff: \"map_to_set m = {} \\ m = Map.empty\"\n \"{} = map_to_set m \\ m = Map.empty\"\n unfolding map_to_set_def by auto\n\nlemma set_to_map_empty_iff: \"set_to_map S = Map.empty \\ S = {}\" (is ?T1)\n \"Map.empty = set_to_map S \\ S = {}\" (is ?T2)\nproof -\n show T1: ?T1\n apply (simp only: set_eq_iff)\n apply (simp only: fun_eq_iff)\n apply (simp add: set_to_map_def)\n apply auto\n done\n from T1 show ?T2 by auto\nqed\n\nlemma map_to_set_upd[simp]: \"map_to_set (m (k \\ v)) = insert (k, v) (map_to_set m - {(k, v') |v'. True})\"\n unfolding map_to_set_def\n apply (simp add: set_eq_iff)\n apply metis\ndone\n\nlemma set_to_map_insert:\nassumes k_nin: \"fst kv \\ fst ` S\"\nshows \"set_to_map (insert kv S) = (set_to_map S) (fst kv \\ snd kv)\"\nproof\n fix k'\n obtain k v where kv_eq[simp]: \"kv = (k, v)\" by (rule prod.exhaust)\n\n from k_nin have k_nin': \"\\v'. (k, v') \\ S\"\n by (auto simp add: image_iff Ball_def)\n\n show \"set_to_map (insert kv S) k' = (set_to_map S(fst kv \\ snd kv)) k'\"\n by (simp add: set_to_map_def k_nin')\nqed\n\nlemma map_to_set_dom :\n \"dom m = fst ` (map_to_set m)\"\nunfolding dom_def map_to_set_def\nby (auto simp add: image_iff)\n\nlemma map_to_set_ran :\n \"ran m = snd ` (map_to_set m)\"\nunfolding ran_def map_to_set_def\nby (auto simp add: image_iff)\n\nlemma set_to_map_dom :\n \"dom (set_to_map S) = fst ` S\"\nunfolding set_to_map_def[abs_def] dom_def\nby (auto simp add: image_iff Bex_def)\n\nlemma set_to_map_ran :\n \"ran (set_to_map S) \\ snd ` S\"\nunfolding set_to_map_def[abs_def] ran_def subset_iff\nby (auto simp add: image_iff Bex_def)\n (metis Eps_Opt_eq_Some)\n\nlemma finite_map_to_set:\n\"finite (map_to_set m) = finite (dom m)\"\nunfolding map_to_set_def map_to_set_dom\n apply (intro iffI finite_imageI)\n apply assumption\n apply (rule finite_imageD[of fst])\n apply assumption\n apply (simp add: inj_on_def)\ndone\n\nlemma card_map_to_set :\n \"card (map_to_set m) = card (dom m)\"\nunfolding map_to_set_def map_to_set_dom\n apply (rule card_image[symmetric])\n apply (simp add: inj_on_def)\ndone\n\nlemma map_of_map_to_set :\n\"distinct (map fst l) \\\n map_of l = m \\ set l = map_to_set m\"\nproof (induct l arbitrary: m)\n case Nil thus ?case by (simp add: map_to_set_empty_iff) blast\nnext\n case (Cons kv l m)\n obtain k v where kv_eq[simp]: \"kv = (k, v)\" by (rule prod.exhaust)\n\n from Cons(2) have dist_l: \"distinct (map fst l)\" and kv'_nin: \"\\v'. (k, v') \\ set l\"\n by (auto simp add: image_iff)\n note ind_hyp = Cons(1)[OF dist_l]\n\n from kv'_nin have l_eq: \"set (kv # l) = map_to_set m \\ (set l = map_to_set (m (k := None))) \\ m k = Some v\"\n apply (simp add: map_to_set_def restrict_map_def set_eq_iff)\n apply (auto)\n apply (metis)\n apply (metis option.inject)\n done\n\n from kv'_nin have m_eq: \"map_of (kv # l) = m \\ map_of l = (m (k := None)) \\ m k = Some v\"\n apply (simp add: fun_eq_iff restrict_map_def map_of_eq_None_iff image_iff Ball_def)\n apply metis\n done\n\n show ?case\n unfolding m_eq l_eq\n using ind_hyp[of \"m (k := None)\"]\n by metis\nqed\n\nlemma map_to_set_map_of :\n\"distinct (map fst l) \\ map_to_set (map_of l) = set l\"\nby (metis map_of_map_to_set)\n\nsubsubsection \\Mapping empty set to None\\\ndefinition \"dflt_None_set S \\ if S={} then None else Some S\"\n\nlemma the_dflt_None_empty[simp]: \"dflt_None_set {} = None\"\n unfolding dflt_None_set_def by simp\n\nlemma the_dflt_None_nonempty[simp]: \"S\\{} \\ dflt_None_set S = Some S\"\n unfolding dflt_None_set_def by simp\n\nlemma the_dflt_None_set[simp]: \"the_default {} (dflt_None_set x) = x\"\n unfolding dflt_None_set_def by auto\n\nsubsection \\Orderings\\\n\n \n \nlemma (in order) min_arg_le[simp]:\n \"n \\ min m n \\ min m n = n\"\n \"m \\ min m n \\ min m n = m\"\n by (auto simp: min_def)\n\nlemma (in linorder) min_arg_not_ge[simp]:\n \"\\ min m n < m \\ min m n = m\"\n \"\\ min m n < n \\ min m n = n\"\n by (auto simp: min_def)\n\nlemma (in linorder) min_eq_arg[simp]:\n \"min m n = m \\ m\\n\"\n \"min m n = n \\ n\\m\"\n by (auto simp: min_def)\n\nlemma min_simps[simp]:\n \"a<(b::'a::order) \\ min a b = a\"\n \"b<(a::'a::order) \\ min a b = b\"\n by (auto simp add: min_def dest: less_imp_le)\n\nlemma (in -) min_less_self_conv[simp]: \n \"min a b < a \\ b < (a::_::linorder)\" \n \"min a b < b \\ a < (b::_::linorder)\" \n by (auto simp: min_def)\n \nlemma ord_eq_le_eq_trans: \"\\ a=b; b\\c; c=d \\ \\ a\\d\" by auto\n\nlemma zero_comp_diff_simps[simp]: \n \"(0::'a::linordered_idom) \\ a - b \\ b \\ a\" \n \"(0::'a::linordered_idom) < a - b \\ b < a\" \n by auto\n \n\nsubsubsection \\Termination Measures\\ \ntext \\Lexicographic measure, assuming upper bound for second component\\\nlemma mlex_fst_decrI:\n fixes a a' b b' N :: nat\n assumes \"a a*N + N\" using \\b by linarith \n also have \"\\ \\ a'*N\" using \\a\n by (metis Suc_leI ab_semigroup_add_class.add.commute \n ab_semigroup_mult_class.mult.commute mult_Suc_right mult_le_mono2) \n also have \"\\ \\ a'*N + b'\" by auto\n finally show ?thesis by auto\nqed \n \n\n\nlemma mlex_bound: \n fixes a b :: nat\n assumes \"aCCPOs\\\n\ncontext ccpo\nbegin\n\nlemma ccpo_Sup_mono:\n assumes C: \"Complete_Partial_Order.chain (\\) A\"\n \"Complete_Partial_Order.chain (\\) B\"\n assumes B: \"\\x\\A. \\y\\B. x\\y\"\n shows \"Sup A \\ Sup B\"\nproof (rule ccpo_Sup_least)\n fix x\n assume \"x\\A\"\n with B obtain y where I: \"y\\B\" and L: \"x\\y\" by blast\n note L\n also from I ccpo_Sup_upper have \"y\\Sup B\" by (blast intro: C)\n finally show \"x\\Sup B\" .\nqed (rule C)\n\nlemma fixp_mono:\n assumes M: \"monotone (\\) (\\) f\" \"monotone (\\) (\\) g\"\n assumes LE: \"\\Z. f Z \\ g Z\"\n shows \"ccpo_class.fixp f \\ ccpo_class.fixp g\"\n unfolding fixp_def[abs_def]\n apply (rule ccpo_Sup_mono)\n apply (rule chain_iterates M)+\nproof rule\n fix x\n assume \"x\\ccpo_class.iterates f\"\n thus \"\\y\\ccpo_class.iterates g. x\\y\"\n proof (induct)\n case (step x)\n then obtain y where I: \"y\\ccpo_class.iterates g\" and L: \"x\\y\" by blast\n hence \"g y \\ ccpo_class.iterates g\" and \"f x \\ g y\"\n apply -\n apply (erule iterates.step)\n apply (rule order_trans)\n apply (erule monotoneD[OF M(1)])\n apply (rule LE)\n done\n thus \"\\y\\ccpo_class.iterates g. f x \\ y\" ..\n next\n case (Sup M)\n define N where \"N = {SOME y. y\\ccpo_class.iterates g \\ x\\y | x. x\\M}\"\n\n have N1: \"\\y\\N. y\\ccpo_class.iterates g \\ (\\x\\M. x\\y)\"\n unfolding N_def\n apply auto\n apply (metis (lifting) Sup.hyps(2) tfl_some)\n by (metis (lifting) Sup.hyps(2) tfl_some)\n\n have N2: \"\\x\\M. \\y\\N. x\\y\"\n unfolding N_def\n apply auto\n by (metis (lifting) Sup.hyps(2) tfl_some)\n\n have \"N \\ ccpo_class.iterates g\" using Sup\n using N1 by auto\n hence C_chain: \"Complete_Partial_Order.chain (\\) N\"\n using chain_iterates[OF M(2)]\n unfolding chain_def by auto\n\n have \"Sup N \\ ccpo_class.iterates g\" and \"Sup M \\ Sup N\"\n apply -\n apply (rule iterates.Sup[OF C_chain])\n using N1 apply blast\n apply (rule ccpo_Sup_mono)\n apply (rule Sup.hyps)\n apply (rule C_chain)\n apply (rule N2)\n done\n\n thus ?case by blast\n qed\nqed\n\nend\n\n \nsubsection \\Code\\ \ntext \\Constant for code-abort. If that gets executed, an abort-exception is raised.\\ \ndefinition [simp]: \"CODE_ABORT f = f ()\"\ndeclare [[code abort: CODE_ABORT]]\n \n \nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Automatic_Refinement/Lib/Misc.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.11757212736159103, "lm_q1q2_score": 0.05329095972301509}} {"text": "(*\n * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *)\n\ntheory WhileLoopRules\nimports \"NonDetMonadVCG\"\nbegin\n\nsection \"Well-ordered measures\"\n\n(* A version of \"measure\" that takes any wellorder, instead of\n * being fixed to \"nat\". *)\ndefinition measure' :: \"('a \\ 'b::wellorder) => ('a \\ 'a) set\"\nwhere \"measure' = (\\f. {(a, b). f a < f b})\"\n\nlemma in_measure'[simp, code_unfold]:\n \"((x,y) : measure' f) = (f x < f y)\"\n by (simp add:measure'_def)\n\nlemma wf_measure' [iff]: \"wf (measure' f)\"\n apply (clarsimp simp: measure'_def)\n apply (insert wf_inv_image [OF wellorder_class.wf, where f=f])\n apply (clarsimp simp: inv_image_def)\n done\n\nlemma wf_wellorder_measure: \"wf {(a, b). (M a :: 'a :: wellorder) < M b}\"\n apply (subgoal_tac \"wf (inv_image ({(a, b). a < b}) M)\")\n apply (clarsimp simp: inv_image_def)\n apply (rule wf_inv_image)\n apply (rule wellorder_class.wf)\n done\n\n\nsection \"whileLoop lemmas\"\n\ntext \\\n The following @{const whileLoop} definitions with additional\n invariant/variant annotations allow the user to annotate\n @{const whileLoop} terms with information that can be used\n by automated tools.\n\\\ndefinition\n \"whileLoop_inv (C :: 'a \\ 'b \\ bool) B x (I :: 'a \\ 'b \\ bool) (R :: (('a \\ 'b) \\ ('a \\ 'b)) set) \\ whileLoop C B x\"\n\ndefinition\n \"whileLoopE_inv (C :: 'a \\ 'b \\ bool) B x (I :: 'a \\ 'b \\ bool) (R :: (('a \\ 'b) \\ ('a \\ 'b)) set) \\ whileLoopE C B x\"\n\nlemma whileLoop_add_inv: \"whileLoop B C = (\\x. whileLoop_inv B C x I (measure' M))\"\n by (clarsimp simp: whileLoop_inv_def)\n\nlemma whileLoopE_add_inv: \"whileLoopE B C = (\\x. whileLoopE_inv B C x I (measure' M))\"\n by (clarsimp simp: whileLoopE_inv_def)\n\nsubsection \"Simple base rules\"\n\nlemma whileLoop_terminates_unfold:\n \"\\ whileLoop_terminates C B r s; (r', s') \\ fst (B r s); C r s \\\n \\ whileLoop_terminates C B r' s'\"\n apply (erule whileLoop_terminates.cases)\n apply simp\n apply force\n done\n\nlemma snd_whileLoop_first_step: \"\\ \\ snd (whileLoop C B r s); C r s \\ \\ \\ snd (B r s)\"\n apply (subst (asm) whileLoop_unroll)\n apply (clarsimp simp: bind_def condition_def)\n done\n\nlemma snd_whileLoopE_first_step: \"\\ \\ snd (whileLoopE C B r s); C r s \\ \\ \\ snd (B r s)\"\n apply (subgoal_tac \"\\ \\ snd (whileLoopE C B r s); C r s \\ \\ \\ snd ((lift B (Inr r)) s)\")\n apply (clarsimp simp: lift_def)\n apply (unfold whileLoopE_def)\n apply (erule snd_whileLoop_first_step)\n apply clarsimp\n done\n\nlemma snd_whileLoop_unfold:\n \"\\ \\ snd (whileLoop C B r s); C r s; (r', s') \\ fst (B r s) \\ \\ \\ snd (whileLoop C B r' s')\"\n apply (clarsimp simp: whileLoop_def)\n apply (auto simp: elim: whileLoop_results.cases whileLoop_terminates.cases\n intro: whileLoop_results.intros whileLoop_terminates.intros)\n done\n\nlemma snd_whileLoopE_unfold:\n \"\\ \\ snd (whileLoopE C B r s); (Inr r', s') \\ fst (B r s); C r s \\ \\ \\ snd (whileLoopE C B r' s')\"\n apply (clarsimp simp: whileLoopE_def)\n apply (drule snd_whileLoop_unfold)\n apply clarsimp\n apply (clarsimp simp: lift_def)\n apply assumption\n apply (clarsimp simp: lift_def)\n done\n\nlemma whileLoop_results_cong [cong]:\n assumes C: \"\\r s. C r s = C' r s\"\n and B:\"\\(r :: 'r) (s :: 's). C' r s \\ B r s = B' r s\"\n shows \"whileLoop_results C B = whileLoop_results C' B'\"\nproof -\n {\n fix x y C B C' B'\n have \"\\ (x, y) \\ whileLoop_results C B;\n \\(r :: 'r) (s :: 's). C r s = C' r s;\n \\r s. C' r s \\ B r s = B' r s \\\n \\ (x, y) \\ whileLoop_results C' B'\"\n apply (induct rule: whileLoop_results.induct)\n apply clarsimp\n apply clarsimp\n apply (rule whileLoop_results.intros, auto)[1]\n apply clarsimp\n apply (rule whileLoop_results.intros, auto)[1]\n done\n }\n\n thus ?thesis\n apply -\n apply (rule set_eqI, rule iffI)\n apply (clarsimp split: prod.splits)\n apply (clarsimp simp: C B split: prod.splits)\n apply (clarsimp split: prod.splits)\n apply (clarsimp simp: C [symmetric] B [symmetric] split: prod.splits)\n done\nqed\n\nlemma whileLoop_terminates_cong [cong]:\n assumes r: \"r = r'\"\n and s: \"s = s'\"\n and C: \"\\r s. C r s = C' r s\"\n and B: \"\\r s. C' r s \\ B r s = B' r s\"\n shows \"whileLoop_terminates C B r s = whileLoop_terminates C' B' r' s'\"\nproof (rule iffI)\n assume T: \"whileLoop_terminates C B r s\"\n show \"whileLoop_terminates C' B' r' s'\"\n apply (insert T r s)\n apply (induct arbitrary: r' s' rule: whileLoop_terminates.induct)\n apply (clarsimp simp: C)\n apply (erule whileLoop_terminates.intros)\n apply (clarsimp simp: C B split: prod.splits)\n apply (rule whileLoop_terminates.intros, assumption)\n apply (clarsimp simp: C B split: prod.splits)\n done\nnext\n assume T: \"whileLoop_terminates C' B' r' s'\"\n show \"whileLoop_terminates C B r s\"\n apply (insert T r s)\n apply (induct arbitrary: r s rule: whileLoop_terminates.induct)\n apply (rule whileLoop_terminates.intros)\n apply (clarsimp simp: C)\n apply (rule whileLoop_terminates.intros, fastforce simp: C)\n apply (clarsimp simp: C B split: prod.splits)\n done\nqed\n\nlemma whileLoop_cong [cong]:\n \"\\ \\r s. C r s = C' r s; \\r s. C r s \\ B r s = B' r s \\ \\ whileLoop C B = whileLoop C' B'\"\n apply (rule ext, clarsimp simp: whileLoop_def)\n done\n\nlemma whileLoopE_cong [cong]:\n \"\\ \\r s. C r s = C' r s ; \\r s. C r s \\ B r s = B' r s \\\n \\ whileLoopE C B = whileLoopE C' B'\"\n apply (clarsimp simp: whileLoopE_def)\n apply (rule whileLoop_cong [THEN arg_cong])\n apply (clarsimp split: sum.splits)\n apply (clarsimp split: sum.splits)\n apply (clarsimp simp: lift_def throwError_def split: sum.splits)\n done\n\nlemma whileLoop_terminates_wf:\n \"wf {(x, y). C (fst y) (snd y) \\ x \\ fst (B (fst y) (snd y)) \\ whileLoop_terminates C B (fst y) (snd y)}\"\n apply (rule wfI [where A=\"UNIV\" and B=\"{(r, s). whileLoop_terminates C B r s}\"])\n apply clarsimp\n apply clarsimp\n apply (erule whileLoop_terminates.induct)\n apply blast\n apply blast\n done\n\nsubsection \"Basic induction helper lemmas\"\n\nlemma whileLoop_results_induct_lemma1:\n \"\\ (a, b) \\ whileLoop_results C B; b = Some (x, y) \\ \\ \\ C x y\"\n apply (induct rule: whileLoop_results.induct, auto)\n done\n\nlemma whileLoop_results_induct_lemma1':\n \"\\ (a, b) \\ whileLoop_results C B; a \\ b \\ \\ \\x. a = Some x \\ C (fst x) (snd x)\"\n apply (induct rule: whileLoop_results.induct, auto)\n done\n\nlemma whileLoop_results_induct_lemma2 [consumes 1]:\n \"\\ (a, b) \\ whileLoop_results C B;\n a = Some (x :: 'a \\ 'b); b = Some y;\n P x; \\s t. \\ P s; t \\ fst (B (fst s) (snd s)); C (fst s) (snd s) \\ \\ P t \\ \\ P y\"\n apply (induct arbitrary: x y rule: whileLoop_results.induct)\n apply simp\n apply simp\n apply atomize\n apply fastforce\n done\n\nlemma whileLoop_results_induct_lemma3 [consumes 1]:\n assumes result: \"(Some (r, s), Some (r', s')) \\ whileLoop_results C B\"\n and inv_start: \"I r s\"\n and inv_step: \"\\r s r' s'. \\ I r s; C r s; (r', s') \\ fst (B r s) \\ \\ I r' s'\"\n shows \"I r' s'\"\n apply (rule whileLoop_results_induct_lemma2 [where P=\"case_prod I\" and y=\"(r', s')\" and x=\"(r, s)\",\n simplified case_prod_unfold, simplified])\n apply (rule result)\n apply simp\n apply simp\n apply fact\n apply (erule (1) inv_step)\n apply clarsimp\n done\n\nsubsection \"Inductive reasoning about whileLoop results\"\n\nlemma in_whileLoop_induct [consumes 1]:\n assumes in_whileLoop: \"(r', s') \\ fst (whileLoop C B r s)\"\n and init_I: \"\\ r s. \\ C r s \\ I r s r s\"\n and step:\n \"\\r s r' s' r'' s''.\n \\ C r s; (r', s') \\ fst (B r s);\n (r'', s'') \\ fst (whileLoop C B r' s');\n I r' s' r'' s'' \\ \\ I r s r'' s''\"\n shows \"I r s r' s'\"\nproof cases\n assume \"C r s\"\n\n {\n obtain a where a_def: \"a = Some (r, s)\"\n by blast\n obtain b where b_def: \"b = Some (r', s')\"\n by blast\n\n have \"\\ (a, b) \\ whileLoop_results C B; \\x. a = Some x; \\x. b = Some x \\\n \\ I (fst (the a)) (snd (the a)) (fst (the b)) (snd (the b))\"\n apply (induct rule: whileLoop_results.induct)\n apply (auto simp: init_I whileLoop_def intro: step)\n done\n\n hence \"(Some (r, s), Some (r', s')) \\ whileLoop_results C B\n \\ I r s r' s'\"\n by (clarsimp simp: a_def b_def)\n }\n\n thus ?thesis\n using in_whileLoop\n by (clarsimp simp: whileLoop_def)\nnext\n assume \"\\ C r s\"\n\n hence \"r' = r \\ s' = s\"\n using in_whileLoop\n by (subst (asm) whileLoop_unroll,\n clarsimp simp: condition_def return_def)\n\n thus ?thesis\n by (metis init_I \\\\ C r s\\)\nqed\n\nlemma snd_whileLoop_induct [consumes 1]:\n assumes induct: \"snd (whileLoop C B r s)\"\n and terminates: \"\\ whileLoop_terminates C B r s \\ I r s\"\n and init: \"\\ r s. \\ snd (B r s); C r s \\ \\ I r s\"\n and step: \"\\r s r' s' r'' s''.\n \\ C r s; (r', s') \\ fst (B r s);\n snd (whileLoop C B r' s');\n I r' s' \\ \\ I r s\"\n shows \"I r s\"\n apply (insert init induct)\n apply atomize\n apply (unfold whileLoop_def)\n apply clarsimp\n apply (erule disjE)\n apply (erule rev_mp)\n apply (induct \"Some (r, s)\" \"None :: ('a \\ 'b) option\"\n arbitrary: r s rule: whileLoop_results.induct)\n apply clarsimp\n apply clarsimp\n apply (erule (1) step)\n apply (clarsimp simp: whileLoop_def)\n apply clarsimp\n apply (metis terminates)\n done\n\nlemma whileLoop_terminatesE_induct [consumes 1]:\n assumes induct: \"whileLoop_terminatesE C B r s\"\n and init: \"\\r s. \\ C r s \\ I r s\"\n and step: \"\\r s r' s'. \\ C r s; \\(v', s') \\ fst (B r s). case v' of Inl _ \\ True | Inr r' \\ I r' s' \\ \\ I r s\"\n shows \"I r s\"\n apply (insert induct)\n apply (clarsimp simp: whileLoop_terminatesE_def)\n apply (subgoal_tac \"(\\r s. case (Inr r) of Inl x \\ True | Inr x \\ I x s) r s\")\n apply simp\n apply (induction rule: whileLoop_terminates.induct)\n apply (case_tac r)\n apply simp\n apply clarsimp\n apply (erule init)\n apply (clarsimp split: sum.splits)\n apply (rule step)\n apply simp\n apply (clarsimp simp: lift_def split: sum.splits)\n apply force\n done\n\nsubsection \"Direct reasoning about whileLoop components\"\n\nlemma fst_whileLoop_cond_false:\n assumes loop_result: \"(r', s') \\ fst (whileLoop C B r s)\"\n shows \"\\ C r' s'\"\n using loop_result\n by (rule in_whileLoop_induct, auto)\n\nlemma snd_whileLoop:\n assumes init_I: \"I r s\"\n and cond_I: \"C r s\"\n and non_term: \"\\r. \\ \\s. I r s \\ C r s \\ \\ snd (B r s) \\\n B r \\\\ \\r' s'. C r' s' \\ I r' s' \\\"\n shows \"snd (whileLoop C B r s)\"\n apply (clarsimp simp: whileLoop_def)\n apply (rotate_tac)\n apply (insert init_I cond_I)\n apply (induct rule: whileLoop_terminates.induct)\n apply clarsimp\n apply (cut_tac r=r in non_term)\n apply (clarsimp simp: exs_valid_def)\n apply (subst (asm) (2) whileLoop_results.simps)\n apply clarsimp\n apply (insert whileLoop_results.simps)\n apply fast\n done\n\nlemma whileLoop_terminates_inv:\n assumes init_I: \"I r s\"\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\\"\n assumes wf_R: \"wf R\"\n shows \"whileLoop_terminates C B r s\"\n apply (insert init_I)\n using wf_R\n apply (induction \"(r, s)\" arbitrary: r s)\n apply atomize\n apply (subst whileLoop_terminates_simps)\n apply clarsimp\n apply (erule use_valid)\n apply (rule hoare_strengthen_post, rule inv)\n apply force\n apply force\n done\n\nlemma not_snd_whileLoop:\n assumes init_I: \"I r s\"\n and inv_holds: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\!\"\n and wf_R: \"wf R\"\n shows \"\\ snd (whileLoop C B r s)\"\nproof -\n {\n fix x y\n have \"\\ (x, y) \\ whileLoop_results C B; x = Some (r, s); y = None \\ \\ False\"\n apply (insert init_I)\n apply (induct arbitrary: r s rule: whileLoop_results.inducts)\n apply simp\n apply simp\n apply (insert snd_validNF [OF inv_holds])[1]\n apply blast\n apply (drule use_validNF [OF _ inv_holds])\n apply simp\n apply clarsimp\n apply blast\n done\n }\n\n also have \"whileLoop_terminates C B r s\"\n apply (rule whileLoop_terminates_inv [where I=I, OF init_I _ wf_R])\n apply (insert inv_holds)\n apply (clarsimp simp: validNF_def)\n done\n\n ultimately show ?thesis\n by (clarsimp simp: whileLoop_def, blast)\nqed\n\nlemma valid_whileLoop:\n assumes first_step: \"\\s. P r s \\ I r s\"\n and inv_step: \"\\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\\"\n and final_step: \"\\r s. \\ I r s; \\ C r s \\ \\ Q r s\"\n shows \"\\ P r \\ whileLoop C B r \\ Q \\\"\nproof -\n {\n fix r' s' s\n assume inv: \"I r s\"\n assume step: \"(r', s') \\ fst (whileLoop C B r s)\"\n\n have \"I r' s'\"\n using step inv\n apply (induct rule: in_whileLoop_induct)\n apply simp\n apply (drule use_valid, rule inv_step, auto)\n done\n }\n\n thus ?thesis\n apply (clarsimp simp: valid_def)\n apply (drule first_step)\n apply (rule final_step, simp)\n apply (metis fst_whileLoop_cond_false)\n done\nqed\n\nlemma whileLoop_wp:\n \"\\ \\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\;\n \\r s. \\ I r s; \\ C r s \\ \\ Q r s \\ \\\n \\ I r \\ whileLoop C B r \\ Q \\\"\n by (rule valid_whileLoop)\n\nlemma whileLoop_wp_inv [wp]:\n \"\\ \\r. \\\\s. I r s \\ C r s\\ B r \\I\\; \\r s. \\I r s; \\ C r s\\ \\ Q r s \\\n \\ \\ I r \\ whileLoop_inv C B r I M \\ Q \\\"\n apply (clarsimp simp: whileLoop_inv_def)\n apply (rule valid_whileLoop [where P=I and I=I], auto)\n done\n\nlemma validE_whileLoopE:\n \"\\\\s. P r s \\ I r s;\n \\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\,\\ A \\;\n \\r s. \\ I r s; \\ C r s \\ \\ Q r s\n \\ \\ \\ P r \\ whileLoopE C B r \\ Q \\,\\ A \\\"\n apply (clarsimp simp: whileLoopE_def validE_def)\n apply (rule valid_whileLoop [where I=\"\\r s. (case r of Inl x \\ A x s | Inr x \\ I x s)\"\n and Q=\"\\r s. (case r of Inl x \\ A x s | Inr x \\ Q x s)\"])\n apply atomize\n apply (clarsimp simp: valid_def lift_def split: sum.splits)\n apply (clarsimp simp: valid_def lift_def split: sum.splits)\n apply (clarsimp split: sum.splits)\n done\n\nlemma whileLoopE_wp:\n \"\\ \\r. \\ \\s. I r s \\ C r s \\ B r \\ I \\, \\ A \\;\n \\r s. \\ I r s; \\ C r s \\ \\ Q r s \\ \\\n \\ I r \\ whileLoopE C B r \\ Q \\, \\ A \\\"\n by (rule validE_whileLoopE)\n\nlemma exs_valid_whileLoop:\n assumes init_T: \"\\s. P s \\ T r s\"\n and iter_I: \"\\ r s0.\n \\ \\s. T r s \\ C r s \\ s = s0 \\\n B r \\\\\\r' s'. T r' s' \\ ((r', s'),(r, s0)) \\ R\\\"\n and wf_R: \"wf R\"\n and final_I: \"\\r s. \\ T r s; \\ C r s \\ \\ Q r s\"\n shows \"\\ P \\ whileLoop C B r \\\\ Q \\\"\nproof (clarsimp simp: exs_valid_def Bex_def)\n fix s\n assume \"P s\"\n\n {\n fix x\n have \"T (fst x) (snd x) \\\n \\r' s'. (r', s') \\ fst (whileLoop C B (fst x) (snd x)) \\ T r' s'\"\n using wf_R\n apply induction\n apply atomize\n apply (case_tac \"C (fst x) (snd x)\")\n apply (subst whileLoop_unroll)\n apply (clarsimp simp: condition_def bind_def' split: prod.splits)\n apply (cut_tac ?s0.0=b and r=a in iter_I)\n apply (clarsimp simp: exs_valid_def)\n apply blast\n apply (subst whileLoop_unroll)\n apply (clarsimp simp: condition_def bind_def' return_def)\n done\n }\n\n thus \"\\r' s'. (r', s') \\ fst (whileLoop C B r s) \\ Q r' s'\"\n by (metis \\P s\\ fst_conv init_T snd_conv\n final_I fst_whileLoop_cond_false)\nqed\n\nlemma empty_fail_whileLoop:\n assumes body_empty_fail: \"\\r. empty_fail (B r)\"\n shows \"empty_fail (whileLoop C B r)\"\nproof -\n {\n fix s A\n assume empty: \"fst (whileLoop C B r s) = {}\"\n\n have cond_true: \"\\x s. fst (whileLoop C B x s) = {} \\ C x s\"\n apply (subst (asm) whileLoop_unroll)\n apply (clarsimp simp: condition_def return_def split: if_split_asm)\n done\n\n have \"snd (whileLoop C B r s)\"\n apply (rule snd_whileLoop [where I=\"\\x s. fst (whileLoop C B x s) = {}\"])\n apply fact\n apply (rule cond_true, fact)\n apply (clarsimp simp: exs_valid_def)\n apply (case_tac \"fst (B r s) = {}\")\n apply (metis empty_failD [OF body_empty_fail])\n apply (subst (asm) whileLoop_unroll)\n apply (fastforce simp: condition_def bind_def split_def cond_true)\n done\n }\n\n thus ?thesis\n by (clarsimp simp: empty_fail_def)\nqed\n\nlemma empty_fail_whileLoopE:\n assumes body_empty_fail: \"\\r. empty_fail (B r)\"\n shows \"empty_fail (whileLoopE C B r)\"\n apply (clarsimp simp: whileLoopE_def)\n apply (rule empty_fail_whileLoop)\n apply (insert body_empty_fail)\n apply (clarsimp simp: empty_fail_def lift_def throwError_def return_def split: sum.splits)\n done\n\nlemma whileLoop_results_bisim:\n assumes base: \"(a, b) \\ whileLoop_results C B\"\n and vars1: \"Q = (case a of Some (r, s) \\ Some (rt r, st s) | _ \\ None)\"\n and vars2: \"R = (case b of Some (r, s) \\ Some (rt r, st s) | _ \\ None)\"\n and inv_init: \"case a of Some (r, s) \\ I r s | _ \\ True\"\n and inv_step: \"\\r s r' s'. \\ I r s; C r s; (r', s') \\ fst (B r s) \\ \\ I r' s'\"\n and cond_match: \"\\r s. I r s \\ C r s = C' (rt r) (st s)\"\n and fail_step: \"\\r s. \\C r s; snd (B r s); I r s\\\n \\ (Some (rt r, st s), None) \\ whileLoop_results C' B'\"\n and refine: \"\\r s r' s'. \\ I r s; C r s; (r', s') \\ fst (B r s) \\\n \\ (rt r', st s') \\ fst (B' (rt r) (st s))\"\n shows \"(Q, R) \\ whileLoop_results C' B'\"\n apply (subst vars1)\n apply (subst vars2)\n apply (insert base inv_init)\n apply (induct rule: whileLoop_results.induct)\n apply clarsimp\n apply (subst (asm) cond_match)\n apply (clarsimp simp: option.splits)\n apply (clarsimp simp: option.splits)\n apply (clarsimp simp: option.splits)\n apply (metis fail_step)\n apply (case_tac z)\n apply (clarsimp simp: option.splits)\n apply (metis cond_match inv_step refine whileLoop_results.intros(3))\n apply (clarsimp simp: option.splits)\n apply (metis cond_match inv_step refine whileLoop_results.intros(3))\n done\n\nlemma whileLoop_terminates_liftE:\n \"whileLoop_terminatesE C (\\r. liftE (B r)) r s = whileLoop_terminates C B r s\"\n apply (subst eq_sym_conv)\n apply (clarsimp simp: whileLoop_terminatesE_def)\n apply (rule iffI)\n apply (erule whileLoop_terminates.induct)\n apply (rule whileLoop_terminates.intros)\n apply clarsimp\n apply (clarsimp simp: split_def)\n apply (rule whileLoop_terminates.intros(2))\n apply clarsimp\n apply (clarsimp simp: liftE_def in_bind return_def lift_def [abs_def]\n bind_def lift_def throwError_def o_def split: sum.splits\n cong: sum.case_cong)\n apply (drule (1) bspec)\n apply clarsimp\n apply (subgoal_tac \"case (Inr r) of Inl _ \\ True | Inr r \\\n whileLoop_terminates (\\r s. (\\r s. case r of Inl _ \\ False | Inr v \\ C v s) (Inr r) s)\n (\\r. (lift (\\r. liftE (B r)) (Inr r)) >>= (\\x. return (theRight x))) r s\")\n apply (clarsimp simp: liftE_def lift_def)\n apply (erule whileLoop_terminates.induct)\n apply (clarsimp simp: liftE_def lift_def split: sum.splits)\n apply (erule whileLoop_terminates.intros)\n apply (clarsimp simp: liftE_def split: sum.splits)\n apply (clarsimp simp: bind_def return_def split_def lift_def)\n apply (erule whileLoop_terminates.intros)\n apply force\n done\n\nlemma snd_X_return [simp]:\n \"\\A X s. snd ((A >>= (\\a. return (X a))) s) = snd (A s)\"\n by (clarsimp simp: return_def bind_def split_def)\n\nlemma whileLoopE_liftE:\n \"whileLoopE C (\\r. liftE (B r)) r = liftE (whileLoop C B r)\"\n apply (rule ext)\n apply (clarsimp simp: whileLoopE_def)\n apply (rule prod_eqI)\n apply (rule set_eqI, rule iffI)\n apply clarsimp\n apply (clarsimp simp: in_bind whileLoop_def liftE_def)\n apply (rule_tac x=\"b\" in exI)\n apply (rule_tac x=\"theRight a\" in exI)\n apply (rule conjI)\n apply (erule whileLoop_results_bisim [where rt=theRight and st=\"\\x. x\" and I=\"\\r s. case r of Inr x \\ True | _ \\ False\"],\n auto intro: whileLoop_results.intros simp: bind_def return_def lift_def split: sum.splits)[1]\n apply (drule whileLoop_results_induct_lemma2 [where P=\"\\(r, s). case r of Inr x \\ True | _ \\ False\"] )\n apply (rule refl)\n apply (rule refl)\n apply clarsimp\n apply (clarsimp simp: return_def bind_def lift_def split: sum.splits)\n apply (clarsimp simp: return_def bind_def lift_def split: sum.splits)\n apply (clarsimp simp: in_bind whileLoop_def liftE_def)\n apply (erule whileLoop_results_bisim [where rt=Inr and st=\"\\x. x\" and I=\"\\r s. True\"],\n auto intro: whileLoop_results.intros intro!: bexI simp: bind_def return_def lift_def split: sum.splits)[1]\n apply (rule iffI)\n apply (clarsimp simp: whileLoop_def liftE_def del: notI)\n apply (erule disjE)\n apply (erule whileLoop_results_bisim [where rt=theRight and st=\"\\x. x\" and I=\"\\r s. case r of Inr x \\ True | _ \\ False\"],\n auto intro: whileLoop_results.intros simp: bind_def return_def lift_def split: sum.splits)[1]\n apply (subst (asm) whileLoop_terminates_liftE [symmetric])\n apply (fastforce simp: whileLoop_def liftE_def whileLoop_terminatesE_def)\n apply (clarsimp simp: whileLoop_def liftE_def del: notI)\n apply (subst (asm) whileLoop_terminates_liftE [symmetric])\n apply (clarsimp simp: whileLoop_def liftE_def whileLoop_terminatesE_def)\n apply (erule disjE)\n apply (erule whileLoop_results_bisim [where rt=Inr and st=\"\\x. x\" and I=\"\\r s. True\"])\n apply (clarsimp split: option.splits)\n apply (clarsimp split: option.splits)\n apply (clarsimp split: option.splits)\n apply (auto intro: whileLoop_results.intros intro!: bexI simp: bind_def return_def lift_def split: sum.splits)\n done\n\nlemma validNF_whileLoop:\n assumes pre: \"\\s. P r s \\ I r s\"\n and inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\!\"\n and wf: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\P r\\ whileLoop C B r \\Q\\!\"\n apply rule\n apply (rule valid_whileLoop)\n apply fact\n apply (insert inv, clarsimp simp: validNF_def\n valid_def split: prod.splits, force)[1]\n apply (metis post_cond)\n apply (unfold no_fail_def)\n apply (intro allI impI)\n apply (rule not_snd_whileLoop [where I=I and R=R])\n apply (auto intro: assms)\n done\n\nlemma validNF_whileLoop_inv [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\!\"\n and wf: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoop_inv C B r I R \\Q\\!\"\n apply (clarsimp simp: whileLoop_inv_def)\n apply (rule validNF_whileLoop [where I=I and R=R])\n apply simp\n apply (rule inv)\n apply (rule wf)\n apply (metis post_cond)\n done\n\nlemma validNF_whileLoop_inv_measure [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ M r' s' < M r s \\!\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoop_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\!\"\n apply (clarsimp simp: whileLoop_inv_def)\n apply (rule validNF_whileLoop [where R=\"measure' (\\(r, s). M r s)\" and I=I])\n apply simp\n apply clarsimp\n apply (rule inv)\n apply simp\n apply (metis post_cond)\n done\n\nlemma validNF_whileLoop_inv_measure_twosteps:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ B r \\ \\r' s'. I r' s' \\!\"\n assumes measure: \"\\r m. \\\\s. I r s \\ C r s \\ M r s = m \\ B r \\ \\r' s'. M r' s' < m \\\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoop_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\!\"\n apply (rule validNF_whileLoop_inv_measure)\n apply (rule validNF_weaken_pre)\n apply (rule validNF_post_comb_conj_L)\n apply (rule inv)\n apply (rule measure)\n apply fast\n apply (metis post_cond)\n done\n\nlemma wf_custom_measure:\n \"\\ \\a b. (a, b) \\ R \\ f a < (f :: 'a \\ nat) b \\ \\ wf R\"\n by (metis in_measure wf_def wf_measure)\n\nlemma validNF_whileLoopE:\n assumes pre: \"\\s. P r s \\ I r s\"\n and inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\,\\ E \\!\"\n and wf: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\ P r \\ whileLoopE C B r \\ Q \\,\\ E \\!\"\n apply (unfold validE_NF_alt_def whileLoopE_def)\n apply (rule validNF_whileLoop [\n where I=\"\\r s. case r of Inl x \\ E x s | Inr x \\ I x s\"\n and R=\"{((r', s'), (r, s)). \\x x'. r' = Inl x' \\ r = Inr x}\n \\ {((r', s'), (r, s)). \\x x'. r' = Inr x' \\ r = Inr x \\ ((x', s'),(x, s)) \\ R}\"])\n apply (simp add: pre)\n apply (insert inv)[1]\n apply (fastforce simp: lift_def validNF_def valid_def\n validE_NF_def throwError_def no_fail_def return_def\n validE_def split: sum.splits prod.splits)\n apply (rule wf_Un)\n apply (rule wf_custom_measure [where f=\"\\(r, s). case r of Inl _ \\ 0 | _ \\ 1\"])\n apply clarsimp\n apply (insert wf_inv_image [OF wf, where f=\"\\(r, s). (theRight r, s)\"])\n apply (drule wf_Int1 [where r'=\"{((r', s'),(r, s)). (\\x. r = Inr x) \\ (\\x. r' = Inr x)}\"])\n apply (erule wf_subset)\n apply rule\n apply (clarsimp simp: inv_image_def split: prod.splits sum.splits)\n apply clarsimp\n apply rule\n apply rule\n apply clarsimp\n apply clarsimp\n apply (clarsimp split: sum.splits)\n apply (blast intro: post_cond)\n done\n\nlemma validNF_whileLoopE_inv [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ ((r', s'), (r, s)) \\ R \\,\\ E \\!\"\n and wf_R: \"wf R\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoopE_inv C B r I R \\Q\\,\\E\\!\"\n apply (clarsimp simp: whileLoopE_inv_def)\n apply (metis validNF_whileLoopE [OF _ inv] post_cond wf_R)\n done\n\nlemma validNF_whileLoopE_inv_measure [wp]:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ s' = s \\ B r \\ \\r' s'. I r' s' \\ M r' s' < M r s \\, \\ E \\!\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoopE_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\,\\E\\!\"\n apply (rule validNF_whileLoopE_inv)\n apply clarsimp\n apply (rule inv)\n apply clarsimp\n apply (metis post_cond)\n done\n\nlemma validNF_whileLoopE_inv_measure_twosteps:\n assumes inv: \"\\r s. \\\\s'. I r s' \\ C r s' \\ B r \\ \\r' s'. I r' s' \\, \\ E \\!\"\n assumes measure: \"\\r m. \\\\s. I r s \\ C r s \\ M r s = m \\ B r \\ \\r' s'. M r' s' < m \\, \\ \\_ _. True \\\"\n and post_cond: \"\\r s. \\I r s; \\ C r s\\ \\ Q r s\"\n shows \"\\I r\\ whileLoopE_inv C B r I (measure' (\\(r, s). M r s)) \\Q\\, \\E\\!\"\n apply (rule validNF_whileLoopE_inv_measure)\n apply (rule validE_NF_weaken_pre)\n apply (rule validE_NF_post_comb_conj_L)\n apply (rule inv)\n apply (rule measure)\n apply fast\n apply (metis post_cond)\n done\n\nlemma whileLoopE_wp_inv [wp]:\n \"\\ \\r. \\\\s. I r s \\ C r s\\ B r \\I\\,\\E\\; \\r s. \\I r s; \\ C r s\\ \\ Q r s \\\n \\ \\ I r \\ whileLoopE_inv C B r I M \\ Q \\,\\ E \\\"\n apply (clarsimp simp: whileLoopE_inv_def)\n apply (rule validE_whileLoopE [where I=I], auto)\n done\n\nsubsection \"Stronger whileLoop rules\"\n\nlemma whileLoop_rule_strong:\n assumes init_U: \"\\ \\s'. s' = s \\ whileLoop C B r \\ \\r s. (r, s) \\ fst Q \\\"\n and path_exists: \"\\r'' s''. \\ (r'', s'') \\ fst Q \\ \\ \\ \\s'. s' = s \\ whileLoop C B r \\\\ \\r s. r = r'' \\ s = s'' \\\"\n and loop_fail: \"snd Q \\ snd (whileLoop C B r s)\"\n and loop_nofail: \"\\ snd Q \\ \\ \\s'. s' = s \\ whileLoop C B r \\ \\_ _. True \\!\"\n shows \"whileLoop C B r s = Q\"\n using assms\n apply atomize\n apply (clarsimp simp: valid_def exs_valid_def validNF_def no_fail_def)\n apply rule\n apply blast\n apply blast\n apply blast\n done\n\nlemma whileLoop_rule_strong_no_fail:\n assumes init_U: \"\\ \\s'. s' = s \\ whileLoop C B r \\ \\r s. (r, s) \\ fst Q \\!\"\n and path_exists: \"\\r'' s''. \\ (r'', s'') \\ fst Q \\ \\ \\ \\s'. s' = s \\ whileLoop C B r \\\\ \\r s. r = r'' \\ s = s'' \\\"\n and loop_no_fail: \"\\ snd Q\"\n shows \"whileLoop C B r s = Q\"\n apply (rule whileLoop_rule_strong)\n apply (metis init_U validNF_valid)\n apply (metis path_exists)\n apply (metis loop_no_fail)\n apply (metis (lifting, no_types) init_U validNF_chain)\n done\n\nsubsection \"Miscellaneous rules\"\n\n(* Failure of one whileLoop implies the failure of another whileloop\n * which will only ever fail more. *)\nlemma snd_whileLoop_subset:\n assumes a_fails: \"snd (whileLoop C A r s)\"\n and b_success_step:\n \"\\r s r' s'. \\ C r s; (r', s') \\ fst (A r s); \\ snd (B r s) \\\n \\ (r', s') \\ fst (B r s)\"\n and b_fail_step: \"\\r s. \\ C r s; snd (A r s) \\ \\ snd (B r s) \"\n shows \"snd (whileLoop C B r s)\"\n apply (insert a_fails)\n apply (induct rule: snd_whileLoop_induct)\n apply (unfold whileLoop_def snd_conv)[1]\n apply (rule disjCI, simp)\n apply rotate_tac\n apply (induct rule: whileLoop_terminates.induct)\n apply (subst (asm) whileLoop_terminates.simps)\n apply simp\n apply (subst (asm) (3) whileLoop_terminates.simps, clarsimp)\n apply (subst whileLoop_results.simps, clarsimp)\n apply (rule classical)\n apply (frule b_success_step, assumption, simp)\n apply (drule (1) bspec)\n apply clarsimp\n apply (frule (1) b_fail_step)\n apply (metis snd_whileLoop_first_step)\n apply (metis b_success_step snd_whileLoop_first_step snd_whileLoop_unfold)\n done\n\nend\n", "meta": {"author": "NICTA", "repo": "l4v", "sha": "3c3514fe99082f7b6a6fb8445b8dfc592ff7f02b", "save_path": "github-repos/isabelle/NICTA-l4v", "path": "github-repos/isabelle/NICTA-l4v/l4v-3c3514fe99082f7b6a6fb8445b8dfc592ff7f02b/lib/Monad_WP/WhileLoopRules.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.11436852014455552, "lm_q1q2_score": 0.0531701047308529}} {"text": "section \\Skeleton for Gabow's SCC Algorithm \\label{sec:skel}\\\ntheory Gabow_Skeleton\nimports CAVA_Automata.Digraph\nbegin\n\n(* TODO: convenience locale, consider merging this with invariants *)\nlocale fr_graph =\n graph G\n for G :: \"('v, 'more) graph_rec_scheme\"\n +\n assumes finite_reachableE_V0[simp, intro!]: \"finite (E\\<^sup>* `` V0)\"\n\ntext \\\n In this theory, we formalize a skeleton of Gabow's SCC algorithm. \n The skeleton serves as a starting point to develop concrete algorithms,\n like enumerating the SCCs or checking emptiness of a generalized Büchi automaton.\n\\\n\nsection \\Statistics Setup\\\ntext \\\n We define some dummy-constants that are included into the generated code,\n and may be mapped to side-effecting ML-code that records statistics and debug information\n about the execution. In the skeleton algorithm, we count the number of visited nodes,\n and include a timing for the whole algorithm.\n\\\n\ndefinition stat_newnode :: \"unit => unit\" \\ \\Invoked if new node is visited\\\n where [code]: \"stat_newnode \\ \\_. ()\"\n\ndefinition stat_start :: \"unit => unit\" \\ \\Invoked once if algorithm starts\\\n where [code]: \"stat_start \\ \\_. ()\"\n\ndefinition stat_stop :: \"unit => unit\" \\ \\Invoked once if algorithm stops\\\n where [code]: \"stat_stop \\ \\_. ()\"\n\nlemma [autoref_rules]: \n \"(stat_newnode,stat_newnode) \\ unit_rel \\ unit_rel\"\n \"(stat_start,stat_start) \\ unit_rel \\ unit_rel\"\n \"(stat_stop,stat_stop) \\ unit_rel \\ unit_rel\"\n by auto\n\nabbreviation \"stat_newnode_nres \\ RETURN (stat_newnode ())\"\nabbreviation \"stat_start_nres \\ RETURN (stat_start ())\"\nabbreviation \"stat_stop_nres \\ RETURN (stat_stop ())\"\n\nlemma discard_stat_refine[refine]:\n \"m1\\m2 \\ stat_newnode_nres \\ m1 \\ m2\"\n \"m1\\m2 \\ stat_start_nres \\ m1 \\ m2\"\n \"m1\\m2 \\ stat_stop_nres \\ m1 \\ m2\"\n by simp_all\n\nsection \\Abstract Algorithm\\\ntext \\\n In this section, we formalize an abstract version of a path-based SCC algorithm.\n Later, this algorithm will be refined to use Gabow's data structure.\n\\\n\nsubsection \\Preliminaries\\\ndefinition path_seg :: \"'a set list \\ nat \\ nat \\ 'a set\"\n \\ \\Set of nodes in a segment of the path\\\n where \"path_seg p i j \\ \\{p!k|k. i\\k \\ ki \\ path_seg p i j = {}\"\n \"path_seg p i (Suc i) = p!i\"\n unfolding path_seg_def\n apply auto []\n apply (auto simp: le_less_Suc_eq) []\n done\n\nlemma path_seg_drop:\n \"\\(set (drop i p)) = path_seg p i (length p)\"\n unfolding path_seg_def\n by (fastforce simp: in_set_drop_conv_nth Bex_def)\n\nlemma path_seg_butlast: \n \"p\\[] \\ path_seg p 0 (length p - Suc 0) = \\(set (butlast p))\"\n apply (cases p rule: rev_cases, simp)\n apply (fastforce simp: path_seg_def nth_append in_set_conv_nth)\n done\n\ndefinition idx_of :: \"'a set list \\ 'a \\ nat\"\n \\ \\Index of path segment that contains a node\\\n where \"idx_of p v \\ THE i. i v\\p!i\"\n\nlemma idx_of_props:\n assumes \n p_disjoint_sym: \"\\i j v. i j v\\p!i \\ v\\p!j \\ i=j\"\n assumes ON_STACK: \"v\\\\(set p)\"\n shows \n \"idx_of p v < length p\" and\n \"v \\ p ! idx_of p v\"\nproof -\n from ON_STACK obtain i where \"i p ! i\"\n by (auto simp add: in_set_conv_nth)\n moreover hence \"\\jp ! j \\ i=j\"\n using p_disjoint_sym by auto\n ultimately show \"idx_of p v < length p\" \n and \"v \\ p ! idx_of p v\" unfolding idx_of_def\n by (metis (lifting) theI')+\nqed\n\nlemma idx_of_uniq:\n assumes \n p_disjoint_sym: \"\\i j v. i j v\\p!i \\ v\\p!j \\ i=j\"\n assumes A: \"ip!i\"\n shows \"idx_of p v = i\"\nproof -\n from A p_disjoint_sym have \"\\jp ! j \\ i=j\" by auto\n with A show ?thesis\n unfolding idx_of_def\n by (metis (lifting) the_equality)\nqed\n\n\nsubsection \\Invariants\\\ntext \\The state of the inner loop consists of the path \\p\\ of\n collapsed nodes, the set \\D\\ of finished (done) nodes, and the set\n \\pE\\ of pending edges.\\\ntype_synonym 'v abs_state = \"'v set list \\ 'v set \\ ('v\\'v) set\"\n\ncontext fr_graph\nbegin\n definition touched :: \"'v set list \\ 'v set \\ 'v set\" \n \\ \\Touched: Nodes that are done or on path\\\n where \"touched p D \\ D \\ \\(set p)\"\n\n definition vE :: \"'v set list \\ 'v set \\ ('v \\ 'v) set \\ ('v \\ 'v) set\"\n \\ \\Visited edges: No longer pending edges from touched nodes\\\n where \"vE p D pE \\ (E \\ (touched p D \\ UNIV)) - pE\"\n\n lemma vE_ss_E: \"vE p D pE \\ E\" \\ \\Visited edges are edges\\\n unfolding vE_def by auto\n\nend\n\nlocale outer_invar_loc \\ \\Invariant of the outer loop\\\n = fr_graph G for G :: \"('v,'more) graph_rec_scheme\" +\n fixes it :: \"'v set\" \\ \\Remaining nodes to iterate over\\\n fixes D :: \"'v set\" \\ \\Finished nodes\\\n\n assumes it_initial: \"it\\V0\" \\ \\Only start nodes to iterate over\\\n\n assumes it_done: \"V0 - it \\ D\" \\ \\Nodes already iterated over are visited\\\n assumes D_reachable: \"D\\E\\<^sup>*``V0\" \\ \\Done nodes are reachable\\\n assumes D_closed: \"E``D \\ D\" \\ \\Done is closed under transitions\\\nbegin\n\n lemma locale_this: \"outer_invar_loc G it D\" by unfold_locales\n\n definition (in fr_graph) \"outer_invar \\ \\it D. outer_invar_loc G it D\"\n\n lemma outer_invar_this[simp, intro!]: \"outer_invar it D\"\n unfolding outer_invar_def apply simp by unfold_locales \nend\n\nlocale invar_loc \\ \\Invariant of the inner loop\\\n = fr_graph G\n for G :: \"('v, 'more) graph_rec_scheme\" +\n fixes v0 :: \"'v\"\n fixes D0 :: \"'v set\"\n fixes p :: \"'v set list\"\n fixes D :: \"'v set\"\n fixes pE :: \"('v\\'v) set\"\n\n assumes v0_initial[simp, intro!]: \"v0\\V0\"\n assumes D_incr: \"D0 \\ D\"\n\n assumes pE_E_from_p: \"pE \\ E \\ (\\(set p)) \\ UNIV\" \n \\ \\Pending edges are edges from path\\\n assumes E_from_p_touched: \"E \\ (\\(set p) \\ UNIV) \\ pE \\ UNIV \\ touched p D\" \n \\ \\Edges from path are pending or touched\\\n assumes D_reachable: \"D\\E\\<^sup>*``V0\" \\ \\Done nodes are reachable\\\n assumes p_connected: \"Suc i p!i \\ p!Suc i \\ (E-pE) \\ {}\"\n \\ \\CNodes on path are connected by non-pending edges\\\n\n assumes p_disjoint: \"\\i \\ p!i \\ p!j = {}\" \n \\ \\CNodes on path are disjoint\\\n assumes p_sc: \"U\\set p \\ U\\U \\ (vE p D pE \\ U\\U)\\<^sup>*\" \n \\ \\Nodes in CNodes are mutually reachable by visited edges\\\n\n assumes root_v0: \"p\\[] \\ v0\\hd p\" \\ \\Root CNode contains start node\\\n assumes p_empty_v0: \"p=[] \\ v0\\D\" \\ \\Start node is done if path empty\\\n \n assumes D_closed: \"E``D \\ D\" \\ \\Done is closed under transitions\\\n (*assumes D_vis: \"E\\D\\D \\ vE\" -- \"All edges from done nodes are visited\"*)\n\n assumes vE_no_back: \"\\i \\ vE p D pE \\ p!j \\ p!i = {}\" \n \\ \\Visited edges do not go back on path\\\n assumes p_not_D: \"\\(set p) \\ D = {}\" \\ \\Path does not contain done nodes\\\nbegin\n abbreviation ltouched where \"ltouched \\ touched p D\"\n abbreviation lvE where \"lvE \\ vE p D pE\"\n\n lemma locale_this: \"invar_loc G v0 D0 p D pE\" by unfold_locales\n\n definition (in fr_graph) \n \"invar \\ \\v0 D0 (p,D,pE). invar_loc G v0 D0 p D pE\"\n\n lemma invar_this[simp, intro!]: \"invar v0 D0 (p,D,pE)\"\n unfolding invar_def apply simp by unfold_locales \n\n lemma finite_reachableE_v0[simp, intro!]: \"finite (E\\<^sup>*``{v0})\"\n apply (rule finite_subset[OF _ finite_reachableE_V0])\n using v0_initial by auto\n\n lemma D_vis: \"E\\D\\UNIV \\ lvE\" \\ \\All edges from done nodes are visited\\\n unfolding vE_def touched_def using pE_E_from_p p_not_D by blast \n\n lemma vE_touched: \"lvE \\ ltouched \\ ltouched\" \n \\ \\Visited edges only between touched nodes\\\n using E_from_p_touched D_closed unfolding vE_def touched_def by blast\n\n lemma lvE_ss_E: \"lvE \\ E\" \\ \\Visited edges are edges\\\n unfolding vE_def by auto\n\n\n lemma path_touched: \"\\(set p) \\ ltouched\" by (auto simp: touched_def)\n lemma D_touched: \"D \\ ltouched\" by (auto simp: touched_def)\n\n lemma pE_by_vE: \"pE = (E \\ \\(set p) \\ UNIV) - lvE\"\n \\ \\Pending edges are edges from path not yet visited\\\n unfolding vE_def touched_def\n using pE_E_from_p\n by auto\n\n lemma pick_pending: \"p\\[] \\ pE \\ last p \\ UNIV = (E-lvE) \\ last p \\ UNIV\"\n \\ \\Pending edges from end of path are non-visited edges from end of path\\\n apply (subst pE_by_vE)\n by auto\n\n lemma p_connected': \n assumes A: \"Suc i p!Suc i \\ lvE \\ {}\" \n proof -\n from A p_not_D have \"p!i \\ set p\" \"p!Suc i \\ set p\" by auto\n with p_connected[OF A] show ?thesis unfolding vE_def touched_def\n by blast\n qed\n\nend\n\nsubsubsection \\Termination\\\n\ncontext fr_graph \nbegin\n text \\The termination argument is based on unprocessed edges: \n Reachable edges from untouched nodes and pending edges.\\\n definition \"unproc_edges v0 p D pE \\ (E \\ (E\\<^sup>*``{v0} - (D \\ \\(set p))) \\ UNIV) \\ pE\"\n\n text \\\n In each iteration of the loop, either the number of unprocessed edges\n decreases, or the path length decreases.\\\n definition \"abs_wf_rel v0 \\ inv_image (finite_psubset <*lex*> measure length)\n (\\(p,D,pE). (unproc_edges v0 p D pE, p))\"\n\n lemma abs_wf_rel_wf[simp, intro!]: \"wf (abs_wf_rel v0)\"\n unfolding abs_wf_rel_def\n by auto\nend\n\nsubsection \\Abstract Skeleton Algorithm\\\n\ncontext fr_graph\nbegin\n\n definition (in fr_graph) initial :: \"'v \\ 'v set \\ 'v abs_state\"\n where \"initial v0 D \\ ([{v0}], D, (E \\ {v0}\\UNIV))\"\n\n definition (in -) collapse_aux :: \"'a set list \\ nat \\ 'a set list\"\n where \"collapse_aux p i \\ take i p @ [\\(set (drop i p))]\"\n\n definition (in -) collapse :: \"'a \\ 'a abs_state \\ 'a abs_state\" \n where \"collapse v PDPE \\ \n let \n (p,D,pE)=PDPE; \n i=idx_of p v;\n p = collapse_aux p i\n in (p,D,pE)\"\n\n definition (in -) \n select_edge :: \"'a abs_state \\ ('a option \\ 'a abs_state) nres\"\n where\n \"select_edge PDPE \\ do {\n let (p,D,pE) = PDPE;\n e \\ SELECT (\\e. e \\ pE \\ last p \\ UNIV);\n case e of\n None \\ RETURN (None,(p,D,pE))\n | Some (u,v) \\ RETURN (Some v, (p,D,pE - {(u,v)}))\n }\"\n\n definition (in fr_graph) push :: \"'v \\ 'v abs_state \\ 'v abs_state\" \n where \"push v PDPE \\ \n let\n (p,D,pE) = PDPE;\n p = p@[{v}];\n pE = pE \\ (E\\{v}\\UNIV)\n in\n (p,D,pE)\"\n\n definition (in -) pop :: \"'v abs_state \\ 'v abs_state\"\n where \"pop PDPE \\ let\n (p,D,pE) = PDPE;\n (p,V) = (butlast p, last p);\n D = V \\ D\n in\n (p,D,pE)\"\n\n text \\The following lemmas match the definitions presented in the paper:\\\n lemma \"select_edge (p,D,pE) \\ do {\n e \\ SELECT (\\e. e \\ pE \\ last p \\ UNIV);\n case e of\n None \\ RETURN (None,(p,D,pE))\n | Some (u,v) \\ RETURN (Some v, (p,D,pE - {(u,v)}))\n }\"\n unfolding select_edge_def by simp\n\n lemma \"collapse v (p,D,pE) \n \\ let i=idx_of p v in (take i p @ [\\(set (drop i p))],D,pE)\"\n unfolding collapse_def collapse_aux_def by simp\n\n lemma \"push v (p, D, pE) \\ (p @ [{v}], D, pE \\ E \\ {v} \\ UNIV)\"\n unfolding push_def by simp\n\n lemma \"pop (p, D, pE) \\ (butlast p, last p \\ D, pE)\"\n unfolding pop_def by auto\n\n thm pop_def[unfolded Let_def, no_vars]\n\n thm select_edge_def[unfolded Let_def]\n\n\n definition skeleton :: \"'v set nres\" \n \\ \\Abstract Skeleton Algorithm\\\n where\n \"skeleton \\ do {\n let D = {};\n r \\ FOREACHi outer_invar V0 (\\v0 D0. do {\n if v0\\D0 then do {\n let s = initial v0 D0;\n\n (p,D,pE) \\ WHILEIT (invar v0 D0)\n (\\(p,D,pE). p \\ []) (\\(p,D,pE). \n do {\n \\ \\Select edge from end of path\\\n (vo,(p,D,pE)) \\ select_edge (p,D,pE);\n\n ASSERT (p\\[]);\n case vo of \n Some v \\ do { \\ \\Found outgoing edge to node \\v\\\\\n if v \\ \\(set p) then do {\n \\ \\Back edge: Collapse path\\\n RETURN (collapse v (p,D,pE))\n } else if v\\D then do {\n \\ \\Edge to new node. Append to path\\\n RETURN (push v (p,D,pE))\n } else do {\n \\ \\Edge to done node. Skip\\\n RETURN (p,D,pE)\n }\n }\n | None \\ do {\n ASSERT (pE \\ last p \\ UNIV = {});\n \\ \\No more outgoing edges from current node on path\\\n RETURN (pop (p,D,pE))\n }\n }) s;\n ASSERT (p=[] \\ pE={});\n RETURN D\n } else\n RETURN D0\n }) D;\n RETURN r\n }\"\n\nend\n\nsubsection \\Invariant Preservation\\\n\ncontext fr_graph begin\n\n lemma set_collapse_aux[simp]: \"\\(set (collapse_aux p i)) = \\(set p)\"\n apply (subst (2) append_take_drop_id[of _ p,symmetric])\n apply (simp del: append_take_drop_id)\n unfolding collapse_aux_def by auto\n\n lemma touched_collapse[simp]: \"touched (collapse_aux p i) D = touched p D\"\n unfolding touched_def by simp\n\n lemma vE_collapse_aux[simp]: \"vE (collapse_aux p i) D pE = vE p D pE\"\n unfolding vE_def by simp\n\n lemma touched_push[simp]: \"touched (p @ [V]) D = touched p D \\ V\"\n unfolding touched_def by auto\n\nend\n\nsubsubsection \\Corollaries of the invariant\\\ntext \\In this section, we prove some more corollaries of the invariant,\n which are helpful to show invariant preservation\\\n\ncontext invar_loc\nbegin\n lemma cnode_connectedI: \n \"\\ip!i; v\\p!i\\ \\ (u,v)\\(lvE \\ p!i\\p!i)\\<^sup>*\"\n using p_sc[of \"p!i\"] by (auto simp: in_set_conv_nth)\n\n lemma cnode_connectedI': \"\\ip!i; v\\p!i\\ \\ (u,v)\\(lvE)\\<^sup>*\"\n by (metis inf.cobounded1 rtrancl_mono_mp cnode_connectedI)\n\n lemma p_no_empty: \"{} \\ set p\"\n proof \n assume \"{}\\set p\"\n then obtain i where IDX: \"i p!i\\{}\"\n using p_no_empty by (metis nth_mem)\n \n lemma p_disjoint_sym: \"\\ip!i; v\\p!j\\ \\ i=j\"\n by (metis disjoint_iff_not_equal linorder_neqE_nat p_disjoint)\n\n lemma pi_ss_path_seg_eq[simp]:\n assumes A: \"ilength p\"\n shows \"p!i\\path_seg p l u \\ l\\i \\ ipath_seg p l u\"\n from A obtain x where \"x\\p!i\" by (blast dest: p_no_empty_idx)\n with B obtain i' where C: \"x\\p!i'\" \"l\\i'\" \"i'i _ \\x\\p!i\\ \\x\\p!i'\\] \\i' \\u\\length p\\\n have \"i=i'\" by simp\n with C show \"l\\i \\ ilength p\" \"l2length p\"\n shows \"path_seg p l1 u1 \\ path_seg p l2 u2 \\ l2\\l1 \\ u1\\u2\"\n proof\n assume S: \"path_seg p l1 u1 \\ path_seg p l2 u2\"\n have \"p!l1 \\ path_seg p l1 u1\" using A by simp\n also note S finally have 1: \"l2\\l1\" using A by simp\n have \"p!(u1 - 1) \\ path_seg p l1 u1\" using A by simp\n also note S finally have 2: \"u1\\u2\" using A by auto\n from 1 2 show \"l2\\l1 \\ u1\\u2\" ..\n next\n assume \"l2\\l1 \\ u1\\u2\" thus \"path_seg p l1 u1 \\ path_seg p l2 u2\"\n using A\n apply (clarsimp simp: path_seg_def) []\n apply (metis dual_order.strict_trans1 dual_order.trans)\n done\n qed\n\n lemma pathI: \n assumes \"x\\p!i\" \"y\\p!j\"\n assumes \"i\\j\" \"j path_seg p i (Suc j)\"\n shows \"(x,y)\\(lvE \\ seg\\seg)\\<^sup>*\"\n \\ \\We can obtain a path between cnodes on path\\\n using assms(3,1,2,4) unfolding seg_def\n proof (induction arbitrary: y rule: dec_induct)\n case base thus ?case by (auto intro!: cnode_connectedI)\n next\n case (step j)\n\n let ?seg = \"path_seg p i (Suc j)\"\n let ?seg' = \"path_seg p i (Suc (Suc j))\"\n\n have SSS: \"?seg \\ ?seg'\" \n apply (subst path_seg_ss_eq)\n using step.hyps step.prems by auto\n\n from p_connected'[OF \\Suc j < length p\\] obtain u v where \n UV: \"(u,v)\\lvE\" \"u\\p!j\" \"v\\p!Suc j\" by auto\n\n have ISS: \"p!j \\ ?seg'\" \"p!Suc j \\ ?seg'\" \n using step.hyps step.prems by simp_all\n\n from p_no_empty_idx[of j] \\Suc j < length p\\ obtain x' where \"x'\\p!j\" \n by auto\n with step.IH[of x'] \\x\\p!i\\ \\Suc j < length p\\ \n have t: \"(x,x')\\(lvE\\?seg\\?seg)\\<^sup>*\" by auto\n have \"(x,x')\\(lvE\\?seg'\\?seg')\\<^sup>*\" using SSS \n by (auto intro: rtrancl_mono_mp[OF _ t])\n also \n from cnode_connectedI[OF _ \\x'\\p!j\\ \\u\\p!j\\] \\Suc j < length p\\ have\n t: \"(x', u) \\ (lvE \\ p ! j \\ p ! j)\\<^sup>*\" by auto\n have \"(x', u) \\ (lvE\\?seg'\\?seg')\\<^sup>*\" using ISS\n by (auto intro: rtrancl_mono_mp[OF _ t])\n also have \"(u,v)\\lvE\\?seg'\\?seg'\" using UV ISS by auto\n also from cnode_connectedI[OF \\Suc j < length p\\ \\v\\p!Suc j\\ \\y\\p!Suc j\\] \n have t: \"(v, y) \\ (lvE \\ p ! Suc j \\ p ! Suc j)\\<^sup>*\" by auto\n have \"(v, y) \\ (lvE\\?seg'\\?seg')\\<^sup>*\" using ISS\n by (auto intro: rtrancl_mono_mp[OF _ t])\n finally show \"(x,y)\\(lvE\\?seg'\\?seg')\\<^sup>*\" .\n qed\n\n lemma p_reachable: \"\\(set p) \\ E\\<^sup>*``{v0}\" \\ \\Nodes on path are reachable\\\n proof \n fix v\n assume A: \"v\\\\(set p)\"\n then obtain i where \"ip!i\" \n by (metis UnionE in_set_conv_nth)\n moreover from A root_v0 have \"v0\\p!0\" by (cases p) auto\n ultimately have \n t: \"(v0,v)\\(lvE \\ path_seg p 0 (Suc i) \\ path_seg p 0 (Suc i))\\<^sup>*\"\n by (auto intro: pathI)\n from lvE_ss_E have \"(v0,v)\\E\\<^sup>*\" by (auto intro: rtrancl_mono_mp[OF _ t])\n thus \"v\\E\\<^sup>*``{v0}\" by auto\n qed\n\n lemma touched_reachable: \"ltouched \\ E\\<^sup>*``V0\" \\ \\Touched nodes are reachable\\\n unfolding touched_def using p_reachable D_reachable by blast\n\n lemma vE_reachable: \"lvE \\ E\\<^sup>*``V0 \\ E\\<^sup>*``V0\"\n apply (rule order_trans[OF vE_touched])\n using touched_reachable by blast\n\n lemma pE_reachable: \"pE \\ E\\<^sup>*``{v0} \\ E\\<^sup>*``{v0}\"\n proof safe\n fix u v\n assume E: \"(u,v)\\pE\"\n with pE_E_from_p p_reachable have \"(v0,u)\\E\\<^sup>*\" \"(u,v)\\E\" by blast+\n thus \"(v0,u)\\E\\<^sup>*\" \"(v0,v)\\E\\<^sup>*\" by auto\n qed\n\n lemma D_closed_vE_rtrancl: \"lvE\\<^sup>*``D \\ D\"\n by (metis D_closed Image_closed_trancl eq_iff reachable_mono lvE_ss_E)\n\n lemma D_closed_path: \"\\path E u q w; u\\D\\ \\ set q \\ D\"\n proof -\n assume a1: \"path E u q w\"\n assume \"u \\ D\"\n hence f1: \"{u} \\ D\"\n using bot.extremum by force\n have \"set q \\ E\\<^sup>* `` {u}\"\n using a1 by (metis insert_subset path_nodes_reachable)\n thus \"set q \\ D\"\n using f1 by (metis D_closed rtrancl_reachable_induct subset_trans)\n qed\n\n lemma D_closed_path_vE: \"\\path lvE u q w; u\\D\\ \\ set q \\ D\"\n by (metis D_closed_path path_mono lvE_ss_E)\n\n lemma path_in_lastnode:\n assumes P: \"path lvE u q v\"\n assumes [simp]: \"p\\[]\"\n assumes ND: \"u\\last p\" \"v\\last p\"\n shows \"set q \\ last p\"\n \\ \\A path from the last Cnode to the last Cnode remains in the last Cnode\\\n (* TODO: This can be generalized in two directions: \n either 1) The path end anywhere. Due to vE_touched we can infer \n that it ends in last cnode \n or 2) We may use any cnode, not only the last one\n *)\n using P ND\n proof (induction)\n case (path_prepend u v l w) \n from \\(u,v)\\lvE\\ vE_touched have \"v\\ltouched\" by auto\n hence \"v\\\\(set p)\"\n unfolding touched_def\n proof\n assume \"v\\D\"\n moreover from \\path lvE v l w\\ have \"(v,w)\\lvE\\<^sup>*\" by (rule path_is_rtrancl)\n ultimately have \"w\\D\" using D_closed_vE_rtrancl by auto\n with \\w\\last p\\ p_not_D have False\n by (metis IntI Misc.last_in_set Sup_inf_eq_bot_iff assms(2) \n bex_empty path_prepend.hyps(2))\n thus ?thesis ..\n qed\n then obtain i where \"ip!i\"\n by (metis UnionE in_set_conv_nth)\n have \"i=length p - 1\"\n proof (rule ccontr)\n assume \"i\\length p - 1\"\n with \\i have \"i < length p - 1\" by simp\n with vE_no_back[of i \"length p - 1\"] \\i \n have \"lvE \\ last p \\ p!i = {}\"\n by (simp add: last_conv_nth)\n with \\(u,v)\\lvE\\ \\u\\last p\\ \\v\\p!i\\ show False by auto\n qed\n with \\v\\p!i\\ have \"v\\last p\" by (simp add: last_conv_nth)\n with path_prepend.IH \\w\\last p\\ \\u\\last p\\ show ?case by auto\n qed simp\n\n lemma loop_in_lastnode:\n assumes P: \"path lvE u q u\"\n assumes [simp]: \"p\\[]\"\n assumes ND: \"set q \\ last p \\ {}\"\n shows \"u\\last p\" and \"set q \\ last p\"\n \\ \\A loop that touches the last node is completely inside the last node\\\n proof -\n from ND obtain v where \"v\\set q\" \"v\\last p\" by auto\n then obtain q1 q2 where [simp]: \"q=q1@v#q2\" \n by (auto simp: in_set_conv_decomp)\n from P have \"path lvE v (v#q2@q1) v\" \n by (auto simp: path_conc_conv path_cons_conv)\n from path_in_lastnode[OF this \\p\\[]\\ \\v\\last p\\ \\v\\last p\\] \n show \"set q \\ last p\" by simp\n from P show \"u\\last p\" \n apply (cases q, simp)\n \n apply simp\n using \\set q \\ last p\\\n apply (auto simp: path_cons_conv)\n done\n qed\n\n\n lemma no_D_p_edges: \"E \\ D \\ \\(set p) = {}\"\n using D_closed p_not_D by auto\n\n lemma idx_of_props:\n assumes ON_STACK: \"v\\\\(set p)\"\n shows \n \"idx_of p v < length p\" and\n \"v \\ p ! idx_of p v\"\n using idx_of_props[OF _ assms] p_disjoint_sym by blast+\n\nend\n\nsubsubsection \\Auxiliary Lemmas Regarding the Operations\\\n\nlemma (in fr_graph) vE_initial[simp]: \"vE [{v0}] {} (E \\ {v0} \\ UNIV) = {}\"\n unfolding vE_def touched_def by auto\n\ncontext invar_loc\nbegin\n lemma vE_push: \"\\ (u,v)\\pE; u\\last p; v\\\\(set p); v\\D \\ \n \\ vE (p @ [{v}]) D ((pE - {(u,v)}) \\ E\\{v}\\UNIV) = insert (u,v) lvE\"\n unfolding vE_def touched_def using pE_E_from_p\n by auto\n\n lemma vE_remove[simp]: \n \"\\p\\[]; (u,v)\\pE\\ \\ vE p D (pE - {(u,v)}) = insert (u,v) lvE\"\n unfolding vE_def touched_def using pE_E_from_p by blast\n\n lemma vE_pop[simp]: \"p\\[] \\ vE (butlast p) (last p \\ D) pE = lvE\"\n unfolding vE_def touched_def \n by (cases p rule: rev_cases) auto\n\n\n lemma pE_fin: \"p=[] \\ pE={}\"\n using pE_by_vE by auto\n\n lemma (in invar_loc) lastp_un_D_closed:\n assumes NE: \"p \\ []\"\n assumes NO': \"pE \\ (last p \\ UNIV) = {}\"\n shows \"E``(last p \\ D) \\ (last p \\ D)\"\n \\ \\On pop, the popped CNode and D are closed under transitions\\\n proof (intro subsetI, elim ImageE)\n from NO' have NO: \"(E - lvE) \\ (last p \\ UNIV) = {}\"\n by (simp add: pick_pending[OF NE])\n\n let ?i = \"length p - 1\"\n from NE have [simp]: \"last p = p!?i\" by (metis last_conv_nth) \n \n fix u v\n assume E: \"(u,v)\\E\"\n assume UI: \"u\\last p \\ D\" hence \"u\\p!?i \\ D\" by simp\n \n {\n assume \"u\\last p\" \"v\\last p\" \n moreover from E NO \\u\\last p\\ have \"(u,v)\\lvE\" by auto\n ultimately have \"v\\D \\ v\\\\(set p)\" \n using vE_touched unfolding touched_def by auto\n moreover {\n assume \"v\\\\(set p)\"\n then obtain j where V: \"jp!j\" \n by (metis UnionE in_set_conv_nth)\n with \\v\\last p\\ have \"jj _] \\(u,v)\\lvE\\ V \\u\\last p\\ have False by auto\n } ultimately have \"v\\D\" by blast\n } with E UI D_closed show \"v\\last p \\ D\" by auto\n qed\n\n\n\nend\n\n\nsubsubsection \\Preservation of Invariant by Operations\\\n\ncontext fr_graph\nbegin\n lemma (in outer_invar_loc) invar_initial_aux: \n assumes \"v0\\it - D\"\n shows \"invar v0 D (initial v0 D)\"\n unfolding invar_def initial_def\n apply simp\n apply unfold_locales\n apply simp_all\n using assms it_initial apply auto []\n using D_reachable it_initial assms apply auto []\n using D_closed apply auto []\n using assms apply auto []\n done\n\n lemma invar_initial: \n \"\\outer_invar it D0; v0\\it; v0\\D0\\ \\ invar v0 D0 (initial v0 D0)\"\n unfolding outer_invar_def\n apply (drule outer_invar_loc.invar_initial_aux) \n by auto\n\n lemma outer_invar_initial[simp, intro!]: \"outer_invar V0 {}\"\n unfolding outer_invar_def\n apply unfold_locales\n by auto\n\n lemma invar_pop:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes NO': \"pE \\ (last p \\ UNIV) = {}\"\n shows \"invar v0 D0 (pop (p,D,pE))\"\n unfolding invar_def pop_def\n apply simp\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp\n\n have [simp]: \"set p = insert (last p) (set (butlast p))\" \n using NE by (cases p rule: rev_cases) auto\n\n from p_disjoint have lp_dj_blp: \"last p \\ \\(set (butlast p)) = {}\"\n apply (cases p rule: rev_cases)\n apply simp\n apply (fastforce simp: in_set_conv_nth nth_append)\n done\n\n {\n fix i\n assume A: \"Suc i < length (butlast p)\"\n hence A': \"Suc i < length p\" by auto\n\n from nth_butlast[of i p] A have [simp]: \"butlast p ! i = p ! i\" by auto\n from nth_butlast[of \"Suc i\" p] A \n have [simp]: \"butlast p ! Suc i = p ! Suc i\" by auto\n\n from p_connected[OF A'] \n have \"butlast p ! i \\ butlast p ! Suc i \\ (E - pE) \\ {}\"\n by simp\n } note AUX_p_connected = this\n\n (*have [simp]: \"(E \\ (last p \\ D \\ \\set (butlast p)) \\ UNIV - pE) = vE\"\n unfolding vE_def touched_def by auto*)\n\n show \"invar_loc G v0 D0 (butlast p) (last p \\ D) pE\"\n apply unfold_locales\n \n unfolding vE_pop[OF NE]\n\n apply simp\n\n using D_incr apply auto []\n\n using pE_E_from_p NO' apply auto []\n \n using E_from_p_touched apply (auto simp: touched_def) []\n \n using D_reachable p_reachable NE apply auto []\n\n apply (rule AUX_p_connected, assumption+) []\n\n using p_disjoint apply (simp add: nth_butlast)\n\n using p_sc apply simp\n\n using root_v0 apply (cases p rule: rev_cases) apply auto [2]\n\n using root_v0 p_empty_v0 apply (cases p rule: rev_cases) apply auto [2]\n\n apply (rule lastp_un_D_closed, insert NO', auto) []\n\n using vE_no_back apply (auto simp: nth_butlast) []\n\n using p_not_D lp_dj_blp apply auto []\n done\n qed\n\n thm invar_pop[of v_0 D_0, no_vars]\n\n lemma invar_collapse:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes E: \"(u,v)\\pE\" and \"u\\last p\"\n assumes BACK: \"v\\\\(set p)\"\n defines \"i \\ idx_of p v\"\n defines \"p' \\ collapse_aux p i\"\n shows \"invar v0 D0 (collapse v (p,D,pE - {(u,v)}))\"\n unfolding invar_def collapse_def\n apply simp\n unfolding i_def[symmetric] p'_def[symmetric]\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp\n\n let ?thesis=\"invar_loc G v0 D0 p' D (pE - {(u,v)})\"\n\n have SETP'[simp]: \"\\(set p') = \\(set p)\" unfolding p'_def by simp\n\n have IL: \"i < length p\" and VMEM: \"v\\p!i\" \n using idx_of_props[OF BACK] unfolding i_def by auto\n\n have [simp]: \"length p' = Suc i\" \n unfolding p'_def collapse_aux_def using IL by auto\n\n have P'_IDX_SS: \"\\j p'!j\"\n unfolding p'_def collapse_aux_def using IL \n by (auto simp add: nth_append path_seg_drop)\n\n from \\u\\last p\\ have \"u\\p!(length p - 1)\" by (auto simp: last_conv_nth)\n\n have defs_fold: \n \"vE p' D (pE - {(u,v)}) = insert (u,v) lvE\" \n \"touched p' D = ltouched\"\n by (simp_all add: p'_def E)\n\n {\n fix j\n assume A: \"Suc j < length p'\" \n hence \"Suc j < length p\" using IL by simp\n from p_connected[OF this] have \"p!j \\ p!Suc j \\ (E-pE) \\ {}\" .\n moreover from P'_IDX_SS A have \"p!j\\p'!j\" and \"p!Suc j \\ p'!Suc j\"\n by auto\n ultimately have \"p' ! j \\ p' ! Suc j \\ (E - (pE - {(u, v)})) \\ {}\" \n by blast\n } note AUX_p_connected = this\n\n have P_IDX_EQ[simp]: \"\\j. j < i \\ p'!j = p!j\"\n unfolding p'_def collapse_aux_def using IL \n by (auto simp: nth_append)\n\n have P'_LAST[simp]: \"p'!i = path_seg p i (length p)\" (is \"_ = ?last_cnode\")\n unfolding p'_def collapse_aux_def using IL \n by (auto simp: nth_append path_seg_drop)\n\n {\n fix j k\n assume A: \"j < k\" \"k < length p'\" \n have \"p' ! j \\ p' ! k = {}\"\n proof (safe, simp)\n fix v\n assume \"v\\p'!j\" and \"v\\p'!k\"\n with A have \"v\\p!j\" by simp\n show False proof (cases)\n assume \"k=i\"\n with \\v\\p'!k\\ obtain k' where \"v\\p!k'\" \"i\\k'\" \"k' p ! k' = {}\"\n using A by (auto intro!: p_disjoint)\n with \\v\\p!j\\ \\v\\p!k'\\ show False by auto\n next\n assume \"k\\i\" with A have \"kj this] \n also have \"p!j = p'!j\" using \\j \\k by simp\n also have \"p!k = p'!k\" using \\k by simp\n finally show False using \\v\\p'!j\\ \\v\\p'!k\\ by auto\n qed\n qed\n } note AUX_p_disjoint = this\n\n {\n fix U\n assume A: \"U\\set p'\"\n then obtain j where \"j U \\ (insert (u, v) lvE \\ U \\ U)\\<^sup>*\" \n proof cases\n assume [simp]: \"j=i\"\n show ?thesis proof (clarsimp)\n fix x y\n assume \"x\\path_seg p i (length p)\" \"y\\path_seg p i (length p)\"\n then obtain ix iy where \n IX: \"x\\p!ix\" \"i\\ix\" \"ixp!iy\" \"i\\iy\" \"iy ?last_cnode\"\n by (subst path_seg_ss_eq) auto\n\n from IY have SS2: \"path_seg p i (Suc iy) \\ ?last_cnode\"\n by (subst path_seg_ss_eq) auto\n\n let ?rE = \"\\R. (lvE \\ R\\R)\"\n let ?E = \"(insert (u,v) lvE \\ ?last_cnode \\ ?last_cnode)\"\n\n from pathI[OF \\x\\p!ix\\ \\u\\p!(length p - 1)\\] have\n \"(x,u)\\(?rE (path_seg p ix (Suc (length p - 1))))\\<^sup>*\" using IX by auto\n hence \"(x,u)\\?E\\<^sup>*\" \n apply (rule rtrancl_mono_mp[rotated]) \n using SS1\n by auto\n\n also have \"(u,v)\\?E\" using \\i\n apply (clarsimp)\n apply (intro conjI)\n apply (rule rev_subsetD[OF \\u\\p!(length p - 1)\\])\n apply (simp)\n apply (rule rev_subsetD[OF VMEM])\n apply (simp)\n done\n also \n from pathI[OF \\v\\p!i\\ \\y\\p!iy\\] have\n \"(v,y)\\(?rE (path_seg p i (Suc iy)))\\<^sup>*\" using IY by auto\n hence \"(v,y)\\?E\\<^sup>*\"\n apply (rule rtrancl_mono_mp[rotated]) \n using SS2\n by auto\n finally show \"(x,y)\\?E\\<^sup>*\" .\n qed\n next\n assume \"j\\i\"\n with \\j have [simp]: \"ji have \"p!j\\set p\"\n by (metis Suc_lessD in_set_conv_nth less_trans_Suc) \n\n thus ?thesis using p_sc[of U] \\p!j\\set p\\\n apply (clarsimp)\n apply (subgoal_tac \"(a,b)\\(lvE \\ p ! j \\ p ! j)\\<^sup>*\")\n apply (erule rtrancl_mono_mp[rotated])\n apply auto\n done\n qed\n } note AUX_p_sc = this\n\n { fix j k\n assume A: \"j p' ! k \\ p' ! j = {}\"\n proof -\n have \"{(u,v)} \\ p' ! k \\ p' ! j = {}\" \n apply auto\n by (metis IL P_IDX_EQ Suc_lessD VMEM \\j < i\\ \n less_irrefl_nat less_trans_Suc p_disjoint_sym)\n moreover have \"lvE \\ p' ! k \\ p' ! j = {}\" \n proof (cases \"ki by auto\n next\n case False with A have [simp]: \"k=i\" by simp\n show ?thesis proof (rule disjointI, clarsimp simp: \\j)\n fix x y\n assume B: \"(x,y)\\lvE\" \"x\\path_seg p i (length p)\" \"y\\p!j\"\n then obtain ix where \"x\\p!ix\" \"i\\ix\" \"ix[]\"\n assumes E: \"(u,v)\\pE\" and UIL: \"u\\last p\"\n assumes VNE: \"v\\\\(set p)\" \"v\\D\"\n shows \"invar v0 D0 (push v (p,D,pE - {(u,v)}))\"\n unfolding invar_def push_def\n apply simp\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp\n\n let ?thesis \n = \"invar_loc G v0 D0 (p @ [{v}]) D (pE - {(u, v)} \\ E \\ {v} \\ UNIV)\"\n\n note defs_fold = vE_push[OF E UIL VNE] touched_push\n\n {\n fix i\n assume SILL: \"Suc i < length (p @ [{v}])\"\n have \"(p @ [{v}]) ! i \\ (p @ [{v}]) ! Suc i \n \\ (E - (pE - {(u, v)} \\ E \\ {v} \\ UNIV)) \\ {}\"\n proof (cases \"i = length p - 1\")\n case True thus ?thesis using SILL E pE_E_from_p UIL VNE\n by (simp add: nth_append last_conv_nth) fast\n next\n case False\n with SILL have SILL': \"Suc i < length p\" by simp\n \n with SILL' VNE have X1: \"v\\p!i\" \"v\\p!Suc i\" by auto\n \n from p_connected[OF SILL'] obtain a b where \n \"a\\p!i\" \"b\\p!Suc i\" \"(a,b)\\E\" \"(a,b)\\pE\" \n by auto\n with X1 have \"a\\v\" \"b\\v\" by auto\n with \\(a,b)\\E\\ \\(a,b)\\pE\\ have \"(a,b)\\(E - (pE - {(u, v)} \\ E \\ {v} \\ UNIV))\"\n by auto\n with \\a\\p!i\\ \\b\\p!Suc i\\\n show ?thesis using SILL'\n by (simp add: nth_append; blast) \n qed\n } note AUX_p_connected = this\n\n {\n fix U\n assume A: \"U \\ set (p @ [{v}])\"\n have \"U \\ U \\ (insert (u, v) lvE \\ U \\ U)\\<^sup>*\"\n proof cases\n assume \"U\\set p\"\n with p_sc have \"U\\U \\ (lvE \\ U\\U)\\<^sup>*\" .\n thus ?thesis\n by (metis (lifting, no_types) Int_insert_left_if0 Int_insert_left_if1 \n in_mono insert_subset rtrancl_mono_mp subsetI)\n next\n assume \"U\\set p\" with A have \"U={v}\" by simp\n thus ?thesis by auto\n qed\n } note AUX_p_sc = this\n\n {\n fix i j\n assume A: \"i < j\" \"j < length (p @ [{v}])\"\n have \"insert (u, v) lvE \\ (p @ [{v}]) ! j \\ (p @ [{v}]) ! i = {}\"\n proof (cases \"j=length p\")\n case False with A have \"ji this VNE show ?thesis \n by (auto simp add: nth_append)\n next\n from p_not_D A have PDDJ: \"p!i \\ D = {}\" \n by (auto simp: Sup_inf_eq_bot_iff)\n case True thus ?thesis\n using A apply (simp add: nth_append)\n apply (rule conjI)\n using UIL A p_disjoint_sym\n apply (metis Misc.last_in_set NE UnionI VNE(1))\n\n using vE_touched VNE PDDJ apply (auto simp: touched_def) []\n done\n qed\n } note AUX_vE_no_back = this\n \n show ?thesis\n apply unfold_locales\n unfolding defs_fold\n\n apply simp\n\n using D_incr apply auto []\n\n using pE_E_from_p apply auto []\n\n using E_from_p_touched VNE apply (auto simp: touched_def) []\n\n apply (rule D_reachable)\n\n apply (rule AUX_p_connected, assumption+) []\n\n using p_disjoint \\v\\\\(set p)\\ apply (auto simp: nth_append) []\n\n apply (rule AUX_p_sc, assumption+) []\n\n using root_v0 apply simp\n\n apply simp\n\n apply (rule D_closed)\n\n apply (rule AUX_vE_no_back, assumption+) []\n\n using p_not_D VNE apply auto []\n done\n qed\n\n lemma invar_skip:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes E: \"(u,v)\\pE\" and UIL: \"u\\last p\"\n assumes VNP: \"v\\\\(set p)\" and VD: \"v\\D\"\n shows \"invar v0 D0 (p,D,pE - {(u, v)})\"\n unfolding invar_def\n apply simp\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp\n let ?thesis = \"invar_loc G v0 D0 p D (pE - {(u, v)})\"\n note defs_fold = vE_remove[OF NE E]\n\n show ?thesis\n apply unfold_locales\n unfolding defs_fold\n \n apply simp\n\n using D_incr apply auto []\n\n using pE_E_from_p apply auto []\n\n using E_from_p_touched VD apply (auto simp: touched_def) []\n\n apply (rule D_reachable)\n\n using p_connected apply auto []\n\n apply (rule p_disjoint, assumption+) []\n\n apply (drule p_sc)\n apply (erule order_trans)\n apply (rule rtrancl_mono)\n apply blast []\n\n apply (rule root_v0, assumption+) []\n\n apply (rule p_empty_v0, assumption+) []\n\n apply (rule D_closed)\n\n using vE_no_back VD p_not_D \n apply clarsimp\n apply (metis Suc_lessD UnionI VNP less_trans_Suc nth_mem)\n\n apply (rule p_not_D)\n done\n qed\n\n\n lemma fin_D_is_reachable: \n \\ \\When inner loop terminates, all nodes reachable from start node are\n finished\\\n assumes INV: \"invar v0 D0 ([], D, pE)\"\n shows \"D \\ E\\<^sup>*``{v0}\"\n proof -\n from INV interpret invar_loc G v0 D0 \"[]\" D pE unfolding invar_def by auto\n\n from p_empty_v0 rtrancl_reachable_induct[OF order_refl D_closed] D_reachable\n show ?thesis by auto\n qed\n\n lemma fin_reachable_path: \n \\ \\When inner loop terminates, nodes reachable from start node are\n reachable over visited edges\\\n assumes INV: \"invar v0 D0 ([], D, pE)\"\n assumes UR: \"u\\E\\<^sup>*``{v0}\"\n shows \"path (vE [] D pE) u q v \\ path E u q v\"\n proof -\n from INV interpret invar_loc G v0 D0 \"[]\" D pE unfolding invar_def by auto\n \n show ?thesis\n proof\n assume \"path lvE u q v\"\n thus \"path E u q v\" using path_mono[OF lvE_ss_E] by blast\n next\n assume \"path E u q v\"\n thus \"path lvE u q v\" using UR\n proof induction\n case (path_prepend u v p w)\n with fin_D_is_reachable[OF INV] have \"u\\D\" by auto\n with D_closed \\(u,v)\\E\\ have \"v\\D\" by auto\n from path_prepend.prems path_prepend.hyps have \"v\\E\\<^sup>*``{v0}\" by auto\n with path_prepend.IH fin_D_is_reachable[OF INV] have \"path lvE v p w\" \n by simp\n moreover from \\u\\D\\ \\v\\D\\ \\(u,v)\\E\\ D_vis have \"(u,v)\\lvE\" by auto\n ultimately show ?case by (auto simp: path_cons_conv)\n qed simp\n qed\n qed\n\n lemma invar_outer_newnode: \n assumes A: \"v0\\D0\" \"v0\\it\" \n assumes OINV: \"outer_invar it D0\"\n assumes INV: \"invar v0 D0 ([],D',pE)\"\n shows \"outer_invar (it-{v0}) D'\"\n proof -\n from OINV interpret outer_invar_loc G it D0 unfolding outer_invar_def .\n from INV interpret inv: invar_loc G v0 D0 \"[]\" D' pE \n unfolding invar_def by simp\n \n from fin_D_is_reachable[OF INV] have [simp]: \"v0\\D'\" by auto\n\n show ?thesis\n unfolding outer_invar_def\n apply unfold_locales\n using it_initial apply auto []\n using it_done inv.D_incr apply auto []\n using inv.D_reachable apply assumption\n using inv.D_closed apply assumption\n done\n qed\n\n lemma invar_outer_Dnode:\n assumes A: \"v0\\D0\" \"v0\\it\" \n assumes OINV: \"outer_invar it D0\"\n shows \"outer_invar (it-{v0}) D0\"\n proof -\n from OINV interpret outer_invar_loc G it D0 unfolding outer_invar_def .\n \n show ?thesis\n unfolding outer_invar_def\n apply unfold_locales\n using it_initial apply auto []\n using it_done A apply auto []\n using D_reachable apply assumption\n using D_closed apply assumption\n done\n qed\n\n lemma pE_fin': \"invar x \\ ([], D, pE) \\ pE={}\"\n unfolding invar_def by (simp add: invar_loc.pE_fin)\n\nend\n\nsubsubsection \\Termination\\\n\ncontext invar_loc \nbegin\n lemma unproc_finite[simp, intro!]: \"finite (unproc_edges v0 p D pE)\"\n \\ \\The set of unprocessed edges is finite\\\n proof -\n have \"unproc_edges v0 p D pE \\ E\\<^sup>*``{v0} \\ E\\<^sup>*``{v0}\"\n unfolding unproc_edges_def \n using pE_reachable\n by auto\n thus ?thesis\n by (rule finite_subset) simp\n qed\n\n lemma unproc_decreasing: \n \\ \\As effect of selecting a pending edge, the set of unprocessed edges\n decreases\\\n assumes [simp]: \"p\\[]\" and A: \"(u,v)\\pE\" \"u\\last p\"\n shows \"unproc_edges v0 p D (pE-{(u,v)}) \\ unproc_edges v0 p D pE\"\n using A unfolding unproc_edges_def\n by fastforce\nend\n\ncontext fr_graph \nbegin\n\n lemma abs_wf_pop:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes NO: \"pE \\ last aba \\ UNIV = {}\"\n shows \"(pop (p,D,pE), (p, D, pE)) \\ abs_wf_rel v0\"\n unfolding pop_def\n apply simp\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp \n let ?thesis = \"((butlast p, last p \\ D, pE), p, D, pE) \\ abs_wf_rel v0\"\n have \"unproc_edges v0 (butlast p) (last p \\ D) pE = unproc_edges v0 p D pE\"\n unfolding unproc_edges_def\n apply (cases p rule: rev_cases, simp)\n apply auto\n done\n thus ?thesis\n by (auto simp: abs_wf_rel_def)\n qed\n\n lemma abs_wf_collapse:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes E: \"(u,v)\\pE\" \"u\\last p\"\n shows \"(collapse v (p,D,pE-{(u,v)}), (p, D, pE))\\ abs_wf_rel v0\"\n unfolding collapse_def\n apply simp\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp \n define i where \"i = idx_of p v\"\n let ?thesis \n = \"((collapse_aux p i, D, pE-{(u,v)}), (p, D, pE)) \\ abs_wf_rel v0\"\n\n have \"unproc_edges v0 (collapse_aux p i) D (pE-{(u,v)}) \n = unproc_edges v0 p D (pE-{(u,v)})\"\n unfolding unproc_edges_def by (auto)\n also note unproc_decreasing[OF NE E]\n finally show ?thesis\n by (auto simp: abs_wf_rel_def)\n qed\n \n lemma abs_wf_push:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes E: \"(u,v)\\pE\" \"u\\last p\" and A: \"v\\D\" \"v\\\\(set p)\"\n shows \"(push v (p,D,pE-{(u,v)}), (p, D, pE)) \\ abs_wf_rel v0\"\n unfolding push_def\n apply simp\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp \n let ?thesis \n = \"((p@[{v}], D, pE-{(u,v)} \\ E\\{v}\\UNIV), (p, D, pE)) \\ abs_wf_rel v0\"\n\n have \"unproc_edges v0 (p@[{v}]) D (pE-{(u,v)} \\ E\\{v}\\UNIV) \n = unproc_edges v0 p D (pE-{(u,v)})\"\n unfolding unproc_edges_def\n using E A pE_reachable\n by auto\n also note unproc_decreasing[OF NE E]\n finally show ?thesis\n by (auto simp: abs_wf_rel_def)\n qed\n\n lemma abs_wf_skip:\n assumes INV: \"invar v0 D0 (p,D,pE)\"\n assumes NE[simp]: \"p\\[]\"\n assumes E: \"(u,v)\\pE\" \"u\\last p\"\n shows \"((p, D, pE-{(u,v)}), (p, D, pE)) \\ abs_wf_rel v0\"\n proof -\n from INV interpret invar_loc G v0 D0 p D pE unfolding invar_def by simp \n from unproc_decreasing[OF NE E] show ?thesis\n by (auto simp: abs_wf_rel_def)\n qed\nend\n\nsubsubsection \\Main Correctness Theorem\\\n\ncontext fr_graph \nbegin\n lemmas invar_preserve = \n invar_initial\n invar_pop invar_push invar_skip invar_collapse \n abs_wf_pop abs_wf_collapse abs_wf_push abs_wf_skip \n outer_invar_initial invar_outer_newnode invar_outer_Dnode\n\n text \\The main correctness theorem for the dummy-algorithm just states that\n it satisfies the invariant when finished, and the path is empty.\n\\\n \n\n show ?thesis\n unfolding skeleton_def select_edge_def select_def\n apply (refine_vcg WHILEIT_rule[OF abs_wf_rel_wf])\n apply (vc_solve solve: invar_preserve simp: pE_fin' finite_V0)\n apply auto\n done\n qed\n\n text \\Short proof, as presented in the paper\\\n context \n notes [refine] = refine_vcg \n begin\n theorem \"skeleton \\ SPEC (\\D. outer_invar {} D)\"\n unfolding skeleton_def select_edge_def select_def\n by (refine_vcg WHILEIT_rule[OF abs_wf_rel_wf])\n (auto intro: invar_preserve simp: pE_fin' finite_V0)\n end\n\nend\n\nsubsection \"Consequences of Invariant when Finished\"\ncontext fr_graph\nbegin\n lemma fin_outer_D_is_reachable:\n \\ \\When outer loop terminates, exactly the reachable nodes are finished\\\n assumes INV: \"outer_invar {} D\"\n shows \"D = E\\<^sup>*``V0\"\n proof -\n from INV interpret outer_invar_loc G \"{}\" D unfolding outer_invar_def by auto\n\n from it_done rtrancl_reachable_induct[OF order_refl D_closed] D_reachable\n show ?thesis by auto\n qed\n\nend\n\n\nsection \\Refinement to Gabow's Data Structure\\text_raw\\\\label{sec:algo-ds}\\\n\ntext \\\n The implementation due to Gabow \\cite{Gabow2000} represents a path as\n a stack \\S\\ of single nodes, and a stack \\B\\ that contains the\n boundaries of the collapsed segments. Moreover, a map \\I\\ maps nodes\n to their stack indices.\n\n As we use a tail-recursive formulation, we use another stack \n \\P :: (nat \\ 'v set) list\\ to represent the pending edges. The\n entries in \\P\\ are sorted by ascending first component,\n and \\P\\ only contains entries with non-empty second component. \n An entry \\(i,l)\\ means that the edges from the node at \n \\S[i]\\ to the nodes stored in \\l\\ are pending.\n\\\n\nsubsection \\Preliminaries\\\nprimrec find_max_nat :: \"nat \\ (nat\\bool) \\ nat\" \n \\ \\Find the maximum number below an upper bound for which a predicate holds\\\n where\n \"find_max_nat 0 _ = 0\"\n| \"find_max_nat (Suc n) P = (if (P n) then n else find_max_nat n P)\"\n\nlemma find_max_nat_correct: \n \"\\P 0; 0 \\ find_max_nat u P = Max {i. i P i}\"\n apply (induction u)\n apply auto\n\n apply (rule Max_eqI[THEN sym])\n apply auto [3]\n \n apply (case_tac u)\n apply simp\n apply clarsimp\n by (metis less_SucI less_antisym)\n\nlemma find_max_nat_param[param]:\n assumes \"(n,n')\\nat_rel\"\n assumes \"\\j j'. \\(j,j')\\nat_rel; j' \\ (P j,P' j')\\bool_rel\"\n shows \"(find_max_nat n P,find_max_nat n' P') \\ nat_rel\"\n using assms\n by (induction n arbitrary: n') auto\n\ncontext begin interpretation autoref_syn .\n lemma find_max_nat_autoref[autoref_rules]:\n assumes \"(n,n')\\nat_rel\"\n assumes \"\\j j'. \\(j,j')\\nat_rel; j' \\ (P j,P'$j')\\bool_rel\"\n shows \"(find_max_nat n P,\n (OP find_max_nat ::: nat_rel \\ (nat_rel\\bool_rel) \\ nat_rel) $n'$P'\n ) \\ nat_rel\"\n using find_max_nat_param[OF assms]\n by simp\n\nend\n\nsubsection \\Gabow's Datastructure\\\n\nsubsubsection \\Definition and Invariant\\\ndatatype node_state = STACK nat | DONE\n\ntype_synonym 'v oGS = \"'v \\ node_state\"\n\ndefinition oGS_\\ :: \"'v oGS \\ 'v set\" where \"oGS_\\ I \\ {v. I v = Some DONE}\"\n\nlocale oGS_invar = \n fixes I :: \"'v oGS\"\n assumes I_no_stack: \"I v \\ Some (STACK j)\"\n\n\ntype_synonym 'a GS \n = \"'a list \\ nat list \\ ('a \\ node_state) \\ (nat \\ 'a set) list\"\nlocale GS = \n fixes SBIP :: \"'a GS\"\nbegin\n definition \"S \\ (\\(S,B,I,P). S) SBIP\"\n definition \"B \\ (\\(S,B,I,P). B) SBIP\"\n definition \"I \\ (\\(S,B,I,P). I) SBIP\"\n definition \"P \\ (\\(S,B,I,P). P) SBIP\"\n\n definition seg_start :: \"nat \\ nat\" \\ \\Start index of segment, inclusive\\\n where \"seg_start i \\ B!i\" \n\n definition seg_end :: \"nat \\ nat\" \\ \\End index of segment, exclusive\\\n where \"seg_end i \\ if i+1 = length B then length S else B!(i+1)\"\n\n definition seg :: \"nat \\ 'a set\" \\ \\Collapsed set at index\\\n where \"seg i \\ {S!j | j. seg_start i \\ j \\ j < seg_end i }\"\n\n definition \"p_\\ \\ map seg [0.. \\Collapsed path\\\n\n definition \"D_\\ \\ {v. I v = Some DONE}\" \\ \\Done nodes\\\n \n definition \"pE_\\ \\ { (u,v) . \\j I. (j,I)\\set P \\ u = S!j \\ v\\I }\" \n \\ \\Pending edges\\\n\n definition \"\\ \\ (p_\\,D_\\,pE_\\)\" \\ \\Abstract state\\\n\nend\n\nlemma GS_sel_simps[simp]:\n \"GS.S (S,B,I,P) = S\"\n \"GS.B (S,B,I,P) = B\"\n \"GS.I (S,B,I,P) = I\"\n \"GS.P (S,B,I,P) = P\"\n unfolding GS.S_def GS.B_def GS.I_def GS.P_def\n by auto\n\ncontext GS begin\n lemma seg_start_indep[simp]: \"GS.seg_start (S',B,I',P') = seg_start\" \n unfolding GS.seg_start_def[abs_def] by (auto)\n lemma seg_end_indep[simp]: \"GS.seg_end (S,B,I',P') = seg_end\" \n unfolding GS.seg_end_def[abs_def] by auto\n lemma seg_indep[simp]: \"GS.seg (S,B,I',P') = seg\" \n unfolding GS.seg_def[abs_def] by auto\n lemma p_\\_indep[simp]: \"GS.p_\\ (S,B,I',P') = p_\\\"\n unfolding GS.p_\\_def by auto\n\n lemma D_\\_indep[simp]: \"GS.D_\\ (S',B',I,P') = D_\\\"\n unfolding GS.D_\\_def by auto\n\n lemma pE_\\_indep[simp]: \"GS.pE_\\ (S,B',I',P) = pE_\\\" \n unfolding GS.pE_\\_def by auto\n\n definition find_seg \\ \\Abs-path index for stack index\\\n where \"find_seg j \\ Max {i. i B!i\\j}\"\n\n definition S_idx_of \\ \\Stack index for node\\\n where \"S_idx_of v \\ case I v of Some (STACK i) \\ i\"\n\nend\n\nlocale GS_invar = GS +\n assumes B_in_bound: \"set B \\ {0..[] \\ B\\[] \\ B!0=0\"\n assumes S_distinct: \"distinct S\"\n\n assumes I_consistent: \"(I v = Some (STACK j)) \\ (j v = S!j)\"\n \n assumes P_sorted: \"sorted (map fst P)\"\n assumes P_distinct: \"distinct (map fst P)\"\n assumes P_bound: \"set P \\ {0..Collect ((\\) {})\"\nbegin\n lemma locale_this: \"GS_invar SBIP\" by unfold_locales\n\nend\n\ndefinition \"oGS_rel \\ br oGS_\\ oGS_invar\"\nlemma oGS_rel_sv[intro!,simp,relator_props]: \"single_valued oGS_rel\"\n unfolding oGS_rel_def by auto\n\ndefinition \"GS_rel \\ br GS.\\ GS_invar\"\nlemma GS_rel_sv[intro!,simp,relator_props]: \"single_valued GS_rel\"\n unfolding GS_rel_def by auto\n\ncontext GS_invar\nbegin\n lemma empty_eq: \"S=[] \\ B=[]\"\n using B_in_bound B0 by auto\n\n lemma B_in_bound': \"i B!i < length S\"\n using B_in_bound nth_mem by fastforce\n\n lemma seg_start_bound:\n assumes A: \"i length S\"\n proof (cases \"i+1=length B\")\n case True thus ?thesis by (simp add: seg_end_def)\n next\n case False with A have \"i+1 seg_start i < seg_end i\"\n unfolding seg_start_def seg_end_def\n using B_in_bound' distinct_sorted_mono[OF B_sorted B_distinct]\n by auto\n\n lemma seg_end_less_start: \"\\i \\ seg_end i \\ seg_start j\"\n unfolding seg_start_def seg_end_def\n by (auto simp: distinct_sorted_mono_iff[OF B_distinct B_sorted])\n\n lemma find_seg_bounds:\n assumes A: \"j j\" \n and \"j < seg_end (find_seg j)\" \n and \"find_seg j < length B\"\n proof -\n let ?M = \"{i. i B!i\\j}\"\n from A have [simp]: \"B\\[]\" using empty_eq by (cases S) auto\n have NE: \"?M\\{}\" using A B0 by (cases B) auto\n\n have F: \"finite ?M\" by auto\n \n from Max_in[OF F NE]\n have LEN: \"find_seg j < length B\" and LB: \"B!find_seg j \\ j\"\n unfolding find_seg_def\n by auto\n\n thus \"find_seg j < length B\" by -\n \n from LB show LB': \"seg_start (find_seg j) \\ j\"\n unfolding seg_start_def by simp\n\n moreover show UB': \"j < seg_end (find_seg j)\"\n unfolding seg_end_def \n proof (split if_split, intro impI conjI)\n show \"j length B\" \n with LEN have P1: \"find_seg j + 1 < length B\" by simp\n\n show \"j < B ! (find_seg j + 1)\"\n proof (rule ccontr, simp only: linorder_not_less)\n assume P2: \"B ! (find_seg j + 1) \\ j\"\n with P1 Max_ge[OF F, of \"find_seg j + 1\", folded find_seg_def]\n show False by simp\n qed\n qed\n qed\n \n lemma find_seg_correct:\n assumes A: \"j seg (find_seg j)\" and \"find_seg j < length B\"\n using find_seg_bounds[OF A]\n unfolding seg_def by auto\n\n lemma set_p_\\_is_set_S:\n \"\\(set p_\\) = set S\"\n apply rule\n unfolding p_\\_def seg_def[abs_def]\n using seg_end_bound apply fastforce []\n\n apply (auto simp: in_set_conv_nth)\n\n using find_seg_bounds\n apply (fastforce simp: in_set_conv_nth)\n done\n\n lemma S_idx_uniq: \n \"\\i \\ S!i=S!j \\ i=j\"\n using S_distinct\n by (simp add: nth_eq_iff_index_eq)\n\n lemma S_idx_of_correct: \n assumes A: \"v\\\\(set p_\\)\"\n shows \"S_idx_of v < length S\" and \"S!S_idx_of v = v\"\n proof -\n from A have \"v\\set S\" by (simp add: set_p_\\_is_set_S)\n then obtain j where G1: \"j_disjoint_sym: \n shows \"\\i j v. i \\ j \\ v\\p_\\!i \\ v\\p_\\!j \\ i=j\"\n proof (intro allI impI, elim conjE)\n fix i j v\n assume A: \"i < length p_\\\" \"j < length p_\\\" \"v \\ p_\\ ! i\" \"v \\ p_\\ ! j\"\n from A have LI: \"i_def)\n\n from A have B1: \"seg_start j < seg_end i\" and B2: \"seg_start i < seg_end j\"\n unfolding p_\\_def seg_def[abs_def]\n apply clarsimp_all\n apply (subst (asm) S_idx_uniq)\n apply (metis dual_order.strict_trans1 seg_end_bound)\n apply (metis dual_order.strict_trans1 seg_end_bound)\n apply simp\n apply (subst (asm) S_idx_uniq)\n apply (metis dual_order.strict_trans1 seg_end_bound)\n apply (metis dual_order.strict_trans1 seg_end_bound)\n apply simp\n done\n\n from B1 have B1: \"(B!j < B!Suc i \\ Suc i < length B) \\ i=length B - 1\"\n using LI unfolding seg_start_def seg_end_def by (auto split: if_split_asm)\n\n from B2 have B2: \"(B!i < B!Suc j \\ Suc j < length B) \\ j=length B - 1\"\n using LJ unfolding seg_start_def seg_end_def by (auto split: if_split_asm)\n\n from B1 have B1: \"j i=length B - 1\"\n using LI LJ distinct_sorted_strict_mono_iff[OF B_distinct B_sorted]\n by auto\n\n from B2 have B2: \"i j=length B - 1\"\n using LI LJ distinct_sorted_strict_mono_iff[OF B_distinct B_sorted]\n by auto\n\n from B1 B2 show \"i=j\"\n using LI LJ\n by auto\n qed\n\nend\n\n\nsubsection \\Refinement of the Operations\\\n\ndefinition GS_initial_impl :: \"'a oGS \\ 'a \\ 'a set \\ 'a GS\" where\n \"GS_initial_impl I v0 succs \\ (\n [v0],\n [0],\n I(v0\\(STACK 0)),\n if succs={} then [] else [(0,succs)])\"\n\ncontext GS\nbegin\n definition \"push_impl v succs \\ \n let\n _ = stat_newnode ();\n j = length S;\n S = S@[v];\n B = B@[j];\n I = I(v \\ STACK j);\n P = if succs={} then P else P@[(j,succs)]\n in\n (S,B,I,P)\"\n\n \n definition mark_as_done \n where \"\\l u I. mark_as_done l u I \\ do {\n (_,I)\\WHILET \n (\\(l,I). l(l,I). do { ASSERT (l DONE))}) \n (l,I);\n RETURN I\n }\"\n\n definition mark_as_done_abs where\n \"\\l u I. mark_as_done_abs l u I \n \\ (\\v. if v\\{S!j | j. l\\j \\ jllength S\\ \\ mark_as_done l u I \n \\ SPEC (\\r. r = mark_as_done_abs l u I)\"\n unfolding mark_as_done_def mark_as_done_abs_def\n apply (refine_rcg \n WHILET_rule[where \n I=\"\\(l',I'). \n I' = (\\v. if v\\{S!j | j. l\\j \\ j l\\l' \\ l'\\u\"\n and R=\"measure (\\(l',_). u-l')\" \n ]\n refine_vcg)\n \n apply (auto intro!: ext simp: less_Suc_eq)\n done \n\n definition \"pop_impl \\ \n do {\n let lsi = length B - 1;\n ASSERT (lsi mark_as_done (seg_start lsi) (seg_end lsi) I;\n ASSERT (B\\[]);\n let S = take (last B) S;\n ASSERT (B\\[]);\n let B = butlast B;\n RETURN (S,B,I,P)\n }\"\n\n definition \"sel_rem_last \\ \n if P=[] then \n RETURN (None,(S,B,I,P))\n else do {\n let (j,succs) = last P;\n ASSERT (length B - 1 < length B);\n if j \\ seg_start (length B - 1) then do {\n ASSERT (succs\\{});\n v \\ SPEC (\\x. x\\succs);\n let succs = succs - {v};\n ASSERT (P\\[] \\ length P - 1 < length P);\n let P = (if succs={} then butlast P else P[length P - 1 := (j,succs)]);\n RETURN (Some v,(S,B,I,P))\n } else RETURN (None,(S,B,I,P))\n }\" \n\n\n definition \"find_seg_impl j \\ find_max_nat (length B) (\\i. B!i\\j)\"\n\n lemma (in GS_invar) find_seg_impl:\n \"j find_seg_impl j = find_seg j\"\n unfolding find_seg_impl_def\n thm find_max_nat_correct\n apply (subst find_max_nat_correct)\n apply (simp add: B0)\n apply (simp add: B0)\n apply (simp add: find_seg_def)\n done\n\n\n definition \"idx_of_impl v \\ do {\n ASSERT (\\i. I v = Some (STACK i));\n let j = S_idx_of v;\n ASSERT (j \n do { \n i\\idx_of_impl v;\n ASSERT (i+1 \\ length B);\n let B = take (i+1) B;\n RETURN (S,B,I,P)\n }\"\n\nend\n\nlemma (in -) GS_initial_correct: \n assumes REL: \"(I,D)\\oGS_rel\"\n assumes A: \"v0\\D\"\n shows \"GS.\\ (GS_initial_impl I v0 succs) = ([{v0}],D,{v0}\\succs)\" (is ?G1)\n and \"GS_invar (GS_initial_impl I v0 succs)\" (is ?G2)\nproof -\n from REL have [simp]: \"D = oGS_\\ I\" and I: \"oGS_invar I\"\n by (simp_all add: oGS_rel_def br_def)\n\n from I have [simp]: \"\\j v. I v \\ Some (STACK j)\"\n by (simp add: oGS_invar_def)\n\n show ?G1\n unfolding GS.\\_def GS_initial_impl_def\n apply (simp split del: if_split) apply (intro conjI)\n\n unfolding GS.p_\\_def GS.seg_def[abs_def] GS.seg_start_def GS.seg_end_def\n apply (auto) []\n\n using A unfolding GS.D_\\_def apply (auto simp: oGS_\\_def) []\n\n unfolding GS.pE_\\_def apply auto []\n done\n\n show ?G2\n unfolding GS_initial_impl_def\n apply unfold_locales\n apply auto\n done\nqed\n\ncontext GS_invar\nbegin\n lemma push_correct:\n assumes A: \"v\\\\(set p_\\)\" and B: \"v\\D_\\\"\n shows \"GS.\\ (push_impl v succs) = (p_\\@[{v}],D_\\,pE_\\ \\ {v}\\succs)\" \n (is ?G1)\n and \"GS_invar (push_impl v succs)\" (is ?G2)\n proof -\n\n note [simp] = Let_def\n\n have A1: \"GS.D_\\ (push_impl v succs) = D_\\\"\n using B\n by (auto simp: push_impl_def GS.D_\\_def)\n\n have iexI: \"\\a b j P. \\a!j = b!j; P j\\ \\ \\j'. a!j = b!j' \\ P j'\"\n by blast\n\n have A2: \"GS.p_\\ (push_impl v succs) = p_\\ @ [{v}]\"\n unfolding push_impl_def GS.p_\\_def GS.seg_def[abs_def] \n GS.seg_start_def GS.seg_end_def\n apply (clarsimp split del: if_split)\n\n apply clarsimp\n apply safe\n apply (((rule iexI)?, \n (auto \n simp: nth_append nat_in_between_eq \n dest: order.strict_trans[OF _ B_in_bound']\n )) []\n ) +\n done\n\n have iexI2: \"\\j I Q. \\(j,I)\\set P; (j,I)\\set P \\ Q j\\ \\ \\j. Q j\"\n by blast\n\n have A3: \"GS.pE_\\ (push_impl v succs) = pE_\\ \\ {v} \\ succs\"\n unfolding push_impl_def GS.pE_\\_def\n using P_bound\n apply (force simp: nth_append elim!: iexI2)\n done\n\n show ?G1\n unfolding GS.\\_def\n by (simp add: A1 A2 A3)\n\n show ?G2\n apply unfold_locales\n unfolding push_impl_def\n apply simp_all\n\n using B_in_bound B_sorted B_distinct apply (auto simp: sorted_append) [3]\n using B_in_bound B0 apply (cases S) apply (auto simp: nth_append) [2]\n\n using S_distinct A apply (simp add: set_p_\\_is_set_S)\n\n using A I_consistent \n apply (auto simp: nth_append set_p_\\_is_set_S split: if_split_asm) []\n \n using P_sorted P_distinct P_bound apply (auto simp: sorted_append) [3]\n done\n qed\n\n lemma no_last_out_P_aux:\n assumes NE: \"p_\\\\[]\" and NS: \"pE_\\ \\ last p_\\ \\ UNIV = {}\"\n shows \"set P \\ {0.. UNIV\"\n proof -\n {\n fix j I\n assume jII: \"(j,I)\\set P\"\n and JL: \"last B\\j\"\n with P_bound have JU: \"j{}\" by auto\n with JL JU have \"S!j \\ last p_\\\"\n using NE\n unfolding p_\\_def \n apply (auto \n simp: last_map seg_def seg_start_def seg_end_def last_conv_nth) \n done\n moreover from jII have \"{S!j} \\ I \\ pE_\\\" unfolding pE_\\_def\n by auto\n moreover note INE NS\n ultimately have False by blast\n } thus ?thesis by fastforce\n qed\n\n lemma pop_correct:\n assumes NE: \"p_\\\\[]\" and NS: \"pE_\\ \\ last p_\\ \\ UNIV = {}\"\n shows \"pop_impl \n \\ \\GS_rel (SPEC (\\r. r=(butlast p_\\, D_\\ \\ last p_\\, pE_\\)))\"\n proof -\n have iexI: \"\\a b j P. \\a!j = b!j; P j\\ \\ \\j'. a!j = b!j' \\ P j'\"\n by blast\n \n have [simp]: \"\\n. n - Suc 0 \\ n \\ n\\0\" by auto\n\n from NE have BNE: \"B\\[]\"\n unfolding p_\\_def by auto\n\n {\n fix i j\n assume B: \"j last B\"\n by (simp add: last_conv_nth)\n finally have \"j < last B\" .\n hence \"take (last B) S ! j = S ! j\" \n and \"take (B!(length B - Suc 0)) S !j = S!j\"\n by (simp_all add: last_conv_nth BNE)\n } note AUX1=this\n\n {\n fix v j\n have \"(mark_as_done_abs \n (seg_start (length B - Suc 0))\n (seg_end (length B - Suc 0)) I v = Some (STACK j)) \n \\ (j < length S \\ j < last B \\ v = take (last B) S ! j)\"\n apply (simp add: mark_as_done_abs_def)\n apply safe []\n using I_consistent\n apply (clarsimp_all\n simp: seg_start_def seg_end_def last_conv_nth BNE\n simp: S_idx_uniq)\n\n apply (force)\n apply (subst nth_take)\n apply force\n apply force\n done\n } note AUX2 = this\n\n define ci where \"ci = ( \n take (last B) S, \n butlast B,\n mark_as_done_abs \n (seg_start (length B - Suc 0)) (seg_end (length B - Suc 0)) I,\n P)\"\n\n have ABS: \"GS.\\ ci = (butlast p_\\, D_\\ \\ last p_\\, pE_\\)\"\n apply (simp add: GS.\\_def ci_def)\n apply (intro conjI)\n apply (auto \n simp del: map_butlast\n simp add: map_butlast[symmetric] butlast_upt\n simp add: GS.p_\\_def GS.seg_def[abs_def] GS.seg_start_def GS.seg_end_def\n simp: nth_butlast last_conv_nth nth_take AUX1\n cong: if_cong\n intro!: iexI\n dest: order.strict_trans[OF _ B_in_bound']\n ) []\n\n apply (auto \n simp: GS.D_\\_def p_\\_def last_map BNE seg_def mark_as_done_abs_def) []\n\n using AUX1 no_last_out_P_aux[OF NE NS]\n apply (auto simp: GS.pE_\\_def mark_as_done_abs_def elim!: bex2I) []\n done\n\n have INV: \"GS_invar ci\"\n apply unfold_locales\n apply (simp_all add: ci_def)\n\n using B_in_bound B_sorted B_distinct \n apply (cases B rule: rev_cases, simp) \n apply (auto simp: sorted_append order.strict_iff_order) [] \n\n using B_sorted BNE apply (auto simp: sorted_butlast) []\n\n using B_distinct BNE apply (auto simp: distinct_butlast) []\n\n using B0 apply (cases B rule: rev_cases, simp add: BNE) \n apply (auto simp: nth_append split: if_split_asm) []\n \n using S_distinct apply (auto) []\n\n apply (rule AUX2)\n\n using P_sorted P_distinct \n apply (auto) [2]\n\n using P_bound no_last_out_P_aux[OF NE NS]\n apply (auto simp: in_set_conv_decomp)\n done\n \n\n show ?thesis\n unfolding pop_impl_def\n apply (refine_rcg \n SPEC_refine refine_vcg order_trans[OF mark_as_done_aux])\n apply (simp_all add: BNE seg_start_less_end seg_end_bound)\n apply (fold ci_def)\n unfolding GS_rel_def\n apply (rule brI)\n apply (simp_all add: ABS INV)\n done\n qed\n\n\n lemma sel_rem_last_correct:\n assumes NE: \"p_\\\\[]\"\n shows\n \"sel_rem_last \\ \\(Id \\\\<^sub>r GS_rel) (select_edge (p_\\,D_\\,pE_\\))\"\n proof -\n {\n fix l i a b b'\n have \"\\i \\ map fst (l[i:=(a,b')]) = map fst l\"\n by (induct l arbitrary: i) (auto split: nat.split)\n } note map_fst_upd_snd_eq = this\n\n from NE have BNE[simp]: \"B\\[]\" unfolding p_\\_def by simp\n\n have INVAR: \"sel_rem_last \\ SPEC (GS_invar o snd)\"\n unfolding sel_rem_last_def\n apply (refine_rcg refine_vcg)\n using locale_this apply (cases SBIP) apply simp\n\n apply simp\n\n using P_bound apply (cases P rule: rev_cases, auto) []\n\n apply simp\n\n apply simp apply (intro impI conjI)\n\n apply (unfold_locales, simp_all) []\n using B_in_bound B_sorted B_distinct B0 S_distinct I_consistent \n apply auto [6]\n\n using P_sorted P_distinct \n apply (auto simp: map_butlast sorted_butlast distinct_butlast) [2]\n\n using P_bound apply (auto dest: in_set_butlastD) []\n\n apply (unfold_locales, simp_all) []\n using B_in_bound B_sorted B_distinct B0 S_distinct I_consistent \n apply auto [6]\n\n using P_sorted P_distinct \n apply (auto simp: last_conv_nth map_fst_upd_snd_eq) [2]\n\n using P_bound \n apply (cases P rule: rev_cases, simp)\n apply (auto) []\n\n using locale_this apply (cases SBIP) apply simp\n done\n\n\n {\n assume NS: \"pE_\\\\last p_\\\\UNIV = {}\"\n hence \"sel_rem_last \n \\ SPEC (\\r. case r of (None,SBIP') \\ SBIP'=SBIP | _ \\ False)\"\n unfolding sel_rem_last_def\n apply (refine_rcg refine_vcg)\n apply (cases SBIP)\n apply simp\n\n apply simp\n using P_bound apply (cases P rule: rev_cases, auto) []\n apply simp\n\n using no_last_out_P_aux[OF NE NS]\n apply (auto simp: seg_start_def last_conv_nth) []\n\n apply (cases SBIP)\n apply simp\n done\n } note SPEC_E = this\n\n {\n assume NON_EMPTY: \"pE_\\\\last p_\\\\UNIV \\ {}\"\n\n then obtain j succs P' where \n EFMT: \"P = P'@[(j,succs)]\"\n unfolding pE_\\_def\n by (cases P rule: rev_cases) auto\n \n with P_bound have J_UPPER: \"j{}\" \n by auto\n\n have J_LOWER: \"seg_start (length B - Suc 0) \\ j\"\n proof (rule ccontr)\n assume \"\\(seg_start (length B - Suc 0) \\ j)\"\n hence \"j < seg_start (length B - 1)\" by simp\n with P_sorted EFMT \n have P_bound': \"set P \\ {0.. UNIV\"\n by (auto simp: sorted_append)\n hence \"pE_\\ \\ last p_\\\\UNIV = {}\"\n by (auto \n simp: p_\\_def last_conv_nth seg_def pE_\\_def S_idx_uniq seg_end_def)\n thus False using NON_EMPTY by simp\n qed\n\n from J_UPPER J_LOWER have SJL: \"S!j\\last p_\\\" \n unfolding p_\\_def seg_def[abs_def] seg_end_def\n by (auto simp: last_map)\n\n from EFMT have SSS: \"{S!j}\\succs\\pE_\\\"\n unfolding pE_\\_def\n by auto\n\n\n {\n fix v\n assume \"v\\succs\"\n with SJL SSS have G: \"(S!j,v)\\pE_\\ \\ last p_\\\\UNIV\" by auto\n \n {\n fix j' succs'\n assume \"S ! j' = S ! j\" \"(j', succs') \\ set P'\"\n with J_UPPER P_bound S_idx_uniq EFMT have \"j'=j\" by auto\n with P_distinct \\(j', succs') \\ set P'\\ EFMT have False by auto\n } note AUX3=this\n\n have G1: \"GS.pE_\\ (S,B,I,P' @ [(j, succs - {v})]) = pE_\\ - {(S!j, v)}\"\n unfolding GS.pE_\\_def using AUX3\n by (auto simp: EFMT)\n \n {\n assume \"succs\\{v}\"\n hence \"GS.pE_\\ (S,B,I,P' @ [(j, succs - {v})]) = GS.pE_\\ (S,B,I,P')\"\n unfolding GS.pE_\\_def by auto\n\n with G1 have \"GS.pE_\\ (S,B,I,P') = pE_\\ - {(S!j, v)}\" by simp\n } note G2 = this\n\n note G G1 G2\n } note AUX3 = this\n\n have \"sel_rem_last \\ SPEC (\\r. case r of \n (Some v,SBIP') \\ \\u. \n (u,v)\\(pE_\\\\last p_\\\\UNIV) \n \\ GS.\\ SBIP' = (p_\\,D_\\,pE_\\-{(u,v)})\n | _ \\ False)\"\n unfolding sel_rem_last_def\n apply (refine_rcg refine_vcg)\n\n using SNE apply (vc_solve simp: J_LOWER EFMT)\n\n apply (frule AUX3(1))\n\n apply safe\n\n apply (drule (1) AUX3(3)) apply (auto simp: EFMT GS.\\_def) []\n apply (drule AUX3(2)) apply (auto simp: GS.\\_def) []\n done\n } note SPEC_NE=this\n\n have SPEC: \"sel_rem_last \\ SPEC (\\r. case r of \n (None, SBIP') \\ SBIP' = SBIP \\ pE_\\ \\ last p_\\ \\ UNIV = {} \\ GS_invar SBIP\n | (Some v, SBIP') \\ \\u. (u, v) \\ pE_\\ \\ last p_\\ \\ UNIV \n \\ GS.\\ SBIP' = (p_\\, D_\\, pE_\\ - {(u, v)})\n \\ GS_invar SBIP'\n )\" \n using INVAR\n apply (cases \"pE_\\ \\ last p_\\ \\ UNIV = {}\") \n apply (frule SPEC_E)\n apply (auto split: option.splits simp: pw_le_iff; blast; fail)\n apply (frule SPEC_NE)\n apply (auto split: option.splits simp: pw_le_iff; blast; fail)\n done \n \n \n have X1: \"(\\y. (y=None \\ \\ y) \\ (\\a b. y=Some (a,b) \\ \\ y a b)) \\\n (\\ None \\ (\\a b. \\ (Some (a,b)) a b))\" for \\ \\\n by auto\n \n\n show ?thesis\n apply (rule order_trans[OF SPEC])\n unfolding select_edge_def select_def \n apply (simp \n add: pw_le_iff refine_pw_simps prod_rel_sv \n del: SELECT_pw\n split: option.splits prod.splits)\n apply (fastforce simp: br_def GS_rel_def GS.\\_def)\n done \n qed\n\n lemma find_seg_idx_of_correct:\n assumes A: \"v\\\\(set p_\\)\"\n shows \"(find_seg (S_idx_of v)) = idx_of p_\\ v\"\n proof -\n note S_idx_of_correct[OF A] idx_of_props[OF p_\\_disjoint_sym A]\n from find_seg_correct[OF \\S_idx_of v < length S\\] have \n \"find_seg (S_idx_of v) < length p_\\\" \n and \"S!S_idx_of v \\ p_\\!find_seg (S_idx_of v)\"\n unfolding p_\\_def by auto\n from idx_of_uniq[OF p_\\_disjoint_sym this] \\S ! S_idx_of v = v\\ \n show ?thesis by auto\n qed\n\n\n lemma idx_of_correct:\n assumes A: \"v\\\\(set p_\\)\"\n shows \"idx_of_impl v \\ SPEC (\\x. x=idx_of p_\\ v \\ x_is_set_S)\n apply (erule S_idx_of_correct)\n apply (simp add: find_seg_impl find_seg_idx_of_correct)\n by (metis find_seg_correct(2) find_seg_impl)\n\n lemma collapse_correct:\n assumes A: \"v\\\\(set p_\\)\"\n shows \"collapse_impl v \\\\GS_rel (SPEC (\\r. r=collapse v \\))\"\n proof -\n {\n fix i\n assume \"i\"\n hence ILEN: \"i_def)\n\n let ?SBIP' = \"(S, take (Suc i) B, I, P)\"\n\n {\n have [simp]: \"GS.seg_start ?SBIP' i = seg_start i\"\n by (simp add: GS.seg_start_def)\n\n have [simp]: \"GS.seg_end ?SBIP' i = seg_end (length B - 1)\"\n using ILEN by (simp add: GS.seg_end_def min_absorb2)\n\n {\n fix j\n assume B: \"seg_start i \\ j\" \"j < seg_end (length B - Suc 0)\"\n hence \"ji have \"(length B - Suc 0) < length B\" by auto\n from seg_end_bound[OF this] \n have \"seg_end (length B - Suc 0) \\ length S\" .\n finally show ?thesis .\n qed\n\n have \"i \\ find_seg j \\ find_seg j < length B \n \\ seg_start (find_seg j) \\ j \\ j < seg_end (find_seg j)\" \n proof (intro conjI)\n show \"i\\find_seg j\"\n by (metis le_trans not_less B(1) find_seg_bounds(2) \n seg_end_less_start ILEN \\j < length S\\)\n qed (simp_all add: find_seg_bounds[OF \\j])\n } note AUX1 = this\n\n {\n fix Q and j::nat\n assume \"Q j\"\n hence \"\\i. S!j = S!i \\ Q i\"\n by blast\n } note AUX_ex_conj_SeqSI = this\n\n have \"GS.seg ?SBIP' i = \\ (seg ` {i.. (S, take (Suc i) B, I, P) = collapse_aux p_\\ i\"\n unfolding GS.p_\\_def collapse_aux_def\n apply (simp add: min_absorb2 drop_map)\n apply (rule conjI)\n apply (auto \n simp: GS.seg_def[abs_def] GS.seg_start_def GS.seg_end_def take_map) []\n\n apply (simp add: AUX2)\n done\n } note AUX1 = this\n\n from A obtain i where [simp]: \"I v = Some (STACK i)\"\n using I_consistent set_p_\\_is_set_S\n by (auto simp: in_set_conv_nth)\n\n {\n have \"(collapse_aux p_\\ (idx_of p_\\ v), D_\\, pE_\\) =\n GS.\\ (S, take (Suc (idx_of p_\\ v)) B, I, P)\"\n unfolding GS.\\_def\n using idx_of_props[OF p_\\_disjoint_sym A]\n by (simp add: AUX1)\n } note ABS=this\n\n {\n have \"GS_invar (S, take (Suc (idx_of p_\\ v)) B, I, P)\"\n apply unfold_locales\n apply simp_all\n\n using B_in_bound B_sorted B_distinct\n apply (auto simp: sorted_take dest: in_set_takeD) [3]\n\n using B0 S_distinct apply auto [2]\n\n using I_consistent apply simp\n\n using P_sorted P_distinct P_bound apply auto [3]\n done\n } note INV=this\n\n show ?thesis\n unfolding collapse_impl_def\n apply (refine_rcg SPEC_refine refine_vcg order_trans[OF idx_of_correct])\n\n apply fact\n apply (metis discrete)\n\n apply (simp add: collapse_def \\_def find_seg_impl)\n unfolding GS_rel_def\n apply (rule brI)\n apply (rule ABS)\n apply (rule INV)\n done\n qed\n\nend\n\ntext \\Technical adjustment for avoiding case-splits for definitions\n extracted from GS-locale\\\nlemma opt_GSdef: \"f \\ g \\ f s \\ case s of (S,B,I,P) \\ g (S,B,I,P)\" by auto\n\nlemma ext_def: \"f\\g \\ f x \\ g x\" by auto\n\ncontext fr_graph begin\n definition \"push_impl v s \\ GS.push_impl s v (E``{v})\" \n lemmas push_impl_def_opt = \n push_impl_def[abs_def, \n THEN ext_def, THEN opt_GSdef, unfolded GS.push_impl_def GS_sel_simps]\n\n text \\Definition for presentation\\\n lemma \"push_impl v (S,B,I,P) \\ (S@[v], B@[length S], I(v\\STACK (length S)),\n if E``{v}={} then P else P@[(length S,E``{v})])\"\n unfolding push_impl_def GS.push_impl_def GS.P_def GS.S_def\n by (auto simp: Let_def)\n\n lemma GS_\\_split: \n \"GS.\\ s = (p,D,pE) \\ (p=GS.p_\\ s \\ D=GS.D_\\ s \\ pE=GS.pE_\\ s)\"\n \"(p,D,pE) = GS.\\ s \\ (p=GS.p_\\ s \\ D=GS.D_\\ s \\ pE=GS.pE_\\ s)\"\n by (auto simp add: GS.\\_def)\n\n lemma push_refine:\n assumes A: \"(s,(p,D,pE))\\GS_rel\" \"(v,v')\\Id\"\n assumes B: \"v\\\\(set p)\" \"v\\D\"\n shows \"(push_impl v s, push v' (p,D,pE))\\GS_rel\"\n proof -\n from A have [simp]: \"p=GS.p_\\ s \\ D=GS.D_\\ s \\ pE=GS.pE_\\ s\" \"v'=v\" \n and INV: \"GS_invar s\"\n by (auto simp add: GS_rel_def br_def GS_\\_split)\n\n from INV B show ?thesis\n by (auto \n simp: GS_rel_def br_def GS_invar.push_correct push_impl_def push_def)\n qed\n\n definition \"pop_impl s \\ GS.pop_impl s\"\n lemmas pop_impl_def_opt = \n pop_impl_def[abs_def, THEN opt_GSdef, unfolded GS.pop_impl_def\n GS.mark_as_done_def GS.seg_start_def GS.seg_end_def \n GS_sel_simps]\n\n lemma pop_refine:\n assumes A: \"(s,(p,D,pE))\\GS_rel\"\n assumes B: \"p \\ []\" \"pE \\ last p \\ UNIV = {}\"\n shows \"pop_impl s \\ \\GS_rel (RETURN (pop (p,D,pE)))\"\n proof -\n from A have [simp]: \"p=GS.p_\\ s \\ D=GS.D_\\ s \\ pE=GS.pE_\\ s\" \n and INV: \"GS_invar s\"\n by (auto simp add: GS_rel_def br_def GS_\\_split)\n\n show ?thesis\n unfolding pop_impl_def[abs_def] pop_def\n apply (rule order_trans[OF GS_invar.pop_correct])\n using INV B\n apply (simp_all add: Un_commute RETURN_def) \n done\n qed\n\n thm pop_refine[no_vars]\n\n definition \"collapse_impl v s \\ GS.collapse_impl s v\"\n lemmas collapse_impl_def_opt = \n collapse_impl_def[abs_def, \n THEN ext_def, THEN opt_GSdef, unfolded GS.collapse_impl_def GS_sel_simps]\n\n lemma collapse_refine:\n assumes A: \"(s,(p,D,pE))\\GS_rel\" \"(v,v')\\Id\"\n assumes B: \"v'\\\\(set p)\"\n shows \"collapse_impl v s \\\\GS_rel (RETURN (collapse v' (p,D,pE)))\"\n proof -\n from A have [simp]: \"p=GS.p_\\ s \\ D=GS.D_\\ s \\ pE=GS.pE_\\ s\" \"v'=v\" \n and INV: \"GS_invar s\"\n by (auto simp add: GS_rel_def br_def GS_\\_split)\n\n show ?thesis\n unfolding collapse_impl_def[abs_def]\n apply (rule order_trans[OF GS_invar.collapse_correct])\n using INV B by (simp_all add: GS.\\_def RETURN_def)\n qed\n\n definition \"select_edge_impl s \\ GS.sel_rem_last s\"\n lemmas select_edge_impl_def_opt = \n select_edge_impl_def[abs_def, \n THEN opt_GSdef, \n unfolded GS.sel_rem_last_def GS.seg_start_def GS_sel_simps]\n\n lemma select_edge_refine: \n assumes A: \"(s,(p,D,pE))\\GS_rel\"\n assumes NE: \"p \\ []\"\n shows \"select_edge_impl s \\ \\(Id \\\\<^sub>r GS_rel) (select_edge (p,D,pE))\"\n proof -\n from A have [simp]: \"p=GS.p_\\ s \\ D=GS.D_\\ s \\ pE=GS.pE_\\ s\" \n and INV: \"GS_invar s\"\n by (auto simp add: GS_rel_def br_def GS_\\_split)\n\n from INV NE show ?thesis\n unfolding select_edge_impl_def\n using GS_invar.sel_rem_last_correct[OF INV] NE\n by (simp)\n qed\n\n definition \"initial_impl v0 I \\ GS_initial_impl I v0 (E``{v0})\"\n\n lemma initial_refine:\n \"\\v0\\D0; (I,D0)\\oGS_rel; (v0i,v0)\\Id\\ \n \\ (initial_impl v0i I,initial v0 D0)\\GS_rel\"\n unfolding initial_impl_def GS_rel_def br_def\n apply (simp_all add: GS_initial_correct)\n apply (auto simp: initial_def)\n done\n\n\n definition \"path_is_empty_impl s \\ GS.S s = []\"\n lemma path_is_empty_refine: \n \"GS_invar s \\ path_is_empty_impl s \\ GS.p_\\ s=[]\"\n unfolding path_is_empty_impl_def GS.p_\\_def GS_invar.empty_eq\n by auto\n\n definition (in GS) \"is_on_stack_impl v \n \\ case I v of Some (STACK _) \\ True | _ \\ False\"\n\n lemma (in GS_invar) is_on_stack_impl_correct:\n shows \"is_on_stack_impl v \\ v\\\\(set p_\\)\"\n unfolding is_on_stack_impl_def\n using I_consistent[of v]\n apply (force \n simp: set_p_\\_is_set_S in_set_conv_nth \n split: option.split node_state.split)\n done\n\n definition \"is_on_stack_impl v s \\ GS.is_on_stack_impl s v\"\n lemmas is_on_stack_impl_def_opt = \n is_on_stack_impl_def[abs_def, THEN ext_def, THEN opt_GSdef, \n unfolded GS.is_on_stack_impl_def GS_sel_simps]\n\n lemma is_on_stack_refine:\n \"\\ GS_invar s \\ \\ is_on_stack_impl v s \\ v\\\\(set (GS.p_\\ s))\"\n unfolding is_on_stack_impl_def GS_rel_def br_def\n by (simp add: GS_invar.is_on_stack_impl_correct)\n\n\n definition (in GS) \"is_done_impl v \n \\ case I v of Some DONE \\ True | _ \\ False\"\n\n lemma (in GS_invar) is_done_impl_correct:\n shows \"is_done_impl v \\ v\\D_\\\"\n unfolding is_done_impl_def D_\\_def\n apply (auto split: option.split node_state.split)\n done\n\n definition \"is_done_oimpl v I \\ case I v of Some DONE \\ True | _ \\ False\"\n\n definition \"is_done_impl v s \\ GS.is_done_impl s v\"\n\n lemma is_done_orefine:\n \"\\ oGS_invar s \\ \\ is_done_oimpl v s \\ v\\oGS_\\ s\"\n unfolding is_done_oimpl_def oGS_rel_def br_def\n by (auto \n simp: oGS_invar_def oGS_\\_def \n split: option.splits node_state.split)\n\n lemma is_done_refine:\n \"\\ GS_invar s \\ \\ is_done_impl v s \\ v\\GS.D_\\ s\"\n unfolding is_done_impl_def GS_rel_def br_def\n by (simp add: GS_invar.is_done_impl_correct)\n\n lemma oinitial_refine: \"(Map.empty, {}) \\ oGS_rel\"\n by (auto simp: oGS_rel_def br_def oGS_\\_def oGS_invar_def)\n\nend\n\nsubsection \\Refined Skeleton Algorithm\\\n\ncontext fr_graph begin\n\n lemma I_to_outer:\n assumes \"((S, B, I, P), ([], D, {})) \\ GS_rel\"\n shows \"(I,D)\\oGS_rel\"\n using assms\n unfolding GS_rel_def oGS_rel_def br_def oGS_\\_def GS.\\_def GS.D_\\_def GS_invar_def oGS_invar_def\n apply (auto simp: GS.p_\\_def)\n done\n \n \n definition skeleton_impl :: \"'v oGS nres\" where\n \"skeleton_impl \\ do {\n stat_start_nres;\n let I=Map.empty;\n r \\ FOREACHi (\\it I. outer_invar it (oGS_\\ I)) V0 (\\v0 I0. do {\n if \\is_done_oimpl v0 I0 then do {\n let s = initial_impl v0 I0;\n\n (S,B,I,P)\\WHILEIT (invar v0 (oGS_\\ I0) o GS.\\)\n (\\s. \\path_is_empty_impl s) (\\s.\n do {\n \\ \\Select edge from end of path\\\n (vo,s) \\ select_edge_impl s;\n\n case vo of \n Some v \\ do {\n if is_on_stack_impl v s then do {\n collapse_impl v s\n } else if \\is_done_impl v s then do {\n \\ \\Edge to new node. Append to path\\\n RETURN (push_impl v s)\n } else do {\n \\ \\Edge to done node. Skip\\\n RETURN s\n }\n }\n | None \\ do {\n \\ \\No more outgoing edges from current node on path\\\n pop_impl s\n }\n }) s;\n RETURN I\n } else\n RETURN I0\n }) I;\n stat_stop_nres;\n RETURN r\n }\"\n\n subsubsection \\Correctness Theorem\\\n\n lemma \"skeleton_impl \\ \\oGS_rel skeleton\"\n using [[goals_limit = 1]]\n unfolding skeleton_impl_def skeleton_def\n apply (refine_rcg\n bind_refine'\n select_edge_refine push_refine \n pop_refine\n collapse_refine \n initial_refine\n oinitial_refine\n inj_on_id\n )\n using [[goals_limit = 5]]\n apply refine_dref_type \n\n apply (vc_solve (nopre) solve: asm_rl I_to_outer\n simp: GS_rel_def br_def GS.\\_def oGS_rel_def oGS_\\_def \n is_on_stack_refine path_is_empty_refine is_done_refine is_done_orefine\n )\n\n done\n\n lemmas skeleton_refines \n = select_edge_refine push_refine pop_refine collapse_refine \n initial_refine oinitial_refine\n lemmas skeleton_refine_simps \n = GS_rel_def br_def GS.\\_def oGS_rel_def oGS_\\_def \n is_on_stack_refine path_is_empty_refine is_done_refine is_done_orefine\n\n text \\Short proof, for presentation\\\n context\n notes [[goals_limit = 1]]\n notes [refine] = inj_on_id bind_refine'\n begin\n lemma \"skeleton_impl \\ \\oGS_rel skeleton\"\n unfolding skeleton_impl_def skeleton_def\n by (refine_rcg skeleton_refines, refine_dref_type)\n (vc_solve (nopre) solve: asm_rl I_to_outer simp: skeleton_refine_simps) \n\n end\n\nend\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Gabow_SCC/Gabow_Skeleton.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.44939264921326705, "lm_q2_score": 0.11757212581561163, "lm_q1q2_score": 0.052836049093913255}} {"text": "(* Title: Containers/Containers_Userguide.thy\n Author: Andreas Lochbihler, ETH Zurich *)\n(*<*)\ntheory Containers_Userguide imports\n Card_Datatype\n List_Proper_Interval\n Containers\nbegin\n(*>*)\nchapter \\User guide\\\ntext_raw \\\\label{chapter:Userguide}\\\n\ntext \\\n This user guide shows how to use and extend the lightweight containers framework (LC).\n For a more theoretical discussion, see \\cite{Lochbihler2013ITP}.\n This user guide assumes that you are familiar with refinement in the code generator \\cite{HaftmannBulwahn2013codetut,HaftmannKrausKuncarNipkow2013ITP}.\n The theory \\Containers_Userguide\\ generates it; so if you want to experiment with the examples, you can find their source code there.\n Further examples can be found in the @{dir \\Examples\\} folder.\n\\\n\nsection \\Characteristics\\\n\ntext_raw \\\n \\isastyletext\n \\begin{itemize}\n\\\ntext_raw \\\n \\isastyletext\n \\item \\textbf{Separate type classes for code generation}\n \\\\\n LC follows the ideal that type classes for code generation should be separate from the standard type classes in Isabelle.\n LC's type classes are designed such that every type can become an instance, so well-sortedness errors during code generation can always be remedied.\n\\\ntext_raw \\\n \\isastyletext\n \\item \\textbf{Multiple implementations}\n \\\\\n LC supports multiple simultaneous implementations of the same container type.\n For example, the following implements at the same time\n (i)~the set of @{typ bool} as a distinct list of the elements,\n (ii)~@{typ \"int set\"} as a RBT of the elements or as the RBT of the complement, and\n (iii)~sets of functions as monad-style lists:\n \\par\n\\\nvalue \"({True}, {1 :: int}, - {2 :: int, 3}, {\\x :: int. x * x, \\y. y + 1})\"\ntext_raw \\\n \\isastyletext\n \\par\n The LC type classes are the key to simultaneously supporting different implementations.\n\n \\item \\textbf{Extensibility}\n \\\\\n The LC framework is designed for being extensible.\n You can add new containers, implementations and element types any time.\n \\end{itemize}\n\\\n\nsection \\Getting started\\\ntext_raw \\\\label{section:getting:started}\\\n\ntext \\\n Add the entry theory @{theory Containers.Containers} for LC to the end of your imports.\n This will reconfigure the code generator such that it implements the types @{typ \"'a set\"} for sets and @{typ \"('a, 'b) mapping\"} for maps with one of the data structures supported.\n As with all the theories that adapt the code generator setup, it is important that @{theory Containers.Containers} comes at the end of the imports.\n\n Run the following command, e.g., to check that LC works correctly and implements sets of @{typ int}s as red-black trees (RBT):\n\\\n\nvalue [code] \"{1 :: int}\"\n\ntext \\\n This should produce @{value [names_short] \"{1 :: int}\"}.\n Without LC, sets are represented as (complements of) a list of elements, i.e., @{term \"set [1 :: int]\"} in the example.\n\\\n\ntext \\\n If your exported code does not use your own types as elements of sets or maps and you have not declared any code equation for these containers, then your \\isacommand{export{\\isacharunderscore}code} command will use LC to implement @{typ \"'a set\"} and @{typ \"('a, 'b) mapping\"}.\n \n Our running example will be arithmetic expressions.\n The function @{term \"vars e\"} computes the variables that occur in the expression @{term e}\n\\\n\ntype_synonym vname = string\ndatatype expr = Var vname | Lit int | Add expr expr\nfun vars :: \"expr \\ vname set\" where\n \"vars (Var v) = {v}\"\n| \"vars (Lit i) = {}\"\n| \"vars (Add e\\<^sub>1 e\\<^sub>2) = vars e\\<^sub>1 \\ vars e\\<^sub>2\"\n\nvalue \"vars (Var ''x'')\"\n\ntext \\\n To illustrate how to deal with type variables, we will use the following variant where variable names are polymorphic:\n\\\n\ndatatype 'a expr' = Var' 'a | Lit' int | Add' \"'a expr'\" \"'a expr'\"\nfun vars' :: \"'a expr' \\ 'a set\" where\n \"vars' (Var' v) = {v}\"\n| \"vars' (Lit' i) = {}\"\n| \"vars' (Add' e\\<^sub>1 e\\<^sub>2) = vars' e\\<^sub>1 \\ vars' e\\<^sub>2\"\n\nvalue \"vars' (Var' (1 :: int))\"\n\nsection \\New types as elements\\\n\ntext \\\n This section explains LC's type classes and shows how to instantiate them.\n If you want to use your own types as the elements of sets or the keys of maps, you must instantiate up to eight type classes: @{class ceq} (\\S\\ref{subsection:ceq}), @{class ccompare} (\\S\\ref{subsection:ccompare}), @{class set_impl} (\\S\\ref{subsection:set_impl}), @{class mapping_impl} (\\S\\ref{subsection:mapping_impl}), @{class cenum} (\\S\\ref{subsection:cenum}), @{class finite_UNIV} (\\S\\ref{subsection:finite_UNIV}), @{class card_UNIV} (\\S\\ref{subsection:card_UNIV}), and @{class cproper_interval} (\\S\\ref{subsection:cproper_interval}).\n Otherwise, well-sortedness errors like the following will occur:\n\\begin{verbatim}\n*** Wellsortedness error:\n*** Type expr not of sort {ceq,ccompare}\n*** No type arity expr :: ceq\n*** At command \"value\"\n\\end{verbatim}\n\n In detail, the sort requirements on the element type @{typ \"'a\"} are:\n \\begin{itemize}\n \\item @{class ceq} (\\S\\ref{subsection:ceq}), @{class ccompare} (\\S\\ref{subsection:ccompare}), and @{class set_impl} (\\S\\ref{subsection:set_impl}) for @{typ \"'a set\"} in general\n \\item @{class cenum} (\\S\\ref{subsection:cenum}) for set comprehensions @{term \"{x. P x}\"},\n \\item @{class card_UNIV}, @{class cproper_interval} for @{typ \"'a set set\"} and any deeper nesting of sets (\\S\\ref{subsection:card_UNIV}),%\n \\footnote{%\n These type classes are only required for set complements (see \\S\\ref{subsection:well:sortedness}).\n }\n and\n \\item @{class equal},%\n \\footnote{%\n We deviate here from the strict separation of type classes, because it does not make sense to store types in a map on which we do not have equality, because the most basic operation @{term \"Mapping.lookup\"} inherently requires equality.\n }\n @{class ccompare} (\\S\\ref{subsection:ccompare}) and @{class mapping_impl} (\\S\\ref{subsection:mapping_impl}) for @{typ \"('a, 'b) mapping\"}.\n \\end{itemize}\n\\\n\nsubsection \\Equality testing\\\ntext_raw \\\\label{subsection:ceq}\\\n\n(*<*)context fixes dummy :: \"'a :: {cenum, ceq, ccompare, set_impl, mapping_impl}\" begin(*>*)\ntext \\\n The type class @{class ceq} defines the operation @{term [source] \"CEQ('a) :: ('a \\ 'a \\ bool) option\" } for testing whether two elements are equal.%\n \\footnote{%\n Technically, the type class @{class ceq} defines the operation @{term [source] ceq}.\n As usage often does not fully determine @{term [source] ceq}'s type, we use the notation @{term \"CEQ('a)\"} that explicitly mentions the type.\n In detail, @{term \"CEQ('a)\"} is translated to @{term [source] \"CEQ('a) :: ('a \\ 'a \\ bool) option\" } including the type constraint.\n We do the same for the other type class operators:\n @{term \"CCOMPARE('a)\"} constrains the operation @{term [source] ccompare} (\\S\\ref{subsection:ccompare}), \n @{term [source] \"SET_IMPL('a)\"} constrains the operation @{term [source] set_impl}, (\\S\\ref{subsection:set_impl}),\n @{term [source] \"MAPPING_IMPL('a)\"} (constrains the operation @{term [source] mapping_impl}, (\\S\\ref{subsection:mapping_impl}), and\n @{term \"CENUM('a)\"} constrains the operation @{term [source] cenum}, \\S\\ref{subsection:cenum}.\n }\n The test is embedded in an \\option\\ value to allow for types that do not support executable equality test such as @{typ \"'a \\ 'b\"}.\n Whenever possible, @{term \"CEQ('a)\"} should provide an executable equality operator.\n Otherwise, membership tests on such sets will raise an exception at run-time.\n\n For data types, the \\derive\\ command can automatically instantiates of @{class ceq},\n we only have to tell it whether an equality operation should be provided or not (parameter \\no\\).\n\\\n(*<*)end(*>*)\n\nderive (eq) ceq expr\n\ndatatype example = Example\nderive (no) ceq example\n\ntext \\\n In the remainder of this subsection, we look at how to manually instantiate a type for @{class ceq}.\n First, the simple case of a type constructor \\simple_tycon\\ without parameters that already is an instance of @{class equal}:\n\\\ntypedecl simple_tycon\naxiomatization where simple_tycon_equal: \"OFCLASS(simple_tycon, equal_class)\"\ninstance simple_tycon :: equal by (rule simple_tycon_equal)\n\ninstantiation simple_tycon :: ceq begin\ndefinition \"CEQ(simple_tycon) = Some (=)\"\ninstance by(intro_classes)(simp add: ceq_simple_tycon_def)\nend\n\ntext \\\n For polymorphic types, this is a bit more involved, as the next example with @{typ \"'a expr'\"} illustrates (note that we could have delegated all this to \\derive\\). \n First, we need an operation that implements equality tests with respect to a given equality operation on the polymorphic type.\n For data types, we can use the relator which the transfer package (method \\transfer\\) requires and the BNF package generates automatically.\n As we have used the old datatype package for @{typ \"'a expr'\"}, we must define it manually:\n\\\n\ncontext fixes R :: \"'a \\ 'b \\ bool\" begin\nfun expr'_rel :: \"'a expr' \\ 'b expr' \\ bool\"\nwhere\n \"expr'_rel (Var' v) (Var' v') \\ R v v'\"\n| \"expr'_rel (Lit' i) (Lit' i') \\ i = i'\"\n| \"expr'_rel (Add' e\\<^sub>1 e\\<^sub>2) (Add' e\\<^sub>1' e\\<^sub>2') \\ expr'_rel e\\<^sub>1 e\\<^sub>1' \\ expr'_rel e\\<^sub>2 e\\<^sub>2'\"\n| \"expr'_rel _ _ \\ False\"\nend\n\ntext \\If we give HOL equality as parameter, the relator is equality:\\\n\nlemma expr'_rel_eq: \"expr'_rel (=) e\\<^sub>1 e\\<^sub>2 \\ e\\<^sub>1 = e\\<^sub>2\"\nby(induct e\\<^sub>1 e\\<^sub>2 rule: expr'_rel.induct) simp_all\ntext \\\n Then, the instantiation is again canonical:\n\\\ninstantiation expr' :: (ceq) ceq begin\ndefinition\n \"CEQ('a expr') =\n (case ID CEQ('a) of None \\ None | Some eq \\ Some (expr'_rel eq))\"\ninstance\n by(intro_classes)\n (auto simp add: ceq_expr'_def expr'_rel_eq[abs_def] \n dest: Collection_Eq.ID_ceq \n split: option.split_asm)\nend\n(*<*)context fixes dummy :: \"'a :: ceq\" begin(*>*)\ntext \\\n Note the following two points:\n First, the instantiation should avoid to use @{term \"(=)\"} on terms of the polymorphic type.\n This keeps the LC framework separate from the type class @{class equal}, i.e., every choice of @{typ \"'a\"}\n in @{typ \"'a expr'\"} can be of sort @{class \"ceq\"}.\n The easiest way to achieve this is to obtain the equality test from @{term \"CEQ('a)\"}.\n Second, we use @{term \"ID CEQ('a)\"} instead of @{term \"CEQ('a)\"}.\n In proofs, we want that the simplifier uses assumptions like \\CEQ('a) = Some \\\\ for rewriting.\n However, @{term \"CEQ('a)\"} is a nullary constant, so the simplifier reverses such an equation, i.e., it only rewrites \\Some \\\\ to @{term \"CEQ('a :: ceq)\"}.\n Applying the identity function @{term \"ID\"} to @{term \"CEQ('a :: ceq)\"} avoids this, and the code generator eliminates all occurrences of @{term \"ID\"}.\n Although @{thm ID_def} by definition, do not use the conventional @{term \"id\"} instead of @{term ID}, because @{term \"id CEQ('a :: ceq)\"} immediately simplifies to @{term \"CEQ('a :: ceq)\"}.\n\\\n(*<*)end(*>*)\n\nsubsection \\Ordering\\\ntext_raw \\\\label{subsection:ccompare}\\\n\n(*<*)context fixes dummy :: \"'a :: {ccompare, ceq}\" begin(*>*)\ntext \\\n LC takes the order for storing elements in search trees from the type class @{class ccompare} rather than @{class compare}, because we cannot instantiate @{class compare} for some types (e.g., @{typ \"'a set\"} as @{term \"(\\)\"} is not linear).\n Similar to @{term \"CEQ('a)\"} in class @{term ceq}, the class @{class ccompare} specifies an optional comparator @{term [source] \"CCOMPARE('a) :: (('a \\ 'a \\ order)) option\" }.\n If you cannot or do not want to implement a comparator on your type, you can default to @{term \"None\"}.\n In that case, you will not be able to use your type as elements of sets or as keys in maps implemented by search trees.\n\n If the type is a data type or instantiates @{class compare} and we wish to use that comparator also for the search tree, instantiation is again canonical:\n For our data type @{typ expr}, derive does everything!\n\\\n(*<*)end(*>*)\n(*<*)(*>*)\nderive ccompare expr\n(*<*)(*>*)\n\ntext \\\n In general, the pattern for type constructors without parameters looks as follows:\n\\\naxiomatization where simple_tycon_compare: \"OFCLASS(simple_tycon, compare_class)\"\ninstance simple_tycon :: compare by (rule simple_tycon_compare)\n\nderive (compare) ccompare simple_tycon\n\n\ntext \\\n For polymorphic types like @{typ \"'a expr'\"}, we should not do everything manually:\n First, we must define a comparator that takes the comparator on the type variable @{typ \"'a\"} as a parameter.\n This is necessary to maintain the separation between Isabelle/HOL's type classes (like @{class compare}) and LC's.\n Such a comparator is again easily defined by derive.\n\\\n\nderive ccompare expr'\n\nthm ccompare_expr'_def comparator_expr'_simps\n\nsubsection \\Heuristics for picking an implementation\\\ntext_raw \\\\label{subsection:set_impl} \\label{subsection:mapping_impl}\\\n(*<*)context fixes dummy :: \"'a :: {ceq, ccompare, set_impl, mapping_impl}\" begin(*>*)\ntext \\\n Now, we have defined the necessary operations on @{typ expr} and @{typ \"'a expr'\"} to store them in a set \n or use them as the keys in a map.\n But before we can actually do so, we also have to say which data structure to use.\n The type classes @{class set_impl} and @{class mapping_impl} are used for this.\n\n They define the overloaded operations @{term [source] \"SET_IMPL('a) :: ('a, set_impl) phantom\" } and @{term [source] \"MAPPING_IMPL('a) :: ('a, mapping_impl) phantom\"}, respectively.\n The phantom type @{typ \"('a, 'b) phantom\"} from theory @{theory \"HOL-Library.Phantom_Type\"} is isomorphic to @{typ \"'b\"}, but formally depends on @{typ \"'a\"}.\n This way, the type class operations meet the requirement that their type contains exactly one type variable.\n The Haskell and ML compiler will get rid of the extra type constructor again.\n\n For sets, you can choose between @{term set_Collect} (characteristic function @{term P} like in @{term \"{x. P x}\"}), @{term set_DList} (distinct list), @{term set_RBT} (red-black tree), and @{term set_Monad} (list with duplicates).\n Additionally, you can define @{term \"set_impl\"} as @{term \"set_Choose\"} which picks the implementation based on the available operations (RBT if @{term \"CCOMPARE('a)\"} provides a linear order, else distinct lists if @{term \"CEQ('a)\"} provides equality testing, and lists with duplicates otherwise).\n @{term \"set_Choose\"} is the safest choice because it picks only a data structure when the required operations are actually available.\n If @{term set_impl} picks a specific implementation, Isabelle does not ensure that all required operations are indeed available.\n\n For maps, the choices are @{term \"mapping_Assoc_List\"} (associative list without duplicates), @{term \"mapping_RBT\"} (red-black tree), and @{term \"mapping_Mapping\"} (closures with function update).\n Again, there is also the @{term \"mapping_Choose\"} heuristics.\n \n For simple cases, \\derive\\ can be used again (even if the type is not a data type).\n Consider, e.g., the following instantiations:\n @{typ \"expr set\"} uses RBTs, @{typ \"(expr, _) mapping\"} and @{typ \"'a expr' set\"} use the heuristics, and @{typ \"('a expr', _) mapping\"} uses the same implementation as @{typ \"('a, _) mapping\"}.\n\\\n(*<*)end(*>*)\n\nderive (rbt) set_impl expr\nderive (choose) mapping_impl expr\nderive (choose) set_impl expr'\n\ntext \\\n More complex cases such as taking the implementation preference of a type parameter must be done manually.\n\\\n\ninstantiation expr' :: (mapping_impl) mapping_impl begin\ndefinition\n \"MAPPING_IMPL('a expr') = \n Phantom('a expr') (of_phantom MAPPING_IMPL('a))\"\ninstance ..\nend\n\n(*<*)\nlocale mynamespace begin\ndefinition empty where \"empty = Mapping.empty\" \ndeclare (in -) mynamespace.empty_def [code]\n(*>*)\ntext \\\n To see the effect of the different configurations, consider the following examples where @{term [names_short] \"empty\"} refers to @{term \"Mapping.empty\"}.\n For that, we must disable pretty printing for sets as follows:\n\\\ndeclare (*<*)(in -) (*>*)pretty_sets[code_post del]\ntext \\\n \\begin{center}\n \\small\n \\begin{tabular}{ll}\n \\toprule\n \\isamarkuptrue\\isacommand{value}\\isamarkupfalse\\ {\\isacharbrackleft}code{\\isacharbrackright}\n &\n \\textbf{result}\n \\\\\n \\midrule\n @{term [source] \"{} :: expr set\"}\n &\n @{value [names_short] \"{} :: expr set\"}\n \\\\\n @{term [source] \"empty :: (expr, unit) mapping\"}\n &\n @{value [names_short] \"empty :: (expr, unit) mapping\"}\n \\\\\n \\midrule\n @{term [source] \"{} :: string expr' set\"}\n &\n @{value [names_short] \"{} :: string expr' set\"}\n \\\\\n @{term [source] \"{} :: (nat \\ nat) expr' set\"}\n &\n @{value [names_short] \"{} :: (nat \\ nat) expr' set\"}\n \\\\\n @{term [source] \"{} :: bool expr' set\"}\n &\n @{value [names_short] \"{} :: bool expr' set\"}\n \\\\\n @{term [source] \"empty :: (bool expr', unit) mapping\"}\n &\n @{value [names_short] \"empty :: (bool expr', unit) mapping\"}\n \\\\\n \\bottomrule\n \\end{tabular}\n \\end{center}\n \n For @{typ expr}, @{term mapping_Choose} picks RBTs, because @{term \"CCOMPARE(expr)\"} provides a comparison operation for @{typ \"expr\"}.\n For @{typ \"'a expr'\"}, the effect of @{term set_Choose} is more pronounced:\n @{term \"CCOMPARE(string)\"} is not @{term \"None\"}, so neither is @{term \"CCOMPARE(string expr')\"}, and @{term set_Choose} picks RBTs.\n As @{typ \"nat \\ nat\"} neither provides equality tests (@{class ceq}) nor comparisons (@{class ccompare}), neither does @{typ \"(nat \\ nat) expr'\"}, so we use lists with duplicates.\n The last two examples show the difference between inheriting a choice and choosing freshly:\n By default, @{typ bool} prefers distinct (associative) lists over RBTs, because there are just two elements.\n As @{typ \"bool expr'\"} enherits the choice for maps from @{typ bool}, an associative list implements @{term [source] \"empty :: (bool expr', unit) mapping\"}.\n For sets, in contrast, @{term \"SET_IMPL('a expr')\"} discards @{typ 'a}'s preferences and picks RBTs, because there is a comparison operation.\n\n Finally, let's enable pretty-printing for sets again:\n\\\ndeclare (*<*)(in -) (*>*)pretty_sets [code_post]\n(*<*)\n (* The following value commands ensure that the code generator executes @{value ...} above,\n I could not find a way to specify [code] to @{value}. *)\n value [code] \"{} :: expr set\"\n value [code] \"empty :: (expr, unit) mapping\"\n value [code] \"{} :: string expr' set\"\n value [code] \"{} :: (nat \\ nat) expr' set\"\n value [code] \"{} :: bool expr' set\"\n value [code] \"empty :: (bool expr', unit) mapping\"\n(*>*) \n(*<*)end(*>*)\n\nsubsection \\Set comprehensions\\\ntext_raw \\\\label{subsection:cenum}\\\n\n(*<*)context fixes dummy :: \"'a :: cenum\" begin(*>*)\ntext \\\n If you use the default code generator setup that comes with Isabelle, set comprehensions @{term [source] \"{x. P x} :: 'a set\"} are only executable if the type @{typ 'a} has sort @{class enum}.\n Internally, Isabelle's code generator transforms set comprehensions into an explicit list of elements which it obtains from the list @{term enum} of all of @{typ \"'a\"}'s elements.\n Thus, the type must be an instance of @{class enum}, i.e., finite in particular.\n For example, @{term \"{c. CHR ''A'' \\ c \\ c \\ CHR ''D''}\"} evaluates to @{term \"set ''ABCD''\"}, the set of the characters A, B, C, and D.\n\n For compatibility, LC also implements such an enumeration strategy, but avoids the finiteness restriction.\n The type class @{class cenum} mimicks @{class enum}, but its single parameter @{term [source] \"cEnum :: ('a list \\ (('a \\ bool) \\ bool) \\ (('a \\ bool) \\ bool)) option\"} combines all of @{class enum}'s parameters, namely a list of all elements, a universal and an existential quantifier.\n \\option\\ ensures that every type can be an instance as @{term \"CENUM('a)\"} can always default to @{term None}.\n \n For types that define @{term \"CENUM('a)\"}, set comprehensions evaluate to a list of their elements.\n Otherwise, set comprehensions are represented as a closure.\n This means that if the generated code contains at least one set comprehension, all element types of a set must instantiate @{class cenum}.\n Infinite types default to @{term None}, and enumerations for finite types are canoncial, see @{theory Containers.Collection_Enum} for examples.\n\\\n(*<*)end(*>*)\n\ninstantiation expr :: cenum begin\ndefinition \"CENUM(expr) = None\"\ninstance by(intro_classes)(simp_all add: cEnum_expr_def)\nend\n\nderive (no) cenum expr'\nderive compare_order expr\n\ntext_raw \\\\par\\medskip \\isastyletext For example,\\\nvalue \"({b. b = True}, {x. compare x (Lit 0) = Lt})\"\ntext_raw \\\n \\isastyletext{}\n yields @{value \"({b. b = True}, {x. compare x (Lit 0) = Lt})\"}\n\\\n\ntext \\\n LC keeps complements of such enumerated set comprehensions, i.e., @{term \"- {b. b = True}\"} evaluates to @{value \"- {b. b = True}\"}.\n If you want that the complement operation actually computes the elements of the complements, you have to replace the code equations for @{term uminus} as follows:\n\\\ndeclare Set_uminus_code[code del] Set_uminus_cenum[code]\n(*<*)value \"- {b. b = True}\"(*>*)\ntext \\\n Then, @{term \"- {b. b = True}\"} becomes @{value \"- {b. b = True}\"}, but this applies to all complement invocations.\n For example, @{term [source] \"UNIV :: bool set\"} becomes @{value \"UNIV :: bool set\"}.\n\\\n(*<*)declare Set_uminus_cenum[code del] Set_uminus_code[code](*>*)\n\nsubsection \\Nested sets\\\ntext_raw \\\\label{subsection:finite_UNIV} \\label{subsection:card_UNIV} \\label{subsection:cproper_interval}\\\n\n(*<*)context fixes dummy :: \"'a :: {card_UNIV, cproper_interval}\" begin(*>*)\ntext \\\n To deal with nested sets such as @{typ \"expr set set\"}, the element type must provide three operations from three type classes:\n \\begin{itemize}\n \\item @{class finite_UNIV} from theory @{theory \"HOL-Library.Cardinality\"} defines the constant @{term [source] \"finite_UNIV :: ('a, bool) phantom\"} which designates whether the type is finite.\n \\item @{class card_UNIV} from theory @{theory \"HOL-Library.Cardinality\"} defines the constant @{term [source] \"card_UNIV :: ('a, nat) phantom\"} which returns @{term \"CARD('a)\"}, i.e., the number of values in @{typ 'a}.\n If @{typ \"'a\"} is infinite, @{term \"CARD('a) = 0\"}.\n \\item @{class cproper_interval} from theory @{theory Containers.Collection_Order} defines the function @{term [source] \"cproper_interval :: 'a option \\ 'a option \\ bool\"}.\n If the type @{typ \"'a\"} is finite and @{term \"CCOMPARE('a)\"} yields a linear order on @{typ \"'a\"}, then @{term \"cproper_interval x y\"} returns whether the open interval between @{term \"x\"} and @{term \"y\"} is non-empty.\n The bound @{term \"None\"} denotes unboundedness.\n \\end{itemize}\n\n Note that the type class @{class finite_UNIV} must not be confused with the type class @{class finite}.\n @{class finite_UNIV} allows the generated code to examine whether a type is finite whereas @{class finite} requires that the type in fact is finite.\n\\\n(*<*)end(*>*)\n\ntext \\\n For datatypes, the theory @{theory Containers.Card_Datatype} defines some machinery to assist in proving that the type is (in)finite and has a given number of elements -- see @{file \\Examples/Card_Datatype_Ex.thy\\} for examples.\n With this, it is easy to instantiate @{class card_UNIV} for our running examples:\n\\\n\nlemma inj_expr [simp]: \"inj Lit\" \"inj Var\" \"inj Add\" \"inj (Add e)\"\nby(simp_all add: fun_eq_iff inj_on_def)\n\nlemma infinite_UNIV_expr: \"\\ finite (UNIV :: expr set)\"\n including card_datatype\nproof -\n have \"rangeIt (Lit 0) (Add (Lit 0)) \\ UNIV\" by simp\n from finite_subset[OF this] show ?thesis by auto\nqed\n\ninstantiation expr :: card_UNIV begin\ndefinition \"finite_UNIV = Phantom(expr) False\"\ndefinition \"card_UNIV = Phantom(expr) 0\"\ninstance\n by intro_classes\n (simp_all add: finite_UNIV_expr_def card_UNIV_expr_def infinite_UNIV_expr)\nend\n\nlemma inj_expr' [simp]: \"inj Lit'\" \"inj Var'\" \"inj Add'\" \"inj (Add' e)\"\nby(simp_all add: fun_eq_iff inj_on_def)\n\nlemma infinite_UNIV_expr': \"\\ finite (UNIV :: 'a expr' set)\"\n including card_datatype\nproof -\n have \"rangeIt (Lit' 0) (Add' (Lit' 0)) \\ UNIV\" by simp\n from finite_subset[OF this] show ?thesis by auto\nqed\n\ninstantiation expr' :: (type) card_UNIV begin\ndefinition \"finite_UNIV = Phantom('a expr') False\"\ndefinition \"card_UNIV = Phantom('a expr') 0\"\ninstance\n by intro_classes\n (simp_all add: finite_UNIV_expr'_def card_UNIV_expr'_def infinite_UNIV_expr')\nend\n\ntext \\\n As @{typ expr} and @{typ \"'a expr'\"} are infinite, instantiating @{class cproper_interval} is trivial,\n because @{class cproper_interval} only makes assumptions about its parameters for finite types.\n Nevertheless, it is important to actually define @{term cproper_interval}, because the\n code generator requires a code equation.\n\\\n\ninstantiation expr :: cproper_interval begin\ndefinition cproper_interval_expr :: \"expr proper_interval\" \n where \"cproper_interval_expr _ _ = undefined\"\ninstance by(intro_classes)(simp add: infinite_UNIV_expr)\nend\n\ninstantiation expr' :: (ccompare) cproper_interval begin\ndefinition cproper_interval_expr' :: \"'a expr' proper_interval\" \n where \"cproper_interval_expr' _ _ = undefined\"\ninstance by(intro_classes)(simp add: infinite_UNIV_expr')\nend\n\nsubsubsection \\Instantiation of @{class proper_interval}\\\n\ntext \\\n To illustrate what to do with finite types, we instantiate @{class proper_interval} for @{typ expr}.\n Like @{class ccompare} relates to @{class compare}, the class @{class cproper_interval} has a counterpart @{class proper_interval} without the finiteness assumption.\n Here, we first have to gather the simplification rules of the comparator from the derive\n invocation, especially, how the strict order of the comparator, @{term lt_of_comp}, can be defined.\n \n Since the order on lists is not yet shown to be consistent with the comparators that are used\n for lists, this part of the userguide is currently not available.\n \n\\\n(*\ninstantiation expr :: proper_interval begin\n\nlemma less_expr_conv: \"(<) = lt_of_comp comparator_expr\" \"(\\) = le_of_comp comparator_expr\"\n using less_expr_def less_eq_expr_def unfolding compare_expr_def by auto\n\nlemma lt_of_comp_expr: \"lt_of_comp comparator_expr e1 e2 = (\n case e1 of \n Var x1 \\ \n (case e2 of \n Var x2 \\ lt_of_comp (comparator_list comparator_of) x1 x2 \n | Lit _ \\ True\n | Add _ _ \\ True)\n | Lit i1 \\\n (case e2 of\n Var _ \\ False\n | Lit i2 \\ lt_of_comp comparator_of i1 i2\n | Add _ _ \\ True)\n | Add a1 b1 \\\n (case e2 of\n Var _ \\ False\n | Lit _ \\ False\n | Add a2 b2 \\ lt_of_comp comparator_expr a1 a2 \n \\ le_of_comp comparator_expr a1 a2 \\ lt_of_comp comparator_expr b1 b2) \n )\"\n by (simp add: lt_of_comp_def le_of_comp_def comp_lex_code split: expr.split order.split)\n \nfun proper_interval_expr :: \"expr option \\ expr option \\ bool\"\nwhere\n \"proper_interval_expr None (Some (Var x)) \\ proper_interval None (Some x)\"\n| \"proper_interval_expr (Some (Var x)) (Some (Var y)) \\ proper_interval (Some x) (Some y)\"\n| \"proper_interval_expr (Some (Lit i)) (Some (Lit j)) \\ proper_interval (Some i) (Some j)\"\n| \"proper_interval_expr (Some (Lit i)) (Some (Var x)) \\ False\"\n| \"proper_interval_expr (Some (Add e1 e2)) (Some (Lit i)) \\ False\"\n| \"proper_interval_expr (Some (Add e1 e2)) (Some (Var x)) \\ False\"\n| \"proper_interval_expr (Some (Add e1 e2)) (Some (Add e1' e2')) \\ \n (case compare e1 e1' of Lt \\ True | Eq \\ proper_interval_expr (Some e2) (Some e2') | Gt \\ False)\"\n| \"proper_interval_expr _ _ \\ True\"\n\ninstance\nproof(intro_classes)\n fix x y :: expr\n show \"proper_interval None (Some y) = (\\z. z < y)\"\n unfolding less_expr_conv\n by (cases y)(auto simp add: lt_of_comp_expr intro: exI[where x=\"''''\"])\n\n { fix x y have \"x < Add x y\" unfolding less_expr_conv \n by(induct x arbitrary: y)(simp_all add: lt_of_comp_expr) }\n note le_Add = this\n thus \"proper_interval (Some x) None = (\\z. x < z)\"\n by(simp add: less_expr_def exI[where x=\"Add x y\"])\n\n note [simp] = less_expr_conv lt_of_comp_expr\n\n show \"proper_interval (Some x) (Some y) = (\\z. x < z \\ z < y)\"\n proof(induct \"Some x\" \"Some y\" arbitrary: x y rule: proper_interval_expr.induct)\n case 2\n show ?case by(auto simp add: proper_interval_list_aux_correct)\n next\n case (3 i j)\n show ?case by(auto intro: exI[where x=\"Lit (i + 1)\"])\n next\n case (7 e1 e2 e1' e2')\n thus ?case by(auto intro: le_Add simp add: le_less)\n next\n case (\"8_2\" i e1 e2)\n show ?case by(auto intro: exI[where x=\"Lit (i + 1)\"])\n next\n case (\"8_5\" x i) show ?case\n by(auto intro: exI[where x=\"Var (x @ [undefined])\"] simp add: less_append_same_iff)\n next\n case (\"8_6\" x e1 e2) show ?case\n by(auto intro: exI[where x=\"Lit 0\"])\n next\n case (\"8_7\" i e1 e2) show ?case\n by(auto intro: exI[where x=\"Lit (i + 1)\"])\n next\n case (\"8_10\" x i) show ?case\n by(auto intro: exI[where x=\"Lit (i - 1)\"])\n next\n case (\"8_12\" x e1 e2) show ?case\n by(auto intro: exI[where x=\"Lit 0\"])\n next\n case (\"8_13\" i e1 e2) show ?case\n by(auto intro: exI[where x=\"Lit (i + 1)\"])\n qed auto\nqed simp\nend\n*)\n(*<*)\nvalue \"{{Lit 1}}\"\nvalue \"{{{Lit 1}}}\"\nvalue \"{{{{Lit 1}}}}\"\n(*>*)\n\nsection \\New implementations for containers\\\ntext_raw \\\\label{section:new:implementation}\\\n\n(*<*)\ntypedecl 'v trie_raw\n(*>*)\n\ntext \\\n This section explains how to add a new implementation for a container type.\n If you do so, please consider to add your implementation to this AFP entry.\n\\\n\nsubsection \\Model and verify the data structure\\\ntext_raw \\\\label{subsection:implement:data:structure}\\\ntext \\\n First, you of course have to define the data structure and verify that it has the required properties.\n As our running example, we use a trie to implement @{typ \"('a, 'b) mapping\"}.\n A trie is a binary tree whose the nodes store the values, the keys are the paths from the root to the given node.\n We use lists of @{typ bool}ans for the keys where the @{typ bool}ean indicates whether we should go to the left or right child.\n\n For brevity, we skip this step and rather assume that the type @{typ \"'v trie_raw\"} of tries has following operations and properties:\n\\\ntype_synonym trie_key = \"bool list\"\naxiomatization\n trie_empty :: \"'v trie_raw\" and\n trie_update :: \"trie_key \\ 'v \\ 'v trie_raw \\ 'v trie_raw\" and\n trie_lookup :: \"'v trie_raw \\ trie_key \\ 'v option\" and\n trie_keys :: \"'v trie_raw \\ trie_key set\"\nwhere trie_lookup_empty: \"trie_lookup trie_empty = Map.empty\"\n and trie_lookup_update: \n \"trie_lookup (trie_update k v t) = (trie_lookup t)(k \\ v)\"\n and trie_keys_dom_lookup: \"trie_keys t = dom (trie_lookup t)\"\n\ntext \\\n This is only a minimal example.\n A full-fledged implementation has to provide more operations and -- for efficiency -- should use more than just @{typ bool}eans for the keys.\n\\\n\n(*<*) (* Implement trie by free term algebra *)\ncode_datatype trie_empty trie_update\nlemmas [code] = trie_lookup_empty trie_lookup_update\n\nlemma trie_keys_empty [code]: \"trie_keys trie_empty = {}\"\nby(simp add: trie_keys_dom_lookup trie_lookup_empty)\n\nlemma trie_keys_update [code]:\n \"trie_keys (trie_update k v t) = insert k (trie_keys t)\"\nby(simp add: trie_keys_dom_lookup trie_lookup_update)\n(*>*)\n\nsubsection \\Generalise the data structure\\\ntext_raw \\\\label{subsection:introduce:type:class}\\\ntext \\\n As @{typ \"('k, 'v) mapping\"} store keys of arbitrary type @{typ \"'k\"}, not just @{typ \"trie_key\"}, we cannot use @{typ \"'v trie_raw\"} directly.\n Instead, we must first convert arbitrary types @{typ \"'k\"} into @{typ \"trie_key\"}.\n Of course, this is not always possbile, but we only have to make sure that we pick tries as implementation only if the types do.\n This is similar to red-black trees which require an order.\n Hence, we introduce a type class to convert arbitrary keys into trie keys.\n We make the conversions optional such that every type can instantiate the type class, just as LC does for @{class ceq} and @{class ccompare}.\n\\\ntype_synonym 'a cbl = \"(('a \\ bool list) \\ (bool list \\ 'a)) option\"\nclass cbl =\n fixes cbl :: \"'a cbl\"\n assumes inj_to_bl: \"ID cbl = Some (to_bl, from_bl) \\ inj to_bl\"\n and to_bl_inverse: \"ID cbl = Some (to_bl, from_bl) \\ from_bl (to_bl a) = a\"\nbegin\nabbreviation from_bl where \"from_bl \\ snd (the (ID cbl))\"\nabbreviation to_bl where \"to_bl \\ fst (the (ID cbl))\"\nend\n\ntext \\\n It is best to immediately provide the instances for as many types as possible.\n Here, we only present two examples: @{typ unit} provides conversion functions, @{typ \"'a \\ 'b\"} does not.\n\\\ninstantiation unit :: cbl begin\ndefinition \"cbl = Some (\\_. [], \\_. ())\"\ninstance by(intro_classes)(auto simp add: cbl_unit_def ID_Some intro: injI)\nend\n\ninstantiation \"fun\" :: (type, type) cbl begin\ndefinition \"cbl = (None :: ('a \\ 'b) cbl)\"\ninstance by intro_classes(simp_all add: cbl_fun_def ID_None)\nend\n\nsubsection \\Hide the invariants of the data structure\\\ntext_raw \\\\label{subsection:hide:invariants}\\\ntext \\\n Many data structures have invariants on which the operations rely.\n You must hide such invariants in a \\isamarkuptrue\\isacommand{typedef}\\isamarkupfalse{} before connecting to the container, because the code generator cannot handle explicit invariants.\n The type must be inhabited even if the types of the elements do not provide the required operations.\n The easiest way is often to ignore all invariants in that case.\n\n In our example, we require that all keys in the trie represent encoded values.\n\\\ntypedef (overloaded) ('k :: cbl, 'v) trie = \n \"{t :: 'v trie_raw. \n trie_keys t \\ range (to_bl :: 'k \\ trie_key) \\ ID (cbl :: 'k cbl) = None}\"\nproof\n show \"trie_empty \\ ?trie\"\n by(simp add: trie_keys_dom_lookup trie_lookup_empty)\nqed\n\ntext \\\n Next, transfer the operations to the new type.\n The transfer package does a good job here.\n\\\n\nsetup_lifting type_definition_trie \\ \\also sets up code generation\\\n\nlift_definition empty :: \"('k :: cbl, 'v) trie\" \n is trie_empty\n by(simp add: trie_keys_empty)\n\nlift_definition lookup :: \"('k :: cbl, 'v) trie \\ 'k \\ 'v option\"\n is \"\\t. trie_lookup t \\ to_bl\" .\n\nlift_definition update :: \"'k \\ 'v \\ ('k :: cbl, 'v) trie \\ ('k, 'v) trie\"\n is \"trie_update \\ to_bl\"\n by(auto simp add: trie_keys_dom_lookup trie_lookup_update)\n\nlift_definition keys :: \"('k :: cbl, 'v) trie \\ 'k set\"\n is \"\\t. from_bl ` trie_keys t\" .\n\ntext \\\n And now we go for the properties.\n Note that some properties hold only if the type class operations are actually provided, i.e., @{term \"cbl \\ None\"} in our example.\n\\\n\nlemma lookup_empty: \"lookup empty = Map.empty\"\nby transfer(simp add: trie_lookup_empty fun_eq_iff)\n\ncontext\n fixes t :: \"('k :: cbl, 'v) trie\"\n assumes ID_cbl: \"ID (cbl :: 'k cbl) \\ None\"\nbegin\n\nlemma lookup_update: \"lookup (update k v t) = (lookup t)(k \\ v)\"\nusing ID_cbl\nby transfer(auto simp add: trie_lookup_update fun_eq_iff dest: inj_to_bl[THEN injD])\n\nlemma keys_conv_dom_lookup: \"keys t = dom (lookup t)\"\nusing ID_cbl\nby transfer(force simp add: trie_keys_dom_lookup to_bl_inverse intro: rev_image_eqI)\n\nend\n\nsubsection \\Connecting to the container\\\ntext_raw \\\\label{subsection:connect:container}\\\ntext \\\n Connecting to the container (@{typ \"('a, 'b) mapping\"} in our example) takes three steps:\n \\begin{enumerate}\n \\item Define a new pseudo-constructor\n \\item Implement the container operations for the new type\n \\item Configure the heuristics to automatically pick an implementation\n \\item Test thoroughly\n \\end{enumerate}\n Thorough testing is particularly important, because Isabelle does not check whether you have implemented all your operations, whether you have configured your heuristics sensibly, nor whether your implementation always terminates.\n\\\n\nsubsubsection \\Define a new pseudo-constructor\\\n\ntext \\\n Define a function that returns the abstract container view for a data structure value, and declare it as a datatype constructor for code generation with \\isamarkuptrue\\isacommand{code{\\isacharunderscore}datatype}\\isamarkupfalse.\n Unfortunately, you have to repeat all existing pseudo-constructors, because there is no way to extract the current set of pseudo-constructors from the code generator.\n We call them pseudo-constructors, because they do not behave like datatype constructors in the logic.\n For example, ours are neither injective nor disjoint.\n\\\n\ndefinition Trie_Mapping :: \"('k :: cbl, 'v) trie \\ ('k, 'v) mapping\" \nwhere [simp, code del]: \"Trie_Mapping t = Mapping.Mapping (lookup t)\"\n\ncode_datatype Assoc_List_Mapping RBT_Mapping Mapping Trie_Mapping\n\nsubsubsection \\Implement the operations\\\n\ntext \\\n Next, you have to prove and declare code equations that implement the container operations for the new implementation.\n Typically, these just dispatch to the operations on the type from \\S\\ref{subsection:hide:invariants}.\n Some operations depend on the type class operations from \\S\\ref{subsection:introduce:type:class} being defined; then, the code equation must check that the operations are indeed defined.\n If not, there is usually no way to implement the operation, so the code should raise an exception.\n Logically, we use the function @{term \"Code.abort\"} of type @{typ \"String.literal \\ (unit \\ 'a) \\ 'a\"} with definition @{term \"\\_ f. f ()\"}, but the generated code raises an exception \\texttt{Fail} with the given message (the unit closure avoids non-termination in strict languages).\n This function gets the exception message and the unit-closure of the equation's left-hand side as argument, because it is then trivial to prove equality.\n\n Again, we only show a small set of operations; a realistic implementation should cover as many as possible.\n\\\ncontext fixes t :: \"('k :: cbl, 'v) trie\" begin\n\nlemma lookup_Trie_Mapping [code]:\n \"Mapping.lookup (Trie_Mapping t) = lookup t\"\n \\ \\Lookup does not need the check on @{term cbl},\n because we have defined the pseudo-constructor @{term Trie_Mapping} in terms of @{term \"lookup\"}\\\nby simp(transfer, simp)\n\nlemma update_Trie_Mapping [code]:\n \"Mapping.update k v (Trie_Mapping t) = \n (case ID cbl :: 'k cbl of\n None \\ Code.abort (STR ''update Trie_Mapping: cbl = None'') (\\_. Mapping.update k v (Trie_Mapping t))\n | Some _ \\ Trie_Mapping (update k v t))\"\nby(simp split: option.split add: lookup_update Mapping.update.abs_eq)\n\nlemma keys_Trie_Mapping [code]:\n \"Mapping.keys (Trie_Mapping t) =\n (case ID cbl :: 'k cbl of\n None \\ Code.abort (STR ''keys Trie_Mapping: cbl = None'') (\\_. Mapping.keys (Trie_Mapping t))\n | Some _ \\ keys t)\"\nby(simp add: Mapping.keys.abs_eq keys_conv_dom_lookup split: option.split)\n\nend\n\ntext \\\n These equations do not replace the existing equations for the other constructors, but they do take precedence over them.\n If there is already a generic implementation for an operation @{term \"foo\"}, say @{term \"foo A = gen_foo A\"}, and you prove a specialised equation @{term \"foo (Trie_Mapping t) = trie_foo t\"}, then when you call @{term \"foo\"} on some @{term \"Trie_Mapping t\"}, your equation will kick in.\n LC exploits this sequentiality especially for binary operators on sets like @{term \"(\\)\"}, where there are generic implementations and faster specialised ones.\n\\\n\nsubsubsection \\Configure the heuristics\\\n\ntext \\\n Finally, you should setup the heuristics that automatically picks a container implementation based on the types of the elements (\\S\\ref{subsection:set_impl}).\n\n The heuristics uses a type with a single value, e.g., @{typ mapping_impl} with value @{term Mapping_IMPL}, but there is one pseudo-constructor for each container implementation in the generated code.\n All these pseudo-constructors are the same in the logic, but they are different in the generated code.\n Hence, the generated code can distinguish them, but we do not have to commit to anything in the logic.\n This allows to reconfigure and extend the heuristic at any time.\n\n First, define and declare a new pseudo-constructor for the heuristics.\n Again, be sure to redeclare all previous pseudo-constructors.\n\\\ndefinition mapping_Trie :: mapping_impl \nwhere [simp]: \"mapping_Trie = Mapping_IMPL\"\n\ncode_datatype \n mapping_Choose mapping_Assoc_List mapping_RBT mapping_Mapping mapping_Trie\n\ntext \\\n Then, adjust the implementation of the automatic choice.\n For every initial value of the container (such as the empty map or the empty set), there is one new constant (e.g., @{term mapping_empty_choose} and @{term set_empty_choose}) equivalent to it.\n Its code equation, however, checks the available operations from the type classes and picks an appropriate implementation.\n \n For example, the following prefers red-black trees over tries, but tries over associative lists:\n\\\n\nlemma mapping_empty_choose_code [code]:\n \"(mapping_empty_choose :: ('a :: {ccompare, cbl}, 'b) mapping) =\n (case ID CCOMPARE('a) of Some _ \\ RBT_Mapping RBT_Mapping2.empty\n | None \\\n case ID (cbl :: 'a cbl) of Some _ \\ Trie_Mapping empty \n | None \\ Assoc_List_Mapping DAList.empty)\"\nby(auto split: option.split simp add: DAList.lookup_empty[abs_def] Mapping.empty_def lookup_empty)\n\ntext \\\n There is also a second function for every such initial value that dispatches on the pseudo-constructors for @{typ mapping_impl}.\n This function is used to pick the right implementation for types that specify a preference.\n\\\nlemma mapping_empty_code [code]:\n \"mapping_empty mapping_Trie = Trie_Mapping empty\"\nby(simp add: lookup_empty Mapping.empty_def)\n\ntext \\\n For @{typ \"('k, 'v) mapping\"}, LC also has a function @{term \"mapping_impl_choose2\"} which is given two preferences and returns one (for @{typ \"'a set\"}, it is called @{term \"set_impl_choose2\"}).\n Polymorphic type constructors like @{typ \"'a + 'b\"} use it to pick an implementation based on the preferences of @{typ \"'a\"} and @{typ \"'b\"}.\n By default, it returns @{term mapping_Choose}, i.e., ignore the preferences.\n You should add a code equation like the following that overrides this choice if both preferences are your new data structure:\n\\\n\nlemma mapping_impl_choose2_Trie [code]:\n \"mapping_impl_choose2 mapping_Trie mapping_Trie = mapping_Trie\"\nby(simp add: mapping_Trie_def)\n\ntext \\\n If your new data structure is better than the existing ones for some element type, you should reconfigure the type's preferene.\n As all preferences are logically equal, you can prove (and declare) the appropriate code equation.\n For example, the following prefers tries for keys of type @{typ \"unit\"}:\n\\\n\nlemma mapping_impl_unit_Trie [code]:\n \"MAPPING_IMPL(unit) = Phantom(unit) mapping_Trie\"\nby(simp add: mapping_impl_unit_def)\n\nvalue \"Mapping.empty :: (unit, int) mapping\"\n\ntext \\\n You can also use your new pseudo-constructor with \\derive\\ in instantiations, just give its name as option:\n\\\nderive (mapping_Trie) mapping_impl simple_tycon\n\nsection \\Changing the configuration\\\n\ntext \\\n As containers are connected to data structures only by refinement in the code generator, this can always be adapted later on.\n You can add new data structures as explained in \\S\\ref{section:new:implementation}.\n If you want to drop one, you redeclare the remaining pseudo-constructors with \\isamarkuptrue\\isacommand{code{\\isacharunderscore}datatype}\\isamarkupfalse{} and delete all code equations that pattern-match on the obsolete pseudo-constructors.\n The command \\isamarkuptrue\\isacommand{code{\\isacharunderscore}thms}\\isamarkupfalse{} will tell you which constants have such code equations.\n You can also freely adapt the heuristics for picking implementations as described in \\S\\ref{subsection:connect:container}.\n\n One thing, however, you cannot change afterwards, namely the decision whether an element type supports an operation and if so how it does, because this decision is visible in the logic.\n\\\n\nsection \\New containers types\\\n\ntext \\\n We hope that the above explanations and the examples with sets and maps suffice to show what you need to do if you add a new container type, e.g., priority queues.\n There are three steps:\n \\begin{enumerate}\n \\item \\textbf{Introduce a type constructor for the container.}\n \\\\\n Your new container type must not be a composite type, like @{typ \"'a \\ 'b option\"} for maps, because refinement for code generation only works with a single type constructor.\n Neither should you reuse a type constructor that is used already in other contexts, e.g., do not use @{typ \"'a list\"} to model queues.\n\n Introduce a new type constructor if necessary (e.g., @{typ \"('a, 'b) mapping\"} for maps) -- if your container type already has its own type constructor, everything is fine.\n\n \\item \\textbf{Implement the data structures} \n \\\\\n and connect them to the container type as described in \\S\\ref{section:new:implementation}.\n\n \\item \\textbf{Define a heuristics for picking an implementation.}\n \\\\\n See \\cite{Lochbihler2013ITP} for an explanation.\n \\end{enumerate}\n\\\n\nsection \\Troubleshooting\\\n\ntext \\\n This section describes some difficulties in using LC that we have come across, provides some background for them, and discusses how to overcome them.\n If you experience other difficulties, please contact the author.\n\\\n\nsubsection \\Nesting of mappings\\\n\ntext \\\n Mappings can be arbitrarily nested on the value side, e.g., @{typ \"('a, ('b, 'c) mapping) mapping\"}.\n However, @{typ \"('a, 'b) mapping\"} cannot currently be the key of a mapping, i.e., code generation fails for @{typ \"(('a, 'b) mapping, 'c) mapping\"}.\n Simiarly, you cannot have a set of mappings like @{typ \"('a, 'b) mapping set\"} at the moment.\n There are no issues to make this work, we have just not seen the need for it.\n If you need to generate code for such types, please get in touch with the author.\n\\\n\nsubsection \\Wellsortedness errors\\\ntext_raw \\\\label{subsection:well:sortedness}\\\n\ntext \\\n LC uses its own hierarchy of type classes which is distinct from Isabelle/HOL's.\n This ensures that every type can be made an instance of LC's type classes.\n Consequently, you must instantiate these classes for your own types.\n The following lists where you can find information about the classes and examples how to instantiate them:\n \\begin{center}\n \\begin{tabular}{lll}\n \\textbf{type class} & \\textbf{user guide} & \\textbf{theory}\n \\\\\n @{class card_UNIV} & \\S\\ref{subsection:card_UNIV} & @{theory \"HOL-Library.Cardinality\"} \n %@{term \"Cardinality.card_UNIV_class\"}\n \\\\\n @{class cenum} & \\S\\ref{subsection:cenum} & @{theory Containers.Collection_Enum}\n %@{term \"Collection_Enum.cenum_class\"}\n \\\\\n @{class ceq} & \\S\\ref{subsection:ceq} & @{theory Containers.Collection_Eq}\n %@{term \"Collection_Eq.ceq_class\"}\n \\\\\n @{class ccompare} & \\S\\ref{subsection:ccompare} & @{theory Containers.Collection_Order}\n %@{term \"Collection_Order.ccompare_class\"}\n \\\\\n @{class cproper_interval} & \\S\\ref{subsection:cproper_interval} & @{theory Containers.Collection_Order}\n %@{term \"Collection_Order.cproper_interval_class\"}\n \\\\\n @{class finite_UNIV} & \\S\\ref{subsection:finite_UNIV} & @{theory \"HOL-Library.Cardinality\"}\n %@{term \"Cardinality.finite_UNIV_class\"}\n \\\\\n @{class mapping_impl} & \\S\\ref{subsection:mapping_impl} & @{theory Containers.Mapping_Impl}\n %@{term \"Mapping_Impl.mapping_impl_class\"}\n \\\\\n @{class set_impl} & \\S\\ref{subsection:set_impl} & @{theory Containers.Set_Impl}\n %@{term \"Set_Impl.set_impl_class\"}\n \\\\\n \\end{tabular}\n \\end{center}\n\n The type classes @{class card_UNIV} and @{class cproper_interval} are only required to implement the operations on set complements.\n If your code does not need complements, you can manually delete the code equations involving @{const \"Complement\"}, the theorem list @{thm [source] set_complement_code} collects them.\n It is also recommended that you remove the pseudo-constructor @{const Complement} from the code generator.\n Note that some set operations like @{term \"A - B\"} and @{const UNIV} have no code equations any more.\n\\\ndeclare set_complement_code[code del]\ncode_datatype Collect_set DList_set RBT_set Set_Monad\n(*<*)\ndatatype minimal_sorts = Minimal_Sorts bool\nderive (eq) ceq minimal_sorts\nderive (no) ccompare minimal_sorts\nderive (monad) set_impl minimal_sorts\nderive (no) cenum minimal_sorts\nvalue \"{Minimal_Sorts True} \\ {} \\ Minimal_Sorts ` {True, False}\"\n(*>*)\n\nsubsection \\Exception raised at run-time\\\ntext_raw \\\\label{subsection:set_impl_unsupported_operation}\\\n\ntext \\\n Not all combinations of data and container implementation are possible.\n For example, you cannot implement a set of functions with a RBT, because there is no order on @{typ \"'a \\ 'b\"}.\n If you try, the code will raise an exception \\texttt{Fail} (with an exception message) or \\texttt{Match}.\n They can occur in three cases:\n\n \\begin{enumerate}\n \\item\n You have misconfigured the heuristics that picks implementations (\\S\\ref{subsection:set_impl}), or you have manually picked an implementation that requires an operation that the element type does not provide.\n Printing a stack trace for the exception may help you in locating the error.\n\n \\item You are trying to invoke an operation on a set complement which cannot be implemented on a complement representation, e.g., @{term \"(`)\"}.\n If the element type is enumerable, provide an instance of @{class cenum} and choose to represent complements of sets of enumerable types by the elements rather than the elements of the complement (see \\S\\ref{subsection:cenum} for how to do this).\n\n \\item You use set comprehensions on types which do not provide an enumeration (i.e., they are represented as closures) or you chose to represent a map as a closure.\n\n A lot of operations are not implementable for closures, in particular those that return some element of the container\n\n Inspect the code equations with \\isacommand{code{\\isacharunderscore}thms} and look for calls to @{term \"Collect_set\"} and @{term \"Mapping\"} which are LC's constructor for sets and maps as closures.\n\n Note that the code generator preprocesses set comprehensions like @{term \"{i < 4|i :: int. i > 2}\"} to @{term \"(\\i :: int. i < 4) ` {i. i > 2}\"}, so this is a set comprehension over @{typ int} rather than @{typ bool}.\n \\end{enumerate}\n\\\n\n(*<*)\ndefinition test_set_impl_unsupported_operation1 :: \"unit \\ (int \\ int) set\"\nwhere \"test_set_impl_unsupported_operation1 _ = RBT_set RBT_Set2.empty \\ {}\"\n\ndefinition test_set_impl_unsupported_operation2 :: \"unit \\ bool set\"\nwhere \"test_set_impl_unsupported_operation2 _ = {i < 4 | i :: int. i > 2}\"\n\ndefinition test_mapping_impl_unsupported_operation :: \"unit \\ bool\"\nwhere \n \"test_mapping_impl_unsupported_operation _ = \n Mapping.is_empty (RBT_Mapping (RBT_Mapping2.empty) :: (Enum.finite_4, unit) mapping)\"\n\nML_val \\\nfun test_fail s f =\n let\n fun error s' = Fail (\"exception Fail \\\"\" ^ s ^ \"\\\" expected, but got \" ^ s')\n in\n (f (); raise (error \"no exception\") )\n handle\n Fail s' => if s = s' then () else raise (error s')\n end;\n\ntest_fail \"union RBT_set Set_Monad: ccompare = None\" @{code test_set_impl_unsupported_operation1};\ntest_fail \"image Collect_set\" @{code test_set_impl_unsupported_operation2};\ntest_fail \"is_empty RBT_Mapping: ccompare = None\" @{code test_mapping_impl_unsupported_operation};\n\\\n(*>*)\n\nsubsection \\LC slows down my code\\\n\ntext \\\n Normally, this will not happen, because LC's data structures are more efficient than Isabelle's list-based implementations.\n However, in some rare cases, you can experience a slowdown:\n\\\n(*<*)\ndefinition tiny_set :: \"nat set\"\nwhere tiny_set_code: \"tiny_set = {1, 2}\"\n(*>*)\ntext_raw \\\n \\isastyletext\n \\begin{enumerate}\n \\item \\textbf{Your containers contain just a few elements.}\n \\\\\n In that case, the overhead of the heuristics to pick an implementation outweighs the benefits of efficient implementations.\n You should identify the tiny containers and disable the heuristics locally.\n You do so by replacing the initial value like @{term \"{}\"} and @{term \"Mapping.empty\"} with low-overhead constructors like @{term \"Set_Monad\"} and @{term \"Mapping\"}.\n For example, if @{thm [source] tiny_set_code}: @{thm tiny_set_code} is your code equation with a tiny set,\n the following changes the code equation to directly use the list-based representation, i.e., disables the heuristics:\n \\par\n\\\nlemma empty_Set_Monad: \"{} = Set_Monad []\" by simp\ndeclare tiny_set_code[code del, unfolded empty_Set_Monad, code]\ntext_raw \\\n \\isastyletext\n \\par\n If you want to globally disable the heuristics, you can also declare an equation like @{thm [source] empty_Set_Monad} as [code].\n\n \\item \\textbf{The element type contains many type constructors and some type variables.}\n \\\\\n LC heavily relies on type classes, and type classes are implemented as dictionaries if the compiler cannot statically resolve them, i.e., if there are type variables.\n For type constructors with type variables (like @{typ \"'a * 'b\"}), LC's definitions of the type class parameters recursively calls itself on the type variables, i.e., @{typ \"'a\"} and @{typ \"'b\"}.\n If the element type is polymorphic, the compiler cannot precompute these recursive calls and therefore they have to be constructed repeatedly at run time.\n If you wrap your complicated type in a new type constructor, you can define optimised equations for the type class parameters.\n \\end{enumerate}\n\\\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Containers/Containers_Userguide.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.11920293297380237, "lm_q1q2_score": 0.05264871769057819}} {"text": "(*\n * Copyright 2019, NTU\n *\n * This software may be distributed and modified according to the terms of\n * the BSD 2-Clause license. Note that NO WARRANTY is provided.\n * See \"LICENSE_BSD2.txt\" for details.\n *\n * Author: Albert Rizaldi, NTU Singapore\n *)\n\ntheory Multiplexer_Hoare\n imports VHDL_Hoare_Complete\nbegin\n\ntext \\Define the new datatype for the all signals occurred in a multiplexer. A multiplexer has three\ninputs: in0, in1, and a selector.\\\n\ndatatype sig = IN0 | IN1 | SEL | OUT\n\n\\ \\We put suffix 2 because it only selects between two inputs\\\ndefinition mux2 :: \"sig conc_stmt\" where\n \"mux2 = process {IN0, IN1, SEL} : Bguarded (Bsig SEL)\n (Bassign_trans OUT (Bsig IN1) 1)\n (Bassign_trans OUT (Bsig IN0) 1)\"\n\nlemma potential_tyenv:\n assumes \"seq_wt \\ (Bguarded (Bsig SEL)\n (Bassign_trans OUT (Bsig IN1) 1)\n (Bassign_trans OUT (Bsig IN0) 1))\"\n shows \"\\ki len. \\ IN0 = Bty \\ \\ IN1 = Bty \\ \\ SEL = Bty \\ \\ OUT = Bty\n \\ \\ IN0 = Lty ki len \\ \\ IN1 = Lty ki len \\ \\ SEL = Bty \\ \\ OUT = Lty ki len\"\nproof (rule seq_wt_cases(3)[OF assms])\n assume \"bexp_wt \\ (Bsig SEL) Bty\"\n assume \"seq_wt \\ (Bassign_trans OUT (Bsig IN1) 1)\"\n assume \"seq_wt \\ (Bassign_trans OUT (Bsig IN0) 1)\"\n have \"\\ SEL = Bty\"\n by (rule bexp_wt_cases_all[OF \\bexp_wt \\ (Bsig SEL) Bty\\]) auto\n have \" bexp_wt \\ (Bsig IN1) (\\ OUT)\"\n using seq_wt_cases(4)[OF \\seq_wt \\ (Bassign_trans OUT (Bsig IN1) 1)\\] by auto\n hence \"\\ IN1 = \\ OUT\"\n by (rule bexp_wt_cases_all) auto\n have \"bexp_wt \\ (Bsig IN0) (\\ OUT)\"\n using seq_wt_cases(4)[OF \\seq_wt \\ (Bassign_trans OUT (Bsig IN0) 1)\\] by auto\n hence \"\\ IN0 = \\ OUT\"\n by (rule bexp_wt_cases_all) auto\n obtain ki len where \"\\ OUT = Bty \\ \\ OUT = Lty ki len\"\n using ty.exhaust by meson\n moreover\n { assume \"\\ OUT = Bty\"\n hence \"\\ IN0 = Bty\"\n by (simp add: \\\\ IN0 = \\ OUT\\)\n moreover have \"\\ IN1 = Bty\"\n using \\\\ IN1 = \\ OUT\\ \\\\ OUT = Bty\\ by auto\n ultimately have ?thesis\n using \\\\ OUT = Bty\\ \\\\ SEL = Bty\\ by blast }\n moreover\n { assume \"\\ OUT = Lty ki len\"\n moreover hence \"\\ IN0 = Lty ki len\" and \"\\ IN1 = Lty ki len\"\n using \\\\ IN0 = \\ OUT\\ \\\\ IN1 = \\ OUT\\ by auto\n ultimately have ?thesis\n using \\\\ SEL = Bty\\ by blast }\n ultimately show ?thesis\n by auto\nqed\n\nabbreviation \"bval_of_wline tw sig t \\ bval_of (wline_of tw sig t)\"\n\ndefinition mux2_inv :: \"sig assn2\" where\n \"mux2_inv \\ \\tw. (\\i < fst tw. wline_of tw OUT (i + 1) =\n (if bval_of_wline tw SEL i then wline_of tw IN1 i else wline_of tw IN0 i))\"\n\ndefinition mux2_inv' :: \"sig assn2\" where\n \"mux2_inv' \\ (\\tw. disjnt {IN0, IN1, SEL} (event_of tw) \\\n (\\i\\fst tw. wline_of tw OUT (i + 1) =\n (if bval_of_wline tw SEL (fst tw) then wline_of tw IN1 (fst tw) else wline_of tw IN0 (fst tw))))\"\n\nsubsection \\Proving that the sequential component preserves @{term \"mux2_inv\"}\\\n\nlemma mux2_inv_next_time:\n assumes \"mux2_inv tw\" and \"beval_world_raw2 tw (Bsig SEL) (Bv True)\"\n assumes \"beval_world_raw2 tw (Bsig IN1) v\"\n defines \"tw' \\ tw[ OUT, 1 :=\\<^sub>2 v]\"\n shows \"\\j \\ {fst tw' <.. next_time_world tw'}. mux2_inv (j, snd tw')\"\nproof (rule)\n fix j\n assume \"j \\ {fst tw' <.. next_time_world tw'}\"\n have assms2: \"beval_world_raw (snd tw) (fst tw) (Bsig SEL) (Bv True)\"\n using assms(2) unfolding beval_world_raw2_def by auto\n have \"bval_of_wline tw SEL (fst tw)\"\n by (rule beval_world_raw_cases[OF assms2], erule beval_cases)\n (metis comp_def state_of_world_def val.sel(1))\n have \"fst tw' < j\"\n using next_time_world_at_least using nat_less_le \n using \\j \\ {get_time tw'<..next_time_world tw'}\\ by auto\n moreover have \"fst tw = fst tw'\"\n unfolding tw'_def worldline_upd2_def worldline_upd_def by auto\n ultimately have \"fst tw < j\"\n by auto\n have 0: \"bval_of_wline tw' SEL (fst tw)= bval_of_wline tw SEL (fst tw)\" and 1: \"wline_of tw IN1 (fst tw) = wline_of tw' IN1 (fst tw)\"\n and 2: \"wline_of tw IN0 (fst tw) = wline_of tw' IN0 (fst tw)\"\n unfolding tw'_def worldline_upd2_def worldline_upd_def by simp+\n have \"\\i < j. wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n proof (rule, rule)\n fix i\n assume \"i < j\"\n have \"i < fst tw \\ fst tw \\ i \\ i < j - 1 \\ i = j - 1\"\n using next_time_world_at_least \\i < j\\ not_less by linarith\n moreover\n { assume \"i < fst tw\"\n hence \"wline_of tw OUT (i + 1) = (if bval_of_wline tw SEL i then wline_of tw IN1 i else wline_of tw IN0 i)\"\n using assms(1) unfolding mux2_inv_def by auto\n moreover have \"wline_of tw OUT (i + 1) = wline_of tw' OUT (i + 1)\" and \"wline_of tw IN1 i = wline_of tw' IN1 i\" and \"wline_of tw IN0 i = wline_of tw' IN0 i\"\n unfolding tw'_def worldline_upd2_def worldline_upd_def by (simp add: \\i < get_time tw\\)+\n ultimately have \"wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n by (metis \\i < get_time tw\\ add.right_neutral add_mono_thms_linordered_field(5) tw'_def\n worldline_upd2_before_dly zero_less_one) }\n moreover\n { assume \"fst tw \\ i \\ i < j - 1\"\n hence \"wline_of tw' OUT (i + 1) = wline_of tw' OUT (fst tw + 1)\"\n using unchanged_until_next_time_world\n by (smt \\get_time tw = get_time tw'\\ \\j \\ {get_time tw'<..next_time_world tw'}\\\n dual_order.strict_trans1 greaterThanAtMost_iff le_add1 less_diff_conv not_less)\n moreover have \"wline_of tw' IN1 i = wline_of tw' IN1 (fst tw)\" and \"wline_of tw' IN0 i = wline_of tw' IN0 (fst tw)\"\n and \"wline_of tw' SEL i = wline_of tw' SEL (fst tw)\"\n using unchanged_until_next_time_world \\fst tw \\ i \\ i < j - 1\\\n by (metis (no_types, lifting) \\get_time tw = get_time tw'\\ \\i < j\\ \\j \\ {get_time\n tw'<..next_time_world tw'}\\ dual_order.strict_trans1 greaterThanAtMost_iff)+\n moreover have \"wline_of tw' OUT (fst tw + 1) =\n (if bval_of_wline tw' SEL (fst tw) then wline_of tw' IN1 (fst tw) else wline_of tw' IN0 (fst tw))\"\n proof -\n have \"wline_of tw' OUT (fst tw + 1) = v\"\n using \\fst tw \\ i \\ i < j - 1\\ unfolding tw'_def worldline_upd2_def worldline_upd_def\n by auto\n also have \"... = wline_of tw IN1 (fst tw)\"\n by (metis assms(3) beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic)\n also have \" ... = (if bval_of_wline tw SEL (fst tw) then wline_of tw IN1 (fst tw) else wline_of tw IN0 (fst tw))\"\n using \\bval_of_wline tw SEL (fst tw)\\ by auto\n \\ \\notice the change from @{term \"tw\"} to @{term \"tw'\"}\\\n also have \"... = (if bval_of_wline tw' SEL (fst tw) then wline_of tw' IN1 (fst tw) else wline_of tw' IN0 (fst tw))\"\n using 0 1 2 by auto\n thus \"wline_of tw' OUT (fst tw + 1) = (if bval_of_wline tw' SEL (fst tw) then wline_of tw' IN1 (fst tw) else wline_of tw' IN0 (fst tw))\"\n using \\bval_of_wline tw SEL (get_time tw)\\ \\v = wline_of tw IN1 (get_time tw)\\ \\wline_of\n tw' OUT (get_time tw + 1) = v\\ by auto\n qed\n ultimately have \"wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n by auto }\n moreover\n { assume \"i = j - 1\"\n hence \"wline_of tw' OUT (i + 1) = wline_of tw' OUT j\"\n using \\i < j\\ by auto\n also have \"... = wline_of tw' OUT (fst tw + 1)\"\n using \\fst tw < j\\ unfolding tw'_def worldline_upd2_def worldline_upd_def by auto\n also have \"... = (if bval_of_wline tw' SEL (fst tw) then wline_of tw' IN1 (fst tw) else wline_of tw' IN0 (fst tw))\"\n proof -\n have \"wline_of tw' OUT (fst tw + 1) = wline_of tw IN1 (fst tw)\"\n unfolding tw'_def\n by (rule beval_world_raw_cases[OF assms2], erule beval_cases)\n (metis assms(3) beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic worldline_upd2_at_dly)\n \\ \\notice that we use @{term \"tw'\"} on the else part; no point of using @{term \"tw\"}\\\n also have \"... = (if bval_of_wline tw SEL (fst tw) then wline_of tw IN1 (fst tw) else wline_of tw' IN0 (fst tw))\"\n using \\bval_of_wline tw SEL (fst tw)\\ by auto\n also have \"... = (if bval_of_wline tw' SEL (fst tw) then wline_of tw' IN1 (fst tw) else wline_of tw' IN0 (fst tw))\"\n using 0 1 by auto\n finally show ?thesis by auto\n qed\n also have \"... = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n by (smt \\get_time tw = get_time tw'\\ \\i < get_time tw \\ wline_of tw' OUT (i + 1) = (if\n bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\\ \\i < j\\ \\j \\\n {get_time tw'<..next_time_world tw'}\\ calculation dual_order.strict_trans1\n greaterThanAtMost_iff not_le unchanged_until_next_time_world)\n finally have \"wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n by auto }\n ultimately show \"wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n by auto\n qed\n thus \"mux2_inv (j, snd tw')\"\n unfolding mux2_inv_def by auto\nqed\n\nlemma mux2_inv_next_time':\n assumes \"mux2_inv tw\" and \"beval_world_raw2 tw (Bsig SEL) (Bv False)\"\n assumes \"beval_world_raw2 tw (Bsig IN0) v\"\n defines \"tw' \\ tw[ OUT, 1 :=\\<^sub>2 v]\"\n shows \"\\j \\ {fst tw' <.. next_time_world tw'}. mux2_inv (j, snd tw')\"\nproof (rule)\n fix j\n assume \"j \\ {fst tw' <.. next_time_world tw'}\"\n have assms2: \"beval_world_raw (snd tw) (fst tw) (Bsig SEL) (Bv False)\"\n using assms(2) unfolding beval_world_raw2_def by auto\n have \"\\ bval_of_wline tw SEL (fst tw)\"\n by (rule beval_world_raw_cases[OF assms2], erule beval_cases)\n (metis comp_def state_of_world_def val.sel(1))\n have \"fst tw' < next_time_world tw'\"\n using next_time_world_at_least using nat_less_le by blast\n moreover have \"fst tw = fst tw'\"\n unfolding tw'_def worldline_upd2_def worldline_upd_def by auto\n ultimately have \"fst tw < next_time_world tw'\"\n by auto\n have 0: \"bval_of_wline tw' SEL (fst tw)= bval_of_wline tw SEL (fst tw)\" and 1: \"wline_of tw IN1 (fst tw) = wline_of tw' IN1 (fst tw)\"\n and 2: \"wline_of tw IN0 (fst tw) = wline_of tw' IN0 (fst tw)\"\n unfolding tw'_def worldline_upd2_def worldline_upd_def by simp+\n have \"\\i < j. wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n proof (rule, rule)\n fix i\n assume \"i < j\"\n have \"i < fst tw \\ fst tw \\ i \\ i < j - 1 \\ i = j - 1\"\n using next_time_world_at_least \\i < j\\ not_less by linarith\n moreover\n { assume \"i < fst tw\"\n hence \"wline_of tw OUT (i + 1) = (if bval_of_wline tw SEL i then wline_of tw IN1 i else wline_of tw IN0 i)\"\n using assms(1) unfolding mux2_inv_def by auto\n moreover have \"wline_of tw OUT (i + 1) = wline_of tw' OUT (i + 1)\" and \"wline_of tw IN1 i = wline_of tw' IN1 i\" and \"wline_of tw IN0 i = wline_of tw' IN0 i\"\n unfolding tw'_def worldline_upd2_def worldline_upd_def by (simp add: \\i < get_time tw\\)+\n ultimately have \"wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n by (metis \\i < get_time tw\\ add.right_neutral add_mono_thms_linordered_field(5) tw'_def\n worldline_upd2_before_dly zero_less_one) }\n moreover\n { assume \"fst tw \\ i \\ i < j - 1\"\n hence \"wline_of tw' OUT (i + 1) = wline_of tw' OUT (fst tw + 1)\"\n using unchanged_until_next_time_world\n by (smt \\get_time tw = get_time tw'\\ \\j \\ {get_time tw'<..next_time_world tw'}\\\n dual_order.strict_trans1 greaterThanAtMost_iff le_add1 less_diff_conv not_less)\n moreover have \"wline_of tw' IN1 i = wline_of tw' IN1 (fst tw)\" and \"wline_of tw' IN0 i = wline_of tw' IN0 (fst tw)\"\n and \"bval_of_wline tw' SEL i \\ bval_of_wline tw' SEL (fst tw)\"\n using unchanged_until_next_time_world \\fst tw \\ i \\ i < j - 1\\\n by (metis (no_types, lifting) \\get_time tw = get_time tw'\\ \\i < j\\ \\j \\ {get_time\n tw' <..next_time_world tw'}\\ dual_order.strict_trans1 greaterThanAtMost_iff)+\n moreover have \"wline_of tw' OUT (fst tw + 1) =\n (if bval_of_wline tw' SEL (fst tw) then wline_of tw' IN1 (fst tw) else wline_of tw' IN0 (fst tw))\"\n proof -\n have \"wline_of tw' OUT (fst tw + 1) = v\"\n using \\fst tw \\ i \\ i < j - 1\\ unfolding tw'_def worldline_upd2_def worldline_upd_def\n by auto\n have \" ... = wline_of tw IN0 (fst tw)\"\n by (rule beval_world_raw_cases[OF assms2], erule beval_cases)\n (metis assms(3) beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic)\n also have \"... = (if bval_of_wline tw SEL (fst tw) then wline_of tw IN1 (fst tw) else wline_of tw IN0 (fst tw))\"\n using \\\\ bval_of_wline tw SEL (fst tw)\\ by auto\n \\ \\notice the change from @{term \"tw\"} to @{term \"tw'\"}\\\n also have \"... = (if bval_of_wline tw' SEL (fst tw) then wline_of tw' IN1 (fst tw) else wline_of tw' IN0 (fst tw))\"\n using 0 1 2 by auto\n finally show \"wline_of tw' OUT (fst tw + 1) = (if bval_of_wline tw' SEL (fst tw) then wline_of tw' IN1 (fst tw) else wline_of tw' IN0 (fst tw))\"\n using \\wline_of tw' OUT (get_time tw + 1) = v\\ by blast\n qed\n ultimately have \"wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n by auto }\n moreover\n { assume \"i = j - 1\"\n hence \"wline_of tw' OUT (i + 1) = wline_of tw' OUT j\"\n using \\i < j\\ by auto\n also have \"... = wline_of tw' OUT (fst tw + 1)\"\n unfolding tw'_def worldline_upd2_def worldline_upd_def using \\j \\ {get_time tw' <..next_time_world tw'}\\ \n by (simp add: \\get_time tw = get_time tw'\\ discrete)\n also have \"... = (if bval_of_wline tw' SEL (fst tw) then wline_of tw' IN1 (fst tw) else wline_of tw' IN0 (fst tw))\"\n proof -\n have \"wline_of tw' OUT (fst tw + 1) = wline_of tw IN0 (fst tw)\"\n by (rule beval_world_raw_cases[OF assms2], erule beval_cases)\n (metis assms(3) beval_world_raw2_Bsig beval_world_raw2_def beval_world_raw_deterministic tw'_def worldline_upd2_at_dly)\n \\ \\notice that we use @{term \"tw'\"} on the else part; no point of using @{term \"tw\"}\\\n have \" ... = (if bval_of_wline tw SEL (fst tw) then wline_of tw' IN1 (fst tw) else wline_of tw IN0 (fst tw))\"\n using \\\\ bval_of_wline tw SEL (fst tw)\\ by auto\n also have \"... = (if bval_of_wline tw' SEL (fst tw) then wline_of tw' IN1 (fst tw) else wline_of tw' IN0 (fst tw))\"\n using 0 2 by auto\n finally show ?thesis\n using \\wline_of tw' OUT (get_time tw + 1) = wline_of tw IN0 (get_time tw)\\ by auto\n qed\n also have \"... = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n by (smt \\get_time tw = get_time tw'\\ \\i < get_time tw \\ wline_of tw' OUT (i + 1) = (if\n bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\\ \\i < j\\ \\j \\\n {get_time tw' <..next_time_world tw'}\\ calculation dual_order.strict_trans1\n greaterThanAtMost_iff not_le unchanged_until_next_time_world)\n finally have \"wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n by auto }\n ultimately show \"wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n by auto\n qed\n thus \"mux2_inv (j, snd tw')\"\n unfolding mux2_inv_def by auto\nqed\n\nlemma mux2_seq_hoare_next_time_if:\n \"\\ [\\tw. (mux2_inv tw \\ wityping \\ (snd tw)) \\ beval_world_raw2 tw (Bsig SEL) (Bv True)] \n Bassign_trans OUT (Bsig IN1) 1 \n [\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv (j, snd tw)]\"\n apply (rule Conseq2[where Q=\"\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv (j, snd tw)\", rotated 1], rule Assign2, simp)\n using mux2_inv_next_time by blast\n\nlemma mux2_seq_hoare_next_time_else:\n \"\\ [\\tw. (mux2_inv tw \\ wityping \\ (snd tw)) \\ beval_world_raw2 tw (Bsig SEL) (Bv False)] \n Bassign_trans OUT (Bsig IN0) 1 \n [\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv (j, snd tw)]\"\n apply (rule Conseq2[where Q=\"\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv (j, snd tw)\", rotated 1], rule Assign2, simp)\n using mux2_inv_next_time' by blast\n\ntheorem mux2_seq_hoare_next_time:\n \"\\ [\\tw. mux2_inv tw \\ wityping \\ (snd tw)]\n Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1)\n [\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv (j, snd tw)]\"\n apply (rule Conseq2[where Q=\"\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv (j, snd tw)\" and P = \"\\tw. mux2_inv tw \\ wityping \\ (snd tw)\", rotated 1], rule If2)\n apply (rule mux2_seq_hoare_next_time_if)\n apply (rule mux2_seq_hoare_next_time_else)\n apply simp+\n done\n\ntheorem mux2_seq_hoare_next_time_wityping:\n assumes \"seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\"\n shows\"\n \\ [\\tw. mux2_inv tw \\ wityping \\ (snd tw)]\n Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1)\n [\\tw. mux2_inv (next_time_world tw, snd tw) \\ wityping \\ (snd tw)]\"\n apply (rule Conj)\n apply (rule Conseq2[rotated])\n apply (rule mux2_seq_hoare_next_time[where \\=\"\\\"])\n apply (simp add: next_time_world_at_least)\n apply simp\n apply (rule strengthen_precondition2)\n apply (rule seq_stmt_preserve_wityping_hoare)\n apply (rule assms)\n done\n\ntheorem mux2_seq_hoare_next_time0:\n \"\\ [\\tw. fst tw = 0 \\ wityping \\ (snd tw)]\n Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1)\n [\\tw. mux2_inv (next_time_world tw, snd tw)]\"\n apply (rule Conseq2[where P=\"\\tw. mux2_inv tw \\ wityping \\ (snd tw)\" and Q=\"\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv (j, snd tw)\"])\n apply (simp add: mux2_inv_def) \n apply (rule mux2_seq_hoare_next_time)\n by (simp add: next_time_world_at_least)\n\ntheorem mux2_seq_hoare_next_time0_wityping:\n assumes \"seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\"\n shows\n \"\\ [\\tw. fst tw = 0 \\ wityping \\ (snd tw)]\n Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1)\n [\\tw. mux2_inv (next_time_world tw, snd tw) \\ wityping \\ (snd tw)]\"\n apply (rule Conj)\n apply (rule mux2_seq_hoare_next_time0)\n apply (rule strengthen_precondition2)\n apply (rule seq_stmt_preserve_wityping_hoare)\n apply (rule assms)\n done\n\nsubsection \\Proving that the sequential component preserves @{term \"mux2_inv'\"}\\\n\nlemma input_signals_unchanged:\n fixes tw any\n assumes \"beval_world_raw2 tw (Bsig any) v\"\n defines \"tw' \\ tw[ OUT, 1 :=\\<^sub>2 v]\"\n defines \"t' \\ next_time_world tw'\"\n assumes \"disjnt {IN0, IN1, SEL} (event_of (t', snd tw'))\"\n shows \"\\s. s \\ {IN0, IN1, SEL} \\ wline_of tw' s t' = wline_of tw s (fst tw)\"\nproof -\n fix s\n assume \"s \\ {IN0, IN1, SEL}\"\n have \"fst tw' < t'\"\n using next_time_world_at_least unfolding t'_def by blast\n moreover have \"fst tw = fst tw'\"\n unfolding tw'_def unfolding worldline_upd2_def by auto\n ultimately have \"fst tw < t'\"\n by auto\n have \"wline_of tw' s t' = wline_of tw s t'\"\n using \\s \\ {IN0, IN1, SEL}\\ unfolding tw'_def worldline_upd2_def worldline_upd_def by auto\n also have \"... = wline_of tw s (t' - 1)\"\n using \\disjnt {IN0, IN1, SEL} (event_of (t', snd tw'))\\ \\fst tw < t'\\\n unfolding event_of_alt_def\n by (smt \\s \\ {IN0, IN1, SEL}\\ comp_apply disjnt_insert1 fst_conv gr_implies_not_zero insert_iff\n mem_Collect_eq sig.distinct(12) sig.distinct(5) sig.distinct(9) singletonD snd_conv tw'_def\n worldline_upd2_def worldline_upd_def)\n also have \"... = wline_of tw s (fst tw)\"\n proof -\n have \"fst tw' \\ t' - 1\" and \"t' - 1 < t'\"\n using \\fst tw' < t'\\ by auto\n hence \"wline_of tw' s (t' - 1) = wline_of tw' s (fst tw')\"\n using unchanged_until_next_time_world[where tw=\"tw'\"] unfolding t'_def by blast\n moreover have \"wline_of tw' s (t' - 1) = wline_of tw s (t' - 1)\"\n unfolding tw'_def worldline_upd2_def worldline_upd_def using \\s \\ {IN0, IN1, SEL}\\ by auto\n moreover have \"wline_of tw' s (fst tw') = wline_of tw s (fst tw')\"\n unfolding tw'_def worldline_upd2_def worldline_upd_def by auto\n ultimately show ?thesis\n using \\fst tw = fst tw'\\ by auto\n qed\n finally show \"wline_of tw' s t' = wline_of tw s (fst tw)\"\n by auto\nqed\n\nlemma mux2_inv'_next_time:\n assumes \"beval_world_raw2 tw (Bsig SEL) (Bv True)\"\n assumes \"beval_world_raw2 tw (Bsig IN1) v\"\n defines \"tw' \\ tw[ OUT, 1 :=\\<^sub>2 v]\"\n shows \"\\j \\ {fst tw' <.. next_time_world tw'}. mux2_inv' (j, snd tw')\"\nproof (rule)\n fix j\n assume \"j \\ {fst tw' <.. next_time_world tw'}\"\n have assms1: \"beval_world_raw (snd tw) (fst tw) (Bsig SEL) (Bv True)\"\n using assms(1) unfolding beval_world_raw2_def by auto\n have \"bval_of_wline tw SEL (fst tw)\"\n apply (rule beval_world_raw_cases[OF assms1], erule beval_cases)\n by (metis comp_def state_of_world_def val.sel(1))\n { assume \"disjnt {IN0, IN1, SEL} (event_of (j, snd tw'))\"\n have \"fst tw' < j\"\n using next_time_world_at_least \n using \\j \\ {get_time tw'<..next_time_world tw'}\\ greaterThanAtMost_iff by blast\n moreover have \"fst tw = fst tw'\"\n unfolding tw'_def unfolding worldline_upd2_def by auto\n ultimately have \"fst tw < j\"\n by auto\n have *: \"\\s. s \\ {IN0, IN1, SEL} \\ wline_of tw' s j = wline_of tw s (fst tw)\"\n using \\disjnt {IN0, IN1, SEL} (event_of (j, snd tw'))\\\n input_signals_unchanged tw'_def assms(2) assms(3) \n by (metis \\get_time tw = get_time tw'\\ \\j \\ {get_time tw'<..next_time_world tw'}\\\n greaterThanAtMost_iff le_neq_implies_less less_add_one less_imp_le_nat\n unchanged_until_next_time_world worldline_upd2_before_dly)\n have \"\\i. j \\ i \\ wline_of tw' OUT (i + 1) =\n (if bval_of_wline tw' SEL j then wline_of tw' IN1 j else wline_of tw' IN0 j)\"\n proof -\n fix i\n assume \"j \\ i\"\n have assms2: \"beval_world_raw (snd tw) (fst tw) (Bsig IN1) v\"\n using assms(2) unfolding beval_world_raw2_def by auto\n have \"wline_of tw' OUT (i + 1) = wline_of tw IN1 (fst tw)\"\n apply (rule beval_world_raw_cases[OF assms2], erule beval_cases)\n using `j \\ i` `fst tw < j` unfolding tw'_def worldline_upd2_def worldline_upd_def\n by (simp add: state_of_world_def)\n also have \"... = (if bval_of_wline tw SEL (fst tw) then wline_of tw IN1 (fst tw) else wline_of tw' IN0 j)\"\n using \\bval_of_wline tw SEL (fst tw)\\ by (simp add: state_of_world_def)\n also have \"... = (if bval_of_wline tw' SEL j then wline_of tw' IN1 j else wline_of tw' IN0 j)\"\n using * by auto\n finally show \"wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL j then wline_of tw' IN1 j else wline_of tw' IN0 j)\"\n by auto\n qed }\n thus \" mux2_inv' (j, snd tw')\"\n unfolding mux2_inv'_def by auto\nqed\n\nlemma mux2_inv'_next_time2:\n assumes \"beval_world_raw2 tw (Bsig SEL) (Bv False)\"\n assumes \"beval_world_raw2 tw (Bsig IN0) v\"\n defines \"tw' \\ tw[ OUT, 1 :=\\<^sub>2 v]\"\n shows \"\\j \\ {fst tw' <.. next_time_world tw'}. mux2_inv' (j, snd tw')\"\nproof (rule)\n fix j\n assume \"j \\ {fst tw' <.. next_time_world tw'}\"\n have assms1: \"beval_world_raw (snd tw) (fst tw) (Bsig SEL) (Bv False)\"\n using assms(1) unfolding beval_world_raw2_def by auto\n have \"\\ bval_of_wline tw SEL (fst tw)\"\n by (rule beval_world_raw_cases[OF assms1], erule beval_cases)\n (metis comp_def state_of_world_def val.sel(1))\n { assume \"disjnt {IN0, IN1, SEL} (event_of (j , snd tw'))\"\n have \"fst tw' < j \"\n using next_time_world_at_least \\j \\ {get_time tw'<..next_time_world tw'}\\ by auto\n moreover have \"fst tw = fst tw'\"\n unfolding tw'_def unfolding worldline_upd2_def by auto\n ultimately have \"fst tw < j \"\n by auto\n have *: \"\\s. s \\ {IN0, IN1, SEL} \\ wline_of tw' s j = wline_of tw s (fst tw)\"\n using \\disjnt {IN0, IN1, SEL} (event_of (j, snd tw'))\\\n input_signals_unchanged tw'_def assms(2) assms(3) \n by (metis \\get_time tw = get_time tw'\\ \\j \\ {get_time tw'<..next_time_world tw'}\\\n greaterThanAtMost_iff le_neq_implies_less less_add_one less_imp_le_nat\n unchanged_until_next_time_world worldline_upd2_before_dly)\n have \"\\i. j \\ i \\ wline_of tw' OUT (i + 1) =\n (if bval_of_wline tw' SEL j then wline_of tw' IN1 j else wline_of tw' IN0 j )\"\n proof -\n fix i\n assume \"j \\ i\"\n have assms2: \"beval_world_raw (snd tw) (fst tw) (Bsig IN0) v\"\n using assms(2) unfolding beval_world_raw2_def by auto\n have \"wline_of tw' OUT (i + 1) = wline_of tw IN0 (fst tw)\"\n apply (rule beval_world_raw_cases[OF assms2], erule beval_cases)\n using `fst tw < j ` and `j \\ i` unfolding tw'_def worldline_upd2_def worldline_upd_def\n state_of_world_def by auto\n also have \"... = (if bval_of_wline tw SEL (fst tw) then wline_of tw IN1 (fst tw) else wline_of tw IN0 (fst tw))\"\n using \\\\ bval_of_wline tw SEL (fst tw)\\ by (simp add: state_of_world_def)\n also have \"... = (if bval_of_wline tw' SEL j then wline_of tw' IN1 j else wline_of tw' IN0 j )\"\n using * by auto\n finally show \"wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL j then wline_of tw' IN1 j else wline_of tw' IN0 j )\"\n by auto\n qed }\n thus \"mux2_inv' (j, snd tw')\"\n unfolding mux2_inv'_def by auto\nqed\n\nlemma mux2_seq_hoare_next_time_if':\n \"\\ [\\tw. wityping \\ (snd tw) \\ beval_world_raw2 tw (Bsig SEL) (Bv True)] \n Bassign_trans OUT (Bsig IN1) 1 \n [\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv' (j, snd tw)]\"\n apply (rule Conseq2[where Q=\"\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv' (j, snd tw)\", rotated 1], rule Assign2, simp)\n using mux2_inv'_next_time by blast\n \nlemma mux2_seq_hoare_next_time_else':\n \" \\ [\\tw. wityping \\ (snd tw) \\ beval_world_raw2 tw (Bsig SEL) (Bv False)] \n Bassign_trans OUT (Bsig IN0) 1 \n [\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv' (j, snd tw)]\"\n apply (rule Conseq2[where Q=\"\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv' (j, snd tw)\", rotated 1], rule Assign2, simp)\n using mux2_inv'_next_time2 by blast\n\ntheorem mux2_seq_hoare_next_time':\n \"\\ [\\tw. wityping \\ (snd tw)] \n Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1) \n [\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv' (j, snd tw)]\"\n apply (rule Conseq2[where Q=\"\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv' (j, snd tw)\" and P = \"\\tw. wityping \\ (snd tw)\", rotated 1], rule If2)\n apply (rule mux2_seq_hoare_next_time_if')\n apply (rule mux2_seq_hoare_next_time_else')\n apply simp+\n done\n\ntheorem mux2_seq_hoare_next_time'_wityping:\n assumes \"seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\"\n shows\n \"\\ [\\tw. wityping \\ (snd tw)]\n Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1)\n [\\tw. (\\j \\ {fst tw <.. next_time_world tw}. mux2_inv' (j, snd tw)) \\ wityping \\ (snd tw)]\"\n apply (rule Conj)\n apply (rule mux2_seq_hoare_next_time')\n apply (rule seq_stmt_preserve_wityping_hoare)\n apply (rule assms)\n done\n\nsubsection \\Proving that the concurrent component\\\n\nlemma mux2_inv_conc_hoare:\n \"\\tw. mux2_inv tw \\ mux2_inv' tw \\ disjnt {IN0, IN1, SEL} (event_of tw) \\ \\k \\ {fst tw <.. next_time_world tw}. mux2_inv (k, snd tw)\"\nproof (rule)\n fix k\n fix tw :: \"nat \\ (sig \\ val) \\ (sig \\ nat \\ val)\"\n assume \"k \\ {fst tw <.. next_time_world tw}\"\n assume \"mux2_inv tw \\ mux2_inv' tw \\ disjnt {IN0, IN1, SEL} (event_of tw)\"\n hence \"mux2_inv tw\" and \"mux2_inv' tw\" and \"disjnt {IN0, IN1, SEL} (event_of tw)\"\n by auto\n hence *: \"\\i < fst tw. wline_of tw OUT (i + 1) = (if bval_of_wline tw SEL i then wline_of tw IN1 i else wline_of tw IN0 i)\"\n unfolding mux2_inv_def by auto\n have **: \"\\i\\fst tw. i < next_time_world tw \\ (\\s. wline_of tw s i = wline_of tw s (fst tw))\"\n using unchanged_until_next_time_world by blast\n have ***: \"(\\i\\ fst tw. wline_of tw OUT (i + 1) = (if bval_of_wline tw SEL (fst tw) then wline_of tw IN1 (fst tw) else wline_of tw IN0 (fst tw)))\"\n using \\mux2_inv' tw\\ \\disjnt {IN0, IN1, SEL} (event_of tw)\\ unfolding mux2_inv'_def by auto\n\n \\ \\obtain the value of A and B at time fst tw\\\n have \"wline_of tw SEL (fst tw) = wline_of tw SEL (fst tw - 1)\" and \"wline_of tw IN0 (fst tw) = wline_of tw IN0 (fst tw - 1)\"\n and \"wline_of tw IN1 (fst tw) = wline_of tw IN1 (fst tw - 1)\"\n using \\disjnt {IN0, IN1, SEL} (event_of tw)\\ unfolding event_of_alt_def\n by (smt diff_0_eq_0 disjnt_insert1 mem_Collect_eq)+\n { fix i\n assume \"i < k\"\n have \"i < fst tw \\ fst tw \\ i\"\n by auto\n moreover\n { assume \"i < fst tw\"\n hence \"wline_of tw OUT (i + 1) = (if bval_of_wline tw SEL i then wline_of tw IN1 i else wline_of tw IN0 i)\"\n using * by auto }\n moreover\n { assume \"fst tw \\ i\"\n hence \"wline_of tw OUT (i + 1) = wline_of tw OUT (fst tw + 1)\"\n using *** by auto\n also have \"... = (if bval_of_wline tw SEL (fst tw) then wline_of tw IN1 (fst tw) else wline_of tw IN0 (fst tw))\"\n using *** \\fst tw \\ i\\ by auto\n also have \"... = (if bval_of_wline tw SEL i then wline_of tw IN1 i else wline_of tw IN0 i)\"\n using ** \\i < k\\ \\fst tw \\ i\\ less_imp_le_nat \n by (smt \\k \\ {get_time tw<..next_time_world tw}\\ dual_order.strict_trans1\n greaterThanAtMost_iff)\n finally have \"wline_of tw OUT (i + 1) = (if bval_of_wline tw SEL i then wline_of tw IN1 i else wline_of tw IN0 i)\"\n by auto }\n ultimately have \"wline_of tw OUT (i + 1) = (if bval_of_wline tw SEL i then wline_of tw IN1 i else wline_of tw IN0 i)\"\n by auto }\n hence \"\\i. i < k \\ wline_of tw OUT (i + 1) = (if bval_of_wline tw SEL i then wline_of tw IN1 i else wline_of tw IN0 i)\"\n by auto\n thus \" mux2_inv (k, snd tw)\"\n unfolding mux2_inv_def by auto\nqed\n\nlemma mux2_inv'_conc_hoare:\n \"\\tw. mux2_inv tw \\ mux2_inv' tw \\ disjnt {IN0, IN1, SEL} (event_of tw) \\ \\j \\ {fst tw <.. next_time_world tw}. mux2_inv' (j, snd tw)\"\nproof (rule)\n fix tw :: \"nat \\ (sig \\ val) \\ (sig \\ nat \\ val)\"\n fix j\n assume \"j \\ {fst tw <.. next_time_world tw}\"\n assume \"mux2_inv tw \\ mux2_inv' tw \\ disjnt {IN0, IN1, SEL} (event_of tw)\"\n hence \"mux2_inv tw\" and \"mux2_inv' tw\" and \"disjnt {IN0, IN1, SEL} (event_of tw)\"\n by auto\n hence 0: \"(\\i\\fst tw. wline_of tw OUT (i + 1) = (if bval_of_wline tw SEL (get_time tw) then wline_of tw IN1 (get_time tw) else wline_of tw IN0 (get_time tw)))\"\n unfolding mux2_inv'_def by auto\n have 1: \"\\i\\fst tw. i < next_time_world tw \\ (\\s. wline_of tw s i = wline_of tw s (fst tw))\"\n using unchanged_until_next_time_world by blast\n { assume \"disjnt {IN0, IN1, SEL} (event_of (j, snd tw))\"\n hence *: \"wline_of tw IN0 j = wline_of tw IN0 (j - 1)\" and **: \"wline_of tw IN1 j = wline_of tw IN1 (j - 1)\"\n and ***: \"wline_of tw SEL j = wline_of tw SEL (j - 1)\"\n unfolding event_of_alt_def\n by (smt comp_apply diff_is_0_eq' disjnt_insert1 fst_conv le_numeral_extra(1) mem_Collect_eq snd_conv)+\n have \"fst tw < j\"\n using \\j \\ {get_time tw<..next_time_world tw}\\ by auto\n { fix i\n assume \"j \\ i\"\n hence \"wline_of tw OUT (i + 1) = (if bval_of_wline tw SEL (fst tw) then wline_of tw IN1 (fst tw) else wline_of tw IN0 (fst tw))\"\n using 0 \\fst tw < j\\ by auto\n moreover have \"wline_of tw IN0 (fst tw) = wline_of tw IN0 (j - 1)\" and \"wline_of tw IN1 (fst tw) = wline_of tw IN1 (j - 1)\"\n and \"wline_of tw SEL (fst tw) = wline_of tw SEL (j - 1)\"\n using 1\n by (metis (no_types, lifting) \\j \\ {get_time tw<..next_time_world tw}\\ add_le_cancel_right\n diff_add diff_is_0_eq' discrete gr_implies_not_zero greaterThanAtMost_iff\n le_numeral_extra(4) neq0_conv)+\n ultimately have \"wline_of tw OUT (i + 1) = (if bval_of_wline tw SEL j then wline_of tw IN1 j else wline_of tw IN0 j)\"\n using * ** *** by auto\n }\n hence \"(\\i\\j. wline_of tw OUT (i + 1) = (if bval_of_wline tw SEL j then wline_of tw IN1 j else wline_of tw IN0 j))\"\n by auto }\n thus \"mux2_inv' (j, snd tw)\"\n unfolding mux2_inv'_def by auto\nqed\n\nlemma mux2_conc_hoare_without:\n assumes \"seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\"\n shows\n \"\\ \\\\tw. (mux2_inv tw \\ mux2_inv' tw) \\ wityping \\ (snd tw)\\\n mux2\n \\\\tw. \\j \\ {fst tw <.. next_time_world tw}. mux2_inv (j, snd tw) \\ mux2_inv' (j, snd tw)\\\"\n unfolding mux2_def\n apply (rule Single)\n apply (rule Conj_univ_qtfd)\n apply (rule Conseq2[rotated])\n apply (rule mux2_seq_hoare_next_time[where \\=\"\\\"])\n apply simp\n apply simp\n apply(rule Conseq2[rotated])\n apply (rule mux2_seq_hoare_next_time'[where \\=\"\\\"])\n apply simp\n apply simp \n using mux2_inv_conc_hoare mux2_inv'_conc_hoare by blast\n\nlemma mux2_conc_hoare:\n assumes \"seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\"\n shows\n \"\\ \\\\tw. (mux2_inv tw \\ mux2_inv' tw) \\ wityping \\ (snd tw)\\\n mux2\n \\\\tw. \\i\\{get_time tw<..next_time_world tw}. (mux2_inv (i, snd tw) \\ mux2_inv' (i, snd tw)) \\ wityping \\ (snd (i, snd tw))\\\"\n apply (rule Conj2_univ_qtfd)\n apply (rule weaken_post_conc_hoare[OF _ mux2_conc_hoare_without], blast)\n apply(rule assms)\n apply (rule strengthen_pre_conc_hoare[rotated])\n apply (rule weaken_post_conc_hoare[rotated])\n unfolding mux2_def apply (rule single_conc_stmt_preserve_wityping_hoare)\n apply (rule assms)\n apply simp\n by auto\n\nsubsection \\Simulation preserves the invariant\\\n\nlemma mux2_conc_sim:\n assumes \"seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\"\n shows\n \"\\\\<^sub>s \\\\tw. (mux2_inv tw \\ mux2_inv' tw) \\ wityping \\ (snd tw)\\ \n mux2 \n \\\\tw. (mux2_inv tw \\ mux2_inv' tw) \\ wityping \\ (snd tw)\\\"\n apply (rule While)\n apply (unfold snd_conv, rule mux2_conc_hoare[unfolded snd_conv])\n apply (rule assms)\n done\n\nlemma mux2_conc_sim':\n assumes \"seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\"\n shows \"\\\\<^sub>s \\\\tw. (mux2_inv tw \\ wityping \\ (snd tw)) \\ mux2_inv' tw\\ mux2 \\mux2_inv'\\\"\n apply (rule Conseq_sim[where Q=\"\\tw. (mux2_inv tw \\ mux2_inv' tw) \\ wityping \\ (snd tw)\" and\n P=\"\\tw. (mux2_inv tw \\ mux2_inv' tw) \\ wityping \\ (snd tw)\"])\n by (blast intro: mux2_conc_sim[OF assms])+\n\nsubsection \\Initialisation preserves the invariant\\\n\nlemma init_sat_mux2_inv:\n assumes \"seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\"\n shows \"init_sim_hoare (\\tw. fst tw = 0 \\ wityping \\ (snd tw)) mux2 (mux2_inv)\"\n unfolding mux2_def\n apply (rule AssignI)\n apply (rule SingleI)\n apply (rule weaken_postcondition[OF mux2_seq_hoare_next_time0_wityping[OF assms]])\n done\n\nlemma init_sat_mux_inv':\n assumes \"seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\"\n shows \"init_sim_hoare (\\tw. wityping \\ (snd tw)) mux2 mux2_inv'\"\n unfolding mux2_def\n apply (rule AssignI)\n apply (rule SingleI)\n apply (rule Conseq2[rotated])\n apply (rule mux2_seq_hoare_next_time'_wityping)\n apply (rule assms)\n apply (simp add: next_time_world_at_least)\n by auto\n\nlemma init_sat_nand_mux_inv_comb:\n assumes \"seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\"\n shows \"init_sim_hoare (\\tw. fst tw = 0 \\ wityping \\ (snd tw)) mux2 (\\tw. mux2_inv tw \\ mux2_inv' tw)\"\n apply (rule ConjI_sim)\n apply (rule init_sat_mux2_inv)\n apply (rule assms)\n apply (rule ConseqI_sim[where P=\"\\tw. wityping \\ (snd tw)\"])\n apply (simp, rule init_sat_mux_inv'[OF assms], simp)\n done\n\nlemma init_sat_nand_mux_inv_comb_wityping:\n assumes \"seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\"\n shows \"init_sim_hoare (\\tw. fst tw = 0 \\ wityping \\ (snd tw)) mux2 (\\tw. (mux2_inv tw \\ mux2_inv' tw) \\ wityping \\ (snd tw))\"\n apply (rule ConjI_sim)\n apply (rule ConseqI_sim[rotated])\n apply (rule init_sat_nand_mux_inv_comb)\n apply (rule assms)\n apply simp\n apply simp\n apply (rule strengthen_precondition_init_sim_hoare[rotated])\n unfolding mux2_def apply (rule single_conc_stmt_preserve_wityping_init_sim_hoare)\n apply (rule assms)\n apply blast\n done\n\nlemma mux2_correctness:\n assumes \"sim_fin w (i + 1) mux2 tw'\" and \"wityping \\ w\"\n assumes \"conc_wt \\ mux2\"\n shows \"wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\nproof -\n obtain tw where \"init_sim (0, w) mux2 tw\" and \"tw, i + 1, mux2 \\\\<^sub>S tw'\"\n using premises_sim_fin_obt[OF assms(1)] by auto\n hence \"i + 1 = fst tw'\"\n using world_maxtime_lt_fst_tres by blast\n have \"conc_stmt_wf mux2\"\n unfolding conc_stmt_wf_def mux2_def by auto\n moreover have \"nonneg_delay_conc mux2\"\n unfolding mux2_def by auto\n moreover have \"seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\"\n using assms(3) by (metis conc_wt_cases(1) mux2_def)\n ultimately have \"init_sim_valid (\\tw. fst tw = 0 \\ wityping \\ (snd tw)) mux2 (\\tw. mux2_inv tw \\ mux2_inv' tw \\ wityping \\ (snd tw))\"\n using init_sim_hoare_soundness[OF init_sat_nand_mux_inv_comb_wityping] by auto\n hence \"mux2_inv tw \\ mux2_inv' tw \\ wityping \\ (snd tw)\"\n using \\init_sim (0, w) mux2 tw\\ fst_conv assms(2) unfolding init_sim_valid_def\n by (metis (full_types) snd_conv)\n hence \"mux2_inv tw\" and \"mux2_inv' tw\" and \"wityping \\ (snd tw)\"\n by auto\n moreover have \"\\\\<^sub>s \\\\tw. (mux2_inv tw \\ mux2_inv' tw) \\ wityping \\ (snd tw)\\ mux2 \\\\tw. (mux2_inv tw \\ mux2_inv' tw) \\ wityping \\ (snd tw)\\\"\n using conc_sim_soundness[OF mux2_conc_sim] \\conc_stmt_wf mux2\\ \\nonneg_delay_conc mux2\\\n using \\seq_wt \\ (Bguarded (Bsig SEL) (Bassign_trans OUT (Bsig IN1) 1) (Bassign_trans OUT (Bsig IN0) 1))\\\n by simp\n ultimately have \"mux2_inv tw'\"\n using \\tw, i + 1, mux2 \\\\<^sub>S tw'\\ unfolding sim_hoare_valid_def by blast\n hence \"\\i < fst tw'. wline_of tw' OUT (i + 1) = (if bval_of_wline tw' SEL i then wline_of tw' IN1 i else wline_of tw' IN0 i)\"\n unfolding mux2_inv_def by auto\n with \\i + 1 = fst tw'\\ show ?thesis\n by (metis less_add_one)\nqed\n\nend", "meta": {"author": "rizaldialbert", "repo": "vhdl-semantics", "sha": "352f89c9ccdfe830c054757dfd86caeadbd67159", "save_path": "github-repos/isabelle/rizaldialbert-vhdl-semantics", "path": "github-repos/isabelle/rizaldialbert-vhdl-semantics/vhdl-semantics-352f89c9ccdfe830c054757dfd86caeadbd67159/Multiplexer_Hoare.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.10818895887524603, "lm_q1q2_score": 0.05240457701783087}} {"text": "(*\n * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *)\n\ntheory Find_Names\nimports Pure\nkeywords \"find_names\" :: diag\nbegin\n\ntext \\The @{command find_names} command, when given a theorem,\n finds other names the theorem appears under, via matching on the whole\n proposition. It will not identify unnamed theorems.\\\n\nML \\\n\nlocal\n(* all_facts_of and pretty_ref taken verbatim from non-exposed version\n in Find_Theorems.ML of official Isabelle/HOL distribution *)\nfun all_facts_of ctxt =\n let\n val thy = Proof_Context.theory_of ctxt;\n val transfer = Global_Theory.transfer_theories thy;\n val local_facts = Proof_Context.facts_of ctxt;\n val global_facts = Global_Theory.facts_of thy;\n in\n (Facts.dest_all (Context.Proof ctxt) false [global_facts] local_facts\n @ Facts.dest_all (Context.Proof ctxt) false [] global_facts)\n |> maps Facts.selections\n |> map (apsnd transfer)\n end;\n\nfun pretty_ref ctxt thmref =\n let\n val (name, sel) =\n (case thmref of\n Facts.Named ((name, _), sel) => (name, sel)\n | Facts.Fact _ => raise Fail \"Illegal literal fact\");\n in\n [Pretty.marks_str (#1 (Proof_Context.markup_extern_fact ctxt name), name),\n Pretty.str (Facts.string_of_selection sel)]\n end;\n\nin\n\nfun find_names ctxt thm =\n let\n fun eq_filter body thmref = (body = Thm.full_prop_of (snd thmref));\n in\n (filter (eq_filter (Thm.full_prop_of thm))) (all_facts_of ctxt)\n |> map #1\n end;\n\nfun pretty_find_names ctxt thm =\n let\n val results = find_names ctxt thm;\n val position_markup = Position.markup (Position.thread_data ()) Markup.position;\n in\n ((Pretty.mark position_markup (Pretty.keyword1 \"find_names\")) ::\n Par_List.map (Pretty.item o (pretty_ref ctxt)) results)\n |> Pretty.fbreaks |> Pretty.block |> Pretty.writeln\n end\n\nend\n\nval _ =\n Outer_Syntax.command @{command_keyword find_names}\n \"find other names of a named theorem\"\n (Parse.thms1 >> (fn srcs => Toplevel.keep (fn st =>\n pretty_find_names (Toplevel.context_of st)\n (hd (Attrib.eval_thms (Toplevel.context_of st) srcs)))));\n\\\n\nend\n", "meta": {"author": "seL4", "repo": "l4v", "sha": "9ba34e269008732d4f89fb7a7e32337ffdd09ff9", "save_path": "github-repos/isabelle/seL4-l4v", "path": "github-repos/isabelle/seL4-l4v/l4v-9ba34e269008732d4f89fb7a7e32337ffdd09ff9/lib/Find_Names.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.13846179767920994, "lm_q1q2_score": 0.05227495969880242}} {"text": "(*\n * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)\n *\n * SPDX-License-Identifier: BSD-2-Clause\n *)\n\n(*\n * Strengthen functions into simpler monads.\n *\n * Each block of lifting lemmas converts functions in the \"L2\" monadic\n * framework (an exception framework) into its own framework.\n *)\n\ntheory TypeStrengthen\nimports\n L2Defs\n \"Lib.OptionMonadND\"\n ExecConcrete\nbegin\n\n(* Set up the database and ts_rule attribute. *)\nML_file \"monad_types.ML\"\nsetup \\\n Attrib.setup (Binding.name \"ts_rule\") Monad_Types.ts_attrib\n \"AutoCorres type strengthening rule\"\n\\\n\n(*\n * Helpers for exception polymorphism lemmas (L2_call_Foo_polymorphic).\n *\n * They are used to rewrite a term like\n *\n * L2_call x = Foo y\n *\n * into an identical term with a different exception type.\n *)\n\ndefinition\n unliftE\nwhere\n \"unliftE (x :: ('a, 'u + 'b) nondet_monad) \\ x (\\_. fail)\"\n\nlemma L2_call_liftE_unliftE:\n \"L2_call x = liftE (unliftE (L2_call x))\"\n apply (clarsimp simp: L2_call_def unliftE_def)\n apply (rule ext)\n apply (clarsimp simp: handleE'_def catch_def liftE_def bind_assoc)\n apply (clarsimp cong: bind_apply_cong)\n apply (clarsimp simp: bind_def split_def return_def split: sum.splits)\n apply (force simp: return_def fail_def split: sum.splits)+\n done\n\nlemma unliftE_liftE [simp]:\n \"unliftE (liftE x) = x\"\n apply (clarsimp simp: unliftE_def catch_liftE)\n done\n\n\n\n(*\n * Lifting into pure functional Isabelle.\n *)\n\ndefinition \"TS_return x \\ liftE (return x)\"\n\nlemma L2_call_TS_return: \"L2_call (TS_return a) = L2_gets (\\_. a) [''ret'']\"\n apply (monad_eq simp: L2_call_def L2_gets_def TS_return_def)\n done\n\nlemma TS_return_L2_gets:\n \"L2_gets (\\_. P) n = TS_return P\"\n by (monad_eq simp: L2_defs TS_return_def)\n\nlemma L2_call_L2_gets_polymorphic:\n \"(L2_call x :: ('s, 'a, 'e1) L2_monad) = L2_gets y n\n \\ (L2_call x :: ('s, 'a, 'e2) L2_monad) = L2_gets y n\"\n apply (monad_eq simp: L2_defs L2_call_def Ball_def split: sum.splits)\n apply blast\n done\n\nsetup \\\nMonad_Types.new_monad_type\n \"pure\"\n \"Pure function\"\n (Monad_Types.check_lifting_head [@{term \"TS_return\"}])\n 100\n @{thms L2_call_TS_return TS_return_L2_gets}\n @{term \"(%a. L2_gets (%_. a) [''ret'']) :: 'a => ('s, 'a, unit) L2_monad\"}\n @{thm L2_call_L2_gets_polymorphic}\n #2\n (fn _ => error \"monad_mono not applicable for pure monad\")\n|> Context.theory_map\n\\\n\nlemma TS_return_L2_seq:\n \"L2_seq (TS_return A) (\\a. TS_return (B a))\n = TS_return (let a = A in B a)\"\n by (monad_eq simp: L2_defs TS_return_def)\n\nlemma TS_return_L2_condition:\n \"L2_condition (\\_. c) (TS_return A) (TS_return B) = TS_return (if c then A else B)\"\n by (monad_eq simp: L2_defs TS_return_def)\n\nlemmas [ts_rule pure] =\n TS_return_L2_gets\n TS_return_L2_seq\n TS_return_L2_condition\n split_distrib[where T = TS_return]\n\nlemma L2_seq_TS_return:\n \"TS_return (let a = A in B a) = L2_seq (L2_gets (\\_. A) []) (\\a. L2_gets (\\_. B a) [])\"\n by (monad_eq simp: L2_defs TS_return_def)\n\nlemma L2_condition_TS_return:\n \"TS_return (if c then A else B) = L2_condition (\\_. c) (L2_gets (\\_. A) []) (L2_gets (\\_. B) [])\"\n by (monad_eq simp: L2_defs TS_return_def)\n\nlemmas [ts_rule pure unlift] =\n TS_return_L2_gets [where n = \"[]\", symmetric]\n TS_return_L2_seq [symmetric]\n TS_return_L2_condition [symmetric]\n L2_seq_TS_return\n L2_condition_TS_return\n split_distrib[where T = TS_return, symmetric]\n\n\n\n(*\n * Lifting into pure functional Isabelle with state.\n *)\n\ndefinition \"TS_gets x \\ liftE (gets x)\"\n\nlemma TS_gets_L2_gets:\n \"L2_gets X n = TS_gets X\"\n by (monad_eq simp: L2_defs TS_gets_def)\n\nlemma L2_call_TS_gets: \"L2_call (TS_gets a) = L2_gets a [''TS_internal_retval'']\"\n apply (monad_eq simp: L2_call_def L2_gets_def TS_gets_def)\n done\n\nsetup \\\nMonad_Types.new_monad_type\n \"gets\"\n \"Read-only function\"\n (Monad_Types.check_lifting_head [@{term \"TS_gets\"}])\n 80\n @{thms L2_call_TS_gets TS_gets_L2_gets}\n @{term \"(%x. L2_gets x [''ret'']) :: ('s => 'a) => ('s, 'a, unit) L2_monad\"}\n @{thm L2_call_L2_gets_polymorphic}\n (fn (state, ret, ex) => state --> ret)\n (fn _ => error \"monad_mono not applicable for gets monad\")\n|> Context.theory_map\n\\\n\nlemma TS_gets_L2_seq:\n \"L2_seq (TS_gets A) (\\x. TS_gets (B x)) = (TS_gets (\\s. let x = A s in B x s))\"\n by (monad_eq simp: L2_defs TS_gets_def)\n\nlemma TS_gets_L2_condition:\n \"L2_condition c (TS_gets A) (TS_gets B) = TS_gets (\\s. if c s then (A s) else (B s))\"\n by (monad_eq simp: L2_defs TS_gets_def)\n\nlemmas [ts_rule gets] =\n TS_gets_L2_gets\n TS_gets_L2_seq\n TS_gets_L2_condition\n split_distrib[where T = TS_gets]\n\nlemmas [ts_rule gets unlift] =\n TS_gets_L2_gets [where n = \"[]\", symmetric]\n TS_gets_L2_seq [symmetric]\n TS_gets_L2_condition [symmetric]\n split_distrib[where T = TS_gets, symmetric]\n\n\n\n(*\n * Lifting into option monad.\n *)\n\ndefinition \"gets_theE \\ \\x. (liftE (gets_the x))\"\n\nlemma L2_call_gets_theE [simp]: \"L2_call (gets_theE x) = gets_theE x\"\n apply (monad_eq simp: L2_call_def L2_gets_def gets_theE_def)\n done\n\nlemma liftE_gets_theE: \"gets_theE X = liftE (gets_the X)\"\n apply (clarsimp simp: gets_theE_def)\n done\nlemma L2_call_gets_theE_polymorphic:\n \"(L2_call x :: ('s, 'a, 'e1) L2_monad) = gets_theE y\n \\ (L2_call x :: ('s, 'a, 'e2) L2_monad) = gets_theE y\"\n apply (metis L2_call_liftE_unliftE liftE_gets_theE unliftE_liftE)\n done\n\nlemma in_gets_theE [monad_eq]:\n \"(rv, s') \\ fst (gets_theE M s) = (\\v'. rv = Inr v' \\ s' = s \\ M s = Some v')\"\n apply (monad_eq simp: gets_theE_def)\n done\n\nlemma snd_gets_theE [monad_eq]:\n \"snd (gets_theE M s) = (M s = None)\"\n apply (monad_eq simp: gets_theE_def gets_the_def Bex_def assert_opt_def split: option.splits)\n done\n\nlemma gets_theE_ofail [simp]:\n \"gets_theE ofail = fail\"\n by (monad_eq simp: L2_defs ofail_def split: option.splits)\n\n(* unused *)\nlemma monad_mono_transfer_option:\n \"\\ \\m. (L2_call (f m) :: ('s, 'a, 'e) L2_monad) = gets_theE (f' m); monad_mono f \\ \\ option_monad_mono f'\"\n apply atomize\n apply (clarsimp simp: monad_mono_def option_monad_mono_def)\n apply (clarsimp split: option.splits)\n apply (erule allE, erule allE, erule (1) impE)\n apply (erule_tac x=s in allE)\n apply (frule_tac x=x in spec)\n apply (drule_tac x=y in spec)\n apply rule\n apply (monad_eq simp: L2_call_def split: sum.splits)\n apply metis\n apply (monad_eq simp: L2_call_def split: sum.splits)\n apply (metis (full_types) sum.inject(2))\n done\n\nsetup \\\nMonad_Types.new_monad_type\n \"option\"\n \"Option monad\"\n (Monad_Types.check_lifting_head [@{term \"gets_theE\"}])\n 60\n @{thms L2_call_gets_theE gets_theE_ofail}\n @{term \"gets_theE :: ('s => 'a option) => ('s, 'a, unit) L2_monad\"}\n @{thm L2_call_gets_theE_polymorphic}\n (fn (state, ret, ex) =>\n state --> Term.map_atyps (fn t => if t = @{typ \"'a\"} then ret else t) @{typ \"'a option\"})\n (fn def => fn mono_thm => @{thm monad_mono_transfer_option} OF [def, mono_thm])\n|> Context.theory_map\n\\\n\nlemma gets_theE_L2_gets:\n \"L2_gets a n = gets_theE (ogets a)\"\n by (monad_eq simp: L2_defs ogets_def)\n\nlemma gets_theE_L2_seq:\n \"L2_seq (gets_theE X) (\\x. gets_theE (Y x)) = gets_theE (X |>> Y)\"\n by (monad_eq simp: L2_defs ogets_def Bex_def obind_def split: option.splits)\n\nlemma gets_theE_L2_guard:\n \"L2_guard G = gets_theE (oguard G)\"\n by (monad_eq simp: L2_defs oguard_def split: option.splits)\n\nlemma gets_theE_L2_condition:\n \"L2_condition C (gets_theE L) (gets_theE R) = gets_theE (ocondition C L R)\"\n by (monad_eq simp: L2_defs ocondition_def split: option.splits)\n\nlemma gets_theE_L2_fail:\n \"L2_fail = gets_theE (ofail)\"\n by (monad_eq simp: L2_defs ofail_def split: option.splits)\n\nlemma gets_theE_L2_recguard:\n \"L2_recguard m (gets_theE x) = gets_theE (ocondition (\\_. m = 0) ofail x)\"\n by (monad_eq simp: L2_defs ocondition_def ofail_def split: option.splits)\n\nlemma gets_theE_L2_while:\n \"L2_while C (\\x. gets_theE (B x)) i n = gets_theE (owhile C B i)\"\n unfolding L2_while_def gets_theE_def gets_the_whileLoop[symmetric]\n by (rule whileLoopE_liftE)\n\n\nlemmas [ts_rule option] =\n gets_theE_L2_seq\n gets_theE_L2_fail\n gets_theE_L2_guard\n gets_theE_L2_recguard\n gets_theE_L2_gets\n gets_theE_L2_condition\n gets_theE_L2_while\n split_distrib[where T = gets_theE]\n\nlemmas [ts_rule option unlift] =\n gets_theE_L2_seq [symmetric]\n gets_theE_L2_fail [symmetric]\n gets_theE_L2_guard [symmetric]\n gets_theE_L2_recguard [symmetric]\n gets_theE_L2_gets [where n = \"[]\", symmetric]\n gets_theE_L2_condition [symmetric]\n gets_theE_L2_while [symmetric]\n split_distrib[where T = gets_theE, symmetric]\n\n\n(*\n * Lifting into the nondeterministic state monad.\n * All L2 terms can be lifted into it.\n *)\n\nlemma L2_call_liftE_polymorphic:\n \"((L2_call x) :: ('s, 'a, 'e1) L2_monad) = liftE y\n \\ (L2_call x :: ('s, 'a, 'e2) L2_monad) = liftE y\"\n apply (metis L2_call_liftE_unliftE unliftE_liftE)\n done\n\nlemma monad_mono_transfer_nondet:\n \"\\ \\m. (L2_call (f m) :: ('s, 'a, 'e) L2_monad) = liftE (f' m); monad_mono f \\ \\ monad_mono f'\"\n apply atomize\n apply (clarsimp simp: monad_mono_def option_monad_mono_def)\n apply (erule allE, erule allE, erule (1) impE)\n apply (erule_tac x=s in allE)\n apply (frule_tac x=x in spec)\n apply (drule_tac x=y in spec)\n apply rule\n apply (monad_eq simp: L2_call_def split: sum.splits)\n apply (metis set_rev_mp sum.inject(2))\n apply (monad_eq simp: L2_call_def split: sum.splits)\n apply (* not *) fast\n done\n\nsetup \\\nMonad_Types.new_monad_type\n \"nondet\"\n \"Nondeterministic state monad (default)\"\n (Monad_Types.check_lifting_head [@{term \"liftE\"}])\n 0\n @{thms L2_call_liftE}\n @{term \"liftE :: ('s, 'a) nondet_monad => ('s, 'a, unit) L2_monad\"}\n @{thm L2_call_liftE_polymorphic}\n (fn (state, ret, ex) =>\n Term.map_atyps (fn t => if t = @{typ \"'a\"} then ret\n else if t = @{typ \"'s\"} then state else t)\n @{typ \"('s, 'a) nondet_monad\"})\n (fn def => fn mono_thm => @{thm monad_mono_transfer_nondet} OF [def, mono_thm])\n|> Context.theory_map\n\\\n\nlemma liftE_L2_seq: \"L2_seq (liftE A) (\\x. liftE (B x)) = (liftE (A >>= B))\"\n apply (clarsimp simp: L2_defs)\n apply (clarsimp simp: liftE_def bindE_def bind_assoc)\n done\n\nlemma liftE_L2_condition: \"L2_condition c (liftE A) (liftE B) = liftE (condition c A B)\"\n apply (clarsimp simp: L2_defs)\n apply (rule ext)+\n apply monad_eq\n apply blast\n done\n\nlemma liftE_L2_modify: \"L2_modify m = liftE (modify m)\"\n apply (clarsimp simp: L2_defs)\n done\n\nlemma liftE_L2_gets: \"L2_gets a n = liftE (gets a)\"\n apply (clarsimp simp: L2_defs)\n done\n\nlemma liftE_L2_recguard:\n \"(L2_recguard x (liftE A)) = liftE (condition (\\s. x > 0) A fail)\"\n apply (case_tac \"x = 0\")\n apply clarsimp\n apply (clarsimp simp: L2_recguard_def)\n done\n\nlemma liftE_L2_while: \"L2_while c (\\r. liftE (B r)) i n = liftE (whileLoop c B i)\"\n apply (clarsimp simp: L2_while_def)\n apply (rule whileLoopE_liftE)\n done\n\nlemma liftE_L2_throw: \"L2_throw X n = throwError X\"\n apply (monad_eq simp: L2_throw_def)\n done\n\nlemma liftE_L2_catch: \"L2_catch (liftE A) B = liftE A\"\n apply (clarsimp simp: L2_defs)\n done\n\nlemma liftE_L2_catch': \"L2_catch A (\\x. liftE (B x)) = liftE (A B)\"\n apply (clarsimp simp: L2_defs)\n apply (clarsimp simp: handleE'_def liftE_def catch_def bind_assoc)\n apply (rule arg_cong [where f=\"\\x. (A >>= x)\"])\n apply (rule ext)\n apply (clarsimp split: sum.splits)\n done\n\nlemma liftE_L2_unknown: \"L2_unknown name = liftE (select UNIV)\"\n apply (clarsimp simp: L2_defs)\n done\n\nlemma liftE_L2_spec: \"L2_spec S = liftE (spec S >>= (\\_. select UNIV))\"\n apply (clarsimp simp: L2_defs)\n done\n\nlemma liftE_L2_guard: \"L2_guard G = liftE (guard G)\"\n apply (clarsimp simp: L2_defs)\n done\n\nlemma liftE_L2_fail: \"L2_fail = liftE (fail)\"\n apply (clarsimp simp: L2_defs liftE_def)\n done\n\nlemma liftE_exec_concrete:\n \"exec_concrete st (liftE x) = liftE (exec_concrete st x)\"\n apply (rule monad_eqI)\n apply (clarsimp simp: in_liftE in_exec_concrete)\n apply force\n apply (clarsimp simp: in_liftE in_exec_concrete)\n apply force\n apply (clarsimp simp: snd_exec_concrete snd_liftE)\n done\n\nlemma liftE_exec_abstract:\n \"exec_abstract st (liftE x) = liftE (exec_abstract st x)\"\n apply (rule monad_eqI)\n apply (clarsimp simp: in_liftE in_exec_abstract)\n apply (clarsimp simp: in_liftE in_exec_abstract)\n apply (clarsimp simp: snd_exec_abstract snd_liftE)\n done\n\nlemma liftE_measure_call:\n \"\\ monad_mono A; \\m. L2_call (A m) = liftE (B m) \\\n \\ L2_call (measure_call A) = liftE (measure_call B)\"\n apply (monad_eq simp: measure_call_def L2_call_def L2_defs)\n apply (fast dest: monad_mono_incl)\n done\n\nlemmas [ts_rule nondet] =\n liftE_L2_seq\n liftE_L2_condition\n liftE_L2_modify\n liftE_L2_gets\n liftE_L2_while\n liftE_L2_throw\n liftE_L2_catch\n liftE_L2_catch'\n liftE_L2_spec\n liftE_L2_guard\n liftE_L2_unknown\n liftE_L2_fail\n liftE_L2_recguard\n liftE_exec_concrete\n liftE_exec_abstract\n liftE_gets_theE\n liftE_measure_call\n split_distrib [where T=liftE]\n\ndefinition\n \"AC_call_L1 arg_xf gs ret_xf l1body\n = liftM (\\rv. case rv of Inr v \\ v)\n (L2_call_L1 arg_xf gs ret_xf l1body)\"\n\nlemma liftE_L2_call_L1[ts_rule nondet]:\n \"L2_call_L1 arg_xf gs ret_xf l1body\n = liftE (AC_call_L1 arg_xf gs ret_xf l1body)\"\n apply (simp add: AC_call_L1_def L2_call_L1_def\n liftE_def liftM_def bind_assoc)\n apply (rule ext)\n apply (simp add: exec_gets exec_get)\n apply (rule bind_apply_cong[OF refl])+\n apply (clarsimp simp: bind_assoc returnOk_def in_monad split: sum.splits)\n done\n\nlemmas [ts_rule nondet unlift] =\n liftE_L2_seq [symmetric]\n liftE_L2_condition [symmetric]\n liftE_L2_modify [symmetric]\n liftE_L2_gets [symmetric]\n liftE_L2_while [symmetric]\n liftE_L2_throw [symmetric]\n liftE_L2_catch [symmetric]\n liftE_L2_catch' [symmetric]\n liftE_L2_spec [symmetric]\n liftE_L2_guard [symmetric]\n liftE_L2_unknown [symmetric]\n liftE_L2_fail [symmetric]\n liftE_L2_recguard [symmetric]\n liftE_exec_concrete [symmetric]\n liftE_exec_abstract [symmetric]\n liftE_gets_theE [symmetric]\n split_distrib [where T=liftE, symmetric]\n\nend\n", "meta": {"author": "NICTA", "repo": "l4v", "sha": "3c3514fe99082f7b6a6fb8445b8dfc592ff7f02b", "save_path": "github-repos/isabelle/NICTA-l4v", "path": "github-repos/isabelle/NICTA-l4v/l4v-3c3514fe99082f7b6a6fb8445b8dfc592ff7f02b/tools/autocorres/TypeStrengthen.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908327, "lm_q2_score": 0.13846179056896438, "lm_q1q2_score": 0.05227495507491796}} {"text": "(* Title: JinjaDCI/BV/BVNoTypeErrors.thy\n\n Author: Gerwin Klein, Susannah Mansky\n Copyright GPL\n\n Based on the Jinja theory BV/BVNoTypeErrors.thy by Gerwin Klein\n*)\n\nsection \\ Welltyped Programs produce no Type Errors \\\n\ntheory BVNoTypeError\nimports \"../JVM/JVMDefensive\" BVSpecTypeSafe\nbegin\n\nlemma has_methodI:\n \"P \\ C sees M,b:Ts\\T = m in D \\ P \\ C has M,b\"\n by (unfold has_method_def) blast\n\ntext \\\n Some simple lemmas about the type testing functions of the\n defensive JVM:\n\\\nlemma typeof_NoneD [simp,dest]: \"typeof v = Some x \\ \\is_Addr v\"\n by (cases v) auto\n\nlemma is_Ref_def2:\n \"is_Ref v = (v = Null \\ (\\a. v = Addr a))\"\n by (cases v) (auto simp add: is_Ref_def)\n\n\n\nlemma is_RefI [intro, simp]: \"P,h \\ v :\\ T \\ is_refT T \\ is_Ref v\"\n(*<*)\nproof(cases T)\nqed (auto simp add: is_refT_def is_Ref_def dest: conf_ClassD)\n(*>*)\n\n\n\nlemma is_BoolI [intro, simp]: \"P,h \\ v :\\ Boolean \\ is_Bool v\"\n(*<*)by (unfold conf_def) auto(*>*)\n\ndeclare defs1 [simp del]\n\nlemma wt_jvm_prog_states_NonStatic:\nassumes wf: \"wf_jvm_prog\\<^bsub>\\\\<^esub> P\"\n and mC: \"P \\ C sees M,NonStatic: Ts\\T = (mxs, mxl, ins, et) in C\"\n and \\: \"\\ C M ! pc = \\\" and pc: \"pc < size ins\"\nshows \"OK \\ \\ states P mxs (1+size Ts+mxl)\"\n(*<*)\nproof -\n let ?wf_md = \"(\\P C (M, b, Ts, T\\<^sub>r, mxs, mxl\\<^sub>0, is, xt).\n wt_method P C b Ts T\\<^sub>r mxs mxl\\<^sub>0 is xt (\\ C M))\"\n have wfmd: \"wf_prog ?wf_md P\" using wf\n by (unfold wf_jvm_prog_phi_def) assumption\n show ?thesis using sees_wf_mdecl[OF wfmd mC] \\ pc\n by (simp add: wf_mdecl_def wt_method_def check_types_def)\n (blast intro: nth_in)\nqed\n(*>*)\n\nlemma wt_jvm_prog_states_Static:\nassumes wf: \"wf_jvm_prog\\<^bsub>\\\\<^esub> P\"\n and mC: \"P \\ C sees M,Static: Ts\\T = (mxs, mxl, ins, et) in C\"\n and \\: \"\\ C M ! pc = \\\" and pc: \"pc < size ins\"\nshows \"OK \\ \\ states P mxs (size Ts+mxl)\"\n(*<*)\nproof -\n let ?wf_md = \"(\\P C (M, b, Ts, T\\<^sub>r, mxs, mxl\\<^sub>0, is, xt).\n wt_method P C b Ts T\\<^sub>r mxs mxl\\<^sub>0 is xt (\\ C M))\"\n have wfmd: \"wf_prog ?wf_md P\" using wf\n by (unfold wf_jvm_prog_phi_def) assumption\n show ?thesis using sees_wf_mdecl[OF wfmd mC] \\ pc\n by (simp add: wf_mdecl_def wt_method_def check_types_def)\n (blast intro: nth_in)\nqed\n(*>*)\n\ntext \\\n The main theorem: welltyped programs do not produce type errors if they\n are started in a conformant state.\n\\\ntheorem no_type_error:\n fixes \\ :: jvm_state\n assumes welltyped: \"wf_jvm_prog\\<^bsub>\\\\<^esub> P\" and conforms: \"P,\\ \\ \\ \\\"\n shows \"exec_d P \\ \\ TypeError\"\n(*<*)\nproof -\n from welltyped obtain mb where wf: \"wf_prog mb P\" by (fast dest: wt_jvm_progD)\n \n obtain xcp h frs sh where s [simp]: \"\\ = (xcp, h, frs, sh)\" by (cases \\)\n\n from conforms have \"xcp \\ None \\ frs = [] \\ check P \\\" \n by (unfold correct_state_def check_def) auto\n moreover {\n assume \"\\(xcp \\ None \\ frs = [])\"\n then obtain stk reg C M pc ics frs' where\n xcp [simp]: \"xcp = None\" and\n frs [simp]: \"frs = (stk,reg,C,M,pc,ics)#frs'\" \n by (clarsimp simp add: neq_Nil_conv)\n\n from conforms obtain ST LT b Ts T mxs mxl ins xt where\n hconf: \"P \\ h \\\" and\n shconf: \"P,h \\\\<^sub>s sh \\\" and\n meth: \"P \\ C sees M,b:Ts\\T = (mxs, mxl, ins, xt) in C\" and\n \\: \"\\ C M ! pc = Some (ST,LT)\" and\n frame: \"conf_f P h sh (ST,LT) ins (stk,reg,C,M,pc,ics)\" and\n frames: \"conf_fs P h sh \\ C M (size Ts) T frs'\"\n by (fastforce simp add: correct_state_def dest: sees_method_fun)\n \n from frame obtain\n stk: \"P,h \\ stk [:\\] ST\" and\n reg: \"P,h \\ reg [:\\\\<^sub>\\] LT\" and\n pc: \"pc < size ins\" \n by (simp add: conf_f_def)\n\n from welltyped meth \\ pc\n have \"OK (Some (ST, LT)) \\ states P mxs (1+size Ts+mxl)\n \\ OK (Some (ST, LT)) \\ states P mxs (size Ts+mxl)\"\n by (cases b, auto dest: wt_jvm_prog_states_NonStatic wt_jvm_prog_states_Static)\n hence \"size ST \\ mxs\" by (auto simp add: JVM_states_unfold)\n with stk have mxs: \"size stk \\ mxs\" \n by (auto dest: list_all2_lengthD)\n\n from welltyped meth pc\n have \"P,T,mxs,size ins,xt \\ ins!pc,pc :: \\ C M\"\n by (rule wt_jvm_prog_impl_wt_instr)\n hence app\\<^sub>0: \"app (ins!pc) P mxs T pc (size ins) xt (\\ C M!pc) \"\n by (simp add: wt_instr_def)\n with \\ have eff: \n \"\\(pc',s')\\set (eff (ins ! pc) P pc xt (\\ C M ! pc)). pc' < size ins\"\n by (unfold app_def) simp\n\n from app\\<^sub>0 \\ have app:\n \"xcpt_app (ins!pc) P pc mxs xt (ST,LT) \\ app\\<^sub>i (ins!pc, P, pc, mxs, T, (ST,LT))\"\n by (clarsimp simp add: app_def)\n\n with eff stk reg \n have \"check_instr (ins!pc) P h stk reg C M pc frs' sh\"\n proof (cases \"ins!pc\")\n case (Getfield F C) \n with app stk reg \\ obtain v vT stk' where\n field: \"P \\ C sees F,NonStatic:vT in C\" and\n stk: \"stk = v # stk'\" and\n conf: \"P,h \\ v :\\ Class C\"\n by auto\n from conf have is_Ref: \"is_Ref v\" by auto\n moreover {\n assume \"v \\ Null\" \n with conf field is_Ref wf\n have \"\\D vs. h (the_Addr v) = Some (D,vs) \\ P \\ D \\\\<^sup>* C\" \n by (auto dest!: non_npD)\n }\n ultimately show ?thesis using Getfield field stk\n has_field_mono[OF has_visible_field[OF field]] hconfD[OF hconf]\n by (unfold oconf_def has_field_def) (fastforce dest: has_fields_fun)\n next\n case (Getstatic C F D) \n with app stk reg \\ obtain vT where\n field: \"P \\ C sees F,Static:vT in D\"\n by auto\n\n then show ?thesis using Getstatic stk\n has_field_idemp[OF has_visible_field[OF field]] shconfD[OF shconf]\n by (unfold soconf_def has_field_def) (fastforce dest: has_fields_fun)\n next\n case (Putfield F C)\n with app stk reg \\ obtain v ref vT stk' where\n field: \"P \\ C sees F,NonStatic:vT in C\" and\n stk: \"stk = v # ref # stk'\" and\n confv: \"P,h \\ v :\\ vT\" and\n confr: \"P,h \\ ref :\\ Class C\"\n by fastforce\n from confr have is_Ref: \"is_Ref ref\" by simp\n moreover {\n assume \"ref \\ Null\" \n with confr field is_Ref wf\n have \"\\D vs. h (the_Addr ref) = Some (D,vs) \\ P \\ D \\\\<^sup>* C\"\n by (auto dest: non_npD)\n }\n ultimately show ?thesis using Putfield field stk confv by fastforce\n next\n case (Invoke M' n)\n with app have n: \"n < size ST\" by simp\n\n from stk have [simp]: \"size stk = size ST\" by (rule list_all2_lengthD)\n \n { assume \"stk!n = Null\" with n Invoke have ?thesis by simp }\n moreover { \n assume \"ST!n = NT\"\n with n stk have \"stk!n = Null\" by (auto simp: list_all2_conv_all_nth)\n with n Invoke have ?thesis by simp\n }\n moreover {\n assume Null: \"stk!n \\ Null\" and NT: \"ST!n \\ NT\"\n\n from NT app Invoke\n obtain D D' Ts T m where\n D: \"ST!n = Class D\" and\n M': \"P \\ D sees M',NonStatic: Ts\\T = m in D'\" and\n Ts: \"P \\ rev (take n ST) [\\] Ts\"\n by auto\n \n from D stk n have \"P,h \\ stk!n :\\ Class D\" \n by (auto simp: list_all2_conv_all_nth)\n with Null obtain a C' fs where \n [simp]: \"stk!n = Addr a\" \"h a = Some (C',fs)\" and\n \"P \\ C' \\\\<^sup>* D\"\n by (fastforce dest!: conf_ClassD) \n\n with M' wf obtain m' Ts' T' D'' where \n C': \"P \\ C' sees M',NonStatic: Ts'\\T' = m' in D''\" and\n Ts': \"P \\ Ts [\\] Ts'\"\n by (auto dest!: sees_method_mono)\n\n from stk have \"P,h \\ take n stk [:\\] take n ST\" ..\n hence \"P,h \\ rev (take n stk) [:\\] rev (take n ST)\" ..\n also note Ts also note Ts'\n finally have \"P,h \\ rev (take n stk) [:\\] Ts'\" .\n\n with Invoke Null n C'\n have ?thesis by (auto simp add: is_Ref_def2 has_methodI)\n }\n ultimately show ?thesis by blast\n next\n case (Invokestatic C M' n)\n with app have n: \"n \\ size ST\" by simp\n\n from stk have [simp]: \"size stk = size ST\" by (rule list_all2_lengthD)\n\n from app Invokestatic\n obtain D Ts T m where\n M': \"P \\ C sees M',Static: Ts\\T = m in D\" and\n Ts: \"P \\ rev (take n ST) [\\] Ts\"\n by auto\n\n from stk have \"P,h \\ take n stk [:\\] take n ST\" ..\n hence \"P,h \\ rev (take n stk) [:\\] rev (take n ST)\" ..\n also note Ts\n finally have \"P,h \\ rev (take n stk) [:\\] Ts\" .\n\n with Invokestatic n M'\n show ?thesis by (auto simp add: is_Ref_def2 has_methodI)\n next\n case Return\n show ?thesis\n proof(cases \"M = clinit\")\n case True\n have \"is_class P C\" by(rule sees_method_is_class[OF meth])\n with wf_sees_clinit[OF wf]\n obtain m where \"P \\ C sees clinit,Static: [] \\ Void = m in C\"\n by(fastforce simp: is_class_def)\n\n with stk app \\ meth frames True Return\n show ?thesis by (auto simp add: has_methodI)\n next\n case False with stk app \\ meth frames Return\n show ?thesis by (auto intro: has_methodI)\n qed\n qed (auto simp add: list_all2_lengthD)\n hence \"check P \\\" using meth pc mxs by (auto simp: check_def intro: has_methodI)\n } ultimately\n have \"check P \\\" by blast\n thus \"exec_d P \\ \\ TypeError\" ..\nqed\n(*>*)\n\n\ntext \\\n The theorem above tells us that, in welltyped programs, the\n defensive machine reaches the same result as the aggressive\n one (after arbitrarily many steps).\n\\\ntheorem welltyped_aggressive_imp_defensive:\n \"wf_jvm_prog\\<^bsub>\\\\<^esub> P \\ P,\\ \\ \\ \\ \\ P \\ \\ -jvm\\ \\'\n \\ P \\ (Normal \\) -jvmd\\ (Normal \\')\"\n(*<*)\nproof -\n assume wf: \"wf_jvm_prog\\<^bsub>\\\\<^esub> P\" and cf: \"P,\\ \\ \\ \\\" and exec: \"P \\ \\ -jvm\\ \\'\"\n then have \"(\\, \\') \\ {(\\, \\'). exec (P, \\) = \\\\'\\}\\<^sup>*\" by(simp only: exec_all_def)\n then show ?thesis proof(induct rule: rtrancl_induct)\n case base\n then show ?case by (simp add: exec_all_d_def1)\n next\n case (step y z)\n then have \\y: \"P \\ \\ -jvm\\ y\" by (simp only: exec_all_def [symmetric])\n have exec_d: \"exec_d P y = Normal \\z\\\" using step\n no_type_error_commutes[OF no_type_error[OF wf BV_correct[OF wf \\y cf]]]\n by (simp add: exec_all_d_def1)\n show ?case using step.hyps(3) exec_1_d_NormalI[OF exec_d]\n by (simp add: exec_all_d_def1)\n qed\nqed\n(*>*)\n\n\ntext \\\n As corollary we get that the aggressive and the defensive machine\n are equivalent for welltyped programs (if started in a conformant\n state or in the canonical start state)\n\\ \ncorollary welltyped_commutes:\n fixes \\ :: jvm_state\n assumes wf: \"wf_jvm_prog\\<^bsub>\\\\<^esub> P\" and conforms: \"P,\\ \\ \\ \\\" \n shows \"P \\ (Normal \\) -jvmd\\ (Normal \\') = P \\ \\ -jvm\\ \\'\"\nproof(rule iffI)\n assume \"P \\ Normal \\ -jvmd\\ Normal \\'\" then show \"P \\ \\ -jvm\\ \\'\"\n by (rule defensive_imp_aggressive)\nnext\n assume \"P \\ \\ -jvm\\ \\'\" then show \"P \\ Normal \\ -jvmd\\ Normal \\'\"\n by (rule welltyped_aggressive_imp_defensive [OF wf conforms])\nqed\n\ncorollary welltyped_initial_commutes:\n assumes wf: \"wf_jvm_prog P\"\n assumes nstart: \"\\ is_class P Start\"\n assumes meth: \"P \\ C sees M,Static:[]\\Void = b in C\" \n assumes nclinit: \"M \\ clinit\"\n assumes Obj_start_m:\n \"(\\b' Ts' T' m' D'. P \\ Object sees start_m, b' : Ts'\\T' = m' in D'\n \\ b' = Static \\ Ts' = [] \\ T' = Void)\"\n defines start: \"\\ \\ start_state P\"\n shows \"start_prog P C M \\ (Normal \\) -jvmd\\ (Normal \\') = start_prog P C M \\ \\ -jvm\\ \\'\"\nproof -\n from wf obtain \\ where wf': \"wf_jvm_prog\\<^bsub>\\\\<^esub> P\" by (auto simp: wf_jvm_prog_def)\n let ?\\ = \"\\_start \\\"\n from start_prog_wf_jvm_prog_phi[where \\'=\"?\\\", OF wf' nstart meth nclinit \\_start Obj_start_m]\n have \"wf_jvm_prog\\<^bsub>?\\\\<^esub>(start_prog P C M)\" by simp\n moreover\n from wf' nstart meth nclinit \\_start(2) have \"start_prog P C M,?\\ \\ \\ \\\"\n unfolding start by (rule BV_correct_initial)\n ultimately show ?thesis by (rule welltyped_commutes)\nqed\n\n\nlemma not_TypeError_eq [iff]:\n \"x \\ TypeError = (\\t. x = Normal t)\"\n by (cases x) auto\n\nlocale cnf =\n fixes P and \\ and \\\n assumes wf: \"wf_jvm_prog\\<^bsub>\\\\<^esub> P\" \n assumes cnf: \"correct_state P \\ \\\" \n\ntheorem (in cnf) no_type_errors:\n \"P \\ (Normal \\) -jvmd\\ \\' \\ \\' \\ TypeError\"\nproof -\n assume \"P \\ (Normal \\) -jvmd\\ \\'\"\n then have \"(Normal \\, \\') \\ (exec_1_d P)\\<^sup>*\" by (unfold exec_all_d_def1) simp\n then show ?thesis proof(induct rule: rtrancl_induct)\n case (step y z)\n then obtain y\\<^sub>n where [simp]: \"y = Normal y\\<^sub>n\" by clarsimp\n have n\\y: \"P \\ Normal \\ -jvmd\\ Normal y\\<^sub>n\" using step.hyps(1)\n by (fold exec_all_d_def1) simp\n have \\y: \"P \\ \\ -jvm\\ y\\<^sub>n\" using defensive_imp_aggressive[OF n\\y] by simp\n show ?case using step no_type_error[OF wf BV_correct[OF wf \\y cnf]]\n by (auto simp add: exec_1_d_eq)\n qed simp\nqed\n\nlocale start =\n fixes P and C and M and \\ and T and b and P\\<^sub>0\n assumes wf: \"wf_jvm_prog P\"\n assumes nstart: \"\\ is_class P Start\"\n assumes sees: \"P \\ C sees M,Static:[]\\Void = b in C\" \n assumes nclinit: \"M \\ clinit\"\n assumes Obj_start_m: \"(\\b' Ts' T' m' D'. P \\ Object sees start_m, b' : Ts'\\T' = m' in D'\n \\ b' = Static \\ Ts' = [] \\ T' = Void)\"\n defines \"\\ \\ Normal (start_state P)\"\n defines [simp]: \"P\\<^sub>0 \\ start_prog P C M\"\n\ncorollary (in start) bv_no_type_error:\n shows \"P\\<^sub>0 \\ \\ -jvmd\\ \\' \\ \\' \\ TypeError\"\nproof -\n from wf obtain \\ where wf': \"wf_jvm_prog\\<^bsub>\\\\<^esub> P\" by (auto simp: wf_jvm_prog_def)\n let ?\\ = \"\\_start \\\"\n from start_prog_wf_jvm_prog_phi[where \\'=\"?\\\", OF wf' nstart sees nclinit \\_start Obj_start_m]\n have \"wf_jvm_prog\\<^bsub>?\\\\<^esub>P\\<^sub>0\" by simp\n moreover\n from BV_correct_initial[where \\'=\"?\\\", OF wf' nstart sees nclinit \\_start(2)]\n have \"correct_state P\\<^sub>0 ?\\ (start_state P)\" by simp\n ultimately have \"cnf P\\<^sub>0 ?\\ (start_state P)\" by (rule cnf.intro)\n moreover assume \"P\\<^sub>0 \\ \\ -jvmd\\ \\'\"\n ultimately show ?thesis by (unfold \\_def) (rule cnf.no_type_errors) \nqed\n\n \nend \n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/JinjaDCI/BV/BVNoTypeError.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167645017354, "lm_q2_score": 0.11279540330049728, "lm_q1q2_score": 0.05200057188026362}} {"text": "(* Title: HOL/SMT.thy\n Author: Sascha Boehme, TU Muenchen\n Author: Jasmin Blanchette, VU Amsterdam\n*)\n\nsection \\Bindings to Satisfiability Modulo Theories (SMT) solvers based on SMT-LIB 2\\\n\ntheory SMT\n imports Divides\n keywords \"smt_status\" :: diag\nbegin\n\nsubsection \\A skolemization tactic and proof method\\\n\nlemma choices:\n \"\\Q. \\x. \\y ya. Q x y ya \\ \\f fa. \\x. Q x (f x) (fa x)\"\n \"\\Q. \\x. \\y ya yb. Q x y ya yb \\ \\f fa fb. \\x. Q x (f x) (fa x) (fb x)\"\n \"\\Q. \\x. \\y ya yb yc. Q x y ya yb yc \\ \\f fa fb fc. \\x. Q x (f x) (fa x) (fb x) (fc x)\"\n \"\\Q. \\x. \\y ya yb yc yd. Q x y ya yb yc yd \\\n \\f fa fb fc fd. \\x. Q x (f x) (fa x) (fb x) (fc x) (fd x)\"\n \"\\Q. \\x. \\y ya yb yc yd ye. Q x y ya yb yc yd ye \\\n \\f fa fb fc fd fe. \\x. Q x (f x) (fa x) (fb x) (fc x) (fd x) (fe x)\"\n \"\\Q. \\x. \\y ya yb yc yd ye yf. Q x y ya yb yc yd ye yf \\\n \\f fa fb fc fd fe ff. \\x. Q x (f x) (fa x) (fb x) (fc x) (fd x) (fe x) (ff x)\"\n \"\\Q. \\x. \\y ya yb yc yd ye yf yg. Q x y ya yb yc yd ye yf yg \\\n \\f fa fb fc fd fe ff fg. \\x. Q x (f x) (fa x) (fb x) (fc x) (fd x) (fe x) (ff x) (fg x)\"\n by metis+\n\nlemma bchoices:\n \"\\Q. \\x \\ S. \\y ya. Q x y ya \\ \\f fa. \\x \\ S. Q x (f x) (fa x)\"\n \"\\Q. \\x \\ S. \\y ya yb. Q x y ya yb \\ \\f fa fb. \\x \\ S. Q x (f x) (fa x) (fb x)\"\n \"\\Q. \\x \\ S. \\y ya yb yc. Q x y ya yb yc \\ \\f fa fb fc. \\x \\ S. Q x (f x) (fa x) (fb x) (fc x)\"\n \"\\Q. \\x \\ S. \\y ya yb yc yd. Q x y ya yb yc yd \\\n \\f fa fb fc fd. \\x \\ S. Q x (f x) (fa x) (fb x) (fc x) (fd x)\"\n \"\\Q. \\x \\ S. \\y ya yb yc yd ye. Q x y ya yb yc yd ye \\\n \\f fa fb fc fd fe. \\x \\ S. Q x (f x) (fa x) (fb x) (fc x) (fd x) (fe x)\"\n \"\\Q. \\x \\ S. \\y ya yb yc yd ye yf. Q x y ya yb yc yd ye yf \\\n \\f fa fb fc fd fe ff. \\x \\ S. Q x (f x) (fa x) (fb x) (fc x) (fd x) (fe x) (ff x)\"\n \"\\Q. \\x \\ S. \\y ya yb yc yd ye yf yg. Q x y ya yb yc yd ye yf yg \\\n \\f fa fb fc fd fe ff fg. \\x \\ S. Q x (f x) (fa x) (fb x) (fc x) (fd x) (fe x) (ff x) (fg x)\"\n by metis+\n\nML \\\nfun moura_tac ctxt =\n Atomize_Elim.atomize_elim_tac ctxt THEN'\n SELECT_GOAL (Clasimp.auto_tac (ctxt addSIs @{thms choice choices bchoice bchoices}) THEN\n ALLGOALS (Metis_Tactic.metis_tac (take 1 ATP_Proof_Reconstruct.partial_type_encs)\n ATP_Proof_Reconstruct.default_metis_lam_trans ctxt [] ORELSE'\n blast_tac ctxt))\n\\\n\nmethod_setup moura = \\\n Scan.succeed (SIMPLE_METHOD' o moura_tac)\n\\ \"solve skolemization goals, especially those arising from Z3 proofs\"\n\nhide_fact (open) choices bchoices\n\n\nsubsection \\Triggers for quantifier instantiation\\\n\ntext \\\nSome SMT solvers support patterns as a quantifier instantiation\nheuristics. Patterns may either be positive terms (tagged by \"pat\")\ntriggering quantifier instantiations -- when the solver finds a\nterm matching a positive pattern, it instantiates the corresponding\nquantifier accordingly -- or negative terms (tagged by \"nopat\")\ninhibiting quantifier instantiations. A list of patterns\nof the same kind is called a multipattern, and all patterns in a\nmultipattern are considered conjunctively for quantifier instantiation.\nA list of multipatterns is called a trigger, and their multipatterns\nact disjunctively during quantifier instantiation. Each multipattern\nshould mention at least all quantified variables of the preceding\nquantifier block.\n\\\n\ntypedecl 'a symb_list\n\nconsts\n Symb_Nil :: \"'a symb_list\"\n Symb_Cons :: \"'a \\ 'a symb_list \\ 'a symb_list\"\n\ntypedecl pattern\n\nconsts\n pat :: \"'a \\ pattern\"\n nopat :: \"'a \\ pattern\"\n\ndefinition trigger :: \"pattern symb_list symb_list \\ bool \\ bool\" where\n \"trigger _ P = P\"\n\n\nsubsection \\Higher-order encoding\\\n\ntext \\\nApplication is made explicit for constants occurring with varying\nnumbers of arguments. This is achieved by the introduction of the\nfollowing constant.\n\\\n\ndefinition fun_app :: \"'a \\ 'a\" where \"fun_app f = f\"\n\ntext \\\nSome solvers support a theory of arrays which can be used to encode\nhigher-order functions. The following set of lemmas specifies the\nproperties of such (extensional) arrays.\n\\\n\nlemmas array_rules = ext fun_upd_apply fun_upd_same fun_upd_other fun_upd_upd fun_app_def\n\n\nsubsection \\Normalization\\\n\nlemma case_bool_if[abs_def]: \"case_bool x y P = (if P then x else y)\"\n by simp\n\nlemmas Ex1_def_raw = Ex1_def[abs_def]\nlemmas Ball_def_raw = Ball_def[abs_def]\nlemmas Bex_def_raw = Bex_def[abs_def]\nlemmas abs_if_raw = abs_if[abs_def]\nlemmas min_def_raw = min_def[abs_def]\nlemmas max_def_raw = max_def[abs_def]\n\nlemma nat_zero_as_int:\n \"0 = nat 0\"\n by simp\n\nlemma nat_one_as_int:\n \"1 = nat 1\"\n by simp\n\nlemma nat_numeral_as_int: \"numeral = (\\i. nat (numeral i))\" by simp\nlemma nat_less_as_int: \"(<) = (\\a b. int a < int b)\" by simp\nlemma nat_leq_as_int: \"(\\) = (\\a b. int a \\ int b)\" by simp\nlemma Suc_as_int: \"Suc = (\\a. nat (int a + 1))\" by (rule ext) simp\nlemma nat_plus_as_int: \"(+) = (\\a b. nat (int a + int b))\" by (rule ext)+ simp\nlemma nat_minus_as_int: \"(-) = (\\a b. nat (int a - int b))\" by (rule ext)+ simp\nlemma nat_times_as_int: \"(*) = (\\a b. nat (int a * int b))\" by (simp add: nat_mult_distrib)\nlemma nat_div_as_int: \"(div) = (\\a b. nat (int a div int b))\" by (simp add: nat_div_distrib)\nlemma nat_mod_as_int: \"(mod) = (\\a b. nat (int a mod int b))\" by (simp add: nat_mod_distrib)\n\nlemma int_Suc: \"int (Suc n) = int n + 1\" by simp\nlemma int_plus: \"int (n + m) = int n + int m\" by (rule of_nat_add)\nlemma int_minus: \"int (n - m) = int (nat (int n - int m))\" by auto\n\nlemma nat_int_comparison:\n fixes a b :: nat\n shows \"(a = b) = (int a = int b)\"\n and \"(a < b) = (int a < int b)\"\n and \"(a \\ b) = (int a \\ int b)\"\n by simp_all\n\nlemma int_ops:\n fixes a b :: nat\n shows \"int 0 = 0\"\n and \"int 1 = 1\"\n and \"int (numeral n) = numeral n\"\n and \"int (Suc a) = int a + 1\"\n and \"int (a + b) = int a + int b\"\n and \"int (a - b) = (if int a < int b then 0 else int a - int b)\"\n and \"int (a * b) = int a * int b\"\n and \"int (a div b) = int a div int b\"\n and \"int (a mod b) = int a mod int b\"\n by (auto intro: zdiv_int zmod_int)\n\nlemma int_if:\n fixes a b :: nat\n shows \"int (if P then a else b) = (if P then int a else int b)\"\n by simp\n\n\nsubsection \\Integer division and modulo for Z3\\\n\ntext \\\nThe following Z3-inspired definitions are overspecified for the case where \\l = 0\\. This\nSchönheitsfehler is corrected in the \\div_as_z3div\\ and \\mod_as_z3mod\\ theorems.\n\\\n\ndefinition z3div :: \"int \\ int \\ int\" where\n \"z3div k l = (if l \\ 0 then k div l else - (k div - l))\"\n\ndefinition z3mod :: \"int \\ int \\ int\" where\n \"z3mod k l = k mod (if l \\ 0 then l else - l)\"\n\nlemma div_as_z3div:\n \"\\k l. k div l = (if l = 0 then 0 else if l > 0 then z3div k l else z3div (- k) (- l))\"\n by (simp add: z3div_def)\n\nlemma mod_as_z3mod:\n \"\\k l. k mod l = (if l = 0 then k else if l > 0 then z3mod k l else - z3mod (- k) (- l))\"\n by (simp add: z3mod_def)\n\n\nsubsection \\Extra theorems for veriT reconstruction\\\n\nlemma verit_sko_forall: \\(\\x. P x) \\ P (SOME x. \\P x)\\\n using someI[of \\\\x. \\P x\\]\n by auto\n\nlemma verit_sko_forall': \\P (SOME x. \\P x) = A \\ (\\x. P x) = A\\\n by (subst verit_sko_forall)\n\nlemma verit_sko_forall_indirect: \\x = (SOME x. \\P x) \\ (\\x. P x) \\ P x\\\n using someI[of \\\\x. \\P x\\]\n by auto\n\nlemma verit_sko_ex: \\(\\x. P x) \\ P (SOME x. P x)\\\n using someI[of \\\\x. P x\\]\n by auto\n\nlemma verit_sko_ex': \\P (SOME x. P x) = A \\ (\\x. P x) = A\\\n by (subst verit_sko_ex)\n\nlemma verit_sko_ex_indirect: \\x = (SOME x. P x) \\ (\\x. P x) \\ P x\\\n using someI[of \\\\x. P x\\]\n by auto\n\nlemma verit_Pure_trans:\n \\P \\ Q \\ Q \\ P\\\n by auto\n\nlemma verit_if_cong:\n assumes \\b \\ c\\\n and \\c \\ x \\ u\\\n and \\\\ c \\ y \\ v\\\n shows \\(if b then x else y) \\ (if c then u else v)\\\n using assms if_cong[of b c x u] by auto\n\nlemma verit_if_weak_cong':\n \\b \\ c \\ (if b then x else y) \\ (if c then x else y)\\\n by auto\n\nlemma verit_ite_intro_simp:\n \\(if c then (a :: 'a) = (if c then P else Q') else Q) = (if c then a = P else Q)\\\n \\(if c then R else b = (if c then R' else Q')) =\n (if c then R else b = Q')\\\n \\(if c then a' = a' else b' = b')\\\n by (auto split: if_splits)\n\nlemma verit_or_neg:\n \\(A \\ B) \\ B \\ \\A\\\n \\(\\A \\ B) \\ B \\ A\\\n by auto\n\nlemma verit_subst_bool: \\P \\ f True \\ f P\\\n by auto\n\nlemma verit_and_pos:\n \\(a \\ \\b \\ A) \\ \\(a \\ b) \\ A\\\n \\(a \\ A) \\ \\a \\ A\\\n \\(\\a \\ A) \\ a \\ A\\\n by blast+\n\nlemma verit_la_generic:\n \\(a::int) \\ x \\ a = x \\ a \\ x\\\n by linarith\n\nlemma verit_tmp_bfun_elim:\n \\(if b then P True else P False) = P b\\\n by (cases b) auto\n\nlemma verit_eq_true_simplify:\n \\(P = True) \\ P\\\n by auto\n\nlemma verit_and_neg:\n \\B \\ B' \\ (A \\ B) \\ \\A \\ B'\\\n \\B \\ B' \\ (\\A \\ B) \\ A \\ B'\\\n by auto\n\nlemma verit_forall_inst:\n \\A \\ B \\ \\A \\ B\\\n \\\\A \\ B \\ A \\ B\\\n \\A \\ B \\ \\B \\ A\\\n \\A \\ \\B \\ B \\ A\\\n \\A \\ B \\ \\A \\ B\\\n \\\\A \\ B \\ A \\ B\\\n by blast+\n\nlemma verit_eq_transitive:\n \\A = B \\ B = C \\ A = C\\\n \\A = B \\ C = B \\ A = C\\\n \\B = A \\ B = C \\ A = C\\\n \\B = A \\ C = B \\ A = C\\\n by auto\n\n\nsubsection \\Setup\\\n\nML_file \\Tools/SMT/smt_util.ML\\\nML_file \\Tools/SMT/smt_failure.ML\\\nML_file \\Tools/SMT/smt_config.ML\\\nML_file \\Tools/SMT/smt_builtin.ML\\\nML_file \\Tools/SMT/smt_datatypes.ML\\\nML_file \\Tools/SMT/smt_normalize.ML\\\nML_file \\Tools/SMT/smt_translate.ML\\\nML_file \\Tools/SMT/smtlib.ML\\\nML_file \\Tools/SMT/smtlib_interface.ML\\\nML_file \\Tools/SMT/smtlib_proof.ML\\\nML_file \\Tools/SMT/smtlib_isar.ML\\\nML_file \\Tools/SMT/z3_proof.ML\\\nML_file \\Tools/SMT/z3_isar.ML\\\nML_file \\Tools/SMT/smt_solver.ML\\\nML_file \\Tools/SMT/cvc4_interface.ML\\\nML_file \\Tools/SMT/cvc4_proof_parse.ML\\\nML_file \\Tools/SMT/verit_proof.ML\\\nML_file \\Tools/SMT/verit_isar.ML\\\nML_file \\Tools/SMT/verit_proof_parse.ML\\\nML_file \\Tools/SMT/conj_disj_perm.ML\\\nML_file \\Tools/SMT/smt_replay_methods.ML\\\nML_file \\Tools/SMT/smt_replay.ML\\\nML_file \\Tools/SMT/z3_interface.ML\\\nML_file \\Tools/SMT/z3_replay_rules.ML\\\nML_file \\Tools/SMT/z3_replay_methods.ML\\\nML_file \\Tools/SMT/z3_replay.ML\\\nML_file \\Tools/SMT/verit_replay_methods.ML\\\nML_file \\Tools/SMT/verit_replay.ML\\\nML_file \\Tools/SMT/smt_systems.ML\\\n\nmethod_setup smt = \\\n Scan.optional Attrib.thms [] >>\n (fn thms => fn ctxt =>\n METHOD (fn facts => HEADGOAL (SMT_Solver.smt_tac ctxt (thms @ facts))))\n\\ \"apply an SMT solver to the current goal\"\n\n\nsubsection \\Configuration\\\n\ntext \\\nThe current configuration can be printed by the command\n\\smt_status\\, which shows the values of most options.\n\\\n\n\nsubsection \\General configuration options\\\n\ntext \\\nThe option \\smt_solver\\ can be used to change the target SMT\nsolver. The possible values can be obtained from the \\smt_status\\\ncommand.\n\\\n\ndeclare [[smt_solver = z3]]\n\ntext \\\nSince SMT solvers are potentially nonterminating, there is a timeout\n(given in seconds) to restrict their runtime.\n\\\n\ndeclare [[smt_timeout = 20]]\n\ntext \\\nSMT solvers apply randomized heuristics. In case a problem is not\nsolvable by an SMT solver, changing the following option might help.\n\\\n\ndeclare [[smt_random_seed = 1]]\n\ntext \\\nIn general, the binding to SMT solvers runs as an oracle, i.e, the SMT\nsolvers are fully trusted without additional checks. The following\noption can cause the SMT solver to run in proof-producing mode, giving\na checkable certificate. This is currently only implemented for Z3.\n\\\n\ndeclare [[smt_oracle = false]]\n\ntext \\\nEach SMT solver provides several commandline options to tweak its\nbehaviour. They can be passed to the solver by setting the following\noptions.\n\\\n\ndeclare [[cvc3_options = \"\"]]\ndeclare [[cvc4_options = \"--full-saturate-quant --inst-when=full-last-call --inst-no-entail --term-db-mode=relevant --multi-trigger-linear\"]]\ndeclare [[verit_options = \"--index-fresh-sorts\"]]\ndeclare [[z3_options = \"\"]]\n\ntext \\\nThe SMT method provides an inference mechanism to detect simple triggers\nin quantified formulas, which might increase the number of problems\nsolvable by SMT solvers (note: triggers guide quantifier instantiations\nin the SMT solver). To turn it on, set the following option.\n\\\n\ndeclare [[smt_infer_triggers = false]]\n\ntext \\\nEnable the following option to use built-in support for datatypes,\ncodatatypes, and records in CVC4. Currently, this is implemented only\nin oracle mode.\n\\\n\ndeclare [[cvc4_extensions = false]]\n\ntext \\\nEnable the following option to use built-in support for div/mod, datatypes,\nand records in Z3. Currently, this is implemented only in oracle mode.\n\\\n\ndeclare [[z3_extensions = false]]\n\n\nsubsection \\Certificates\\\n\ntext \\\nBy setting the option \\smt_certificates\\ to the name of a file,\nall following applications of an SMT solver a cached in that file.\nAny further application of the same SMT solver (using the very same\nconfiguration) re-uses the cached certificate instead of invoking the\nsolver. An empty string disables caching certificates.\n\nThe filename should be given as an explicit path. It is good\npractice to use the name of the current theory (with ending\n\\.certs\\ instead of \\.thy\\) as the certificates file.\nCertificate files should be used at most once in a certain theory context,\nto avoid race conditions with other concurrent accesses.\n\\\n\ndeclare [[smt_certificates = \"\"]]\n\ntext \\\nThe option \\smt_read_only_certificates\\ controls whether only\nstored certificates are should be used or invocation of an SMT solver\nis allowed. When set to \\true\\, no SMT solver will ever be\ninvoked and only the existing certificates found in the configured\ncache are used; when set to \\false\\ and there is no cached\ncertificate for some proposition, then the configured SMT solver is\ninvoked.\n\\\n\ndeclare [[smt_read_only_certificates = false]]\n\n\nsubsection \\Tracing\\\n\ntext \\\nThe SMT method, when applied, traces important information. To\nmake it entirely silent, set the following option to \\false\\.\n\\\n\ndeclare [[smt_verbose = true]]\n\ntext \\\nFor tracing the generated problem file given to the SMT solver as\nwell as the returned result of the solver, the option\n\\smt_trace\\ should be set to \\true\\.\n\\\n\ndeclare [[smt_trace = false]]\n\n\nsubsection \\Schematic rules for Z3 proof reconstruction\\\n\ntext \\\nSeveral prof rules of Z3 are not very well documented. There are two\nlemma groups which can turn failing Z3 proof reconstruction attempts\ninto succeeding ones: the facts in \\z3_rule\\ are tried prior to\nany implemented reconstruction procedure for all uncertain Z3 proof\nrules; the facts in \\z3_simp\\ are only fed to invocations of\nthe simplifier when reconstructing theory-specific proof steps.\n\\\n\nlemmas [z3_rule] =\n refl eq_commute conj_commute disj_commute simp_thms nnf_simps\n ring_distribs field_simps times_divide_eq_right times_divide_eq_left\n if_True if_False not_not\n NO_MATCH_def\n\nlemma [z3_rule]:\n \"(P \\ Q) = (\\ (\\ P \\ \\ Q))\"\n \"(P \\ Q) = (\\ (\\ Q \\ \\ P))\"\n \"(\\ P \\ Q) = (\\ (P \\ \\ Q))\"\n \"(\\ P \\ Q) = (\\ (\\ Q \\ P))\"\n \"(P \\ \\ Q) = (\\ (\\ P \\ Q))\"\n \"(P \\ \\ Q) = (\\ (Q \\ \\ P))\"\n \"(\\ P \\ \\ Q) = (\\ (P \\ Q))\"\n \"(\\ P \\ \\ Q) = (\\ (Q \\ P))\"\n by auto\n\nlemma [z3_rule]:\n \"(P \\ Q) = (Q \\ \\ P)\"\n \"(\\ P \\ Q) = (P \\ Q)\"\n \"(\\ P \\ Q) = (Q \\ P)\"\n \"(True \\ P) = P\"\n \"(P \\ True) = True\"\n \"(False \\ P) = True\"\n \"(P \\ P) = True\"\n \"(\\ (A \\ \\ B)) \\ (A \\ B)\"\n by auto\n\nlemma [z3_rule]:\n \"((P = Q) \\ R) = (R \\ (Q = (\\ P)))\"\n by auto\n\nlemma [z3_rule]:\n \"(\\ True) = False\"\n \"(\\ False) = True\"\n \"(x = x) = True\"\n \"(P = True) = P\"\n \"(True = P) = P\"\n \"(P = False) = (\\ P)\"\n \"(False = P) = (\\ P)\"\n \"((\\ P) = P) = False\"\n \"(P = (\\ P)) = False\"\n \"((\\ P) = (\\ Q)) = (P = Q)\"\n \"\\ (P = (\\ Q)) = (P = Q)\"\n \"\\ ((\\ P) = Q) = (P = Q)\"\n \"(P \\ Q) = (Q = (\\ P))\"\n \"(P = Q) = ((\\ P \\ Q) \\ (P \\ \\ Q))\"\n \"(P \\ Q) = ((\\ P \\ \\ Q) \\ (P \\ Q))\"\n by auto\n\nlemma [z3_rule]:\n \"(if P then P else \\ P) = True\"\n \"(if \\ P then \\ P else P) = True\"\n \"(if P then True else False) = P\"\n \"(if P then False else True) = (\\ P)\"\n \"(if P then Q else True) = ((\\ P) \\ Q)\"\n \"(if P then Q else True) = (Q \\ (\\ P))\"\n \"(if P then Q else \\ Q) = (P = Q)\"\n \"(if P then Q else \\ Q) = (Q = P)\"\n \"(if P then \\ Q else Q) = (P = (\\ Q))\"\n \"(if P then \\ Q else Q) = ((\\ Q) = P)\"\n \"(if \\ P then x else y) = (if P then y else x)\"\n \"(if P then (if Q then x else y) else x) = (if P \\ (\\ Q) then y else x)\"\n \"(if P then (if Q then x else y) else x) = (if (\\ Q) \\ P then y else x)\"\n \"(if P then (if Q then x else y) else y) = (if P \\ Q then x else y)\"\n \"(if P then (if Q then x else y) else y) = (if Q \\ P then x else y)\"\n \"(if P then x else if P then y else z) = (if P then x else z)\"\n \"(if P then x else if Q then x else y) = (if P \\ Q then x else y)\"\n \"(if P then x else if Q then x else y) = (if Q \\ P then x else y)\"\n \"(if P then x = y else x = z) = (x = (if P then y else z))\"\n \"(if P then x = y else y = z) = (y = (if P then x else z))\"\n \"(if P then x = y else z = y) = (y = (if P then x else z))\"\n by auto\n\nlemma [z3_rule]:\n \"0 + (x::int) = x\"\n \"x + 0 = x\"\n \"x + x = 2 * x\"\n \"0 * x = 0\"\n \"1 * x = x\"\n \"x + y = y + x\"\n by (auto simp add: mult_2)\n\nlemma [z3_rule]: (* for def-axiom *)\n \"P = Q \\ P \\ Q\"\n \"P = Q \\ \\ P \\ \\ Q\"\n \"(\\ P) = Q \\ \\ P \\ Q\"\n \"(\\ P) = Q \\ P \\ \\ Q\"\n \"P = (\\ Q) \\ \\ P \\ Q\"\n \"P = (\\ Q) \\ P \\ \\ Q\"\n \"P \\ Q \\ P \\ \\ Q\"\n \"P \\ Q \\ \\ P \\ Q\"\n \"P \\ (\\ Q) \\ P \\ Q\"\n \"(\\ P) \\ Q \\ P \\ Q\"\n \"P \\ Q \\ P \\ (\\ Q)\"\n \"P \\ Q \\ (\\ P) \\ Q\"\n \"P \\ \\ Q \\ P \\ Q\"\n \"\\ P \\ Q \\ P \\ Q\"\n \"P \\ y = (if P then x else y)\"\n \"P \\ (if P then x else y) = y\"\n \"\\ P \\ x = (if P then x else y)\"\n \"\\ P \\ (if P then x else y) = x\"\n \"P \\ R \\ \\ (if P then Q else R)\"\n \"\\ P \\ Q \\ \\ (if P then Q else R)\"\n \"\\ (if P then Q else R) \\ \\ P \\ Q\"\n \"\\ (if P then Q else R) \\ P \\ R\"\n \"(if P then Q else R) \\ \\ P \\ \\ Q\"\n \"(if P then Q else R) \\ P \\ \\ R\"\n \"(if P then \\ Q else R) \\ \\ P \\ Q\"\n \"(if P then Q else \\ R) \\ P \\ R\"\n by auto\n\nhide_type (open) symb_list pattern\nhide_const (open) Symb_Nil Symb_Cons trigger pat nopat fun_app z3div z3mod\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/SMT.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.1081889459357195, "lm_q1q2_score": 0.051982481722590984}} {"text": "(* Title: Uint_Userguide.thy\n Author: Andreas Lochbihler, ETH Zurich\n*)\n\nchapter \\User guide for native words\\\n\n(*<*)\ntheory Uint_Userguide imports\n Uint32\n Uint16\n Code_Target_Int_Bit\nbegin\n(*>*)\n\ntext \\\n This tutorial explains how to best use the types for native\n words like @{typ \"uint32\"} in your formalisation.\n You can base your formalisation\n \\begin{enumerate}\n \\item either directly on these types,\n \\item or on the generic @{typ \"'a word\"} and only introduce native\n words a posteriori via code generator refinement.\n \\end{enumerate}\n\n The first option causes the least overhead if you have to prove only\n little about the words you use and start a fresh formalisation.\n Just use the native type @{typ uint32} instead of @{typ \"32 word\"}\n and similarly for \\uint64\\, \\uint16\\, and \\uint8\\.\n As native word types are meant only for code generation, the lemmas\n about @{typ \"'a word\"} have not been duplicated, but you can transfer\n theorems between native word types and @{typ \"'a word\"} using the\n transfer package.\n\n Note, however, that this option restricts your work a bit:\n your own functions cannot be ``polymorphic'' in the word length,\n but you have to define a separate function for every word length you need.\n\n The second option is recommended if you already have a formalisation\n based on @{typ \"'a word\"} or if your proofs involve words and their\n properties. It separates code generation from modelling and proving,\n i.e., you can work with words as usual. Consequently, you have to\n manually setup the code generator to use the native types wherever\n you want. The following describes how to achieve this with moderate\n effort.\n\n Note, however, that some target languages of the code generator\n (especially OCaml) do not support all the native word types provided.\n Therefore, you should only import those types that you need -- the\n theory file for each type mentions at the top the restrictions for\n code generation. For example, PolyML does not provide the Word16\n structure, and OCaml provides neither Word8 nor Word16.\n You can still use these theories provided that you also import\n the theory @{theory Native_Word.Code_Target_Int_Bit} (which implements\n @{typ int} by target-language integers), but these words will\n be implemented via Isabelle's \\Word\\ library, i.e.,\n you do not gain anything in terms of efficiency.\n\n \\textbf{There is a separate code target \\SML_word\\ for SML.}\n If you use one of the native words that PolyML does not support\n (such as \\uint16\\ and \\uint64\\ in 32-bit mode), but would\n like to map its operations to the Standard Basis Library functions,\n make sure to use the target \\SML_word\\ instead of \\SML\\;\n if you only use native word sizes that PolyML supports, you can stick\n with \\SML\\. This ensures that code generation within Isabelle\n as used by \\Quickcheck\\, \\value\\ and @\\{code\\} in ML blocks\n continues to work.\n\\\n\nsection \\Lifting functions from @{typ \"'a word\"} to native words\\\n\ntext \\\n This section shows how to convert functions from @{typ \"'a word\"} to native \n words. For example, the following function \\sum_squares\\ computes \n the sum of the first @{term n} square numbers in 16 bit arithmetic using\n a tail-recursive function \\gen_sum_squares\\ with accumulator;\n for convenience, \\sum_squares_int\\ takes an integer instead of a word.\n\\\n\nfunction gen_sum_squares :: \"16 word \\ 16 word \\ 16 word\" where (*<*)[simp del]:(*>*)\n\n \"gen_sum_squares accum n =\n (if n = 0 then accum else gen_sum_squares (accum + n * n) (n - 1))\"\n(*<*)by pat_completeness simp\ntermination by (relation \\measure (nat \\ uint \\ snd)\\) (simp_all add: measure_unat)(*>*)\n\ndefinition sum_squares :: \"16 word \\ 16 word\" where\n \"sum_squares = gen_sum_squares 0\"\n\ndefinition sum_squares_int :: \"int \\ 16 word\" where\n \"sum_squares_int n = sum_squares (word_of_int n)\"\n\ntext \\\n The generated code for @{term sum_squares} and @{term sum_squares_int} \n emulates words with unbounded integers and explicit modulus as specified \n in the theory @{theory \"HOL-Library.Word\"}. But for efficiency, we want that the\n generated code uses machine words and machine arithmetic. Unfortunately,\n as @{typ \"'a word\"} is polymorphic in the word length, the code generator\n can only do this if we use another type for machine words. The theory\n @{theory Native_Word.Uint16} defines the type @{typ uint16} for machine words of\n 16~bits. We just have to follow two steps to use it:\n \n First, we lift all our functions from @{typ \"16 word\"} to @{typ uint16},\n i.e., @{term sum_squares}, @{term gen_sum_squares}, and \n @{term sum_squares_int} in our case. The theory @{theory Native_Word.Uint16} sets\n up the lifting package for this and has already taken care of the\n arithmetic and bit-wise operations.\n\\\nlift_definition gen_sum_squares_uint :: \"uint16 \\ uint16 \\ uint16\" \n is gen_sum_squares .\nlift_definition sum_squares_uint :: \"uint16 \\ uint16\" is sum_squares .\nlift_definition sum_squares_int_uint :: \"int \\ uint16\" is sum_squares_int .\n\ntext \\\n Second, we also have to transfer the code equations for our functions.\n The attribute \\Transfer.transferred\\ takes care of that, but it is\n better to check that the transfer succeeded: inspect the theorem to check\n that the new constants are used throughout.\n\\\n\nlemmas [Transfer.transferred, code] =\n gen_sum_squares.simps\n sum_squares_def\n sum_squares_int_def\n\ntext \\\n Finally, we export the code to standard ML. We use the target\n \\SML_word\\ instead of \\SML\\ to have the operations\n on @{typ uint16} mapped to the Standard Basis Library. As PolyML\n does not provide a Word16 type, the mapping for @{typ uint16} is only\n active in the refined target \\SML_word\\.\n\\\nexport_code sum_squares_int_uint in SML_word\n\ntext \\\n Nevertheless, we can still evaluate terms with @{term \"uint16\"} within \n Isabelle, i.e., PolyML, but this will be translated to @{typ \"16 word\"}\n and therefore less efficient.\n\\\n\nvalue \"sum_squares_int_uint 40\"\n\nsection \\Storing native words in datatypes\\\n\ntext \\\n The above lifting is necessary for all functions whose type mentions\n the word type. Fortunately, we do not have to duplicate functions that\n merely operate on datatypes that contain words. Nevertheless, we have\n to tell the code generator that these functions should call the new ones,\n which operate on machine words. This section shows how to achieve this\n with data refinement.\n\\\n\nsubsection \\Example: expressions and two semantics\\\n\ntext \\\n As the running example, we consider a language of expressions (literal values, less-than comparisions and conditional) where values are either booleans or 32-bit words.\n The original specification uses the type @{typ \"32 word\"}.\n\\\n\ndatatype val = Bool bool | Word \"32 word\"\ndatatype expr = Lit val | LT expr expr | IF expr expr expr\n\nabbreviation (input) word :: \"32 word \\ expr\" where \"word i \\ Lit (Word i)\"\nabbreviation (input) bool :: \"bool \\ expr\" where \"bool i \\ Lit (Bool i)\"\n\n\\ \\Denotational semantics of expressions, @{term None} denotes a type error\\\nfun eval :: \"expr \\ val option\" where\n \"eval (Lit v) = Some v\"\n| \"eval (LT e\\<^sub>1 e\\<^sub>2) = \n (case (eval e\\<^sub>1, eval e\\<^sub>2) \n of (Some (Word i\\<^sub>1), Some (Word i\\<^sub>2)) \\ Some (Bool (i\\<^sub>1 < i\\<^sub>2))\n | _ \\ None)\"\n| \"eval (IF e\\<^sub>1 e\\<^sub>2 e\\<^sub>3) =\n (case eval e\\<^sub>1 of Some (Bool b) \\ if b then eval e\\<^sub>2 else eval e\\<^sub>3\n | _ \\ None)\"\n\n\\ \\Small-step semantics of expressions, it gets stuck upon type errors.\\\ninductive step :: \"expr \\ expr \\ bool\" (\"_ \\ _\" [50, 50] 60) where\n \"e \\ e' \\ LT e e\\<^sub>2 \\ LT e' e\\<^sub>2\"\n| \"e \\ e' \\ LT (word i) e \\ LT (word i) e'\"\n| \"LT (word i\\<^sub>1) (word i\\<^sub>2) \\ bool (i\\<^sub>1 < i\\<^sub>2)\"\n| \"e \\ e' \\ IF e e\\<^sub>1 e\\<^sub>2 \\ IF e' e\\<^sub>1 e\\<^sub>2\"\n| \"IF (bool True) e\\<^sub>1 e\\<^sub>2 \\ e\\<^sub>1\"\n| \"IF (bool False) e\\<^sub>1 e\\<^sub>2 \\ e\\<^sub>2\"\n\n\\ \\Compile the inductive definition with the predicate compiler\\\ncode_pred (modes: i \\ o \\ bool as reduce, i \\ i \\ bool as step') step .\n\nsubsection \\Change the datatype to use machine words\\\n\ntext \\\n Now, we want to use @{typ uint32} instead of @{typ \"32 word\"}.\n The goal is to make the code generator use the new type without\n duplicating any of the types (@{typ val}, @{typ expr}) or the\n functions (@{term eval}, @{term reduce}) on such types.\n\n The constructor @{term Word} has @{typ \"32 word\"} in its type, so\n we have to lift it to \\Word'\\, and the same holds for the\n case combinator @{term case_val}, which @{term case_val'} replaces.%\n \\footnote{%\n Note that we should not declare a case translation for the new\n case combinator because this will break parsing case expressions\n with old case combinator.\n }\n Next, we set up the code generator accordingly:\n @{term Bool} and @{term Word'} are the new constructors for @{typ val},\n and @{term case_val'} is the new case combinator with an appropriate \n case certificate.%\n \\footnote{%\n Case certificates tell the code generator to replace the HOL\n case combinator for a datatype with the case combinator of the\n target language. Without a case certificate, the code generator\n generates a function that re-implements the case combinator; \n in a strict languages like ML or Scala, this means that the code\n evaluates all possible cases before it decides which one is taken.\n\n Case certificates are described in Haftmann's PhD thesis\n \\<^cite>\\\\Def.\\ 27\\ in \"Haftmann2009PhD\"\\. For a datatype \\dt\\\n with constructors \\C\\<^sub>1\\ to \\C\\<^sub>n\\\n where each constructor \\C\\<^sub>i\\ takes \\k\\<^sub>i\\ parameters,\n the certificate for the case combinator \\case_dt\\\n looks as follows:\n\n {\n \\isamarkuptrue\\isacommand{lemma}\\isamarkupfalse\\isanewline%\n \\ \\ \\isakeyword{assumes}\\ {\\isachardoublequoteopen}CASE\\ {\\isasymequiv}\\ dt{\\isacharunderscore}case\\ c\\isactrlsub {\\isadigit{1}}\\ c\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ c\\isactrlsub{n}{\\isachardoublequoteclose}\\isanewline\n \\ \\ \\isakeyword{shows}\\ {\\isachardoublequoteopen}{\\isacharparenleft}CASE\\ {\\isacharparenleft}C\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {\\isadigit{1}}\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {\\isadigit{1}}\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ a\\isactrlsub {\\isadigit{1}}\\isactrlsub {k\\ensuremath{{}_1}}{\\isacharparenright}\\ {\\isasymequiv}\\ c\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {\\isadigit{1}}\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {\\isadigit{1}}\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ a\\isactrlsub {\\isadigit{1}}\\isactrlsub {k\\ensuremath{{}_1}}{\\isacharparenright}\\isanewline\n \\ \\ \\ \\ {\\isacharampersand}{\\isacharampersand}{\\isacharampersand}\\ {\\isacharparenleft}CASE\\ {\\isacharparenleft}C\\isactrlsub {\\isadigit{2}}\\ a\\isactrlsub {\\isadigit{2}}\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {\\isadigit{2}}\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ a\\isactrlsub {\\isadigit{2}}\\isactrlsub {k\\ensuremath{{}_2}}{\\isacharparenright}\\ {\\isasymequiv}\\ c\\isactrlsub {\\isadigit{2}}\\ a\\isactrlsub {\\isadigit{2}}\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {\\isadigit{2}}\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ a\\isactrlsub {\\isadigit{2}}\\isactrlsub {k\\ensuremath{{}_2}}{\\isacharparenright}\\isanewline\n \\ \\ \\ \\ {\\isacharampersand}{\\isacharampersand}{\\isacharampersand}\\ \\ldots\\isanewline\n \\ \\ \\ \\ {\\isacharampersand}{\\isacharampersand}{\\isacharampersand}\\ {\\isacharparenleft}CASE\\ {\\isacharparenleft}C\\isactrlsub {n}\\ a\\isactrlsub {n}\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {n}\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ a\\isactrlsub {n}\\isactrlsub {k\\ensuremath{{}_n}}{\\isacharparenright}\\ {\\isasymequiv}\\ c\\isactrlsub {n}\\ a\\isactrlsub {n}\\isactrlsub {\\isadigit{1}}\\ a\\isactrlsub {n}\\isactrlsub {\\isadigit{2}}\\ \\ldots\\ a\\isactrlsub {n}\\isactrlsub {k\\ensuremath{{}_n}}{\\isacharparenright}{\\isachardoublequoteclose}\\isanewline\n }\n }\n We delete the code equations for the old constructor @{term Word}\n and case combinator @{term case_val} such that the code generator\n reports missing adaptations.\n\\\n\nlift_definition Word' :: \"uint32 \\ val\" is Word .\n\ncode_datatype Bool Word'\n\nlift_definition case_val' :: \"(bool \\ 'a) \\ (uint32 \\ 'a) \\ val \\ 'a\" is case_val .\n\nlemmas [code, simp] = val.case [Transfer.transferred]\n\nlemma case_val'_cert:\n fixes bool word' b w\n assumes \"CASE \\ case_val' bool word'\"\n shows \"(CASE (Bool b) \\ bool b) &&& (CASE (Word' w) \\ word' w)\"\n by (simp_all add: assms)\n\nsetup \\Code.declare_case_global @{thm case_val'_cert}\\\n\ndeclare [[code drop: case_val Word]]\n\n\nsubsection \\Make functions use functions on machine words\\\n\ntext \\\n Finally, we merely have to change the code equations to use the \n new functions that operate on @{typ uint32}. As before, the\n attribute \\Transfer.transferred\\ does the job. In our example,\n we adapt the equality test on @{typ val} (code equations\n @{thm [source] val.eq.simps}) and the denotational and small-step \n semantics (code equations @{thm [source] eval.simps} and\n @{thm [source] step.equation}, respectively).\n\n We check that the adaptation has suceeded by exporting the functions.\n As we only use native word sizes that PolyML supports, we can use \n the usual target \\SML\\ instead of \\SML_word\\.\n\\\n\nlemmas [code] = \n val.eq.simps[THEN meta_eq_to_obj_eq, Transfer.transferred, THEN eq_reflection]\n eval.simps[Transfer.transferred]\n step.equation[Transfer.transferred]\n\nexport_code reduce step' eval checking SML\n\nsection \\Troubleshooting\\\n\ntext \\\n This section explains some possible problems when using native words.\n If you experience other difficulties, please contact the author.\n\\\n\nsubsection \\\\export_code\\ raises an exception \\label{section:export_code:exception}\\\n\ntext \\\n Probably, you have defined and are using a function on a native word type,\n but the code equation refers to emulated words. For example, the following\n defines a function \\double\\ that doubles a word. When we try to export\n code for \\double\\ without any further setup, \\export_code\\ will\n raise an exception or generate code that does not compile.\n\\\n\nlift_definition double :: \"uint32 \\ uint32\" is \"\\x. x + x\" .\n\ntext \\\n We have to prove a code equation that only uses the existing operations on\n @{typ uint32}. Then, \\export_code\\ works again.\n\\\n\nlemma double_code [code]: \"double n = n + n\"\nby transfer simp\n\nsubsection \\The generated code does not compile\\\n\ntext \\\n Probably, you have been exporting to a target language for which there\n is no setup, or your compiler does not provide the required API. Every\n theory for native words mentions at the start the limitations on code\n generation. Check that your concrete application meets all the\n requirements.\n\n Alternatively, this might be an instance of the problem described \n in \\S\\ref{section:export_code:exception}.\n\n For Haskell, you have to enable the extension TypeSynonymInstances with \\texttt{-XTypeSynonymInstances}\n if you are using polymorphic bit operations on the native word types.\n\\\n\nsubsection \\The generated code is too slow\\\n\ntext \\\n The generated code will most likely not be as fast as a direct implementation in the target language with manual tuning.\n This is because we want the configuration of the code generation to be sound (as it can be used to prove theorems in Isabelle).\n Therefore, the bit operations sometimes perform range checks before they call the target language API.\n Here are some examples:\n \\begin{itemize}\n \\item Shift distances and bit indices in target languages are often expected to fit into a bounded integer or word.\n However, the size of these types varies across target languages and platforms.\n Hence, no Isabelle/HOL type can model uniformly all of them.\n Instead, the bit operations use arbitrary-precision integers for such quantities and check at run-time that the values fit into a bounded integer or word, respectively -- if not, they raise an exception.\n \n \\item Division and modulo operations explicitly test whether the divisor is $0$ and return the HOL value of division by $0$ in that case.\n This is necessary because some languages leave the behaviour of division by 0 unspecified.\n \\end{itemize}\n \n If you have better ideas how to eliminate such checks and speed up the generated code without sacrificing soundness, please contact the author!\n\\\n\n(*<*)end(*>*)\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Native_Word/Uint_Userguide.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.11596071825396674, "lm_q1q2_score": 0.0512167189702583}} {"text": "theory week10A_demo\nimports\n \"autocorres-1.4/autocorres/AutoCorres\"\n GCD\nbegin\n\ntext {*\n To run this demo you must have the AutoCorres tool.\n This demo was tested with the AutoCorres tarball from the COMP4161 website.\n\n You can download AutoCorres from \n \\url{http://www.cse.unsw.edu.au/~cs4161/autocorres-1.4.tar.gz}\n\n The following instructions assume you downloaded autocorres-1.4.tar.gz\n\n 1. Unpack the .tar.gz file, which will create the directory autocorres-1.4\n \n tar -xzf autocorres-1.4.tar.gz\n\n 2. To test that it builds with your Isabelle version, build the AutoCorres heap\n\n L4V_ARCH=X64 isabelle build -v -b -d autocorres-1.4 AutoCorres\nOR:\n L4V_ARCH=ARM isabelle build -v -b -d autocorres-1.4 AutoCorres\n\n (depending whether you want 32-bit or 64-bit words)\n\n 3. Load this demo theory using the AutoCorres heap\n\n L4V_ARCH=X64 isabelle jedit -d autocorres-1.4 -l AutoCorres week10A_demo.thy\nOR:\n L4V_ARCH=ARM isabelle jedit -d autocorres-1.4 -l AutoCorres week10A_demo.thy\n\n (needs to be the same as the one used to build the heap in 2.)\n\n To parse the C file you need to have 'cpp' installed. On Linux you\n will probably already have gcc. On Mac OS, you may need to download\n the Command Line Tools. You can do this via Xcode if you have it installed.\n Or you can download standalone packages with command \n xcode-select --install \n in a terminal window.\n\n Make sure the demo C file simple.c is in the same directory as this .thy file\n*}\n\ntext {*\n Parse in the C file; give each function a deeply embedded semantics in\n the SIMPL language.\n*}\ninstall_C_file \"simple.c\"\n\ntext {*\n Use AutoCorres to give each function a (monadic) shallow embedding that\n is designed to be more easily reasoned about.\n (The ts_force_nondet option below forces AutoCorres not to type strengthen\n the gcd function. Try removing it to see type strengthening in action.\n You might also like to experiment with forcing other levels of type\n strengthening for max by adding ts_force monad=max where monad is\n one of pure, gets, option, nondet.)\n*}\nautocorres [unsigned_word_abs=gcd max except, ts_force nondet=gcd] \"simple.c\"\ntext {*\n Enter the environment in which all of the C parser and AutoCorres output is placed\n*}\ncontext simple begin\n\ntext {* \n View the AutoCorres semantics of the max function\n*}\nthm max'_def\n\ntext {*\n This is its original semantics in SIMPL\n*}\nthm max_body_def\n\ntext {*\n The state type of the monad that AutoCorres produces is called @{typ lifted_globals}.\n\n It is a record containing a set of heaps, one for each pointer \n type used in the program. Ours uses only unsigned *, i.e. 32-bit word pointers.\n*}\nterm heap_w32\nterm heap_w32_update\n\ntext {*\n This is the AutoCorres semantics of the func function. Observe that it\n is very similar to the hand-written example from the last lecture.\n*}\nthm func'_def\n\ntext {*\n The automated tactic \"wp\" does automatic rule application of the monadic\n weakest precondition style rules we saw last lecture.\n*}\nlemma func'_partial_wp: \n \"\\\\s. heap_w32 s p \\ 10 \\ Q () s\\ func' p \\Q\\\"\n apply(unfold func'_def)\n apply(rule hoare_weaken_pre)\n apply wp\n apply auto\n done\n\ntext {*\n AutoCorres gives the gcd function a semantics in the nondeterministic\n state monad with failure (from last lecture). Observe that the guard to\n check for the absence of division by zero in the SIMPL is absent from the\n state monad version, because AutoCorres can prove it isn't needed due to the\n loop condition.\n*}\nthm gcd'_def gcd_body_def\n\ntext {*\n AutoCorres also proves that its (monadic) abstractions of each function\n correspond to their semantics in SIMPL. In this sense AutoCorres is a\n self-certifying tool, and doesn't need to be trusted.\n*}\nthm gcd'_ac_corres max'_ac_corres func'_ac_corres\n\nlemma gcd'_correct:\n \"\\\\_. True\\ gcd' a b \\\\r s. r = gcd a b\\\"\n apply(unfold gcd'_def)\n apply(rule hoare_weaken_pre)\n apply wp\n apply(rule whileLoop_wp[where I=\"\\(x,y) _. gcd x y = gcd a b\"])\n apply clarsimp\n apply wp\n apply clarsimp (*sledgehammer*)\n apply (metis gcd.commute gcd_red_nat)\n apply clarsimp (*sledgehammer*)\n using gr_zeroI apply fastforce\n apply clarsimp\n done\n\nlemma gcd'_correct2:\n \"\\\\_. True\\ gcd' a b \\\\r s. r = gcd a b\\\"\n apply (unfold gcd'_def)\n apply (rule hoare_weaken_pre)\n (*sledgehammer*)\n apply (metis (no_types, lifting) hoare_chain simple.gcd'_correct simple.gcd'_def)\n apply simp\n done\n\ntext {*\n AutoCorres loops can be annotated with invariants which will be used by\n the wp ruleset when doing automated proofs. You annotate a rule by\n using the @{thm whileLoop_add_inv} substitution rule.\n*}\nlemma gcd'_le:\n \"\\\\_. True\\ gcd' a b \\\\r s. r \\ max a b\\\"\n apply(unfold gcd'_def)\n apply(subst whileLoop_add_inv[where I=\"\\(x,y) _. max x y \\ max a b\"])\n apply wp \n apply clarsimp\n using dual_order.trans mod_le_divisor apply blast\n apply clarsimp\n apply clarsimp\n done\n\n\n\n\n\nthm unlessE_def\ntext {*\n A helper lemma about @{term unlessE}.\n*}\nlemma validE_unlessE[wp]:\n \"\\P'\\ f \\Q\\,\\R\\ \\\n \\\\s. if P then Q () s else P' s\\ unlessE P f \\Q\\,\\R\\\"\n apply(clarsimp simp: unlessE_def)\n apply wp\n done\n\n\ntext {*\n wp tends to handle most reasoning about exceptions over AutoCorres output\n*}\nlemma except'_result:\n \"\\\\_. True\\ except' u \\\\r _. r \\ 6 \\ r \\ 8\\\"\n apply(unfold except'_def)\n apply(subst whileLoopE_add_inv[where I=\"\\(ret, u) _. u < 9\"])\n apply wp\n apply clarsimp\n apply clarsimp\n apply clarsimp\n apply wp\n done\n\n\ntext {*\n Some more helper lemmas.\n*}\nlemma no_fail_returnOk [simp]:\n \"no_fail P (returnOk v)\"\n apply(auto simp: no_fail_def)\n done\n\nlemma validNF_unlessE[wp]:\n \"\\P'\\ f \\Q\\,\\R\\! \\\n \\\\s. if P then Q () s else P' s\\ unlessE P f \\Q\\,\\R\\!\"\n apply(clarsimp simp: validE_NF_def unlessE_def | wp )+\n done\nthm valid_def validNF_def no_fail_def\n\ntext {*\n This lemma proves additionally that the @{term except'} function never\n fails --- i.e. it proves \\emph{total correctness}, and guarantees the\n side-conditions on the soundness of the AutoCorres-produced abstraction of\n the C code.\n*}\nlemma except'_result_nf:\n \"\\\\_. True\\ except' u \\\\r _. r \\ 6 \\ r \\ 8\\!\"\n apply(unfold except'_def)\n apply(subst whileLoopE_add_inv[where I=\"\\(ret,u) _. u \\ 8\" and M=\"\\((ret,u),_). (9::nat) - u\"])\n apply (wp | clarsimp)+\n apply(simp add: UINT_MAX_def, arith)\n apply clarsimp\n apply wp\n apply clarsimp\n done\n\nend (* context simple *)\n\nend", "meta": {"author": "z5146542", "repo": "TOR", "sha": "9a82d491288a6d013e0764f68e602a63e48f92cf", "save_path": "github-repos/isabelle/z5146542-TOR", "path": "github-repos/isabelle/z5146542-TOR/TOR-9a82d491288a6d013e0764f68e602a63e48f92cf/181210/week10A_demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.14223188773801163, "lm_q1q2_score": 0.051113040751478135}} {"text": "(* Title: HOL/Nitpick_Examples/Mono_Nits.thy\n Author: Jasmin Blanchette, TU Muenchen\n Copyright 2009-2011\n\nExamples featuring Nitpick's monotonicity check.\n*)\n\nsection \\Examples Featuring Nitpick's Monotonicity Check\\\n\ntheory Mono_Nits\nimports MainRLT\n (* \"~/afp/thys/DPT-SAT-Solver/DPT_SAT_Solver\" *)\n (* \"~/afp/thys/AVL-Trees/AVL2\" \"~/afp/thys/Huffman/Huffman\" *)\nbegin\n\nML \\\nopen Nitpick_Util\nopen Nitpick_HOL\nopen Nitpick_Preproc\n\nexception BUG\n\nval thy = \\<^theory>\nval ctxt = \\<^context>\nval subst = []\nval tac_timeout = seconds 1.0\nval case_names = case_const_names ctxt\nval defs = all_defs_of thy subst\nval nondefs = all_nondefs_of ctxt subst\nval def_tables = const_def_tables ctxt subst defs\nval nondef_table = const_nondef_table nondefs\nval simp_table = Unsynchronized.ref (const_simp_table ctxt subst)\nval psimp_table = const_psimp_table ctxt subst\nval choice_spec_table = const_choice_spec_table ctxt subst\nval intro_table = inductive_intro_table ctxt subst def_tables\nval ground_thm_table = ground_theorem_table thy\nval ersatz_table = ersatz_table ctxt\nval hol_ctxt as {thy, ...} : hol_context =\n {thy = thy, ctxt = ctxt, max_bisim_depth = ~1, boxes = [], wfs = [],\n user_axioms = NONE, debug = false, whacks = [], binary_ints = SOME false,\n destroy_constrs = true, specialize = false, star_linear_preds = false,\n total_consts = NONE, needs = NONE, tac_timeout = tac_timeout, evals = [],\n case_names = case_names, def_tables = def_tables,\n nondef_table = nondef_table, nondefs = nondefs, simp_table = simp_table,\n psimp_table = psimp_table, choice_spec_table = choice_spec_table,\n intro_table = intro_table, ground_thm_table = ground_thm_table,\n ersatz_table = ersatz_table, skolems = Unsynchronized.ref [],\n special_funs = Unsynchronized.ref [], unrolled_preds = Unsynchronized.ref [],\n wf_cache = Unsynchronized.ref [], constr_cache = Unsynchronized.ref []}\nval binarize = false\n\nfun is_mono t =\n Nitpick_Mono.formulas_monotonic hol_ctxt binarize \\<^typ>\\'a\\ ([t], [])\n\nfun is_const t =\n let val T = fastype_of t in\n Logic.mk_implies (Logic.mk_equals (Free (\"dummyP\", T), t), \\<^Const>\\False\\)\n |> is_mono\n end\n\nfun mono t = is_mono t orelse raise BUG\nfun nonmono t = not (is_mono t) orelse raise BUG\nfun const t = is_const t orelse raise BUG\nfun nonconst t = not (is_const t) orelse raise BUG\n\\\n\nML \\Nitpick_Mono.trace := false\\\n\nML_val \\const \\<^term>\\A::('a\\'b)\\\\\nML_val \\const \\<^term>\\(A::'a set) = A\\\\\nML_val \\const \\<^term>\\(A::'a set set) = A\\\\\nML_val \\const \\<^term>\\(\\x::'a set. a \\ x)\\\\\nML_val \\const \\<^term>\\{{a::'a}} = C\\\\\nML_val \\const \\<^term>\\{f::'a\\nat} = {g::'a\\nat}\\\\\nML_val \\const \\<^term>\\A \\ (B::'a set)\\\\\nML_val \\const \\<^term>\\\\A B x::'a. A x \\ B x\\\\\nML_val \\const \\<^term>\\P (a::'a)\\\\\nML_val \\const \\<^term>\\\\a::'a. b (c (d::'a)) (e::'a) (f::'a)\\\\\nML_val \\const \\<^term>\\\\A::'a set. a \\ A\\\\\nML_val \\const \\<^term>\\\\A::'a set. P A\\\\\nML_val \\const \\<^term>\\P \\ Q\\\\\nML_val \\const \\<^term>\\A \\ B = (C::'a set)\\\\\nML_val \\const \\<^term>\\(\\A B x::'a. A x \\ B x) A B = C\\\\\nML_val \\const \\<^term>\\(if P then (A::'a set) else B) = C\\\\\nML_val \\const \\<^term>\\let A = (C::'a set) in A \\ B\\\\\nML_val \\const \\<^term>\\THE x::'b. P x\\\\\nML_val \\const \\<^term>\\(\\x::'a. False)\\\\\nML_val \\const \\<^term>\\(\\x::'a. True)\\\\\nML_val \\const \\<^term>\\(\\x::'a. False) = (\\x::'a. False)\\\\\nML_val \\const \\<^term>\\(\\x::'a. True) = (\\x::'a. True)\\\\\nML_val \\const \\<^term>\\Let (a::'a) A\\\\\nML_val \\const \\<^term>\\A (a::'a)\\\\\nML_val \\const \\<^term>\\insert (a::'a) A = B\\\\\nML_val \\const \\<^term>\\- (A::'a set)\\\\\nML_val \\const \\<^term>\\finite (A::'a set)\\\\\nML_val \\const \\<^term>\\\\ finite (A::'a set)\\\\\nML_val \\const \\<^term>\\finite (A::'a set set)\\\\\nML_val \\const \\<^term>\\\\a::'a. A a \\ \\ B a\\\\\nML_val \\const \\<^term>\\A < (B::'a set)\\\\\nML_val \\const \\<^term>\\A \\ (B::'a set)\\\\\nML_val \\const \\<^term>\\[a::'a]\\\\\nML_val \\const \\<^term>\\[a::'a set]\\\\\nML_val \\const \\<^term>\\[A \\ (B::'a set)]\\\\\nML_val \\const \\<^term>\\[A \\ (B::'a set)] = [C]\\\\\nML_val \\const \\<^term>\\{(\\x::'a. x = a)} = C\\\\\nML_val \\const \\<^term>\\(\\a::'a. \\ A a) = B\\\\\nML_val \\const \\<^prop>\\\\F f g (h::'a set). F f \\ F g \\ \\ f a \\ g a \\ \\ f a\\\\\nML_val \\const \\<^term>\\\\A B x::'a. A x \\ B x \\ A = B\\\\\nML_val \\const \\<^term>\\p = (\\(x::'a) (y::'a). P x \\ \\ Q y)\\\\\nML_val \\const \\<^term>\\p = (\\(x::'a) (y::'a). p x y :: bool)\\\\\nML_val \\const \\<^term>\\p = (\\A B x. A x \\ \\ B x) (\\x. True) (\\y. x \\ y)\\\\\nML_val \\const \\<^term>\\p = (\\y. x \\ y)\\\\\nML_val \\const \\<^term>\\(\\x. (p::'a\\bool\\bool) x False)\\\\\nML_val \\const \\<^term>\\(\\x y. (p::'a\\'a\\bool\\bool) x y False)\\\\\nML_val \\const \\<^term>\\f = (\\x::'a. P x \\ Q x)\\\\\nML_val \\const \\<^term>\\\\a::'a. P a\\\\\n\nML_val \\nonconst \\<^term>\\\\P (a::'a). P a\\\\\nML_val \\nonconst \\<^term>\\THE x::'a. P x\\\\\nML_val \\nonconst \\<^term>\\SOME x::'a. P x\\\\\nML_val \\nonconst \\<^term>\\(\\A B x::'a. A x \\ B x) = myunion\\\\\nML_val \\nonconst \\<^term>\\(\\x::'a. False) = (\\x::'a. True)\\\\\nML_val \\nonconst \\<^prop>\\\\F f g (h::'a set). F f \\ F g \\ \\ a \\ f \\ a \\ g \\ F h\\\\\n\nML_val \\mono \\<^prop>\\Q (\\x::'a set. P x)\\\\\nML_val \\mono \\<^prop>\\P (a::'a)\\\\\nML_val \\mono \\<^prop>\\{a} = {b::'a}\\\\\nML_val \\mono \\<^prop>\\(\\x. x = a) = (\\y. y = (b::'a))\\\\\nML_val \\mono \\<^prop>\\(a::'a) \\ P \\ P \\ P = P\\\\\nML_val \\mono \\<^prop>\\\\F::'a set set. P\\\\\nML_val \\mono \\<^prop>\\\\ (\\F f g (h::'a set). F f \\ F g \\ \\ a \\ f \\ a \\ g \\ F h)\\\\\nML_val \\mono \\<^prop>\\\\ Q (\\x::'a set. P x)\\\\\nML_val \\mono \\<^prop>\\\\ (\\x::'a. P x)\\\\\nML_val \\mono \\<^prop>\\myall P = (P = (\\x::'a. True))\\\\\nML_val \\mono \\<^prop>\\myall P = (P = (\\x::'a. False))\\\\\nML_val \\mono \\<^prop>\\\\x::'a. P x\\\\\nML_val \\mono \\<^term>\\(\\A B x::'a. A x \\ B x) \\ myunion\\\\\n\nML_val \\nonmono \\<^prop>\\A = (\\x::'a. True) \\ A = (\\x. False)\\\\\nML_val \\nonmono \\<^prop>\\\\F f g (h::'a set). F f \\ F g \\ \\ a \\ f \\ a \\ g \\ F h\\\\\n\nML \\\nval preproc_timeout = seconds 5.0\nval mono_timeout = seconds 1.0\n\nfun is_forbidden_theorem name =\n length (Long_Name.explode name) <> 2 orelse\n String.isPrefix \"type_definition\" (List.last (Long_Name.explode name)) orelse\n String.isPrefix \"arity_\" (List.last (Long_Name.explode name)) orelse\n String.isSuffix \"_def\" name orelse\n String.isSuffix \"_raw\" name\n\nfun theorems_of thy =\n filter (fn (name, th) =>\n not (is_forbidden_theorem name) andalso\n Thm.theory_name th = Context.theory_name thy)\n (Global_Theory.all_thms_of thy true)\n\nfun check_formulas tsp =\n let\n fun is_type_actually_monotonic T =\n Nitpick_Mono.formulas_monotonic hol_ctxt binarize T tsp\n val free_Ts = fold Term.add_tfrees ((op @) tsp) [] |> map TFree\n val (mono_free_Ts, nonmono_free_Ts) =\n Timeout.apply mono_timeout\n (List.partition is_type_actually_monotonic) free_Ts\n in\n if not (null mono_free_Ts) then \"MONO\"\n else if not (null nonmono_free_Ts) then \"NONMONO\"\n else \"NIX\"\n end\n handle Timeout.TIMEOUT _ => \"TIMEOUT\"\n | NOT_SUPPORTED _ => \"UNSUP\"\n | exn => if Exn.is_interrupt exn then Exn.reraise exn else \"UNKNOWN\"\n\nfun check_theory thy =\n let\n val path = File.tmp_path (Context.theory_name thy ^ \".out\" |> Path.explode)\n val _ = File.write path \"\"\n fun check_theorem (name, th) =\n let\n val t = th |> Thm.prop_of |> Type.legacy_freeze |> close_form\n val neg_t = Logic.mk_implies (t, \\<^prop>\\False\\)\n val (nondef_ts, def_ts, _, _, _, _) =\n Timeout.apply preproc_timeout (preprocess_formulas hol_ctxt [])\n neg_t\n val res = name ^ \": \" ^ check_formulas (nondef_ts, def_ts)\n in File.append path (res ^ \"\\n\"); writeln res end\n handle Timeout.TIMEOUT _ => ()\n in thy |> theorems_of |> List.app check_theorem end\n\\\n\n(*\nML_val {* check_theory @{theory AVL2} *}\nML_val {* check_theory @{theory Fun} *}\nML_val {* check_theory @{theory Huffman} *}\nML_val {* check_theory @{theory List} *}\nML_val {* check_theory @{theory Map} *}\nML_val {* check_theory @{theory Relation} *}\n*)\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Nitpick_Examples/Mono_Nits.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4649015862011227, "lm_q2_score": 0.10970577387797076, "lm_q1q2_score": 0.0510023882912903}} {"text": "theory Introduction\nimports Setup\nbegin (*<*)\n\nML \\\n Isabelle_System.mkdirs (File.tmp_path (Path.basic \"examples\"))\n\\ (*>*)\n\nsection \\Introduction\\\n\ntext \\\n This tutorial introduces the code generator facilities of \\Isabelle/HOL\\. It allows to turn (a certain class of) HOL\n specifications into corresponding executable code in the programming\n languages \\SML\\ @{cite SML}, \\OCaml\\ @{cite OCaml},\n \\Haskell\\ @{cite \"haskell-revised-report\"} and \\Scala\\\n @{cite \"scala-overview-tech-report\"}.\n\n To profit from this tutorial, some familiarity and experience with\n Isabelle/HOL @{cite \"isa-tutorial\"} and its basic theories is assumed.\n\\\n\n\nsubsection \\Code generation principle: shallow embedding \\label{sec:principle}\\\n\ntext \\\n The key concept for understanding Isabelle's code generation is\n \\emph{shallow embedding}: logical entities like constants, types and\n classes are identified with corresponding entities in the target\n language. In particular, the carrier of a generated program's\n semantics are \\emph{equational theorems} from the logic. If we view\n a generated program as an implementation of a higher-order rewrite\n system, then every rewrite step performed by the program can be\n simulated in the logic, which guarantees partial correctness\n @{cite \"Haftmann-Nipkow:2010:code\"}.\n\\\n\n\nsubsection \\A quick start with the Isabelle/HOL toolbox \\label{sec:queue_example}\\\n\ntext \\\n In a HOL theory, the @{command_def datatype} and @{command_def\n definition}/@{command_def primrec}/@{command_def fun} declarations\n form the core of a functional programming language. By default\n equational theorems stemming from those are used for generated code,\n therefore \\qt{naive} code generation can proceed without further\n ado.\n\n For example, here a simple \\qt{implementation} of amortised queues:\n\\\n\ndatatype %quote 'a queue = AQueue \"'a list\" \"'a list\"\n\ndefinition %quote empty :: \"'a queue\" where\n \"empty = AQueue [] []\"\n\nprimrec %quote enqueue :: \"'a \\ 'a queue \\ 'a queue\" where\n \"enqueue x (AQueue xs ys) = AQueue (x # xs) ys\"\n\nfun %quote dequeue :: \"'a queue \\ 'a option \\ 'a queue\" where\n \"dequeue (AQueue [] []) = (None, AQueue [] [])\"\n | \"dequeue (AQueue xs (y # ys)) = (Some y, AQueue xs ys)\"\n | \"dequeue (AQueue xs []) =\n (case rev xs of y # ys \\ (Some y, AQueue [] ys))\" (*<*)\n\nlemma %invisible dequeue_nonempty_Nil [simp]:\n \"xs \\ [] \\ dequeue (AQueue xs []) = (case rev xs of y # ys \\ (Some y, AQueue [] ys))\"\n by (cases xs) (simp_all split: list.splits) (*>*)\n\ntext \\\\noindent Then we can generate code e.g.~for \\SML\\ as follows:\\\n\nexport_code %quote empty dequeue enqueue in SML module_name Example\n\ntext \\\\noindent resulting in the following code:\\\n\ntext %quote \\\n @{code_stmts empty enqueue dequeue (SML)}\n\\\n\ntext \\\n \\noindent The @{command_def export_code} command takes multiple constants\n for which code shall be generated; anything else needed for those is\n added implicitly. Then follows a target language identifier and a freely\n chosen \\<^theory_text>\\module_name\\.\n\n Output is written to a logical file-system within the theory context,\n with the theory name and ``\\<^verbatim>\\code\\'' as overall prefix. There is also a\n formal session export using the same name: the result may be explored in\n the Isabelle/jEdit Prover IDE using the file-browser on the URL\n ``\\<^verbatim>\\isabelle-export:\\''.\n\n The file name is determined by the target language together with an\n optional \\<^theory_text>\\file_prefix\\ (the default is ``\\<^verbatim>\\export\\'' with a consecutive\n number within the current theory). For \\SML\\, \\OCaml\\ and \\Scala\\, the\n file prefix becomes a plain file with extension (e.g.\\ ``\\<^verbatim>\\.ML\\'' for\n SML). For \\Haskell\\ the file prefix becomes a directory that is populated\n with a separate file for each module (with extension ``\\<^verbatim>\\.hs\\'').\n\n Consider the following example:\n\\\n\nexport_code %quote empty dequeue enqueue in Haskell\n module_name Example file_prefix example\n\ntext \\\n \\noindent This is the corresponding code:\n\\\n\ntext %quote \\\n @{code_stmts empty enqueue dequeue (Haskell)}\n\\\n\ntext \\\n \\noindent For more details about @{command export_code} see\n \\secref{sec:further}.\n\\\n\n\nsubsection \\Type classes\\\n\ntext \\\n Code can also be generated from type classes in a Haskell-like\n manner. For illustration here an example from abstract algebra:\n\\\n\nclass %quote semigroup =\n fixes mult :: \"'a \\ 'a \\ 'a\" (infixl \"\\\" 70)\n assumes assoc: \"(x \\ y) \\ z = x \\ (y \\ z)\"\n\nclass %quote monoid = semigroup +\n fixes neutral :: 'a (\"\\\")\n assumes neutl: \"\\ \\ x = x\"\n and neutr: \"x \\ \\ = x\"\n\ninstantiation %quote nat :: monoid\nbegin\n\nprimrec %quote mult_nat where\n \"0 \\ n = (0::nat)\"\n | \"Suc m \\ n = n + m \\ n\"\n\ndefinition %quote neutral_nat where\n \"\\ = Suc 0\"\n\nlemma %quote add_mult_distrib:\n fixes n m q :: nat\n shows \"(n + m) \\ q = n \\ q + m \\ q\"\n by (induct n) simp_all\n\ninstance %quote proof\n fix m n q :: nat\n show \"m \\ n \\ q = m \\ (n \\ q)\"\n by (induct m) (simp_all add: add_mult_distrib)\n show \"\\ \\ n = n\"\n by (simp add: neutral_nat_def)\n show \"m \\ \\ = m\"\n by (induct m) (simp_all add: neutral_nat_def)\nqed\n\nend %quote\n\ntext \\\n \\noindent We define the natural operation of the natural numbers\n on monoids:\n\\\n\nprimrec %quote (in monoid) pow :: \"nat \\ 'a \\ 'a\" where\n \"pow 0 a = \\\"\n | \"pow (Suc n) a = a \\ pow n a\"\n\ntext \\\n \\noindent This we use to define the discrete exponentiation\n function:\n\\\n\ndefinition %quote bexp :: \"nat \\ nat\" where\n \"bexp n = pow n (Suc (Suc 0))\"\n\ntext \\\n \\noindent The corresponding code in Haskell uses that language's\n native classes:\n\\\n\ntext %quote \\\n @{code_stmts bexp (Haskell)}\n\\\n\ntext \\\n \\noindent This is a convenient place to show how explicit dictionary\n construction manifests in generated code -- the same example in\n \\SML\\:\n\\\n\ntext %quote \\\n @{code_stmts bexp (SML)}\n\\\n\ntext \\\n \\noindent Note the parameters with trailing underscore (\\<^verbatim>\\A_\\), which are the dictionary parameters.\n\\\n\n\nsubsection \\How to continue from here\\\n\ntext \\\n What you have seen so far should be already enough in a lot of\n cases. If you are content with this, you can quit reading here.\n\n Anyway, to understand situations where problems occur or to increase\n the scope of code generation beyond default, it is necessary to gain\n some understanding how the code generator actually works:\n\n \\begin{itemize}\n\n \\item The foundations of the code generator are described in\n \\secref{sec:foundations}.\n\n \\item In particular \\secref{sec:utterly_wrong} gives hints how to\n debug situations where code generation does not succeed as\n expected.\n\n \\item The scope and quality of generated code can be increased\n dramatically by applying refinement techniques, which are\n introduced in \\secref{sec:refinement}.\n\n \\item Inductive predicates can be turned executable using an\n extension of the code generator \\secref{sec:inductive}.\n\n \\item If you want to utilize code generation to obtain fast\n evaluators e.g.~for decision procedures, have a look at\n \\secref{sec:evaluation}.\n\n \\item You may want to skim over the more technical sections\n \\secref{sec:adaptation} and \\secref{sec:further}.\n\n \\item The target language Scala @{cite \"scala-overview-tech-report\"}\n comes with some specialities discussed in \\secref{sec:scala}.\n\n \\item For exhaustive syntax diagrams etc. you should visit the\n Isabelle/Isar Reference Manual @{cite \"isabelle-isar-ref\"}.\n\n \\end{itemize}\n\n \\bigskip\n\n \\begin{center}\\fbox{\\fbox{\\begin{minipage}{8cm}\n\n \\begin{center}\\textit{Happy proving, happy hacking!}\\end{center}\n\n \\end{minipage}}}\\end{center}\n\\\n\nend\n\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/Doc/Codegen/Introduction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.10521053950871515, "lm_q1q2_score": 0.05014120220728455}} {"text": "theory Introduction\nimports Setup\nbegin (*<*)\n\nML \\\n Isabelle_System.make_directory (File.tmp_path (Path.basic \"examples\"))\n\\ (*>*)\n\nsection \\Introduction\\\n\ntext \\\n This tutorial introduces the code generator facilities of \\Isabelle/HOL\\. It allows to turn (a certain class of) HOL\n specifications into corresponding executable code in the programming\n languages \\SML\\ @{cite SML}, \\OCaml\\ @{cite OCaml},\n \\Haskell\\ @{cite \"haskell-revised-report\"} and \\Scala\\\n @{cite \"scala-overview-tech-report\"}.\n\n To profit from this tutorial, some familiarity and experience with\n Isabelle/HOL @{cite \"isa-tutorial\"} and its basic theories is assumed.\n\\\n\n\nsubsection \\Code generation principle: shallow embedding \\label{sec:principle}\\\n\ntext \\\n The key concept for understanding Isabelle's code generation is\n \\emph{shallow embedding}: logical entities like constants, types and\n classes are identified with corresponding entities in the target\n language. In particular, the carrier of a generated program's\n semantics are \\emph{equational theorems} from the logic. If we view\n a generated program as an implementation of a higher-order rewrite\n system, then every rewrite step performed by the program can be\n simulated in the logic, which guarantees partial correctness\n @{cite \"Haftmann-Nipkow:2010:code\"}.\n\\\n\n\nsubsection \\A quick start with the Isabelle/HOL toolbox \\label{sec:queue_example}\\\n\ntext \\\n In a HOL theory, the @{command_def datatype} and @{command_def\n definition}/@{command_def primrec}/@{command_def fun} declarations\n form the core of a functional programming language. By default\n equational theorems stemming from those are used for generated code,\n therefore \\qt{naive} code generation can proceed without further\n ado.\n\n For example, here a simple \\qt{implementation} of amortised queues:\n\\\n\ndatatype %quote 'a queue = AQueue \"'a list\" \"'a list\"\n\ndefinition %quote empty :: \"'a queue\" where\n \"empty = AQueue [] []\"\n\nprimrec %quote enqueue :: \"'a \\ 'a queue \\ 'a queue\" where\n \"enqueue x (AQueue xs ys) = AQueue (x # xs) ys\"\n\nfun %quote dequeue :: \"'a queue \\ 'a option \\ 'a queue\" where\n \"dequeue (AQueue [] []) = (None, AQueue [] [])\"\n | \"dequeue (AQueue xs (y # ys)) = (Some y, AQueue xs ys)\"\n | \"dequeue (AQueue xs []) =\n (case rev xs of y # ys \\ (Some y, AQueue [] ys))\" (*<*)\n\nlemma %invisible dequeue_nonempty_Nil [simp]:\n \"xs \\ [] \\ dequeue (AQueue xs []) = (case rev xs of y # ys \\ (Some y, AQueue [] ys))\"\n by (cases xs) (simp_all split: list.splits) (*>*)\n\ntext \\\\noindent Then we can generate code e.g.~for \\SML\\ as follows:\\\n\nexport_code %quote empty dequeue enqueue in SML module_name Example\n\ntext \\\\noindent resulting in the following code:\\\n\ntext %quote \\\n @{code_stmts empty enqueue dequeue (SML)}\n\\\n\ntext \\\n \\noindent The @{command_def export_code} command takes multiple constants\n for which code shall be generated; anything else needed for those is\n added implicitly. Then follows a target language identifier and a freely\n chosen \\<^theory_text>\\module_name\\.\n\n Output is written to a logical file-system within the theory context,\n with the theory name and ``\\<^verbatim>\\code\\'' as overall prefix. There is also a\n formal session export using the same name: the result may be explored in\n the Isabelle/jEdit Prover IDE using the file-browser on the URL\n ``\\<^verbatim>\\isabelle-export:\\''.\n\n The file name is determined by the target language together with an\n optional \\<^theory_text>\\file_prefix\\ (the default is ``\\<^verbatim>\\export\\'' with a consecutive\n number within the current theory). For \\SML\\, \\OCaml\\ and \\Scala\\, the\n file prefix becomes a plain file with extension (e.g.\\ ``\\<^verbatim>\\.ML\\'' for\n SML). For \\Haskell\\ the file prefix becomes a directory that is populated\n with a separate file for each module (with extension ``\\<^verbatim>\\.hs\\'').\n\n Consider the following example:\n\\\n\nexport_code %quote empty dequeue enqueue in Haskell\n module_name Example file_prefix example\n\ntext \\\n \\noindent This is the corresponding code:\n\\\n\ntext %quote \\\n @{code_stmts empty enqueue dequeue (Haskell)}\n\\\n\ntext \\\n \\noindent For more details about @{command export_code} see\n \\secref{sec:further}.\n\\\n\n\nsubsection \\Type classes\\\n\ntext \\\n Code can also be generated from type classes in a Haskell-like\n manner. For illustration here an example from abstract algebra:\n\\\n\nclass %quote semigroup =\n fixes mult :: \"'a \\ 'a \\ 'a\" (infixl \"\\\" 70)\n assumes assoc: \"(x \\ y) \\ z = x \\ (y \\ z)\"\n\nclass %quote monoid = semigroup +\n fixes neutral :: 'a (\"\\\")\n assumes neutl: \"\\ \\ x = x\"\n and neutr: \"x \\ \\ = x\"\n\ninstantiation %quote nat :: monoid\nbegin\n\nprimrec %quote mult_nat where\n \"0 \\ n = (0::nat)\"\n | \"Suc m \\ n = n + m \\ n\"\n\ndefinition %quote neutral_nat where\n \"\\ = Suc 0\"\n\nlemma %quote add_mult_distrib:\n fixes n m q :: nat\n shows \"(n + m) \\ q = n \\ q + m \\ q\"\n by (induct n) simp_all\n\ninstance %quote proof\n fix m n q :: nat\n show \"m \\ n \\ q = m \\ (n \\ q)\"\n by (induct m) (simp_all add: add_mult_distrib)\n show \"\\ \\ n = n\"\n by (simp add: neutral_nat_def)\n show \"m \\ \\ = m\"\n by (induct m) (simp_all add: neutral_nat_def)\nqed\n\nend %quote\n\ntext \\\n \\noindent We define the natural operation of the natural numbers\n on monoids:\n\\\n\nprimrec %quote (in monoid) pow :: \"nat \\ 'a \\ 'a\" where\n \"pow 0 a = \\\"\n | \"pow (Suc n) a = a \\ pow n a\"\n\ntext \\\n \\noindent This we use to define the discrete exponentiation\n function:\n\\\n\ndefinition %quote bexp :: \"nat \\ nat\" where\n \"bexp n = pow n (Suc (Suc 0))\"\n\ntext \\\n \\noindent The corresponding code in Haskell uses that language's\n native classes:\n\\\n\ntext %quote \\\n @{code_stmts bexp (Haskell)}\n\\\n\ntext \\\n \\noindent This is a convenient place to show how explicit dictionary\n construction manifests in generated code -- the same example in\n \\SML\\:\n\\\n\ntext %quote \\\n @{code_stmts bexp (SML)}\n\\\n\ntext \\\n \\noindent Note the parameters with trailing underscore (\\<^verbatim>\\A_\\), which are the dictionary parameters.\n\\\n\n\nsubsection \\How to continue from here\\\n\ntext \\\n What you have seen so far should be already enough in a lot of\n cases. If you are content with this, you can quit reading here.\n\n Anyway, to understand situations where problems occur or to increase\n the scope of code generation beyond default, it is necessary to gain\n some understanding how the code generator actually works:\n\n \\begin{itemize}\n\n \\item The foundations of the code generator are described in\n \\secref{sec:foundations}.\n\n \\item In particular \\secref{sec:utterly_wrong} gives hints how to\n debug situations where code generation does not succeed as\n expected.\n\n \\item The scope and quality of generated code can be increased\n dramatically by applying refinement techniques, which are\n introduced in \\secref{sec:refinement}.\n\n \\item Inductive predicates can be turned executable using an\n extension of the code generator \\secref{sec:inductive}.\n\n \\item If you want to utilize code generation to obtain fast\n evaluators e.g.~for decision procedures, have a look at\n \\secref{sec:evaluation}.\n\n \\item You may want to skim over the more technical sections\n \\secref{sec:adaptation} and \\secref{sec:further}.\n\n \\item The target language Scala @{cite \"scala-overview-tech-report\"}\n comes with some specialities discussed in \\secref{sec:scala}.\n\n \\item For exhaustive syntax diagrams etc. you should visit the\n Isabelle/Isar Reference Manual @{cite \"isabelle-isar-ref\"}.\n\n \\end{itemize}\n\n \\bigskip\n\n \\begin{center}\\fbox{\\fbox{\\begin{minipage}{8cm}\n\n \\begin{center}\\textit{Happy proving, happy hacking!}\\end{center}\n\n \\end{minipage}}}\\end{center}\n\\\n\nend\n\n", "meta": {"author": "m-fleury", "repo": "isabelle-emacs", "sha": "756c662195e138a1941d22d4dd7ff759cbf6b6b9", "save_path": "github-repos/isabelle/m-fleury-isabelle-emacs", "path": "github-repos/isabelle/m-fleury-isabelle-emacs/isabelle-emacs-756c662195e138a1941d22d4dd7ff759cbf6b6b9/src/Doc/Codegen/Introduction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.10521053670308636, "lm_q1q2_score": 0.050141200870178974}}