1use std::collections::HashMap;
36use std::env;
37use std::path::{Path, PathBuf};
38use std::process::Command;
39
40use anyhow::{anyhow, bail, Result};
41use serde::{Deserialize, Serialize};
42use serde_json::Value;
43
44use super::C;
45use crate::base::FfnId;
46use crate::foreign::contract::{FnContract, Term, UnaryOp};
47use crate::foreign::{ForeignFn, ForeignLang, ForeignModule, Lift};
48
49const DEFAULT_BEHAVIOR: &str = "default!";
51
52#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct FnSpec {
55 pub name: String,
57 pub params: Vec<String>,
59 pub behaviors: Vec<Behavior>,
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct Behavior {
66 pub name: String,
68 pub requires: Vec<Clause>,
70 pub ensures: Vec<Ensures>,
72 pub assigns: Assigns,
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct Clause {
79 pub text: String,
81 pub pred: Value,
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct Ensures {
88 pub kind: String,
90 pub text: String,
92 pub pred: Value,
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
98#[serde(untagged)]
99pub enum Assigns {
100 Any(String),
102 Writes(Vec<Written>),
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct Written {
109 pub text: String,
111 pub term: Value,
113}
114
115impl FnSpec {
116 fn default_behavior(&self) -> Option<&Behavior> {
117 self.behaviors.iter().find(|b| b.name == DEFAULT_BEHAVIOR)
118 }
119}
120
121impl Lift for C {
122 fn notation(&self) -> &'static str {
123 "ACSL"
124 }
125
126 fn lift(
128 &self,
129 module: &ForeignModule,
130 functions: &[(FfnId, &str)],
131 consts: &[&str],
132 ) -> Result<HashMap<FfnId, FnContract>> {
133 if module.contracts.is_empty() {
134 return Ok(HashMap::new());
135 }
136 let specs = match specs(&module.file, &module.includes) {
137 Ok(specs) => specs,
138 Err(e) => {
139 eprintln!(
140 "warning: {}: ACSL present but Frama-C could not read it ({e}); \
141 calls into this file stay opaque in the model",
142 module.file.display()
143 );
144 return Ok(HashMap::new());
145 }
146 };
147 let mut out = HashMap::new();
148 for &(id, name) in functions {
149 let f = module.export(name).expect("a called function is exported");
150 if let Some(spec) = specs.get(name) {
151 out.insert(id, from_foreign(f, spec, consts)?);
152 }
153 }
154 Ok(out)
155 }
156}
157
158pub fn from_foreign(func: &ForeignFn, spec: &FnSpec, consts: &[&str]) -> Result<FnContract> {
169 let Some(behavior) = spec.default_behavior() else {
170 bail!(
171 "function `{}`: only named behaviours; fic reads the default behaviour",
172 func.name
173 );
174 };
175 let params: Vec<String> = func
176 .params
177 .iter()
178 .map(|p| p.name.clone().unwrap_or_default())
179 .collect();
180 let mut requires = Vec::new();
181 let mut ensures = Vec::new();
182
183 for c in &behavior.requires {
184 let t = lower_pred(&c.pred)
185 .map_err(|e| anyhow!("function `{}`: `requires {}` {e}", func.name, c.text))?;
186 check_identifiers(&func.name, &c.text, &t, ¶ms, consts)?;
187 requires.push(t);
188 }
189 for e in &behavior.ensures {
190 if e.kind != "Normal" {
193 continue;
194 }
195 let t = lower_pred(&e.pred)
196 .map_err(|err| anyhow!("function `{}`: `ensures {}` {err}", func.name, e.text))?;
197 check_identifiers(&func.name, &e.text, &t, ¶ms, consts)?;
198 ensures.push(t);
199 }
200
201 let impurity = match &behavior.assigns {
202 Assigns::Writes(w) if w.is_empty() => None,
203 Assigns::Writes(w) => Some(format!(
204 "it assigns `{}`",
205 w.iter()
206 .map(|x| x.text.as_str())
207 .collect::<Vec<_>>()
208 .join(", ")
209 )),
210 Assigns::Any(_) => Some("it has no `assigns` clause, so it may write anything".to_string()),
211 };
212
213 FnContract::from_clauses(
214 ForeignLang::C,
215 func.name.clone(),
216 params,
217 requires,
218 ensures,
219 impurity,
220 )
221}
222
223fn node(v: &Value) -> Result<&str> {
224 v.get("node")
225 .and_then(Value::as_str)
226 .ok_or_else(|| anyhow!("malformed fic-acsl JSON: a node without a `node` field"))
227}
228
229fn field<'a>(v: &'a Value, name: &str) -> Result<&'a Value> {
230 v.get(name).ok_or_else(|| {
231 let kind = node(v).unwrap_or("a node");
232 anyhow!("malformed fic-acsl JSON: `{kind}` without `{name}`")
233 })
234}
235
236fn text_field<'a>(v: &'a Value, name: &str) -> Result<&'a str> {
237 field(v, name)?
238 .as_str()
239 .ok_or_else(|| anyhow!("malformed fic-acsl JSON: `{name}` is not a string"))
240}
241
242fn lower_pred(v: &Value) -> Result<Term> {
244 Ok(match node(v)? {
245 "Ptrue" => Term::Bool(true),
246 "Pfalse" => Term::Bool(false),
247 "Prel" => {
248 let op = match text_field(v, "rel")? {
249 "Rlt" => "<",
250 "Rgt" => ">",
251 "Rle" => "<=",
252 "Rge" => ">=",
253 "Req" => "==",
254 "Rneq" => "!=",
255 other => bail!("malformed fic-acsl JSON: relation `{other}`"),
256 };
257 Term::binary(
258 op,
259 lower_term(field(v, "lhs")?)?,
260 lower_term(field(v, "rhs")?)?,
261 )
262 }
263 "Pand" => Term::binary(
264 "&&",
265 lower_pred(field(v, "lhs")?)?,
266 lower_pred(field(v, "rhs")?)?,
267 ),
268 "Por" => Term::binary(
269 "||",
270 lower_pred(field(v, "lhs")?)?,
271 lower_pred(field(v, "rhs")?)?,
272 ),
273 "Pnot" => Term::Unary {
274 op: UnaryOp::Not,
275 operand: Box::new(lower_pred(field(v, "pred")?)?),
276 },
277 "Pif" => Term::Ternary {
278 cond: Box::new(lower_cond(field(v, "cond")?)?),
279 then: Box::new(lower_pred(field(v, "then")?)?),
280 els: Box::new(lower_pred(field(v, "else")?)?),
281 },
282 "Pat" => at(text_field(v, "label")?, lower_pred(field(v, "pred")?)?)?,
283 other => return Err(unsupported(other, v)),
284 })
285}
286
287fn lower_term(v: &Value) -> Result<Term> {
289 Ok(match node(v)? {
290 "TConst" => {
291 let c = field(v, "const")?;
292 match text_field(c, "kind")? {
293 "Integer" => Term::Int(
294 text_field(c, "value")?
295 .parse()
296 .map_err(|e| anyhow!("integer constant: {e}"))?,
297 ),
298 "Boolean" => Term::Bool(
299 field(c, "value")?
300 .as_bool()
301 .ok_or_else(|| anyhow!("malformed fic-acsl JSON: Boolean value"))?,
302 ),
303 kind => bail!("uses a {kind} constant, which is outside fic's contract subset"),
304 }
305 }
306 "TLval" => {
307 let host = field(v, "host")?;
308 let base = match text_field(host, "kind")? {
309 "TVar" => Term::Param(text_field(host, "name")?.to_string()),
310 "TResult" => Term::RetVal,
311 _ => bail!("uses a memory access `*p`, which is outside fic's contract subset"),
312 };
313 let offset = field(v, "offset")?;
317 if offset.as_bool() == Some(true) {
318 bail!(
319 "uses a field or index access, which this fic-acsl build cannot describe: \
320 rebuild the plugin"
321 );
322 }
323 let offsets = offset.as_array().map(Vec::as_slice).unwrap_or_default();
324 if !offsets.is_empty() && base != Term::RetVal {
325 bail!(
326 "uses a field or index of a parameter, which is outside fic's contract subset"
327 );
328 }
329 offsets.iter().try_fold(base, |base, offset| {
330 if text_field(offset, "kind")? != "TField" {
331 bail!("uses an index access, which is outside fic's contract subset");
332 }
333 Ok(Term::Field {
334 base: Box::new(base),
335 name: text_field(offset, "name")?.to_string(),
336 })
337 })?
338 }
339 "TUnOp" => {
340 let op = match text_field(v, "op")? {
341 "Neg" => UnaryOp::Neg,
342 "LNot" => UnaryOp::Not,
343 _ => bail!("uses the bit operator `~`, which is outside fic's contract subset"),
344 };
345 Term::Unary {
346 op,
347 operand: Box::new(lower_term(field(v, "term")?)?),
348 }
349 }
350 "TBinOp" => {
351 let op = match text_field(v, "op")? {
352 "PlusA" => "+",
353 "MinusA" => "-",
354 "Mult" => "*",
355 "Div" => "/",
356 "Mod" => "%",
357 "Lt" => "<",
358 "Gt" => ">",
359 "Le" => "<=",
360 "Ge" => ">=",
361 "Eq" => "==",
362 "Ne" => "!=",
363 "LAnd" => "&&",
364 "LOr" => "||",
365 "Shiftlt" => return Err(outside("the bit operator `<<`")),
366 "Shiftrt" => return Err(outside("the bit operator `>>`")),
367 "BAnd" => return Err(outside("the bit operator `&`")),
368 "BOr" => return Err(outside("the bit operator `|`")),
369 "BXor" => return Err(outside("the bit operator `^`")),
370 _ => return Err(outside("pointer arithmetic")),
371 };
372 Term::binary(
373 op,
374 lower_term(field(v, "lhs")?)?,
375 lower_term(field(v, "rhs")?)?,
376 )
377 }
378 "Tif" => Term::Ternary {
380 cond: Box::new(lower_cond(field(v, "cond")?)?),
381 then: Box::new(lower_term(field(v, "then")?)?),
382 els: Box::new(lower_term(field(v, "else")?)?),
383 },
384 "Tat" => at(text_field(v, "label")?, lower_term(field(v, "term")?)?)?,
385 "TCast" if field(v, "implicit")?.as_bool() == Some(true) => lower_term(field(v, "term")?)?,
387 "TCast" => return Err(outside("a C cast")),
388 other => return Err(unsupported(other, v)),
389 })
390}
391
392fn lower_cond(v: &Value) -> Result<Term> {
394 if node(v)?.starts_with('P') {
395 lower_pred(v)
396 } else {
397 lower_term(v)
398 }
399}
400
401fn at(label: &str, inner: Term) -> Result<Term> {
403 match label {
404 "Old" => Ok(Term::Old(Box::new(inner))),
405 "Here" => Ok(inner),
406 other => Err(outside(&format!("the label `{other}`"))),
407 }
408}
409
410fn outside(what: &str) -> anyhow::Error {
411 anyhow!(
412 "uses {what}, which is outside fic's contract subset \
413 (arithmetic, comparisons, `! && ||`, `? :`, `\\old`, `\\result`, parameters)"
414 )
415}
416
417fn unsupported(node: &str, v: &Value) -> anyhow::Error {
419 let what = match node {
420 "Pforall" => r"the quantifier `\forall`".to_string(),
421 "Pexists" => r"the quantifier `\exists`".to_string(),
422 "Pimplies" => "implication `==>`".to_string(),
423 "Piff" => "equivalence `<==>`".to_string(),
424 "Pxor" => "exclusive or `^^`".to_string(),
425 "Papp" => "a predicate application".to_string(),
426 "Plet" | "Tlet" => r"`\let`".to_string(),
427 "Pvalid" => r"`\valid`".to_string(),
428 "Pvalid_read" => r"`\valid_read`".to_string(),
429 "Pinitialized" => r"`\initialized`".to_string(),
430 "Pseparated" => r"`\separated`".to_string(),
431 "Pfresh" | "Pallocable" | "Pfreeable" | "Pdangling" | "Pobject_pointer" => {
432 "a memory-state predicate".to_string()
433 }
434 "Tapp" => "a logic function application".to_string(),
435 "Tlambda" => "a lambda".to_string(),
436 "TSizeOf" | "TSizeOfE" | "TSizeOfStr" => "`sizeof`".to_string(),
437 "TAlignOf" | "TAlignOfE" => "`alignof`".to_string(),
438 "TAddrOf" => "address-of `&`".to_string(),
439 "TStartOf" => "an array".to_string(),
440 "Tnull" => r"`\null`".to_string(),
441 "Trange" | "Tempty_set" | "Tunion" | "Tinter" | "Tcomprehension" => "a set".to_string(),
442 "TUpdate" => r"`\with`".to_string(),
443 "Tbase_addr" | "Toffset" | "Tblock_length" => "a block-address function".to_string(),
444 other => match v.get("text").and_then(Value::as_str) {
445 Some(text) => format!("`{text}` ({other})"),
446 None => format!("`{other}`"),
447 },
448 };
449 outside(&what)
450}
451
452fn check_identifiers(
453 fn_name: &str,
454 text: &str,
455 t: &Term,
456 params: &[String],
457 consts: &[&str],
458) -> Result<()> {
459 for id in t.identifiers() {
460 if !params.iter().any(|p| p == id) && !consts.contains(&id) {
461 bail!(
462 "function `{fn_name}`: clause `{}` refers to `{id}`, which is neither a parameter \
463 nor a `.fis` constant (globals and the heap are outside fic's contract subset)",
464 text.trim()
465 );
466 }
467 }
468 Ok(())
469}
470
471#[derive(Deserialize)]
473struct Dump {
474 functions: Vec<FnSpec>,
475}
476
477fn specs(file: &Path, includes: &[PathBuf]) -> Result<HashMap<String, FnSpec>, String> {
483 match run(file, includes, env::var("FIC_ACSL_PLUGIN").ok().as_deref()) {
484 Err(e) if e.contains("already loaded") => run(file, includes, None),
486 other => other,
487 }
488}
489
490fn run(
491 file: &Path,
492 includes: &[PathBuf],
493 plugin: Option<&str>,
494) -> Result<HashMap<String, FnSpec>, String> {
495 let binary = env::var("FRAMAC").unwrap_or_else(|_| "frama-c".to_string());
496 let mut cmd = Command::new(&binary);
497 cmd.arg("-quiet").arg("-no-unicode");
498 if let Some(plugin) = plugin {
499 cmd.arg("-load-module").arg(plugin);
500 }
501 cmd.arg("-fic-acsl-json");
502 if let Some(dir) = file.parent().filter(|d| !d.as_os_str().is_empty()) {
504 cmd.arg(format!("-cpp-extra-args=-I{}", dir.display()));
505 }
506 for dir in includes {
507 cmd.arg(format!("-cpp-extra-args=-I{}", dir.display()));
508 }
509 cmd.arg("-cpp-extra-args=-std=c17");
511 cmd.arg(file);
512
513 let out = cmd
514 .output()
515 .map_err(|e| format!("could not run `{binary}`: {e}"))?;
516 let stdout = String::from_utf8_lossy(&out.stdout);
517 if !out.status.success() {
518 let log = format!("{stdout}\n{}", String::from_utf8_lossy(&out.stderr));
519 let log = log.trim();
520 if log.contains("-fic-acsl-json") && log.contains("unknown") {
521 return Err(format!(
522 "the fic-acsl plugin is not installed (see fic-acsl/README.md): {log}"
523 ));
524 }
525 return Err(log.to_string());
526 }
527 let json = stdout
529 .lines()
530 .rev()
531 .find(|l| l.trim_start().starts_with('{'))
532 .ok_or_else(|| {
533 "frama-c printed no contract JSON — is the fic-acsl plugin installed? \
534 (see fic-acsl/README.md)"
535 .to_string()
536 })?;
537 let dump: Dump = serde_json::from_str(json).map_err(|e| format!("fic-acsl JSON: {e}"))?;
538 Ok(dump
539 .functions
540 .into_iter()
541 .map(|f| (f.name.clone(), f))
542 .collect())
543}
544
545#[cfg(test)]
546#[allow(clippy::needless_pass_by_value)]
548mod tests {
549 use std::fs;
550
551 use serde_json::json;
552
553 use super::*;
554 use crate::foreign::{ForeignParam, ForeignType};
555
556 fn shape(t: &Term) -> String {
559 match t {
560 Term::Int(n) => n.to_string(),
561 Term::Bool(b) => b.to_string(),
562 Term::Param(name) => name.clone(),
563 Term::RetVal => r"\result".to_string(),
564 Term::Field { base, name } => format!("{}.{name}", shape(base)),
565 Term::Old(inner) => shape(inner),
566 Term::Unary { op, operand } => {
567 let sym = match op {
568 UnaryOp::Not => "!",
569 UnaryOp::Neg => "-",
570 };
571 format!("{sym}({})", shape(operand))
572 }
573 Term::Binary { op, lhs, rhs } => {
574 format!("({}) {} ({})", shape(lhs), op.symbol(), shape(rhs))
575 }
576 Term::Ternary { cond, then, els } => {
577 format!("({}) ? ({}) : ({})", shape(cond), shape(then), shape(els))
578 }
579 }
580 }
581
582 fn int(n: i64) -> Value {
585 json!({"node": "TConst", "const": {"kind": "Integer", "value": n.to_string()}})
586 }
587 fn var(name: &str) -> Value {
588 json!({"node": "TLval", "host": {"kind": "TVar", "name": name}, "offset": []})
589 }
590 fn result() -> Value {
591 json!({"node": "TLval", "host": {"kind": "TResult"}, "offset": []})
592 }
593 fn promote(t: Value) -> Value {
594 json!({"node": "TCast", "implicit": true, "term": t})
595 }
596 fn old(t: Value) -> Value {
597 json!({"node": "Tat", "label": "Old", "term": t})
598 }
599 fn rel(r: &str, a: Value, b: Value) -> Value {
600 json!({"node": "Prel", "rel": r, "lhs": a, "rhs": b})
601 }
602 fn binop(op: &str, a: Value, b: Value) -> Value {
603 json!({"node": "TBinOp", "op": op, "lhs": a, "rhs": b})
604 }
605 fn clause(text: &str, pred: Value) -> Clause {
606 Clause {
607 text: text.into(),
608 pred,
609 }
610 }
611 fn ensures(text: &str, pred: Value) -> Ensures {
612 Ensures {
613 kind: "Normal".into(),
614 text: text.into(),
615 pred,
616 }
617 }
618 fn nothing() -> Assigns {
619 Assigns::Writes(Vec::new())
620 }
621
622 type Case = (ForeignFn, FnSpec);
623
624 fn func(name: &str, params: &[&str], behavior: Behavior) -> Case {
625 (
626 ForeignFn {
627 name: name.to_string(),
628 params: params
629 .iter()
630 .map(|p| ForeignParam {
631 name: Some((*p).to_string()),
632 ty: ForeignType::Scalar("int".to_string()),
633 })
634 .collect(),
635 ret: ForeignType::Scalar("int".to_string()),
636 variadic: false,
637 span: 0..0,
638 },
639 FnSpec {
640 name: name.to_string(),
641 params: params.iter().map(|p| (*p).to_string()).collect(),
642 behaviors: vec![behavior],
643 },
644 )
645 }
646
647 fn lift(case: &Case, consts: &[&str]) -> Result<FnContract> {
648 from_foreign(&case.0, &case.1, consts)
649 }
650
651 fn default(requires: Vec<Clause>, ensures: Vec<Ensures>, assigns: Assigns) -> Behavior {
652 Behavior {
653 name: DEFAULT_BEHAVIOR.into(),
654 requires,
655 ensures,
656 assigns,
657 }
658 }
659
660 fn tally() -> Case {
662 func(
663 "tally",
664 &["r"],
665 default(
666 vec![clause(
667 "0 <= r < 5",
668 json!({"node": "Pand",
669 "lhs": rel("Rle", int(0), promote(var("r"))),
670 "rhs": rel("Rlt", promote(var("r")), int(5))}),
671 )],
672 vec![ensures(
673 r"\result == \old(r) + 1",
674 rel(
675 "Req",
676 promote(result()),
677 binop("PlusA", promote(old(var("r"))), int(1)),
678 ),
679 )],
680 nothing(),
681 ),
682 )
683 }
684
685 #[test]
686 fn frama_c_normalised_clauses_lower_to_the_subset() {
687 let c = lift(&tally(), &[]).unwrap();
688 assert_eq!(shape(&c.requires[0]), "((0) <= (r)) && ((r) < (5))");
691 assert_eq!(shape(c.retval.as_ref().unwrap()), "(r) + (1)");
692 assert!(c.impurity.is_none(), "assigns \\nothing is pure");
693 }
694
695 #[test]
696 fn a_conditional_and_the_logical_operators_lower() {
697 let keep = func(
698 "keep_playing",
699 &["r"],
700 default(
701 Vec::new(),
702 vec![ensures(
703 r"\result == (\old(r) < 5 ? 1 : 0)",
704 rel(
705 "Req",
706 promote(result()),
707 json!({"node": "Tif",
708 "cond": binop("Lt", promote(old(var("r"))), int(5)),
709 "then": int(1), "else": int(0)}),
710 ),
711 )],
712 nothing(),
713 ),
714 );
715 let c = lift(&keep, &[]).unwrap();
716 assert_eq!(shape(c.retval.as_ref().unwrap()), "((r) < (5)) ? (1) : (0)");
717
718 let t = lower_term(&json!({"node": "Tif",
720 "cond": rel("Rlt", promote(var("r")), int(5)),
721 "then": int(1), "else": int(0)}))
722 .unwrap();
723 assert_eq!(shape(&t), "((r) < (5)) ? (1) : (0)");
724
725 let t = lower_pred(&json!({"node": "Pnot", "pred":
726 json!({"node": "Por",
727 "lhs": rel("Req", var("x"), int(1)),
728 "rhs": json!({"node": "Pif", "cond": var("c"),
729 "then": {"node": "Ptrue"}, "else": {"node": "Pfalse"}})})}))
730 .unwrap();
731 assert_eq!(shape(&t), "!(((x) == (1)) || ((c) ? (true) : (false)))");
732 let t = lower_term(&json!({"node": "TUnOp", "op": "Neg", "term": var("r")})).unwrap();
733 assert_eq!(shape(&t), "-(r)");
734 }
735
736 #[test]
737 fn a_range_leaves_the_return_free_and_no_assigns_is_impure() {
738 let poll = func(
739 "poll",
740 &[],
741 default(
742 Vec::new(),
743 vec![ensures(
744 r"0 <= \result <= 1",
745 json!({"node": "Pand",
746 "lhs": rel("Rle", int(0), promote(result())),
747 "rhs": rel("Rle", promote(result()), int(1))}),
748 )],
749 Assigns::Any("any".into()),
750 ),
751 );
752 let c = lift(&poll, &[]).unwrap();
753 assert!(c.retval.is_none());
754 assert_eq!(
755 c.impurity.as_deref(),
756 Some("it has no `assigns` clause, so it may write anything")
757 );
758 }
759
760 #[test]
763 fn a_field_of_the_result_is_read() {
764 let field =
765 |host: Value, offset: Value| json!({"node": "TLval", "host": host, "offset": offset});
766 let origin = json!([{"kind": "TField", "name": "origin"}]);
767 assert_eq!(
768 lower_term(&field(json!({"kind": "TResult"}), origin.clone())).unwrap(),
769 Term::Field {
770 base: Box::new(Term::RetVal),
771 name: "origin".into()
772 }
773 );
774 let of_param = field(json!({"kind": "TVar", "name": "f"}), origin);
775 let err = lower_term(&of_param).unwrap_err().to_string();
776 assert!(err.contains("a field or index of a parameter"), "{err}");
777 let old = lower_term(&field(json!({"kind": "TResult"}), json!(true))).unwrap_err();
778 assert!(old.to_string().contains("rebuild the plugin"), "{old}");
779 let index = json!([{"kind": "TIndex", "term": int(0)}]);
780 let err = lower_term(&field(json!({"kind": "TResult"}), index))
781 .unwrap_err()
782 .to_string();
783 assert!(err.contains("an index access"), "{err}");
784 }
785
786 #[test]
787 fn purity_comes_from_assigns() {
788 let f = func(
789 "bump",
790 &[],
791 default(
792 Vec::new(),
793 Vec::new(),
794 Assigns::Writes(vec![Written {
795 text: "count".into(),
796 term: var("count"),
797 }]),
798 ),
799 );
800 let c = lift(&f, &[]).unwrap();
801 assert_eq!(c.impurity.as_deref(), Some("it assigns `count`"));
802 }
803
804 #[test]
805 fn constructs_outside_the_subset_are_named() {
806 let err = |pred: Value| {
807 lift(
808 &func(
809 "f",
810 &["p"],
811 default(vec![clause("…", pred)], Vec::new(), nothing()),
812 ),
813 &[],
814 )
815 .unwrap_err()
816 .to_string()
817 };
818 assert!(err(json!({"node": "Pvalid", "text": r"\valid(p)"})).contains(r"`\valid`"));
819 assert!(err(
820 json!({"node": "Pimplies", "lhs": {"node": "Ptrue"}, "rhs": {"node": "Ptrue"}})
821 )
822 .contains("implication"));
823 assert!(err(json!({"node": "Pforall", "text": "…"})).contains(r"\forall"));
824 let deref =
825 json!({"node": "TLval", "host": {"kind": "TMem", "term": var("p")}, "offset": false});
826 assert!(err(rel("Req", result(), deref)).contains("memory access"));
827 assert!(
828 err(rel("Req", result(), binop("BAnd", var("p"), int(1)))).contains("bit operator `&`")
829 );
830 assert!(err(rel(
831 "Req",
832 result(),
833 json!({"node": "TCast", "implicit": false, "term": var("p")})
834 ))
835 .contains("a C cast"));
836 let novel = err(json!({"node": "Pbrand_new", "text": "something"}));
837 assert!(novel.contains("`something` (Pbrand_new)"), "{novel}");
838 assert!(novel.contains("`requires …`"), "{novel}");
840 }
841
842 #[test]
843 fn identifiers_are_parameters_or_fis_constants() {
844 let f = |rhs: &str| {
845 func(
846 "f",
847 &["r"],
848 default(
849 Vec::new(),
850 vec![ensures("…", rel("Req", result(), var(rhs)))],
851 nothing(),
852 ),
853 )
854 };
855 let err = lift(&f("g"), &[]).unwrap_err().to_string();
856 assert!(err.contains("`g`, which is neither a parameter"), "{err}");
857 lift(&f("ROUNDS"), &["ROUNDS"]).unwrap();
858 }
859
860 #[test]
861 fn only_the_default_behaviour_is_read() {
862 let mut f = tally();
863 f.1.behaviors[0].name = "fast".into();
864 let err = lift(&f, &[]).unwrap_err().to_string();
865 assert!(err.contains("only named behaviours"), "{err}");
866
867 let mut f = tally();
868 f.1.behaviors[0].ensures[0].kind = "Exits".into();
869 let c = lift(&f, &[]).unwrap();
870 assert!(
871 c.retval.is_none(),
872 "an `exits` post-condition is not a return value"
873 );
874 }
875
876 #[test]
877 fn the_plugins_json_deserialises() {
878 #[derive(Deserialize)]
879 struct Dump {
880 functions: Vec<FnSpec>,
881 }
882 let text = r#"{"functions":[{"name":"tally","params":["r"],"behaviors":[{"name":"default!",
883 "requires":[{"text":"0 <= r < 5","pred":{"node":"Ptrue"}}],
884 "ensures":[{"kind":"Normal","text":"x","pred":{"node":"Ptrue"}}],
885 "assigns":[]}]},
886 {"name":"poll","params":[],"behaviors":[{"name":"default!","requires":[],"ensures":[],"assigns":"any"}]}]}"#;
887 let d: Dump = serde_json::from_str(text).unwrap();
888 assert_eq!(d.functions.len(), 2);
889 assert!(
890 matches!(d.functions[0].behaviors[0].assigns, Assigns::Writes(ref w) if w.is_empty())
891 );
892 assert!(matches!(
893 d.functions[1].behaviors[0].assigns,
894 Assigns::Any(_)
895 ));
896 }
897
898 const HEADER: &str = "#define N 5\n\
899 /*@ requires 0 <= r < N;\n\
900 @ ensures \\result == r + 1;\n\
901 @ assigns \\nothing;\n\
902 @*/\n\
903 int tally(int r);\n\
904 /*@ ensures 0 <= \\result <= 1; */\n\
905 int poll(void);\n\
906 void plain(void);\n";
907
908 #[test]
910 fn frama_c_hands_over_its_typed_specifications() {
911 let dir = env::temp_dir().join("fic-framac-test");
912 fs::create_dir_all(&dir).expect("temp dir");
913 let header = dir.join("io.h");
914 fs::write(&header, HEADER).expect("write header");
915
916 let found = match specs(&header, &[]) {
917 Ok(found) => found,
918 Err(e) if e.contains("could not run") || e.contains("fic-acsl plugin") => {
919 eprintln!("skipping: {e}");
920 return;
921 }
922 Err(e) => panic!("frama-c failed: {e}"),
923 };
924 assert!(!found.contains_key("plain"), "no specification, no entry");
925
926 let tally = found.get("tally").expect("tally has a specification");
927 assert_eq!(tally.params, ["r"]);
928 let b = &tally.behaviors[0];
930 assert_eq!(b.requires[0].text, "0 <= r < 5");
931 assert_eq!(b.ensures[0].text, r"\result == \old(r) + 1");
932 assert!(matches!(&b.assigns, Assigns::Writes(w) if w.is_empty()));
933
934 let contract = from_foreign(
935 &ForeignFn {
936 name: "tally".into(),
937 params: vec![ForeignParam {
938 name: Some("r".into()),
939 ty: ForeignType::Scalar("int".into()),
940 }],
941 ret: ForeignType::Scalar("int".into()),
942 variadic: false,
943 span: 0..0,
944 },
945 tally,
946 &[],
947 )
948 .expect("the typed specification is in fic's subset");
949 assert!(contract.retval.is_some(), "a deterministic return value");
950 assert!(contract.impurity.is_none(), "assigns \\nothing is pure");
951
952 let poll = found.get("poll").expect("poll has a specification");
953 assert_eq!(poll.behaviors[0].ensures.len(), 1);
954 }
955}