├── .gitignore ├── LICENSE ├── README.md ├── leanpkg.toml └── src ├── basic └── control.lean ├── example.lean └── tactic ├── autoname ├── autoname.lean └── default.lean └── gptf ├── backends └── openai.lean ├── basic.lean ├── default.lean ├── gptf.lean └── utils ├── default.lean ├── derive_has_to_format.lean └── util.lean /.gitignore: -------------------------------------------------------------------------------- 1 | *.olean 2 | /_target 3 | /leanpkg.path 4 | **/*~ 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # lean-gptf 2 | 3 | This repository lets you use GPT-f to suggest tactics based on the goal state. The current model is trained on 80% of the tactic proofs in `mathlib` (commit `33483a3de6d91066e0fb9efd6aa4c0275d7ac44c`). 4 | 5 | # Setup 6 | 7 | ```bash 8 | # download pre-built binaries and build the project 9 | leanpkg configure && leanpkg build 10 | ``` 11 | 12 | After Lean is finished compiling, try commenting out the proofs in `src/example.lean` and calling `gptf` inside the `begin ... end` blocks. Make sure your API key is set up (see below). For example, 13 | 14 | ```lean 15 | example {α} (a : α) : a = a := 16 | begin 17 | gptf, 18 | end 19 | ``` 20 | 21 | should succeed with a message like this: 22 | 23 | ```lean 24 | Successes: 25 | ---------- 26 | Try this: refl 27 | 28 | All predictions: 29 | ---------------- 30 | Try this: refl 31 | ``` 32 | 33 | # Importing `lean-gptf` as a dependency for your own project 34 | 35 | ``` 36 | leanpkg add jesse-michael-han/lean-gptf 37 | 38 | leanpkg configure 39 | 40 | leanproject get-mathlib-cache 41 | 42 | leanpkg build 43 | ``` 44 | 45 | then remember to `import tactic.gptf` at the top. 46 | 47 | # Accessing the OpenAI API 48 | 49 | GPT-f is a generative language model trained by OpenAI. It is available over the OpenAI API using an API key. It receives a formatted tactic state as a prompt and will emit a list of tactics to try. The `gptf` tactic will try these tactics and return the ones that succeed as `Try this: ...` suggestions. 50 | 51 | To get an API key, apply to join the beta here: https://bit.ly/3nNWMyB 52 | 53 | Once you have recieved an API key, either add it as an OS environment variable called `OPENAI_API_KEY` 54 | 55 | ``` 56 | # ~/.zshenv, /etc/environment, etc. 57 | export OPENAI_API_KEY= # you may have to log out and back in to get this to work 58 | ``` 59 | 60 | __or__ you can paste the key directly in to the Lean document: 61 | 62 | ``` 63 | -- located in ./src/tactic/gptf/gptf.lean 64 | 65 | /- set to `some $KEY` if you don't want to mess with environment variables 66 | WARNING: do _not_ leave your key in committed source code -/ 67 | private meta def OPENAI_API_KEY : option string := none 68 | ``` 69 | 70 | # Usage 71 | 72 | ``` 73 | import tactic.gptf 74 | 75 | lemma my_lemma {α} (a : α) : a = a := 76 | begin 77 | gptf {n := 32, temp := 1.0} -- this will query the server and return a set of 'try this' commands. 78 | end 79 | 80 | ``` 81 | 82 | ## Options 83 | 84 | - `temperature`: Controls the randomness of the predictions; defaults to 1.0. Decrease to make the model's predictions more deterministic. 85 | - `n`: Number of predictions to try at once. 86 | 87 | ## Considerations 88 | 89 | The `gptf` tactic will query a model via the OpenAI API using `curl`. This query will be re-executed every time Lean compiles the tactic, and will count towards your API key rate limit. Thus, to avoid hitting the rate-limit and being throttled, please: 90 | - try not to have more than one uncommented `gptf` in a live Lean file at a time 91 | - replace calls to `gptf` by successful predictions whenever possible 92 | 93 | Also remember that even if the system doesn't progress the goal, you may be able to see clues of how to progress by looking at the suggestions which fail given in the 'Predictions' list. Currently, the model tends to predict long chains of rewrites; often, the first few rewrites in the chain will succeed. 94 | -------------------------------------------------------------------------------- /leanpkg.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lean-gptf" 3 | version = "0.1" 4 | lean_version = "leanprover-community/lean:3.33.0" 5 | path = "src" 6 | 7 | [dependencies] 8 | mathlib = {git = "https://github.com/leanprover-community/mathlib", rev = "2fd713a76e15eebdcdfd2f94472584b3f5f2bfc7"} 9 | -------------------------------------------------------------------------------- /src/basic/control.lean: -------------------------------------------------------------------------------- 1 | /- Author: E.W.Ayers © 2019. 2 | 3 | Some helpers for dealing with monads etc. 4 | -/ 5 | import control.monad.writer control.fold 6 | 7 | universes u v 8 | 9 | section 10 | /- Having a writer with append is really useful! -/ 11 | def writer_m (ω : Type) (α : Type) := ω × α 12 | variables {ω : Type} [has_append ω] [has_emptyc ω] {α : Type} 13 | instance writer_m.is_monad : monad (writer_m ω) := 14 | { pure := λ α a, (∅, a) 15 | , bind := λ α β ⟨w,a⟩ f, let ⟨w₂,b⟩ := f a in ⟨w ++ w₂, b⟩ 16 | } 17 | def writer_m.tell : ω → writer_m ω unit 18 | | x := (x, ()) 19 | def writer_m.run : writer_m ω α → ω × α := id 20 | end 21 | 22 | namespace writer_t 23 | 24 | variables {ω : Type u} {m : Type u → Type v} [monad m] {α β : Type u} [has_emptyc ω] [has_append ω] 25 | 26 | instance monad_of_append : monad (writer_t ω m) := 27 | @writer_t.monad ω m _ ⟨∅⟩ ⟨(++)⟩ 28 | 29 | instance lift_of_empty : has_monad_lift m (writer_t ω m) := 30 | ⟨λ α, @writer_t.lift _ _ _ _ ⟨∅⟩⟩ 31 | 32 | end writer_t 33 | 34 | def list_writer_t (σ : Type u) := writer_t (free_monoid σ) 35 | 36 | namespace list_writer_t 37 | local attribute [reducible] list_writer_t free_monoid 38 | variables {σ : Type u} {m : Type u → Type v} [monad m] 39 | instance : monad (list_writer_t σ m) := by apply_instance 40 | instance : monad_writer (list σ) (list_writer_t σ m) := by apply_instance 41 | 42 | end list_writer_t 43 | 44 | namespace alternative 45 | 46 | section 47 | variables {T S : Type u → Type u} [applicative T] [alternative S] 48 | instance : alternative (T ∘ S) := 49 | { pure := λ α x, (pure (pure x) : T (S _)), 50 | failure := λ x, (pure $ failure : T (S _)), 51 | seq := λ α β f x, show T(S β), from pure (<*>) <*> f <*> x, 52 | orelse := λ α a b, show T(S α), from pure (<|>) <*> a <*> b 53 | } 54 | end 55 | 56 | variables {T : Type u → Type v} [alternative T] {α β : Type u} 57 | 58 | def returnopt : option α → T α 59 | | none := failure 60 | | (some x) := pure x 61 | 62 | def optreturn : T α → T (option α) 63 | | t := (some <$> t) <|> (pure none) 64 | 65 | def is_ok {T : Type → Type v} [alternative T] {α : Type}: T α → T (bool) 66 | | t := (t *> pure (tt)) <|> pure (ff) 67 | 68 | def mguard {T : Type → Type v} [alternative T] [monad T]: T bool → T unit 69 | | c := do b ← c, if b then pure () else failure 70 | 71 | variables [monad T] 72 | 73 | meta def repeat (t : T α) : T (list α) := 74 | (pure list.cons <*> t <*> (pure punit.star >>= λ _, repeat)) <|> pure [] 75 | 76 | end alternative 77 | 78 | def except.flip {ε : Type u} {α : Type v} : except ε α → except α ε 79 | | e := except.rec except.ok except.error e 80 | 81 | instance monad_except.of_statet {ε σ} {m : Type → Type} [monad m] [monad_except ε m] : monad_except ε (state_t σ m) := 82 | { throw := λ α e, state_t.lift $ throw e 83 | , catch := λ α S e, ⟨λ s, catch (state_t.run S s) (λ x, state_t.run (e x) s)⟩ -- [note] alternatively, you could propagate the state. 84 | } 85 | 86 | instance monad_except.alt {ε} [inhabited ε] {m : Type → Type} [monad m] [monad_except ε m] : alternative m := 87 | { failure := λ α,throw $ inhabited.default ε 88 | , orelse := λ α x y, monad_except.orelse x y 89 | } 90 | 91 | def monad_state.hypothetically {m : Type → Type} [monad m] {σ α : Type} [monad_state σ m] : m α → m α 92 | | m := do s ← get, a ← m, put s, pure a 93 | 94 | notation `⍐` := monad_lift 95 | 96 | 97 | namespace interaction_monad 98 | 99 | namespace result 100 | 101 | variables {σ α β : Type} 102 | 103 | protected meta def map (f : α → β) : interaction_monad.result σ α → interaction_monad.result σ β 104 | | (success b s) := success (f b) s 105 | | (exception m p s) := exception m p s 106 | 107 | meta def map_state {τ : Type} (f : σ → τ) : result σ α → result τ α 108 | | (success a s) := success a (f s) 109 | | (exception m p s) := exception m p (f s) 110 | 111 | meta def state : result σ α → σ 112 | | (success b s) := s 113 | | (exception m p s) := s 114 | 115 | meta def get : result σ α → option α 116 | | (success b _) := some b 117 | | (exception _ _ _) := none 118 | 119 | meta def as_success : result σ α → option (α × σ) 120 | | (success b s) := some (b,s) 121 | | _ := none 122 | 123 | meta def as_exception : result σ α → option (option (unit → format) × option pos × σ) 124 | | (success b s) := none 125 | | (exception m p s) := (m,p,s) 126 | 127 | meta def as_except : result σ α → except (option (unit → format) × option pos) α 128 | | (success b s) := except.ok b 129 | | (exception m p s) := except.error $ (m, p) 130 | 131 | meta instance {σ} : functor (result σ) := {map := @result.map σ} 132 | 133 | end result 134 | 135 | meta instance {σ} : monad_state σ (interaction_monad σ) := 136 | {lift := λ α s x, let ⟨a,x⟩ := s.run x in result.success a x } 137 | 138 | meta instance {σ} : alternative (interaction_monad σ) := 139 | { failure := @interaction_monad.failed _, 140 | orelse := @interaction_monad_orelse _ } 141 | 142 | meta def lift_of_lens {τ σ} (get : τ → σ) (put : σ → τ → τ) 143 | : Π {α}, (interaction_monad σ α) → (interaction_monad τ α) 144 | | α s t := result.map_state (function.swap put $ t) $ s $ get t 145 | 146 | meta def has_monad_lift_of_lens {τ σ} (get : τ → σ) (put : σ → τ → τ) 147 | : has_monad_lift (interaction_monad σ) (interaction_monad τ) := 148 | ⟨λ α, lift_of_lens get put⟩ 149 | 150 | /-- Perform the given tactic but then just keep the result and throw away the state. -/ 151 | meta def hypothetically {σ α} : interaction_monad σ α → interaction_monad σ α 152 | | t s := result.map_state (λ _, s) $ t s 153 | 154 | meta def get_state_after {σ α}: interaction_monad σ α → interaction_monad σ σ 155 | | t s := let s := result.state $ t s in result.success s s 156 | 157 | meta def return_except {ε σ α} [has_to_format ε] : except ε α → interaction_monad σ α 158 | | (except.ok a) := pure a 159 | | (except.error e) := interaction_monad.fail e 160 | 161 | meta def run_simple {σ α}: interaction_monad σ α → σ → option (α × σ) 162 | | m s := result.as_success $ m s 163 | 164 | /-- If the given tactic fails, trace the failure message. -/ 165 | meta def trace_fail {σ α} (tr : format → interaction_monad σ unit) (t : interaction_monad σ α) : (interaction_monad σ α) 166 | | s := 167 | match t s with 168 | |(interaction_monad.result.exception msg pos _) := 169 | let msg := ("Exception: ":format) ++ (option.rec_on msg (to_fmt "silent") ($ ())) in 170 | ((tr msg) >> t) s 171 | |r := r 172 | end 173 | 174 | -- meta def lift_state_except {σ} : Π {α}, interaction_monad σ α → state_t σ (except_t (option (unit → format) × option pos) id) α 175 | -- | m := do 176 | -- s ← get, 177 | -- match m s with 178 | -- | (success b s) := put s *> pure b 179 | -- | (exception m p s) := put s *> throw (m,p) 180 | -- end 181 | 182 | end interaction_monad 183 | -------------------------------------------------------------------------------- /src/example.lean: -------------------------------------------------------------------------------- 1 | import tactic.gptf 2 | import data.list.sigma 3 | 4 | section gptf 5 | 6 | example {α} (a : α) : a = a := 7 | begin 8 | refl 9 | end 10 | 11 | example : ∃ n : ℕ, 8 = 2*n := 12 | begin 13 | exact ⟨4, rfl⟩ 14 | end 15 | 16 | example {P Q R : Prop} : P → (P → R) → R := 17 | begin 18 | intro h1, exact λ h2, h2 h1 19 | end 20 | 21 | example {p q r : Prop} (h₁ : p) (h₂ : q) : (p ∧ q) ∨ r := 22 | begin 23 | exact or.inl ⟨h₁, h₂⟩ 24 | end 25 | 26 | example {P Q : Prop} : (¬ P) ∧ (¬ Q) → ¬ (P ∨ Q) := 27 | begin 28 | exact not_or_distrib.mpr -- `gptf {pfx := "exact"}` 29 | end 30 | 31 | example {P Q R : Prop} : (P ∧ Q) → ((P → R) → ¬ (Q → ¬ R)) := 32 | begin 33 | rintros ⟨h₁, h₂⟩ h₃, try {exact λ h, h₁ _ h}, rw [imp_not_comm], 34 | apply not_imp_not.mpr (λ con, _), exact id, apply con, apply h₃, 35 | apply h₁, exact h₂ 36 | end 37 | 38 | example (n : ℕ) (m : ℕ) : nat.succ n < nat.succ n + 1 := 39 | begin 40 | {[smt] eblast_using [nat.add_one], exact nat.lt_succ_self _} 41 | end 42 | 43 | example : ∀ (F1 F2 F3 : Prop), ((¬F1 ∧ F3) ∨ (F2 ∧ ¬F3)) → (F2 → F1) → (F2 → F3) → ¬F2 := 44 | begin 45 | intros P Q R H₁ H₂ H₃ H₄, 46 | apply H₁.elim, -- `gptf {pfx := "apply"}` 47 | { assume h, simp * at * }, -- `gptf` 48 | cc -- `gptf` 49 | end 50 | 51 | example : ∀ (f : nat → Prop), f 2 → ∃ x, f x := 52 | begin 53 | exact λ f hf, ⟨_, hf⟩ -- by `gptf {pfx := "exact"}` :D 54 | end 55 | 56 | example {G : Type} [group G] (x y z : G) : (x * z) * (z⁻¹ * y) = x * y := 57 | begin 58 | simp [mul_assoc] 59 | end 60 | universes u v 61 | 62 | example {α : Type u} {β : α → Type v} [_inst_1 : decidable_eq α] {a : α} {l₁ l₂ : list (sigma β)} : 63 | (list.kerase a l₁).kunion (list.kerase a l₂) = list.kerase a (l₁.kunion l₂) := 64 | begin 65 | induction l₁ generalizing l₂, case list.nil { refl }, simp 66 | end 67 | 68 | end gptf 69 | -------------------------------------------------------------------------------- /src/tactic/autoname/autoname.lean: -------------------------------------------------------------------------------- 1 | import tactic.gptf.basic 2 | import tactic.gptf.backends.openai 3 | import tactic.gptf.utils.util 4 | import tactic.gptf.gptf 5 | import tactic.finish 6 | 7 | open openai 8 | 9 | namespace tactic 10 | 11 | meta def autoname_core (e : expr) (cfg : interactive.GPTSuggestConfig := {}) : tactic (list name) := do { 12 | let cfg := {prompt_token := "PREDICTNAME", ..cfg}, 13 | let req := { 14 | n := cfg.n, 15 | temperature := cfg.temp, 16 | prompt_token := cfg.prompt_token, 17 | prompt_prefix := cfg.pfx, 18 | replace_prefix := cfg.postprocess, 19 | .. default_partial_req 20 | }, 21 | api_key ← get_openai_api_key, 22 | completion_request ← (autoname_serialize_ts_core e req), 23 | response_msg ← tactic.unsafe_run_io $ (openai_api cfg.engine_id api_key).query completion_request, 24 | responses ← list.map prod.fst <$> 25 | ((list.qsort (λ x y : string × native.float, prod.snd x > prod.snd y) <$> 26 | unwrap_lm_response_logprobs "" none "autonamer" response_msg) >>= list.dedup'), 27 | eval_trace format! "[autoname_core] RESPONSES: {responses}", 28 | list.filter_map id <$> 29 | responses.mmap (λ x, (optional $ lean.parser.run $ prod.fst <$> 30 | lean.parser.with_input lean.parser.ident x)) 31 | } 32 | 33 | namespace interactive 34 | 35 | meta def autoname (cfg : GPTSuggestConfig := {n := 12, temp := 1.0}) : tactic unit := do { 36 | ts ← tactic.read, 37 | e ← ts.fully_qualified >>= λ x, do { 38 | tactic.write x, 39 | extract_fully_bound_goal 40 | }, 41 | tactic.pp e >>= λ e, tactic.trace format! "[autoname] Suggested names for goal\n------\n{e}\n------\n", 42 | tactic.write ts, 43 | nms ← autoname_core e cfg, 44 | nms.mmap' $ λ nm, 45 | tactic.trythis nm.to_string 46 | } 47 | 48 | end interactive 49 | end tactic 50 | -------------------------------------------------------------------------------- /src/tactic/autoname/default.lean: -------------------------------------------------------------------------------- 1 | import tactic.autoname.autoname 2 | -------------------------------------------------------------------------------- /src/tactic/gptf/backends/openai.lean: -------------------------------------------------------------------------------- 1 | import tactic 2 | import tactic.gptf.utils 3 | import tactic.gptf.basic 4 | 5 | namespace openai 6 | 7 | section openai_api 8 | 9 | meta structure CompletionRequest : Type := 10 | (prompt : string) 11 | (max_tokens : int := 16) 12 | (temperature : native.float := 1.0) 13 | (top_p : native.float := 1) 14 | (n : int := 1) 15 | (best_of : option int := none) 16 | (stream : option bool := none) 17 | (logprobs : int := 0) 18 | (echo : option bool := none) 19 | (stop : option string := none) -- TODO(jesse): list string 20 | (presence_penalty : option native.float := none) 21 | (frequency_penalty : option native.float := none) 22 | (show_trace : bool := ff) 23 | (prompt_token := "PROOFSTEP") 24 | (prompt_prefix := "") 25 | (replace_prefix : option (string → string) := none) 26 | 27 | meta def CompletionRequest.to_tactic_json : CompletionRequest → tactic json := 28 | let validate_max_tokens : int → bool := λ n, n ≤ 2048 in 29 | let validate_float_frac : native.float → bool := λ k, 0 ≤ k ∧ k ≤ 1 in 30 | let validate_and_return {α} [has_to_format α] (pred : α → bool) : α → tactic α := 31 | λ a, ((guard $ pred a) *> pure a <|> by {tactic.unfreeze_local_instances, exact (tactic.fail format!"[openai.CompletionRequest.to_tactic_json] VALIDATION FAILED FOR {a}")}) in 32 | let validate_optional_and_return {α} [has_to_format α] (pred : α → bool) : option α → tactic (option α) := λ x, do { 33 | match x with 34 | | (some val) := some <$> by {tactic.unfreeze_local_instances, exact (validate_and_return pred val)} 35 | | none := pure none 36 | end 37 | } in 38 | let MAX_N : int := 128 in 39 | λ req, match req with 40 | | ⟨prompt, max_tokens, temperature, top_p, n, best_of, 41 | stream, logprobs, echo, stop, presence_penalty, frequency_penalty, _, prompt_token, prompt_prefix, replace_prefix⟩ := do 42 | -- TODO(jesse): ensure validation does not fail silently 43 | max_tokens ← validate_and_return validate_max_tokens max_tokens, 44 | -- temperature ← validate_and_return validate_float_frac temperature, 45 | top_p ← validate_and_return validate_float_frac top_p, 46 | n ← validate_and_return (λ x, 0 ≤ x ∧ x ≤ MAX_N) /- go wild with the candidates -/ n, 47 | best_of ← validate_optional_and_return (λ x, n ≤ x ∧ x ≤ MAX_N) best_of, 48 | presence_penalty ← validate_optional_and_return validate_float_frac presence_penalty, 49 | frequency_penalty ← validate_optional_and_return validate_float_frac frequency_penalty, 50 | 51 | eval_trace $ "[openai.CompletionRequest.to_tactic_json] VALIDATION PASSED", 52 | 53 | let pre_kvs : list (string × option json) := [ 54 | ("prompt", json.of_string prompt), 55 | ("max_tokens", json.of_int max_tokens), 56 | ("temperature", json.of_float temperature), 57 | ("top_p", json.of_float top_p), 58 | ("n", json.of_int n), 59 | ("best_of", json.of_int <$> best_of), 60 | ("stream", json.of_bool <$> stream), 61 | ("logprobs", some $ json.of_int logprobs), 62 | ("echo", json.of_bool <$> echo), 63 | ("stop", json.of_string <$> stop), 64 | ("presence_penalty", json.of_float <$> presence_penalty), 65 | ("frequency_penalty", json.of_float <$> frequency_penalty) 66 | ], 67 | 68 | pure $ json.object $ pre_kvs.filter_map (λ ⟨k,mv⟩, prod.mk k <$> mv) 69 | end 70 | 71 | meta def CompletionRequest.to_cmd (engine_id : string) (api_key : string) : CompletionRequest → io (io.process.spawn_args) 72 | | req@⟨prompt, max_tokens, temperature, top_p, n, best_of, 73 | stream, logprobs, echo, stop, presence_penalty, frequency_penalty, _, prompt_token, prompt_prefix, replace_prefix⟩ := do 74 | when (tactic.is_trace_enabled_for `gptf) $ io.put_str_ln' format!"[openai.CompletionRequest.to_cmd] ENTERING", 75 | serialized_req ← io.run_tactic' $ req.to_tactic_json, 76 | when (tactic.is_trace_enabled_for `gptf) $ io.put_str_ln' format!"[openai.CompletionRequest.to_cmd] SERIALIZED", 77 | win ← io.run_tactic is_windows, 78 | pure { 79 | cmd := "curl", 80 | args := [ 81 | "--silent" 82 | , " -N" 83 | , "-u" 84 | , format.to_string $ format!":{api_key}" 85 | , "-X" 86 | , "POST" 87 | , format.to_string format!"https://api.openai.com/v1/engines/{engine_id}/completions" 88 | , "-H", "OpenAI-Organization: org-kuQ09yewcuHU5GN5YYEUp2hh" 89 | , "-H", "Content-Type: application/json" 90 | , "-d" 91 | , let jr := json.unparse serialized_req in if win then 92 | "\\\"".intercalate (jr.split (= '\"')) 93 | else 94 | jr 95 | ] 96 | } 97 | 98 | meta def mk_binding' (ctor : name → binder_info → expr → expr → expr) (e : expr) : Π (l : expr), tactic expr 99 | | h@(expr.local_const n pp_n bi ty) := do { 100 | ty ← tactic.infer_type h, 101 | pure $ ctor pp_n bi ty (e.abstract_local n) 102 | } 103 | | _ := pure $ e 104 | 105 | meta def extract_fully_bound_goal : tactic expr := do { 106 | locals ← list.reverse <$> tactic.local_context, 107 | locals_with_types ← locals.mmap (λ x, prod.mk x <$> tactic.infer_type x), 108 | g ← tactic.target, 109 | locals.iterM g $ λ acc h, do { 110 | mk_binding' expr.pi acc h 111 | } 112 | } 113 | 114 | meta def autoname_serialize_ts_core (e : expr) (req : CompletionRequest) 115 | : tactic CompletionRequest := do { 116 | ts_str ← tactic.with_full_names $ do { 117 | format.to_string <$> format.flatten <$> tactic.pp e 118 | }, 119 | let prompt : string := 120 | "[LN] GOAL " ++ ts_str ++ (format!" {req.prompt_token} ").to_string ++ req.prompt_prefix, 121 | eval_trace format!"\n \n \n PROMPT: {prompt} \n \n \n ", 122 | pure { 123 | prompt := prompt, 124 | ..req} 125 | } 126 | 127 | meta def serialize_ts 128 | (req : CompletionRequest) 129 | : tactic_state → tactic CompletionRequest := λ ts, do { 130 | ts_str ← ts.fully_qualified >>= postprocess_tactic_state, 131 | let prompt : string := 132 | "[LN] GOAL " ++ ts_str ++ (format!" {req.prompt_token} ").to_string ++ req.prompt_prefix, 133 | eval_trace format!"\n \n \n PROMPT: {prompt} \n \n \n ", 134 | pure { 135 | prompt := prompt, 136 | ..req} 137 | } 138 | 139 | setup_tactic_parser 140 | 141 | private meta def decode_response_msg : json → io (json × json) := λ response_msg, do { 142 | (json.array choices) ← option.to_monad $ response_msg.lookup "choices" | io.fail' format!"can't find choices in {response_msg}", 143 | prod.mk <$> (json.array <$> choices.mmap (λ choice, option.to_monad $ json.lookup choice "text")) <*> do { 144 | logprobss ← choices.mmap (λ msg, option.to_monad $ msg.lookup "logprobs"), 145 | scoress ← logprobss.mmap (λ logprobs, option.to_monad $ logprobs.lookup "token_logprobs"), 146 | result ← json.array <$> scoress.mmap (option.to_monad ∘ json_float_array_sum), 147 | pure result 148 | } 149 | } 150 | 151 | meta def openai_api (engine_id : string) (api_key : string) : ModelAPI CompletionRequest := 152 | let fn : CompletionRequest → io json := λ req, do { 153 | proc_cmds ← req.to_cmd engine_id api_key, 154 | response_raw ← io.cmd proc_cmds, 155 | when req.show_trace $ io.put_str_ln' format!"[openai_api] RAW RESPONSE: {response_raw}", 156 | 157 | response_msg ← (option.to_monad $ json.parse response_raw) | io.fail' format!"[openai_api] JSON PARSE FAILED {response_raw}", 158 | 159 | when req.show_trace $ io.put_str_ln' format!"GOT RESPONSE_MSG", 160 | 161 | do { 162 | predictions ← decode_response_msg response_msg | io.fail' format!"[openai_api] UNEXPECTED RESPONSE MSG: {response_msg}", 163 | when req.show_trace $ io.put_str_ln' format!"PREDICTIONS: {predictions}", 164 | pure (json.array [predictions.fst, predictions.snd]) 165 | } <|> pure (json.array $ [json.of_string $ format.to_string $ format!"ERROR {response_msg}"]) -- catch API errors here 166 | } in ⟨fn⟩ 167 | 168 | end openai_api 169 | 170 | section openai_proof_search 171 | 172 | meta def read_first_line : string → io string := λ path, do 173 | buffer.to_string <$> (io.mk_file_handle path io.mode.read >>= io.fs.get_line) 174 | 175 | meta def default_partial_req : openai.CompletionRequest := 176 | { 177 | prompt := "", 178 | max_tokens := 128, 179 | temperature := (0.7 : native.float), 180 | top_p := 1, 181 | n := 1, 182 | best_of := none, 183 | stream := none, 184 | logprobs := 0, 185 | echo := none, 186 | stop := none, -- TODO(jesse): list string, 187 | presence_penalty := none, 188 | frequency_penalty := none, 189 | show_trace := (tactic.is_trace_enabled_for `gptf) 190 | } 191 | 192 | meta def proof_search_step 193 | {input_format} 194 | (api : ModelAPI input_format) 195 | (serialize_ts : tactic_state → tactic input_format) 196 | (decode_response : json → tactic (list (tactic_result unit × string × native.float) × list string)) 197 | : tactic (list string × list string) := do { 198 | serialized_ts ← tactic.read >>= serialize_ts, 199 | response_msg ← tactic.unsafe_run_io $ api.query serialized_ts, 200 | ⟨successes, candidates⟩ ← decode_response response_msg, 201 | pure $ flip prod.mk candidates $ successes.map (prod.fst ∘ prod.snd) 202 | } 203 | 204 | meta def gptf_proof_search_step (engine_id : string) (api_key : string) (req : CompletionRequest) : tactic (list string × list string) := do { 205 | proof_search_step 206 | (openai_api 207 | engine_id api_key) 208 | (serialize_ts req) (run_all_beam_candidates $ unwrap_lm_response_logprobs req.prompt_prefix req.replace_prefix "[gptf_proof_search_step]") 209 | } 210 | 211 | end openai_proof_search 212 | 213 | end openai 214 | -------------------------------------------------------------------------------- /src/tactic/gptf/basic.lean: -------------------------------------------------------------------------------- 1 | /- 2 | Copyright (c) 2021 Jesse Michael Han. All rights reserved. 3 | Released under Apache 2.0 license as described in the file LICENSE. 4 | Author(s): Jesse Michael Han, Ed Ayers 5 | 6 | Core logic of the `gptf` tactic 7 | -/ 8 | 9 | import system.io 10 | import tactic 11 | import tactic.gptf.utils.util 12 | import basic.control 13 | 14 | meta structure ModelAPI (input_format : Type := json) : Type := 15 | (query : input_format → io json) 16 | 17 | /- for testing -/ 18 | meta def dummy_api {α} : ModelAPI α := 19 | ⟨λ _, pure $ json.of_string "[DummyAPI] FAILURE"⟩ 20 | 21 | 22 | meta structure BFSNode : Type := 23 | (state : tactic_state) 24 | (score : ℤ := 0) 25 | (tactics : list string := []) 26 | (depth : ℕ := 0) 27 | 28 | meta def BFSNode.to_json : BFSNode → json 29 | | ⟨state, score, tacs, depth⟩ := 30 | json.object $ 31 | [ 32 | ("state", json.of_string $ (format.to_string ∘ has_to_format.to_format) state) 33 | , ("score", json.of_int score) 34 | , ("tactics", json.array $ json.of_string <$> tacs) 35 | , ("depth", json.of_int depth) 36 | ] 37 | 38 | meta instance : has_to_tactic_json BFSNode := 39 | ⟨pure ∘ BFSNode.to_json⟩ 40 | 41 | meta instance : has_to_format BFSNode := 42 | ⟨has_to_format.to_format ∘ BFSNode.to_json⟩ 43 | 44 | namespace BFSNode 45 | 46 | meta def of_current_state (score : ℤ := 0) (tacs : list string := []) : tactic BFSNode := do { 47 | ts ← tactic.read, 48 | pure $ ⟨ts, score, tacs, 0⟩ 49 | } 50 | 51 | end BFSNode 52 | 53 | section run_all_beam_candidates 54 | 55 | meta def get_tac_and_capture_result (next_candidate : string) (timeout : ℕ := 5000) : tactic (tactic_result _) := do { 56 | tac ← do { 57 | env ← tactic.get_env, 58 | eval_trace format!"[get_tac_and_capture_result] PARSING TACTIC: {next_candidate}", 59 | tac ← parse_itactic next_candidate, 60 | eval_trace format!"[get_tac_and_capture_result] PARSE SUCCESSFUL", 61 | tactic.set_env env, 62 | pure tac 63 | }, 64 | eval_trace format!"[get_tac_and_capture_result] TRYING TACTIC: {next_candidate}", 65 | result ← tactic.capture' (tactic.try_for_time timeout $ tactic.try_for 200000 tac), -- if `tac` fails, exception is captured here 66 | eval_trace format!"[get_tac_and_capture_result] RESULT: {result}", 67 | pure result 68 | } 69 | 70 | /-- This takes a 'next_candidate' object and then if the tactic result is a success then it will 71 | update the candidate name to reflect the result it returned. -/ 72 | -- private meta def candidate_modify : (string) → tactic_result string → (tactic_result unit) × (string) := 73 | -- λ s r, ⟨r.map (λ _, ()), s <| r.get⟩ 74 | 75 | meta def try_get_tac_and_capture_result (tac_string : string) (timeout : ℕ := 5000) : tactic ((tactic_result unit) × string) := do { 76 | result_with_string ← get_tac_and_capture_result tac_string timeout <|> do { 77 | let msg : format := format!"[try_get_tac_and_capture_result] parse_itactic failed on {tac_string}", 78 | eval_trace msg, 79 | interaction_monad.mk_exception msg none <$> tactic.read 80 | }, 81 | 82 | let candidate_modify : string → tactic_result string → ((tactic_result unit) × string) := 83 | λ s r, ⟨r.map $ (λ _, ()), s <| r.get⟩, 84 | pure $ candidate_modify tac_string result_with_string 85 | } 86 | 87 | /- TODO(jesse): since this is now used only for the interactive frontend, 88 | replace the inner loop with a `run_async <$> ...` -/ 89 | meta def run_all_beam_candidates 90 | (get_candidates : json → tactic (list (string × native.float))) 91 | (msg : json) 92 | : tactic (list (tactic_result unit × string × native.float) × list string) := do { 93 | 94 | -- let try_candidate_state := (list (string × native.float) × (list $ option $ tactic_result unit × string × native.float)), 95 | -- let stop : option (tactic_result unit × string × native.float) → state_t try_candidate_state tactic bool := 96 | -- λ arg, match arg with 97 | -- | some ⟨result, candidate⟩ := do { 98 | -- state_t.lift result.is_done 99 | -- } 100 | -- | none := pure ff 101 | -- end, 102 | 103 | -- let try_candidate : state_t try_candidate_state tactic (option $ tactic_result unit × string × native.float) := do { 104 | -- state_t.lift $ eval_trace format!"[try_candidate] ENTERING", 105 | -- ts ← state_t.lift tactic.read, 106 | -- state_t.lift $ eval_trace format!"[try_candidate] READ TACTIC STATE", 107 | -- ⟨rest, _⟩ ← state_t.get, 108 | -- match rest with 109 | -- | [] := do { 110 | -- state_t.lift $ eval_trace format!"[try_candidate] END OF LOOP", 111 | -- pure $ some ⟨interaction_monad.fail "all candidates failed" ts, "FAILURE", 0.0⟩ 112 | -- } 113 | -- | (next_candidate::candidates) := do { 114 | -- state_t.modify (λ ⟨_, rs⟩, ⟨candidates, rs⟩), 115 | -- result ← monad_lift $ try_get_tac_and_capture_result next_candidate.fst, 116 | -- when (interaction_monad.result.is_success $ result) $ 117 | -- state_t.modify $ λ ⟨candidates, rs⟩, ⟨candidates, rs ++ [some $ ⟨result, next_candidate⟩]⟩, 118 | -- state_t.lift $ eval_trace format!"[try_candidate] CAPTURED RESULT: {result}", 119 | -- pure $ some ⟨result, next_candidate⟩ 120 | -- } 121 | -- end 122 | -- }, 123 | 124 | let find_successful_candidates 125 | (candidates : list (string × native.float)) 126 | : tactic (list (tactic_result unit × string × native.float)) := do { 127 | tasks ← candidates.mmap (λ arg, flip prod.mk arg <$> tactic.run_async (try_get_tac_and_capture_result arg.fst : tactic $ tactic_result unit × string)), 128 | tactic.using_new_ref ff $ λ flag, do 129 | tasks.iterM [] $ λ acc ⟨task, tac_string, score⟩, do { 130 | mcond (tactic.read_ref flag) (pure acc) $ do { 131 | let ⟨result, new_tac_string⟩ := task.get, 132 | if (interaction_monad.result.is_success result) then do { 133 | whenM (result.is_done) $ tactic.write_ref flag tt, 134 | pure $ acc ++ [⟨result, new_tac_string, score⟩] 135 | } else do { 136 | pure acc 137 | } 138 | } 139 | } 140 | }, 141 | 142 | -- this is responsible for gracefully handling "error" JSON messages and should return an empty list of candidates 143 | candidates ← list.filter (λ x, not $ "tidy".is_prefix_of $ prod.fst x) <$> (get_candidates msg >>= list.dedup'), 144 | 145 | eval_trace format!"[run_all_beam_candidates] CANDIDATES: {candidates}", 146 | 147 | -- successful_candidates ← (prod.snd <$> prod.snd <$> state_t.run (iterate_until try_candidate stop candidates.length $ pure none) ⟨candidates, []⟩), 148 | successful_candidates ← (list.map pure) <$> (get_candidates msg >>= list.dedup' >>= find_successful_candidates), 149 | 150 | eval_trace format!"[run_all_beam_candidates] EXITING TRY_CANDIDATE LOOP", 151 | eval_trace format!"[run_all_beam_candidates] SUCCESSFUL CANDIDATES: {successful_candidates}", 152 | pure ⟨successful_candidates.filter_map id, prod.fst <$> candidates⟩ 153 | } 154 | 155 | 156 | 157 | end run_all_beam_candidates 158 | -------------------------------------------------------------------------------- /src/tactic/gptf/default.lean: -------------------------------------------------------------------------------- 1 | import tactic.gptf.gptf 2 | -------------------------------------------------------------------------------- /src/tactic/gptf/gptf.lean: -------------------------------------------------------------------------------- 1 | import system.io 2 | import tactic 3 | import tactic.gptf.backends.openai 4 | 5 | /-! A tactic that will ring up GPT to ask for help solving a goal. 6 | Remember to set the `OPEN_AI_KEY` environment variable. 7 | Eg: 8 | ```sh 9 | # ~/.zshenv 10 | export OPEN_AI_KEY="" 11 | ``` 12 | you may need to relogin to update. 13 | 14 | `n` is the number of iterations for the greedy search. 15 | `temperature` is a float between 0 and 1, and controls how deterministic the predictions are. -/ 16 | 17 | /- set to `some $KEY` if you don't want to mess with environment variables 18 | WARNING: do _not_ leave your key in committed source code -/ 19 | private meta def OPENAI_API_KEY : option string := none 20 | 21 | meta def try_lookup_key (env : environment) : tactic string := 22 | ↑OPENAI_API_KEY 23 | 24 | meta def get_openai_api_key : tactic string := do { 25 | env ← tactic.get_env, 26 | (try_lookup_key env <|> (tactic.unsafe_run_io $ io.env.get "OPENAI_API_KEY") >>= option.to_monad) <|> 27 | tactic.fail "[get_openai_api_key] ERROR: can't find an OpenAI API key" 28 | } 29 | section gptf 30 | namespace tactic 31 | namespace interactive 32 | setup_tactic_parser 33 | 34 | open openai 35 | 36 | meta structure GPTSuggestConfig : Type := 37 | (n : ℕ := 32) 38 | (temp : native.float := 1.0) 39 | (silent := ff) 40 | (engine_id : string := "formal-lean-pact") 41 | (api_key : option string := none) 42 | (prompt_token := "PROOFSTEP") 43 | (pfx := "") 44 | (postprocess : option (string → string) := none) 45 | 46 | meta def gptf_core (cfg : GPTSuggestConfig := {}) : tactic (list string × list string) := do { 47 | tactic.success_if_fail done *> do { 48 | let req := { n := cfg.n, temperature := cfg.temp, prompt_token := cfg.prompt_token, prompt_prefix := cfg.pfx, replace_prefix := cfg.postprocess, .. default_partial_req }, 49 | api_key ← (cfg.api_key <|> get_openai_api_key), 50 | gptf_proof_search_step cfg.engine_id api_key req 51 | } 52 | } 53 | 54 | meta def gptf (cfg : GPTSuggestConfig := {}) : tactic unit := do { 55 | ⟨successes, predictions⟩ ← gptf_core cfg, 56 | if (successes.length > 0) then do { 57 | tactic.trace "\nSuccesses:\n----------", 58 | successes.mmap' tactic.trythis 59 | } else do { 60 | tactic.trace "no predictions succeeded" 61 | }, 62 | when (predictions.length > 0) $ 63 | tactic.trace "\nAll predictions: \n----------------" *> predictions.mmap' tactic.trythis 64 | } 65 | 66 | meta def neuro_eblast : tactic unit := 67 | gptf { pfx := "rw [", 68 | postprocess := λ x, "{[smt] eblast_using [" ++ (x) ++ "}" } 69 | 70 | end interactive 71 | end tactic 72 | 73 | end gptf 74 | -------------------------------------------------------------------------------- /src/tactic/gptf/utils/default.lean: -------------------------------------------------------------------------------- 1 | import tactic.gptf.utils.util 2 | -------------------------------------------------------------------------------- /src/tactic/gptf/utils/derive_has_to_format.lean: -------------------------------------------------------------------------------- 1 | /- 2 | Copyright (c) 2021 Jesse Michael Han. All rights reserved. 3 | Released under Apache 2.0 license as described in the file LICENSE. 4 | Author(s): Jesse Michael Han 5 | 6 | derive has_to_format 7 | -/ 8 | 9 | import tactic 10 | 11 | meta def expr.join (tp : expr) : list expr → tactic expr := λ xs, 12 | xs.foldr (λ e₁ acc, do {acc ← acc, tactic.to_expr ``(@list.cons %%tp %%e₁ %%acc)}) (tactic.to_expr ``(list.nil)) 13 | 14 | meta def format.join_using : format → list format → format := λ x xs, 15 | format.join $ list.intercalate [x] (pure <$> xs) 16 | 17 | meta def format.apply_constructor : format → list format → format := λ f fs, 18 | match fs with 19 | | [] := f 20 | | fs := format.join_using " " [f, format.join ["(", format.join_using " " fs, ")"]] 21 | end 22 | 23 | open tactic 24 | namespace tactic 25 | namespace interactive 26 | 27 | meta def mk_to_format (type : name) : tactic unit := do { 28 | ls ← local_context, 29 | (x::_) ← tactic.intro_lst [`arg], 30 | et ← infer_type x, 31 | xs ← tactic.induction x, 32 | xs.mmap' $ λ ⟨c, args, _⟩, do 33 | (args', rec_call) ← args.mpartition $ λ e, do { 34 | e' ← tactic.to_expr ``(format), 35 | bnot <$> e'.occurs <$> tactic.infer_type e 36 | }, 37 | args'' ← args'.mmap (λ a, flip prod.mk a <$> (et.occurs <$> tactic.infer_type a)), 38 | let fn : list (bool × expr) → state_t (list expr) tactic (list expr) := λ args'', do { 39 | let pop : state_t (list expr) tactic (option expr) := do { 40 | xs ← get, 41 | match xs with 42 | | (a::as) := modify (λ _, as) *> pure (some a) 43 | | [] := pure none 44 | end 45 | }, 46 | args''.mmap (λ ⟨b, a⟩, if b then do (some x) ← pop, pure x else state_t.lift $ do 47 | a_tp ← infer_type a, 48 | _inst ← mk_app ``has_to_format [a_tp] >>= mk_instance, 49 | tactic.to_expr ``(@has_to_format.to_format _ (%%_inst) %%a)) 50 | }, 51 | args''' ← prod.fst <$> (fn args'').run rec_call, 52 | c ← tactic.resolve_constant c, 53 | nm_tp ← to_expr ``(name), 54 | nm_fmt ← mk_app ``has_to_format [nm_tp] >>= mk_instance, 55 | fs ← expr.join `(format) args''', 56 | result ← to_expr ``(format.apply_constructor (@has_to_format.to_format %%nm_tp %%nm_fmt %%c) %%fs), 57 | tactic.exact result 58 | } 59 | 60 | meta def derive_has_to_format (pre : option name) : tactic unit := do { 61 | vs ← local_context, 62 | `(has_to_format %%f) ← target, 63 | env ← get_env, 64 | let n := f.get_app_fn.const_name, 65 | d ← get_decl n, 66 | refine ``( { to_format := _ } ), 67 | tgt ← target, 68 | extract_def (with_prefix pre n <.> "to_format") ff $ mk_to_format n 69 | } 70 | 71 | meta def has_to_format_derive_handler' (nspace : option name := none) : derive_handler := 72 | higher_order_derive_handler ``has_to_format (derive_has_to_format nspace) [] nspace 73 | 74 | @[derive_handler] 75 | meta def has_to_format_derive_handler : derive_handler := 76 | guard_class ``has_to_format has_to_format_derive_handler' 77 | 78 | inductive my_nat : Type 79 | | zero : my_nat 80 | | succ : my_nat → my_nat 81 | 82 | attribute [derive [has_to_format]] my_nat -- whee 83 | 84 | end interactive 85 | end tactic 86 | 87 | section instances 88 | 89 | attribute [derive has_to_format] interactive.loc -- :D 90 | 91 | end instances 92 | -------------------------------------------------------------------------------- /src/tactic/gptf/utils/util.lean: -------------------------------------------------------------------------------- 1 | /- 2 | Copyright (c) 2021 Jesse Michael Han. All rights reserved. 3 | Released under Apache 2.0 license as described in the file LICENSE. 4 | Author(s): Jesse Michael Han, Ed Ayers 5 | 6 | Utils for `gptf`. 7 | -/ 8 | 9 | import system.io 10 | import tactic 11 | import tactic.gptf.utils.derive_has_to_format 12 | 13 | section string 14 | 15 | namespace string 16 | 17 | def replace_char : string → char → char → string 18 | | ⟨cs⟩ c₁ c₂ := ⟨cs.map (λ c, if c = c₁ then c₂ else c)⟩ 19 | 20 | end string 21 | 22 | end string 23 | 24 | namespace io 25 | 26 | meta def fail' {α} (fmt : format) : io α := io.fail $ format.to_string fmt 27 | 28 | meta def put_str_ln' : Π (fmt : format), io unit := io.put_str_ln ∘ format.to_string 29 | 30 | end io 31 | 32 | section io 33 | open interaction_monad interaction_monad.result 34 | namespace io 35 | 36 | /-- verion of io.run_tactic' which does not suppress the exception msg -/ 37 | meta def run_tactic' {α} (tac :tactic α) : io α := do { 38 | io.run_tactic $ do { 39 | result ← tactic.capture tac, 40 | match result with 41 | | (success val _) := pure val 42 | | (exception m_fmt pos _) := do { 43 | let fmt_msg := (m_fmt.get_or_else (λ _, format!"none")) (), 44 | let msg := format!"[io.run_tactic'] {pos}: tactic failed\n-------\n{fmt_msg}\n-------\n", 45 | tactic.trace msg, 46 | tactic.fail msg 47 | } 48 | end 49 | } 50 | } 51 | 52 | end io 53 | end io 54 | 55 | section tactic_state 56 | open interaction_monad.result 57 | setup_tactic_parser 58 | 59 | meta def num_goals' : tactic_state → option ℕ := 60 | λ ts, match tactic.num_goals ts with | (success val _) := pure val | _ := none end 61 | 62 | -- TODO(jesse): this is a hack. might be better to do this in python 63 | meta def consume_with_parser {α} (p : lean.parser α) : string → io string := λ inp, do { 64 | io.run_tactic' $ do 65 | prod.snd <$> lean.parser.run (with_input p inp) 66 | } 67 | 68 | -- TODO(jesse): performance 69 | meta def consume_spaces : string → string 70 | | arg@⟨[]⟩ := arg 71 | | arg@⟨(x::xs)⟩ := if x = ' ' then consume_spaces ⟨xs⟩ else arg 72 | 73 | -- WARNING: this is a hack 74 | meta def remove_indents_with_split (c : char := '\t'): string → string := λ str, 75 | let strs := str.split (= '\t') in 76 | string.intercalate (⟨['\t']⟩ : string) (consume_spaces <$> strs) 77 | 78 | meta def postprocess_tactic_state : tactic_state → tactic string := λ ts, do 79 | let main : tactic string := do { 80 | let ts_str := "\\\"".intercalate (ts.to_format.to_string.split (= '"')), 81 | tabbed_ts_str ← do { 82 | if (num_goals' ts).get_or_else 0 ≤ 1 83 | then pure $ ts_str.replace_char '\n' '\t' 84 | else tactic.unsafe_run_io $ (λ x, string.replace_char x '\n' '\t') 85 | <$> (consume_with_parser small_nat >=> 86 | consume_with_parser ident) ts_str}, 87 | pure $ remove_indents_with_split '\t' tabbed_ts_str 88 | }, 89 | main <|> (let msg := "[postprocess_tactic_state] WARNING: POSTPROCESSING FAILED" in 90 | tactic.trace msg *> tactic.fail msg) 91 | 92 | end tactic_state 93 | 94 | section json 95 | 96 | section has_to_json 97 | universe u 98 | 99 | meta class has_to_json (α : Type u) : Type (u+1) := 100 | (to_json : α → json) 101 | 102 | meta class has_to_tactic_json (α : Type u) : Type (u+1) := 103 | (to_tactic_json : α → tactic json) 104 | 105 | meta class has_from_json (α : Type u) : Type (u+1) := 106 | (from_json : json → tactic α) 107 | 108 | end has_to_json 109 | 110 | meta def list.lookup_prod {α β} : (list (α × β)) → (α → bool) → option β 111 | | [] _ := none 112 | | (⟨a,b⟩::xs) p := if p a then pure b else xs.lookup_prod p 113 | 114 | meta def json.get_string : json → option string 115 | | (json.of_string str) := pure str 116 | | _ := none 117 | 118 | meta def json.get_float : json → option native.float 119 | | (json.of_float str) := pure str 120 | | _ := none 121 | 122 | meta def json.lookup : json → string → option json 123 | | (json.object kvs) str := kvs.lookup_prod $ λ k, k = str 124 | | _ _ := none 125 | 126 | end json 127 | 128 | meta def json_float_array_sum : json → option json 129 | | (json.array xs) := json.of_float <$> xs.mfoldr (λ msg acc, match msg with 130 | | (json.of_float val) := pure $ acc + val 131 | | (json.of_int val) := pure $ acc + native.float.of_int val 132 | | exc := none 133 | end) (0.0 : native.float) 134 | | exc := none 135 | 136 | meta def unwrap_lm_response_logprobs (prompt_prefix : string) (replace_prefix : option $ string → string) (ident : option string) : json → tactic (list $ string × native.float) 137 | | (json.array $ [(json.array predictions), (json.array scores)]) := do { 138 | decoded_strings ← predictions.mmap $ option.to_monad ∘ json.get_string, 139 | let decoded_strings := (λ x, replace_prefix.get_or_else (λ x, prompt_prefix ++ x) x) <$> decoded_strings, 140 | decoded_scores ← scores.mmap $ option.to_monad ∘ json.get_float, 141 | pure $ list.zip decoded_strings decoded_scores 142 | } 143 | | exc := tactic.trace format!"{ident.get_or_else \"[unwrap_lm_response_logprobs.anonymous]\"} run_best_beam_candidate UNEXPECTED MESSAGE:\n---\n{exc}\n---\n" *> pure [] 144 | 145 | section json 146 | 147 | -- for debugging 148 | 149 | meta def json.compare : Π (x y : json), bool 150 | | (json.of_string s) (json.of_string s') := s = s' 151 | | (json.of_int k) (json.of_int k') := k = k' 152 | | (json.of_float x) (json.of_float x') := x = x' -- might have to make this tt 153 | | (json.of_bool b) (json.of_bool b') := b = b' 154 | | (json.null) (json.null) := tt 155 | | (json.object kvs) (json.object kvs') := (list.zip kvs kvs').foldr 156 | (λ ⟨⟨k₁, v₁⟩, ⟨k₂, v₂⟩⟩ acc, 157 | json.compare k₁ k₂ && json.compare v₁ v₂ && acc) tt 158 | | (json.array args) (json.array args') := (list.zip args args').foldr 159 | (λ ⟨j₁, j₂⟩ acc, acc && json.compare j₁ j₂) tt 160 | | _ _ := ff 161 | 162 | meta def json.to_raw_fmt : json → format 163 | | (json.of_string s) := format!"(json.of_string \"{s}\")" 164 | | (json.of_int k) := format!"(json.of_int {k})" 165 | | (json.of_float x) := format!"(json.of_float {x})" 166 | | (json.of_bool b) := format!"(json.of_bool {b})" 167 | | (json.null) := "(json.null)" 168 | | (json.object kvs) := let f : string × json → format := 169 | (λ ⟨k,v⟩, json.to_raw_fmt k ++ " : " ++ json.to_raw_fmt v) in 170 | format!"(json.object " ++ format.join_using " " (f <$> kvs) ++ ")" 171 | | (json.array args) := "(json.array " ++ format.join_using " " (json.to_raw_fmt <$> args) ++ ")" 172 | 173 | end json 174 | 175 | meta def tactic_state.is_done (state : tactic_state) : tactic bool := do { 176 | ts ← tactic.read, 177 | result ← do { 178 | tactic.write state, 179 | (tactic.done *> pure tt) <|> pure ff 180 | }, 181 | tactic.write ts, 182 | pure result 183 | } 184 | 185 | meta def tactic_result.is_done {α} (tr : tactic_result α) : tactic bool := do { 186 | match tr with 187 | | (interaction_monad.result.success val state) := state.is_done 188 | | (interaction_monad.result.exception _ _ _) := pure ff 189 | end 190 | } 191 | 192 | section interaction_monad 193 | 194 | meta def interaction_monad.result.is_success {σ α} : interaction_monad.result σ α → bool := λ x, 195 | match x with | (interaction_monad.result.success _ _) := tt | _ := ff end 196 | 197 | end interaction_monad 198 | 199 | section run_with_state' 200 | 201 | declare_trace gptf 202 | 203 | meta def set_show_eval_trace : bool → tactic unit := tactic.set_bool_option `evaltrace 204 | 205 | meta def eval_trace {α} [has_to_tactic_format α] : α → tactic unit | a := do { 206 | when (tactic.is_trace_enabled_for `gptf) (tactic.trace a) 207 | } 208 | 209 | namespace interaction_monad 210 | open interaction_monad.result 211 | meta def run_with_state' {σ₁ σ₂ : Type} {α : Type*} (state : σ₁) (tac : interaction_monad σ₁ α) : interaction_monad σ₂ α := 212 | λ s, match (tac state) with 213 | | (success val _) := success val s 214 | | (exception fn pos _) := exception fn pos s 215 | end 216 | end interaction_monad 217 | end run_with_state' 218 | 219 | section list -- WARNING: hack 220 | 221 | local notation `α` := string 222 | 223 | meta structure dedup_state' : Type := 224 | (seen : native.rb_map α native.float := native.mk_rb_map) 225 | (result : list (α) := []) 226 | 227 | local notation `m` := tactic 228 | meta def dedup_list_aux' : list (α × native.float) → state_t dedup_state' m unit 229 | | [] := pure () 230 | | (x::xs) := do { 231 | σ ← get, 232 | if (σ.seen.contains x.1) then (do 233 | (some old_score) ← (pure $ σ.seen.find x.1) | state_t.lift tactic.failed, 234 | let new_seen := if x.2 > old_score then (σ.seen.erase x.1).insert x.1 x.2 else σ.seen, 235 | modify $ λ σ, dedup_state'.mk new_seen (σ.result), 236 | dedup_list_aux' xs) 237 | else do 238 | modify $ λ σ, dedup_state'.mk (σ.seen.insert x.1 x.2) (σ.result ++ [x.1]), 239 | dedup_list_aux' xs 240 | } 241 | 242 | meta def list.dedup' : list (α × native.float) → m (list $ α × native.float) := λ xs, do 243 | σ ← prod.snd <$> state_t.run (dedup_list_aux' xs) {}, 244 | σ.result.mmap (λ x, do { prod.mk x <$> σ.seen.find x }) 245 | 246 | end list 247 | 248 | section iterate_until 249 | 250 | meta def iterate_until_aux 251 | {m} [monad m] [alternative m] {α} 252 | (tac : m α) (stop : α → m bool) (fuel_exhausted_callback : m α) 253 | : Π (fuel : ℕ), m α 254 | | 0 := do {result ← tac, mcond (stop result) (pure result) fuel_exhausted_callback} 255 | | (n+1) := do { result ← tac, mcond (stop result) (pure result) (iterate_until_aux n)} 256 | 257 | meta def iterate_until 258 | {m} [monad m] [alternative m] {α} 259 | (tac : m α) (stop : α → m bool) (fuel := 100000) 260 | (fuel_exhausted_callback : m α := alternative.failure) 261 | : m α 262 | := 263 | iterate_until_aux tac stop fuel_exhausted_callback fuel 264 | 265 | end iterate_until 266 | 267 | namespace tactic 268 | 269 | open interaction_monad.result 270 | meta def run (tac : tactic unit) : tactic (interaction_monad.result tactic_state unit) := do { 271 | σ ← get_state, 272 | match tac σ with 273 | | r@(success _ new_state) := interaction_monad.set_state new_state *> pure r 274 | | r@(exception fn pos new_state) := pure r 275 | end 276 | } 277 | 278 | meta instance has_to_format_tactic_result {α : Type*} [has_to_format α] : has_to_format (interaction_monad.result tactic_state α) := 279 | ⟨λ r, 280 | match r with 281 | | (success val new_state) := format!"SUCCESS!\nNEW_STATE: {new_state}\nVAL: {val}" 282 | | (exception fn pos old_state) := do { 283 | let msg := (fn.get_or_else (λ _, format.of_string "n/a")) (), 284 | format!"EXCEPTION!\nMSG: {msg}\nPOS: {pos}\nOLD_STATE: {old_state}" 285 | } 286 | end 287 | ⟩ 288 | 289 | meta instance has_to_tactic_format_tactic_result {α : Type*} [has_to_format α] : has_to_tactic_format (interaction_monad.result tactic_state α) := 290 | ⟨λ σ, pure $ has_to_format.to_format σ⟩ 291 | 292 | /-- Prints a 'Try this:' message. -/ 293 | meta def trythis : string → tactic unit 294 | | s := tactic.trace (sformat!"Try this: {s}") 295 | 296 | end tactic 297 | 298 | meta def serialize_list_string : list string → json := λ xs, 299 | json.array $ json.of_string <$> xs 300 | 301 | meta def score_of_float : native.float → int := 302 | λ x, native.float.floor ((1000.0 : native.float) * x) 303 | 304 | namespace tactic 305 | open interaction_monad interaction_monad.result 306 | 307 | /- capture but backtrack the state -/ 308 | meta def capture' {α} (t : tactic α) : tactic (tactic_result α) := 309 | λ s, match t s with 310 | | (success r s') := success (success r s') s 311 | | (exception f p s') := success (exception f p s') s 312 | end 313 | 314 | end tactic 315 | 316 | section parse_tac 317 | 318 | setup_tactic_parser 319 | 320 | open tactic 321 | 322 | /-- Run the given parser on the given string input. -/ 323 | meta def run_on_input {α} (p : lean.parser α) (s : string) : tactic α := 324 | lean.parser.run $ do 325 | get_state >>= λ ps, of_tactic $ do 326 | tactic.set_env ps.env, 327 | -- eval_trace format!"[parse_itactic_reflected] TRYING TO PARSE {itactic_string}", 328 | prod.fst <$> (@interaction_monad.run_with_state' parser_state _ _ ps $ with_input p s) 329 | 330 | section squeeze_rewrite -- credit: Ed Ayers 331 | open tactic.interactive 332 | open lean.parser 333 | 334 | -- attribute [derive has_to_format] loc 335 | 336 | meta def tk_ident (n : name) : lean.parser name := do 337 | m ← lean.parser.ident, 338 | if n = m then pure m else 339 | fail format!"expected ident {n} but got {m}" 340 | 341 | meta def parse_rw : lean.parser (_ × loc) := 342 | tk_ident `rw 343 | *> pure prod.mk <*> rw_rules <*> types.location 344 | 345 | meta def sublists {α} : list α → list (list α) 346 | | [] := [] 347 | | (h::t) := list.cons [h] $ list.cons h <$> sublists t 348 | 349 | meta def subrules : rw_rules_t → list rw_rules_t 350 | | ⟨l,x⟩ := flip rw_rules_t.mk x <$> sublists l 351 | 352 | open interaction_monad.result 353 | 354 | meta def last_to_not_fail {α} : list (tactic α) → tactic α 355 | | [] s := tactic.fail "didn't work" s 356 | | (h::t) s := 357 | let match_arg : tactic_result _ := (-- tactic.trace format! "[last_to_not_fail] ENTERING {t.length}" *> 358 | h) s in 359 | match match_arg with 360 | | r@(success a s₁) := 361 | match (last_to_not_fail t s) with 362 | | r@(success a s₂) := r 363 | | e@(exception _ _ _) := r 364 | end 365 | | e@(exception _ _ _) := e 366 | end 367 | 368 | /-- Reverse-parses a rewrite rule. -/ 369 | meta def rw_rule.pp : rw_rule → tactic format 370 | | ⟨_, symm, p⟩ := pure format.compose <*> (pure $ if symm then "←" else "") <*> (tactic.pp p) 371 | 372 | meta instance : has_to_tactic_format rw_rule := 373 | ⟨rw_rule.pp⟩ 374 | 375 | /-- Reverse-parse a rw tactic statement from the rules and a location. -/ 376 | meta def rw_to_string : rw_rules_t → loc → tactic string 377 | | ⟨rs,b⟩ l := do 378 | rs ← list.mmap rw_rule.pp rs, 379 | pure $ "rw " ++ "[" ++ (format.to_string $ format.intercalate ", " rs) ++ "]" ++ loc.to_string l 380 | 381 | -- TODO(jesse): generic has_to_format derive handler for structures with named fields 382 | meta instance : has_to_tactic_format rw_rules_t := 383 | ⟨λ ⟨rs, loc⟩, (++) <$> ((++) "{rs := " <$> has_to_tactic_format.to_tactic_format rs) <*> (pure $ ", loc := " ++ has_to_format.to_format loc ++ "}")⟩ 384 | 385 | /-- This will attempt successive sublists of the given rules until one succeeds. 386 | Then, it will return a reverse-parsed interactive tactic statement `rw [x,y]` 387 | where `[x,y]` is the sublist of the given rules that causes the tactic to succeed. -/ 388 | meta def squeeze_rewrite (rules : rw_rules_t) (l : loc) (cfg : rewrite_cfg := {}) : tactic (string × rw_rules_t) := 389 | last_to_not_fail $ list.map (λ rs, tactic.interactive.rewrite rs l cfg *> flip prod.mk rs <$> rw_to_string rs l) $ subrules rules 390 | 391 | /-- Parse a rewrite expression from a string. -/ 392 | meta def parse_squeeze_rewrite (s : string) : tactic (tactic string) := do 393 | eval_trace format!"[parse_squeeze_rewrite] trying to rw parse {s}", 394 | (rs,l) ← run_on_input parse_rw s, 395 | rs_fmt ← has_to_tactic_format.to_tactic_format rs, 396 | eval_trace format!"[parse_squeeze_rewrite] success! {rs_fmt} {l}", 397 | (result_tac_str, successful_rules) ← squeeze_rewrite rs l {}, 398 | successful_rules_fmt ← has_to_tactic_format.to_tactic_format successful_rules, 399 | eval_trace format!"[parse_squeeze_rewrite] successful rules: {successful_rules_fmt}", 400 | pure $ pure result_tac_str 401 | 402 | end squeeze_rewrite 403 | 404 | namespace tactic 405 | 406 | namespace interactive 407 | 408 | meta def squeeze_rw 409 | (q : parse rw_rules) 410 | (l : parse location) 411 | (cfg : rewrite_cfg := {}) 412 | : tactic unit := propagate_tags $ do { 413 | (squeeze_rewrite q l cfg) >>= tactic.trace 414 | } 415 | 416 | end interactive 417 | 418 | 419 | 420 | 421 | end tactic 422 | 423 | 424 | -- meta def gpt_output_parser : lean.parser (tactic unit) := parser.itactic_reflected 425 | 426 | 427 | /-- Parse a reflected interactive tactic from a string. 428 | The result can be evaluated to a `tactic unit` by using 429 | `eval_expr (tactic unit)`. -/ 430 | meta def parse_itactic_reflected (tactic_string : string) : tactic expr := do 431 | let itactic_string := "{ " ++ tactic_string ++ " }", 432 | r ← run_on_input parser.itactic_reflected itactic_string, 433 | pure $ reflected_value.expr r 434 | 435 | /-- Parse an interactive tactic from a string. -/ 436 | meta def parse_itactic (tactic_string : string) : tactic (tactic string) := 437 | (parse_squeeze_rewrite tactic_string) 438 | <|> do 439 | rtac ← parse_itactic_reflected tactic_string, 440 | u ← eval_expr (tactic unit) rtac, 441 | pure (u *> pure tactic_string) 442 | 443 | end parse_tac 444 | 445 | section os_env_var 446 | 447 | meta def os_env_var : tactic (option string) := 448 | tactic.unsafe_run_io $ io.env.get "OS" 449 | 450 | meta def is_windows : tactic bool := 451 | flip option.get_or_else ff <$> functor.map (= "Windows_NT") <$> os_env_var 452 | 453 | end os_env_var 454 | 455 | section full_names 456 | 457 | namespace tactic 458 | 459 | meta def enable_full_names : tactic unit := do { 460 | set_bool_option `pp.full_names true 461 | } 462 | 463 | meta def with_full_names {α} (tac : tactic α) : tactic α := 464 | tactic.save_options $ enable_full_names *> tac 465 | 466 | end tactic 467 | 468 | meta def tactic_state.fully_qualified (ts : tactic_state) : tactic tactic_state := do { 469 | ts₀ ← tactic.read, 470 | tactic.write ts, 471 | result_ts ← tactic.with_full_names $ tactic.read, 472 | tactic.write ts₀, 473 | pure result_ts 474 | } 475 | 476 | meta def tactic_state.fully_qualified_string (ts : tactic_state) : tactic string := do { 477 | ts₀ ← tactic.read, 478 | tactic.write ts, 479 | result ← tactic.with_full_names $ (tactic.read >>= λ ts, pure ts.to_format.to_string), 480 | tactic.write ts₀, 481 | pure result 482 | } 483 | 484 | end full_names 485 | 486 | section iterM 487 | 488 | /-- version of list.mfoldl with sane argument ordering -/ 489 | def list.iterM {m} [monad m] {α β} (xs : list α) (init : β) (body : β → α → m β) : m β := 490 | list.mfoldl body init xs 491 | 492 | def list.iter {α β} (xs : list α) (init : β) (body : β → α → β) : β := 493 | list.foldl body init xs 494 | 495 | end iterM 496 | 497 | section whenM 498 | 499 | def whenM {m} [monad m] (cond : m bool) (body : m unit) := 500 | mcond cond body $ pure () 501 | 502 | end whenM 503 | --------------------------------------------------------------------------------