1use crate::foreign::contract::{BinOp as TermBinOp, FnContract, Term, UnaryOp as TermUnOp};
7
8use super::xta::{BinOp, Expr, FnDecl, Param, Stmt, Type, TypeExpr, UnOp};
9
10pub(super) fn pancake_function(contract: &FnContract) -> FnDecl {
17 let params = contract
18 .params
19 .iter()
20 .map(|p| Param::value(TypeExpr::plain(Type::Int), p))
21 .collect();
22 let mut body: Vec<Stmt> = contract
23 .requires
24 .iter()
25 .map(|clause| Stmt::Assert(term(clause)))
26 .collect();
27 let ret = match &contract.retval {
28 Some(e) => {
29 body.push(Stmt::Return(Some(term(e))));
30 Type::Int
31 }
32 None => Type::Void,
33 };
34 FnDecl {
35 ret: TypeExpr::plain(ret),
36 name: ffi_name(&contract.name),
37 params,
38 body_vars: Vec::new(),
39 body,
40 }
41}
42
43pub(super) fn ffi_name(name: &str) -> String {
46 format!("ffi_{name}")
47}
48
49fn term(t: &Term) -> Expr {
52 term_with(t, "retval")
53}
54
55pub(super) fn term_with(t: &Term, result: &str) -> Expr {
57 let sub = |t| term_with(t, result);
58 match t {
59 Term::Int(n) => Expr::Int(*n),
60 Term::Bool(b) => Expr::Bool(*b),
61 Term::Param(name) => Expr::ident(name),
62 Term::RetVal => Expr::ident(result),
63 Term::Field { base, name } => Expr::Field {
64 base: Box::new(sub(base)),
65 name: name.clone(),
66 },
67 Term::Old(inner) => sub(inner),
68 Term::Unary { op, operand } => Expr::unary((*op).into(), sub(operand)),
69 Term::Binary { op, lhs, rhs } => Expr::binary((*op).into(), sub(lhs), sub(rhs)),
70 Term::Ternary { cond, then, els } => Expr::Ternary {
71 cond: Box::new(sub(cond)),
72 then: Box::new(sub(then)),
73 els: Box::new(sub(els)),
74 },
75 }
76}
77
78pub(super) fn term_args(t: &Term, args: &[(&str, Expr)]) -> Expr {
80 let sub = |t| term_args(t, args);
81 match t {
82 Term::Param(name) => args
83 .iter()
84 .find(|(p, _)| p == name)
85 .map_or_else(|| Expr::ident(name), |(_, a)| a.clone()),
86 Term::Old(inner) => sub(inner),
87 Term::Unary { op, operand } => Expr::unary((*op).into(), sub(operand)),
88 Term::Binary { op, lhs, rhs } => Expr::binary((*op).into(), sub(lhs), sub(rhs)),
89 Term::Ternary { cond, then, els } => Expr::Ternary {
90 cond: Box::new(sub(cond)),
91 then: Box::new(sub(then)),
92 els: Box::new(sub(els)),
93 },
94 t => term(t),
95 }
96}
97
98pub(super) fn chosen(k: usize) -> String {
100 format!("fic_r{k}")
101}
102
103pub(super) struct Choice {
107 pub(super) name: String,
109 pub(super) range: (i128, i128),
111 pub(super) guard: Vec<String>,
113}
114
115impl From<TermUnOp> for UnOp {
116 fn from(op: TermUnOp) -> Self {
117 match op {
118 TermUnOp::Not => UnOp::Not,
119 TermUnOp::Neg => UnOp::Neg,
120 }
121 }
122}
123
124impl From<TermBinOp> for BinOp {
125 fn from(op: TermBinOp) -> Self {
126 match op {
127 TermBinOp::Add => BinOp::Add,
128 TermBinOp::Sub => BinOp::Sub,
129 TermBinOp::Mul => BinOp::Mul,
130 TermBinOp::Div => BinOp::Div,
131 TermBinOp::Mod => BinOp::Mod,
132 TermBinOp::Eq => BinOp::Eq,
133 TermBinOp::Ne => BinOp::Ne,
134 TermBinOp::Lt => BinOp::Lt,
135 TermBinOp::Le => BinOp::Le,
136 TermBinOp::Gt => BinOp::Gt,
137 TermBinOp::Ge => BinOp::Ge,
138 TermBinOp::And => BinOp::And,
139 TermBinOp::Or => BinOp::Or,
140 }
141 }
142}
143
144#[cfg(test)]
145mod tests {
146 use std::path::{Path, PathBuf};
147
148 use crate::ast::RawAst;
149 use crate::ccfg::build as build_ccfg;
150 use crate::foreign::contract::ContractTable;
151 use crate::foreign::extract;
152 use crate::foreign::{ForeignLang, ForeignModules};
153 use crate::frontend::{data_layer, front_end};
154 use crate::parser::parse_foreign;
155 use crate::rast::env::ast_of;
156 use crate::xta_backend::model::transpile;
157 use crate::xta_backend::xta::ProcLocalDecl;
158 use crate::xta_backend::xta::Template;
159
160 fn project(fis: &str, pd: &str, fi: &str) -> RawAst {
163 ast_of(fis, &[(pd, fi)])
164 }
165
166 fn decl_text(decls: &[ProcLocalDecl]) -> String {
169 decls
170 .iter()
171 .map(ToString::to_string)
172 .collect::<Vec<_>>()
173 .join("\n")
174 }
175
176 const SOURCE: &str = "\
178export fun 1 say_ping() { @dbg(0, 0, 0, 1); return 0; }
179export fun 1 tally(1 r) {
180 /@ requires 0 <= r && r < ROUNDS @/
181 /@ ensures retval == r + 1 @/
182 return r + 1;
183}
184export fun 1 keep_playing(1 r) {
185 /@ requires 0 <= r @/
186 /@ ensures retval == (r < ROUNDS ? 1 : 0) @/
187 return r < ROUNDS;
188}
189";
190
191 fn pancake_module() -> ForeignModules {
193 let mut foreign = ForeignModules::new();
194 foreign.insert(
195 parse_foreign(
196 SOURCE,
197 Path::new("pingpong.pnk"),
198 PathBuf::from("pingpong.pnk"),
199 ForeignLang::Pancake,
200 &[],
201 )
202 .unwrap(),
203 );
204 foreign
205 }
206
207 const PING_FIS: &str = "
208 const ROUNDS: int = 5;
209 ProtectionDomain ping(100);
210 ProtectionDomain pong(101);
211 Chan ball = ping <-> pong;
212 System = ping ||| pong;
213 ";
214
215 fn ping_template(fi: &str, with_contracts: bool) -> Template {
218 let rawast = project(PING_FIS, "ping", fi);
219 let mut foreign = pancake_module();
220 foreign.bind(&rawast);
221 let (env, tenv) = data_layer(&rawast).expect("data layer");
222 let front = front_end(&rawast, &mut foreign, env, tenv).expect("front end");
223 let contracts = if with_contracts {
224 extract(&front, &foreign).unwrap()
225 } else {
226 ContractTable::default()
227 };
228 let ccfg = build_ccfg(&front).expect("builds the ccfg");
229 let nta = transpile(&front, &ccfg, &contracts);
230 nta.templates
231 .into_iter()
232 .find(|t| t.name == "Ping")
233 .unwrap()
234 }
235
236 #[test]
237 fn pancake_contracts_become_declared_functions() {
238 const FI: &str = r#"
239import "pingpong.pnk" as io;
240rounds: uint;
241evt say_ping: io.say_ping();
242evt tally: rounds = io.tally(rounds);
243@bind(microkit.init)
244proc Init() { ball! -> Skip; }
245@bind(microkit.notified)
246proc Notified() {
247 ball? -> say_ping -> tally -> Skip;
248 [io.keep_playing(rounds) != 0] ball! -> Notified()
249 default Skip;
250}
251"#;
252 let ping = ping_template(FI, true);
253 let decls = decl_text(&ping.declarations);
254 assert!(
256 decls.contains("int ffi_tally(int r) {\n assert(((0) <= (r)) && ((r) < (ROUNDS)));\n return (r) + (1);\n}"),
257 "{decls}"
258 );
259 assert!(decls.contains("rounds = ffi_tally(rounds);"), "{decls}");
261 assert!(
262 decls.contains("void say_ping() {\n ffi_say_ping();\n}"),
263 "{decls}"
264 );
265 let guards: Vec<&str> = ping
266 .transitions
267 .iter()
268 .filter_map(|t| t.guard.as_deref())
269 .collect();
270 assert!(
275 guards.contains(&"(ffi_keep_playing(rounds)) != (0)"),
276 "{guards:?}"
277 );
278 assert!(
279 guards
280 .iter()
281 .any(|g| g.starts_with("!(") && g.contains("(ffi_keep_playing(rounds)) != (0)")),
282 "{guards:?}"
283 );
284
285 let ping = ping_template(FI, false);
287 assert!(decl_text(&ping.declarations).contains("rounds = /* tally() */ 0;"));
288 }
289
290 #[test]
293 fn effect_only_contracted_call_is_still_a_call() {
294 let ping = ping_template(
295 r#"
296import "pingpong.pnk" as io;
297evt bump: io.tally(1);
298@bind(microkit.init)
299proc Init() { Skip; }
300@bind(microkit.notified)
301proc Notified() { ball? -> bump -> Skip; }
302"#,
303 true,
304 );
305 let decls = decl_text(&ping.declarations);
306 assert!(
308 decls.contains("void bump() {\n ffi_tally(1);\n}"),
309 "{decls}"
310 );
311 assert!(!decls.contains("// tally"), "{decls}");
312 }
313
314 #[test]
316 fn dbg_is_erased() {
317 let ping = ping_template(
318 r#"
319import "pingpong.pnk" as io;
320rounds: uint;
321evt tally: { dbg("ping ", rounds); rounds = io.tally(rounds); }
322@bind(microkit.init)
323proc Init() { Skip; }
324@bind(microkit.notified)
325proc Notified() { ball? -> tally -> Skip; }
326"#,
327 true,
328 );
329 let decls = decl_text(&ping.declarations);
330 assert!(
331 decls.contains("void tally() {\n rounds = ffi_tally(rounds);\n}"),
332 "{decls}"
333 );
334 }
335}