-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathacl2.rs
More file actions
1807 lines (1644 loc) · 60.1 KB
/
Copy pathacl2.rs
File metadata and controls
1807 lines (1644 loc) · 60.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2025 ECHIDNA Project Team
// SPDX-License-Identifier: MPL-2.0
#![allow(dead_code)]
//! ACL2 theorem prover backend implementation
//!
//! ACL2 (A Computational Logic for Applicative Common Lisp) is a theorem prover
//! for a first-order logic based on Common Lisp. It uses a "waterfall" proof
//! strategy with hints rather than explicit tactics.
//!
//! Key features:
//! - S-expression based syntax (Lisp)
//! - Automated proof with hints
//! - Industrial strength (AMD, Intel, etc.)
//! - Executable specifications
use anyhow::{anyhow, Context as AnyhowContext, Result};
use async_trait::async_trait;
use std::collections::HashMap;
use std::path::PathBuf;
use std::process::Stdio;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, Command};
use tokio::sync::Mutex;
use crate::core::{Context, Definition, Goal, ProofState, Tactic, TacticResult, Term, Theorem};
use crate::provers::{ProverBackend, ProverConfig, ProverKind};
/// ACL2 theorem prover backend
pub struct ACL2Backend {
config: ProverConfig,
session: Mutex<Option<ACL2Session>>,
}
/// Active ACL2 session
struct ACL2Session {
process: Child,
ready: bool,
}
/// ACL2 S-expression representation
#[derive(Debug, Clone, PartialEq)]
pub enum SExp {
/// Atom (symbol or number)
Atom(String),
/// String literal
Str(String),
/// Number
Num(i64),
/// List of S-expressions
List(Vec<SExp>),
/// Quoted expression
Quote(Box<SExp>),
/// Nil
Nil,
}
impl SExp {
/// Create an atom
pub fn atom(s: &str) -> Self {
SExp::Atom(s.to_string())
}
/// Create a list
pub fn list(items: Vec<SExp>) -> Self {
SExp::List(items)
}
/// Create a quoted expression
pub fn quote(inner: SExp) -> Self {
SExp::Quote(Box::new(inner))
}
/// Convert to Lisp string representation
pub fn to_lisp(&self) -> String {
match self {
SExp::Atom(s) => s.clone(),
SExp::Str(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
SExp::Num(n) => n.to_string(),
SExp::List(items) => {
let inner = items
.iter()
.map(|i| i.to_lisp())
.collect::<Vec<_>>()
.join(" ");
format!("({})", inner)
},
SExp::Quote(inner) => format!("'{}", inner.to_lisp()),
SExp::Nil => "nil".to_string(),
}
}
/// Parse S-expression from string
pub fn parse(input: &str) -> Result<Self> {
let mut chars = input.chars().peekable();
skip_whitespace(&mut chars);
parse_sexp_inner(&mut chars)
}
/// Check if this is a specific atom
pub fn is_atom(&self, name: &str) -> bool {
matches!(self, SExp::Atom(s) if s.eq_ignore_ascii_case(name))
}
/// Get as list
pub fn as_list(&self) -> Option<&Vec<SExp>> {
match self {
SExp::List(items) => Some(items),
_ => None,
}
}
/// Get as atom string
pub fn as_atom(&self) -> Option<&str> {
match self {
SExp::Atom(s) => Some(s),
_ => None,
}
}
}
fn skip_whitespace(chars: &mut std::iter::Peekable<std::str::Chars>) {
while let Some(&c) = chars.peek() {
if c.is_whitespace() {
chars.next();
} else if c == ';' {
// Skip comment to end of line
while let Some(&c) = chars.peek() {
chars.next();
if c == '\n' {
break;
}
}
} else {
break;
}
}
}
fn parse_sexp_inner(chars: &mut std::iter::Peekable<std::str::Chars>) -> Result<SExp> {
skip_whitespace(chars);
match chars.peek() {
None => Err(anyhow!("Unexpected end of input")),
Some(&'(') => {
chars.next();
let mut items = Vec::new();
loop {
skip_whitespace(chars);
match chars.peek() {
None => return Err(anyhow!("Unmatched opening parenthesis")),
Some(&')') => {
chars.next();
break;
},
Some(&'.') => {
// Dotted pair - skip for simplicity
chars.next();
skip_whitespace(chars);
let _tail = parse_sexp_inner(chars)?;
skip_whitespace(chars);
if chars.next() != Some(')') {
return Err(anyhow!("Expected ) after dotted pair"));
}
break;
},
_ => {
items.push(parse_sexp_inner(chars)?);
},
}
}
if items.is_empty() {
Ok(SExp::Nil)
} else {
Ok(SExp::List(items))
}
},
Some(&')') => Err(anyhow!("Unexpected closing parenthesis")),
Some(&'\'') => {
chars.next();
let inner = parse_sexp_inner(chars)?;
Ok(SExp::Quote(Box::new(inner)))
},
Some(&'`') => {
// Backquote - treat like quote for simplicity
chars.next();
let inner = parse_sexp_inner(chars)?;
Ok(SExp::Quote(Box::new(inner)))
},
Some(&'"') => {
// String literal
chars.next();
let mut s = String::new();
let mut escape = false;
loop {
match chars.next() {
None => return Err(anyhow!("Unterminated string")),
Some('\\') if !escape => escape = true,
Some('"') if !escape => break,
Some(c) => {
escape = false;
s.push(c);
},
}
}
Ok(SExp::Str(s))
},
Some(&c) if c == '-' || c.is_ascii_digit() => {
// Try to parse as number
let mut num_str = String::new();
while let Some(&c) = chars.peek() {
if c.is_ascii_digit() || c == '-' {
num_str.push(c);
chars.next();
} else {
break;
}
}
if let Ok(n) = num_str.parse::<i64>() {
Ok(SExp::Num(n))
} else {
// It's an atom starting with -
let mut atom = num_str;
while let Some(&c) = chars.peek() {
if c.is_whitespace() || c == '(' || c == ')' {
break;
}
atom.push(c);
chars.next();
}
Ok(SExp::Atom(atom))
}
},
Some(_) => {
// Atom
let mut atom = String::new();
while let Some(&c) = chars.peek() {
if c.is_whitespace() || c == '(' || c == ')' || c == '\'' || c == '"' {
break;
}
atom.push(c);
chars.next();
}
if atom.eq_ignore_ascii_case("nil") {
Ok(SExp::Nil)
} else if atom.eq_ignore_ascii_case("t") {
Ok(SExp::Atom("t".to_string()))
} else {
Ok(SExp::Atom(atom))
}
},
}
}
/// ACL2 event types
#[derive(Debug, Clone)]
pub enum ACL2Event {
/// Function definition (defun)
Defun {
name: String,
params: Vec<String>,
body: SExp,
guard: Option<SExp>,
},
/// Theorem definition (defthm)
Defthm {
name: String,
formula: SExp,
hints: Vec<ACL2Hint>,
rule_classes: Option<SExp>,
},
/// Encapsulate block
Encapsulate {
signatures: Vec<(String, SExp)>,
events: Vec<ACL2Event>,
},
/// Include book
IncludeBook { name: String, dir: Option<String> },
/// In-theory event
InTheory(SExp),
/// Mutual recursion
MutualRecursion(Vec<ACL2Event>),
/// Constant definition (defconst)
Defconst { name: String, value: SExp },
/// Macro definition (defmacro)
Defmacro {
name: String,
params: Vec<String>,
body: SExp,
},
/// Other/unknown event
Other(SExp),
}
/// ACL2 proof hints
#[derive(Debug, Clone)]
pub enum ACL2Hint {
/// :induct hint
Induct(SExp),
/// :use hint
Use(Vec<SExp>),
/// :expand hint
Expand(Vec<SExp>),
/// :in-theory hint
InTheory(SExp),
/// :cases hint
Cases(Vec<SExp>),
/// :by hint
By(SExp),
/// :hands-off hint
HandsOff(Vec<String>),
/// :do-not hint
DoNot(Vec<String>),
/// :do-not-induct hint
DoNotInduct(bool),
/// Goal-specific hint
Goal {
goal_name: String,
hints: Vec<ACL2Hint>,
},
/// Other hint
Other(String, SExp),
}
impl ACL2Backend {
/// Create a new ACL2 backend with configuration
pub fn new(config: ProverConfig) -> Self {
ACL2Backend {
config,
session: Mutex::new(None),
}
}
/// Start a new ACL2 session
async fn start_session(&self) -> Result<ACL2Session> {
let exe = if self.config.executable.as_os_str().is_empty() {
"acl2"
} else {
self.config.executable.to_str().unwrap_or("acl2")
};
let mut cmd = Command::new(exe);
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
for arg in &self.config.args {
cmd.arg(arg);
}
let process = cmd.spawn().context("Failed to start ACL2 process")?;
Ok(ACL2Session {
process,
ready: false,
})
}
/// Ensure session is running
async fn ensure_session(&self) -> Result<()> {
let mut session_lock = self.session.lock().await;
if session_lock.is_none() {
let mut session = self.start_session().await?;
// Wait for ACL2 to be ready
self.wait_for_prompt(&mut session).await?;
session.ready = true;
*session_lock = Some(session);
}
Ok(())
}
/// Wait for ACL2 prompt
async fn wait_for_prompt(&self, session: &mut ACL2Session) -> Result<String> {
let stdout = session
.process
.stdout
.as_mut()
.ok_or_else(|| anyhow!("No stdout"))?;
let mut reader = BufReader::new(stdout);
let mut output = String::new();
let mut line = String::new();
loop {
line.clear();
let bytes = reader.read_line(&mut line).await?;
if bytes == 0 {
break;
}
output.push_str(&line);
// ACL2 prompt is typically "ACL2 !>" or similar
if line.contains("ACL2") && (line.contains(">") || line.contains("!>")) {
break;
}
}
Ok(output)
}
/// Send command to ACL2 and get response
async fn send_command(&self, cmd: &str) -> Result<String> {
self.ensure_session().await?;
let mut session_lock = self.session.lock().await;
let session = session_lock
.as_mut()
.ok_or_else(|| anyhow!("No active session"))?;
let stdin = session
.process
.stdin
.as_mut()
.ok_or_else(|| anyhow!("No stdin"))?;
// Send command with newline
let cmd_with_newline = format!("{}\n", cmd);
stdin
.write_all(cmd_with_newline.as_bytes())
.await
.context("Failed to write command")?;
stdin.flush().await.context("Failed to flush")?;
// Read response until next prompt
self.wait_for_prompt(session).await
}
/// Parse ACL2 file content
fn parse_file_content(&self, content: &str) -> Result<Vec<ACL2Event>> {
let mut events = Vec::new();
let mut remaining = content.trim();
while !remaining.is_empty() {
// Skip whitespace and comments
remaining = remaining.trim_start();
if remaining.starts_with(';') {
// Skip comment line
if let Some(pos) = remaining.find('\n') {
remaining = &remaining[pos + 1..];
} else {
break;
}
continue;
}
if remaining.starts_with('(') {
// Parse S-expression
match SExp::parse(remaining) {
Ok(sexp) => {
if let Some(event) = self.parse_event(&sexp)? {
events.push(event);
}
// Find end of this S-expression to advance
let sexp_len = find_sexp_end(remaining)?;
remaining = &remaining[sexp_len..];
},
Err(e) => {
// Try to skip to next top-level form
if let Some(pos) = remaining[1..].find("\n(") {
remaining = &remaining[pos + 1..];
} else {
return Err(e);
}
},
}
} else if remaining.starts_with('#') {
// Skip reader macros
if let Some(pos) = remaining.find('\n') {
remaining = &remaining[pos + 1..];
} else {
break;
}
} else {
// Skip unknown content
if let Some(pos) = remaining.find('\n') {
remaining = &remaining[pos + 1..];
} else {
break;
}
}
}
Ok(events)
}
/// Parse a single ACL2 event from S-expression
fn parse_event(&self, sexp: &SExp) -> Result<Option<ACL2Event>> {
let list = match sexp.as_list() {
Some(l) if !l.is_empty() => l,
_ => return Ok(None),
};
let head = match list[0].as_atom() {
Some(s) => s.to_lowercase(),
None => return Ok(Some(ACL2Event::Other(sexp.clone()))),
};
match head.as_str() {
"defun" | "defund" => self.parse_defun(list),
"defthm" | "defthmd" => self.parse_defthm(list),
"defconst" => self.parse_defconst(list),
"defmacro" => self.parse_defmacro(list),
"encapsulate" => self.parse_encapsulate(list),
"include-book" => self.parse_include_book(list),
"in-theory" => Ok(Some(ACL2Event::InTheory(
list.get(1).cloned().unwrap_or(SExp::Nil),
))),
"mutual-recursion" => self.parse_mutual_recursion(list),
_ => Ok(Some(ACL2Event::Other(sexp.clone()))),
}
}
/// Parse defun event
fn parse_defun(&self, list: &[SExp]) -> Result<Option<ACL2Event>> {
if list.len() < 4 {
return Err(anyhow!("Invalid defun: too few elements"));
}
let name = list[1]
.as_atom()
.ok_or_else(|| anyhow!("Invalid defun name"))?
.to_string();
let params = match &list[2] {
SExp::List(params) => params
.iter()
.filter_map(|p| p.as_atom().map(String::from))
.collect(),
SExp::Nil => vec![],
_ => return Err(anyhow!("Invalid defun params")),
};
// Find body and guard
let mut body = list[3].clone();
let mut guard = None;
// Check for declare forms
for item in list.iter().skip(3) {
if let SExp::List(decl) = item {
if let Some(head) = decl.first().and_then(|h| h.as_atom()) {
if head.eq_ignore_ascii_case("declare") {
// Look for xargs with guard
for item in decl.iter().skip(1) {
if let SExp::List(xargs) = item {
if xargs
.first()
.and_then(|h| h.as_atom())
.map(|s| s.eq_ignore_ascii_case("xargs"))
.unwrap_or(false)
{
// Look for :guard
let mut iter = xargs.iter().skip(1);
while let Some(key) = iter.next() {
if key.is_atom(":guard") {
if let Some(val) = iter.next() {
guard = Some(val.clone());
}
}
}
}
}
}
continue;
}
}
}
body = item.clone();
}
Ok(Some(ACL2Event::Defun {
name,
params,
body,
guard,
}))
}
/// Parse defthm event
fn parse_defthm(&self, list: &[SExp]) -> Result<Option<ACL2Event>> {
if list.len() < 3 {
return Err(anyhow!("Invalid defthm: too few elements"));
}
let name = list[1]
.as_atom()
.ok_or_else(|| anyhow!("Invalid defthm name"))?
.to_string();
let formula = list[2].clone();
// Parse hints and rule-classes
let mut hints = Vec::new();
let mut rule_classes = None;
let mut i = 3;
while i < list.len() {
if let Some(key) = list[i].as_atom() {
match key.to_lowercase().as_str() {
":hints" if i + 1 < list.len() => {
hints = self.parse_hints(&list[i + 1])?;
i += 1;
},
":rule-classes" if i + 1 < list.len() => {
rule_classes = Some(list[i + 1].clone());
i += 1;
},
_ => {},
}
}
i += 1;
}
Ok(Some(ACL2Event::Defthm {
name,
formula,
hints,
rule_classes,
}))
}
/// Parse hints
fn parse_hints(&self, sexp: &SExp) -> Result<Vec<ACL2Hint>> {
let list = match sexp.as_list() {
Some(l) => l,
None => return Ok(vec![]),
};
let mut hints = Vec::new();
for item in list {
if let SExp::List(goal_hint) = item {
if goal_hint.len() >= 2 {
if let SExp::Str(goal_name) = &goal_hint[0] {
let mut goal_hints = Vec::new();
let mut j = 1;
while j < goal_hint.len() {
if let Some(key) = goal_hint[j].as_atom() {
if j + 1 < goal_hint.len() {
let hint = self.parse_single_hint(key, &goal_hint[j + 1])?;
goal_hints.push(hint);
j += 1;
}
}
j += 1;
}
hints.push(ACL2Hint::Goal {
goal_name: goal_name.clone(),
hints: goal_hints,
});
}
}
}
}
Ok(hints)
}
/// Parse a single hint
fn parse_single_hint(&self, key: &str, value: &SExp) -> Result<ACL2Hint> {
match key.to_lowercase().as_str() {
":induct" => Ok(ACL2Hint::Induct(value.clone())),
":use" => {
let uses = match value.as_list() {
Some(l) => l.clone(),
None => vec![value.clone()],
};
Ok(ACL2Hint::Use(uses))
},
":expand" => {
let expands = match value.as_list() {
Some(l) => l.clone(),
None => vec![value.clone()],
};
Ok(ACL2Hint::Expand(expands))
},
":in-theory" => Ok(ACL2Hint::InTheory(value.clone())),
":cases" => {
let cases = match value.as_list() {
Some(l) => l.clone(),
None => vec![value.clone()],
};
Ok(ACL2Hint::Cases(cases))
},
":by" => Ok(ACL2Hint::By(value.clone())),
":hands-off" => {
let fns = match value.as_list() {
Some(l) => l
.iter()
.filter_map(|s| s.as_atom().map(String::from))
.collect(),
None => value
.as_atom()
.map(|s| vec![s.to_string()])
.unwrap_or_default(),
};
Ok(ACL2Hint::HandsOff(fns))
},
":do-not" => {
let actions = match value.as_list() {
Some(l) => l
.iter()
.filter_map(|s| s.as_atom().map(String::from))
.collect(),
None => vec![],
};
Ok(ACL2Hint::DoNot(actions))
},
":do-not-induct" => Ok(ACL2Hint::DoNotInduct(true)),
_ => Ok(ACL2Hint::Other(key.to_string(), value.clone())),
}
}
/// Parse defconst
fn parse_defconst(&self, list: &[SExp]) -> Result<Option<ACL2Event>> {
if list.len() < 3 {
return Err(anyhow!("Invalid defconst"));
}
let name = list[1]
.as_atom()
.ok_or_else(|| anyhow!("Invalid defconst name"))?
.to_string();
let value = list[2].clone();
Ok(Some(ACL2Event::Defconst { name, value }))
}
/// Parse defmacro
fn parse_defmacro(&self, list: &[SExp]) -> Result<Option<ACL2Event>> {
if list.len() < 4 {
return Err(anyhow!("Invalid defmacro"));
}
let name = list[1]
.as_atom()
.ok_or_else(|| anyhow!("Invalid defmacro name"))?
.to_string();
let params = match &list[2] {
SExp::List(params) => params
.iter()
.filter_map(|p| p.as_atom().map(String::from))
.collect(),
SExp::Nil => vec![],
_ => vec![],
};
let body = list.last().cloned().unwrap_or(SExp::Nil);
Ok(Some(ACL2Event::Defmacro { name, params, body }))
}
/// Parse encapsulate
fn parse_encapsulate(&self, list: &[SExp]) -> Result<Option<ACL2Event>> {
if list.len() < 2 {
return Err(anyhow!("Invalid encapsulate"));
}
let signatures = match &list[1] {
SExp::List(sigs) => sigs
.iter()
.filter_map(|sig| {
if let SExp::List(parts) = sig {
if parts.len() >= 2 {
let name = parts[0].as_atom()?.to_string();
return Some((name, parts[1].clone()));
}
}
None
})
.collect(),
SExp::Nil => vec![],
_ => vec![],
};
let mut events = Vec::new();
for item in list.iter().skip(2) {
if let Some(event) = self.parse_event(item)? {
events.push(event);
}
}
Ok(Some(ACL2Event::Encapsulate { signatures, events }))
}
/// Parse include-book
fn parse_include_book(&self, list: &[SExp]) -> Result<Option<ACL2Event>> {
if list.len() < 2 {
return Err(anyhow!("Invalid include-book"));
}
let name = match &list[1] {
SExp::Str(s) => s.clone(),
SExp::Atom(s) => s.clone(),
_ => return Err(anyhow!("Invalid book name")),
};
let mut dir = None;
let mut i = 2;
while i < list.len() {
if list[i].is_atom(":dir") && i + 1 < list.len() {
dir = list[i + 1].as_atom().map(String::from);
i += 1;
}
i += 1;
}
Ok(Some(ACL2Event::IncludeBook { name, dir }))
}
/// Parse mutual-recursion
fn parse_mutual_recursion(&self, list: &[SExp]) -> Result<Option<ACL2Event>> {
let mut events = Vec::new();
for item in list.iter().skip(1) {
if let Some(event) = self.parse_event(item)? {
events.push(event);
}
}
Ok(Some(ACL2Event::MutualRecursion(events)))
}
/// Convert ACL2 S-expression to universal Term
fn sexp_to_term(&self, sexp: &SExp) -> Term {
match sexp {
SExp::Atom(s) => {
if s.starts_with(':') || s.chars().next().map(|c| c.is_uppercase()).unwrap_or(false)
{
Term::Const(s.clone())
} else {
Term::Var(s.clone())
}
},
SExp::Str(s) => Term::Const(format!("\"{}\"", s)),
SExp::Num(n) => Term::Const(n.to_string()),
SExp::Nil => Term::Const("nil".to_string()),
SExp::Quote(inner) => Term::App {
func: Box::new(Term::Const("quote".to_string())),
args: vec![self.sexp_to_term(inner)],
},
SExp::List(items) => {
if items.is_empty() {
Term::Const("nil".to_string())
} else {
let head = &items[0];
// Check for special forms
if let Some(name) = head.as_atom() {
match name.to_lowercase().as_str() {
"if" if items.len() >= 4 => {
return Term::App {
func: Box::new(Term::Const("if".to_string())),
args: items[1..4]
.iter()
.map(|i| self.sexp_to_term(i))
.collect(),
};
},
"let" | "let*" if items.len() >= 3 => {
// Simplify let to lambda application
if let Some(last_item) = items.last() {
let body = self.sexp_to_term(last_item);
return body;
}
},
"lambda" if items.len() >= 3 => {
let params = match &items[1] {
SExp::List(ps) => ps
.iter()
.filter_map(|p| p.as_atom().map(String::from))
.collect::<Vec<_>>(),
_ => vec![],
};
let body = if let Some(last_item) = items.last() {
self.sexp_to_term(last_item)
} else {
Term::Const("nil".to_string())
};
// Build nested lambdas
let mut result = body;
for param in params.into_iter().rev() {
result = Term::Lambda {
param,
param_type: None,
body: Box::new(result),
};
}
return result;
},
"implies" if items.len() >= 3 => {
return Term::Pi {
param: "_".to_string(),
param_type: Box::new(self.sexp_to_term(&items[1])),
body: Box::new(self.sexp_to_term(&items[2])),
};
},
"and" | "or" | "not" | "equal" | "+" | "-" | "*" | "/" => {
return Term::App {
func: Box::new(Term::Const(name.to_string())),
args: items[1..].iter().map(|i| self.sexp_to_term(i)).collect(),
};
},
_ => {},
}
}
// Generic function application
Term::App {
func: Box::new(self.sexp_to_term(head)),
args: items[1..].iter().map(|i| self.sexp_to_term(i)).collect(),
}
}
},
}
}
/// Convert core Pattern to ACL2 S-expression
fn pattern_to_sexp(&self, pattern: &crate::core::Pattern) -> SExp {
match pattern {
crate::core::Pattern::Wildcard => SExp::Atom("_".to_string()),
crate::core::Pattern::Var(name) => SExp::Atom(name.clone()),
crate::core::Pattern::Constructor { name, args } => {
if args.is_empty() {
SExp::Atom(name.clone())
} else {
let mut items = vec![SExp::Atom(name.clone())];
items.extend(args.iter().map(|a| self.pattern_to_sexp(a)));
SExp::List(items)
}
},
}
}
/// Convert universal Term to ACL2 S-expression
fn term_to_sexp(&self, term: &Term) -> SExp {
match term {
Term::Var(name) => SExp::Atom(name.clone()),
Term::Const(name) => SExp::Atom(name.clone()),
Term::Universe(_) => SExp::Atom("T".to_string()),
Term::App { func, args } => {
let mut items = vec![self.term_to_sexp(func)];
items.extend(args.iter().map(|a| self.term_to_sexp(a)));
SExp::List(items)
},
Term::Lambda { param, body, .. } => SExp::List(vec![
SExp::Atom("lambda".to_string()),
SExp::List(vec![SExp::Atom(param.clone())]),
self.term_to_sexp(body),
]),
Term::Pi {
param,
param_type,
body,
} => {
if param == "_" {
// Non-dependent: implies
SExp::List(vec![
SExp::Atom("implies".to_string()),
self.term_to_sexp(param_type),
self.term_to_sexp(body),
])
} else {
// Dependent: forall (not directly supported, approximate)
SExp::List(vec![
SExp::Atom("implies".to_string()),
self.term_to_sexp(param_type),
self.term_to_sexp(body),
])
}
},
Term::Sigma {
param_type, body, ..
} => {
// Sigma types approximated as conjunction (and A B)
SExp::List(vec![
SExp::Atom("and".to_string()),
self.term_to_sexp(param_type),
self.term_to_sexp(body),
])
},
Term::Let {
name, value, body, ..
} => SExp::List(vec![
SExp::Atom("let".to_string()),
SExp::List(vec![SExp::List(vec![
SExp::Atom(name.clone()),
self.term_to_sexp(value),
])]),
self.term_to_sexp(body),
]),
Term::Match {
scrutinee,
branches,
..
} => {
// ACL2 doesn't have pattern matching, approximate with cond
let mut cond_clauses = Vec::new();
for (pattern, body) in branches {
let pattern_sexp = self.pattern_to_sexp(pattern);