-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfstar.rs
More file actions
313 lines (292 loc) · 10.3 KB
/
Copy pathfstar.rs
File metadata and controls
313 lines (292 loc) · 10.3 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
// SPDX-License-Identifier: MPL-2.0
//! F* (F-star) backend -- dependent types with effects
//!
//! F* is a proof-oriented programming language with dependent types and
//! a sophisticated effect system. Used in Project Everest/HACL* for
//! verified cryptography.
#![allow(dead_code)]
use anyhow::{Context, Result};
use async_trait::async_trait;
use std::path::PathBuf;
use std::process::Stdio;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
use super::{ProverBackend, ProverConfig, ProverKind};
use crate::core::{Goal, ProofState, Tactic, TacticResult, Term};
use crate::types::{Effect, TypeInfo};
/// F* backend
pub struct FStarBackend {
config: ProverConfig,
}
impl FStarBackend {
pub fn new(config: ProverConfig) -> Self {
FStarBackend { config }
}
fn to_input_format(&self, state: &ProofState) -> Result<String> {
let mut input = String::from("module Echidna.Export\n\n");
for (i, axiom) in state.context.axioms.iter().enumerate() {
input.push_str(&format!("assume val axiom_{} : {}\n", i, axiom));
}
// Emit definitions with effect and refinement annotations from TypeInfo
for def in &state.context.definitions {
let effect_str = def
.type_info
.as_ref()
.map(Self::effect_to_fstar)
.unwrap_or_default();
let refinement_str = def
.type_info
.as_ref()
.and_then(|ti| ti.refinement.as_ref())
.map(|pred| format!("{{v:{} | {}}}", def.ty, pred))
.unwrap_or_else(|| format!("{}", def.ty));
input.push_str(&format!(
"val {} : {}{}\n",
def.name, effect_str, refinement_str
));
}
if let Some(goal) = state.goals.first() {
input.push_str(&format!("\nval goal : {}\n", goal.target));
}
Ok(input)
}
/// Convert effect row from [`TypeInfo`] to an F* effect annotation prefix.
fn effect_to_fstar(ti: &TypeInfo) -> String {
if ti.effects.is_empty() {
return String::new();
}
let effect_name = ti
.effects
.effects
.first()
.map(|e| match e {
Effect::Pure | Effect::Tot => "Tot",
Effect::IO => "IO",
Effect::State => "ST",
Effect::Exception => "Exn",
Effect::Div => "Div",
Effect::Ghost => "GTot",
Effect::NonDet => "ALL",
Effect::Async => "ALL",
Effect::Custom(s) => s.as_str(),
})
.unwrap_or("Tot");
format!("{} ", effect_name)
}
fn parse_result(&self, output: &str) -> Result<bool> {
let lower = output.to_lowercase();
if lower.contains("verified") || lower.contains("all verification conditions discharged") {
Ok(true)
} else if lower.contains("error") || lower.contains("failed") {
Ok(false)
} else {
Err(anyhow::anyhow!(
"F* inconclusive: {}",
output.lines().take(5).collect::<Vec<_>>().join("\n")
))
}
}
}
#[async_trait]
impl ProverBackend for FStarBackend {
fn kind(&self) -> ProverKind {
ProverKind::FStar
}
async fn version(&self) -> Result<String> {
let output = Command::new(&self.config.executable)
.arg("--version")
.output()
.await
.context("Failed to get F* version")?;
Ok(String::from_utf8_lossy(&output.stdout)
.lines()
.next()
.unwrap_or("unknown")
.trim()
.to_string())
}
async fn parse_file(&self, path: PathBuf) -> Result<ProofState> {
let content = super::bounded_read_proof_file(&path)
.await
.context("Failed to read F* file")?;
let mut state = self.parse_string(&content).await?;
state.metadata.insert(
"source_path".to_string(),
serde_json::Value::String(path.to_string_lossy().into_owned()),
);
Ok(state)
}
async fn parse_string(&self, content: &str) -> Result<ProofState> {
let mut state = ProofState::default();
state.metadata.insert(
"fstar_source".to_string(),
serde_json::Value::String(content.to_string()),
);
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with("//") || line.starts_with("(*") {
continue;
}
if line.starts_with("val ") || line.starts_with("let ") {
state.goals.push(Goal {
id: format!("goal_{}", state.goals.len()),
target: Term::Const(line.to_string()),
hypotheses: vec![],
});
} else if line.starts_with("assume") {
state.context.axioms.push(line.to_string());
}
}
if state.goals.is_empty() {
state.goals.push(Goal {
id: "goal_0".to_string(),
target: Term::Const("True".to_string()),
hypotheses: vec![],
});
}
Ok(state)
}
async fn apply_tactic(&self, _state: &ProofState, _tactic: &Tactic) -> Result<TacticResult> {
Err(anyhow::anyhow!(
"F*: interactive tactics not directly supported"
))
}
async fn verify_proof(&self, state: &ProofState) -> Result<bool> {
if let Some(path) = state.metadata.get("source_path").and_then(|v| v.as_str()) {
let output = tokio::time::timeout(
tokio::time::Duration::from_secs(self.config.timeout + 5),
Command::new(&self.config.executable)
.arg(path)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output(),
)
.await
.context("F* timed out")??;
return self.parse_result(&format!(
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
));
}
let input = if let Some(src) = state.metadata.get("fstar_source").and_then(|v| v.as_str()) {
src.to_string()
} else {
self.to_input_format(state)?
};
let mut child = Command::new(&self.config.executable)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.context("Failed to spawn F*")?;
if let Some(mut stdin) = child.stdin.take() {
stdin.write_all(input.as_bytes()).await?;
drop(stdin);
}
let output = tokio::time::timeout(
tokio::time::Duration::from_secs(self.config.timeout + 5),
child.wait_with_output(),
)
.await
.context("F* timed out")??;
self.parse_result(&format!(
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
))
}
async fn export(&self, state: &ProofState) -> Result<String> {
self.to_input_format(state)
}
async fn suggest_tactics(&self, state: &ProofState, limit: usize) -> Result<Vec<Tactic>> {
// F* supports both a tactic DSL (Tactics monad) and SMT-backed
// verification. The canonical first-pass tactics are listed below.
let tactics = vec![
Tactic::Custom {
prover: "fstar".to_string(),
command: "norm".to_string(),
args: vec!["[delta; iota; zeta; primops]".to_string()],
},
Tactic::Custom {
prover: "fstar".to_string(),
command: "smt".to_string(),
args: vec![],
},
Tactic::Custom {
prover: "fstar".to_string(),
command: "trivial".to_string(),
args: vec![],
},
Tactic::Custom {
prover: "fstar".to_string(),
command: "decide".to_string(),
args: vec![],
},
Tactic::Custom {
prover: "fstar".to_string(),
command: "exact".to_string(),
args: vec![],
},
Tactic::Simplify,
Tactic::Assumption,
Tactic::Reflexivity,
];
Ok(super::gnn_augment_tactics(&self.config, state, "fstar", tactics, limit).await)
}
async fn search_theorems(&self, _pattern: &str) -> Result<Vec<String>> {
// F* does not expose a programmatic theorem-search interface.
Ok(vec![])
}
fn config(&self) -> &ProverConfig {
&self.config
}
fn set_config(&mut self, config: ProverConfig) {
self.config = config;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_fstar_export() {
let backend = FStarBackend::new(ProverConfig {
executable: PathBuf::from("fstar.exe"),
timeout: 10,
..Default::default()
});
let mut state = ProofState::default();
state.goals.push(Goal {
id: "g0".to_string(),
target: Term::Const("nat".to_string()),
hypotheses: vec![],
});
let output = backend.to_input_format(&state).unwrap();
assert!(output.contains("module Echidna.Export"));
}
#[tokio::test]
async fn test_fstar_parse() {
let backend = FStarBackend::new(ProverConfig {
executable: PathBuf::from("fstar.exe"),
timeout: 10,
..Default::default()
});
let state = backend
.parse_string("val test : nat -> nat\nassume val ax : prop")
.await
.unwrap();
assert!(!state.goals.is_empty());
}
#[test]
fn test_fstar_result_parsing() {
let backend = FStarBackend::new(ProverConfig {
executable: PathBuf::from("fstar.exe"),
timeout: 10,
..Default::default()
});
assert!(backend
.parse_result("All verification conditions discharged")
.unwrap());
assert!(!backend.parse_result("Error in module").unwrap());
}
}