logicaffeine_proof/
development.rs1use crate::formula::{parse_formula, FormulaError};
27use crate::verify::{prove_library_with_axioms, LibraryResult, LibraryTheorem};
28use crate::ProofExpr;
29
30#[derive(Debug, Clone, PartialEq)]
32pub struct Development {
33 pub axioms: Vec<(String, ProofExpr)>,
35 pub theorems: Vec<LibraryTheorem>,
37 pub simp_tagged: Vec<String>,
40}
41
42impl Development {
43 pub fn axiom_exprs(&self) -> Vec<ProofExpr> {
45 self.axioms.iter().map(|(_, e)| e.clone()).collect()
46 }
47
48 pub fn simp_lemmas(&self) -> &[String] {
50 &self.simp_tagged
51 }
52}
53
54pub fn parse_development(body: &str) -> Result<Development, FormulaError> {
56 let mut axioms = Vec::new();
57 let mut theorems = Vec::new();
58
59 let mut simp_tagged = Vec::new();
60
61 for stmt in split_on_top_level(body, '.') {
62 let stmt = stmt.trim();
63 if stmt.is_empty() {
64 continue;
65 }
66 let words: Vec<&str> = stmt.split_whitespace().collect();
67 match words.first().map(|w| w.to_lowercase()).as_deref() {
68 Some("axiom") => {
69 let (decl, simp) = parse_axiom_decl(stmt)?;
70 if simp {
71 simp_tagged.push(decl.0.clone());
72 }
73 axioms.push(decl);
74 }
75 Some("theorem") => {
76 let (thm, simp) = parse_theorem_decl(stmt)?;
77 if simp {
78 simp_tagged.push(thm.name.clone());
79 }
80 theorems.push(thm);
81 }
82 other => {
83 return Err(FormulaError::new(format!(
84 "expected a declaration starting with 'Axiom' or 'Theorem', found {other:?}"
85 )))
86 }
87 }
88 }
89
90 Ok(Development {
91 axioms,
92 theorems,
93 simp_tagged,
94 })
95}
96
97pub fn prove_development(body: &str) -> Result<Vec<(String, LibraryResult)>, FormulaError> {
101 let dev = parse_development(body)?;
102 let axioms = dev.axiom_exprs();
103 let results = prove_library_with_axioms(&axioms, &dev.theorems);
104 Ok(dev
105 .theorems
106 .iter()
107 .map(|t| t.name.clone())
108 .zip(results)
109 .collect())
110}
111
112fn strip_simp_attr<'a>(words: &[&'a str]) -> (Vec<&'a str>, bool) {
120 let mut simp = false;
121 let kept = words
122 .iter()
123 .filter(|w| {
124 if w.eq_ignore_ascii_case("[simp]") {
125 simp = true;
126 false
127 } else {
128 true
129 }
130 })
131 .copied()
132 .collect();
133 (kept, simp)
134}
135
136fn parse_axiom_decl(stmt: &str) -> Result<((String, ProofExpr), bool), FormulaError> {
138 let (header, formula_src) = split_once_top_level(stmt, ':').ok_or_else(|| {
139 FormulaError::new("an 'Axiom' declaration needs a ':' before its formula")
140 })?;
141 let hwords: Vec<&str> = header.split_whitespace().collect();
142 let (hwords, simp) = strip_simp_attr(&hwords);
143 let name = hwords
144 .get(1)
145 .ok_or_else(|| FormulaError::new("'Axiom' declaration is missing a name"))?
146 .to_string();
147 let formula = parse_formula(&formula_src)?;
148 Ok(((name, formula), simp))
149}
150
151fn parse_theorem_decl(stmt: &str) -> Result<(LibraryTheorem, bool), FormulaError> {
153 let (header, body) = split_once_top_level(stmt, ':').ok_or_else(|| {
154 FormulaError::new("a 'Theorem' declaration needs a ':' before its clauses")
155 })?;
156
157 let hwords: Vec<&str> = header.split_whitespace().collect();
159 let (hwords, simp) = strip_simp_attr(&hwords);
160 let name = hwords
161 .get(1)
162 .ok_or_else(|| FormulaError::new("'Theorem' declaration is missing a name"))?
163 .to_string();
164 let mut cites = Vec::new();
165 if let Some(kw) = hwords.get(2) {
166 if matches!(kw.to_lowercase().as_str(), "cites" | "using" | "from") {
167 for w in &hwords[3..] {
168 for part in w.split(',') {
169 let part = part.trim();
170 if !part.is_empty() {
171 cites.push(part.to_string());
172 }
173 }
174 }
175 }
176 }
177
178 let is_clause_kw = |w: &str| matches!(w, "given" | "assume" | "prove" | "show");
184 let words: Vec<&str> = body.split_whitespace().collect();
185 let mut premises = Vec::new();
186 let mut goal: Option<ProofExpr> = None;
187 let mut i = 0;
188 while i < words.len() {
189 let kw = words[i].to_lowercase();
190 if !is_clause_kw(&kw) {
191 i += 1;
193 continue;
194 }
195 i += 1;
196 let start = i;
197 while i < words.len() && !is_clause_kw(&words[i].to_lowercase()) {
198 i += 1;
199 }
200 let formula_src = words[start..i].join(" ");
201 match kw.as_str() {
202 "given" | "assume" => premises.push(parse_formula(&formula_src)?),
203 _ => {
204 if goal.is_some() {
205 return Err(FormulaError::new(format!(
206 "theorem '{name}' has more than one 'prove' clause"
207 )));
208 }
209 goal = Some(parse_formula(&formula_src)?);
210 }
211 }
212 }
213
214 let goal =
215 goal.ok_or_else(|| FormulaError::new(format!("theorem '{name}' has no 'prove' clause")))?;
216 Ok((
217 LibraryTheorem {
218 name,
219 premises,
220 goal,
221 cites,
222 },
223 simp,
224 ))
225}
226
227fn split_on_top_level(s: &str, delim: char) -> Vec<String> {
233 let mut out = Vec::new();
234 let mut depth = 0i32;
235 let mut cur = String::new();
236 for c in s.chars() {
237 match c {
238 '(' => {
239 depth += 1;
240 cur.push(c);
241 }
242 ')' => {
243 depth -= 1;
244 cur.push(c);
245 }
246 c if c == delim && depth == 0 => {
247 out.push(std::mem::take(&mut cur));
248 }
249 c => cur.push(c),
250 }
251 }
252 out.push(cur);
253 out
254}
255
256fn split_once_top_level(s: &str, delim: char) -> Option<(String, String)> {
258 let mut depth = 0i32;
259 for (i, c) in s.char_indices() {
260 match c {
261 '(' => depth += 1,
262 ')' => depth -= 1,
263 c if c == delim && depth == 0 => {
264 return Some((s[..i].to_string(), s[i + c.len_utf8()..].to_string()));
265 }
266 _ => {}
267 }
268 }
269 None
270}