LTL Formula with Aorai - frama-c

I am trying to find an example about the LTL operator _ F_ which means fatally with Aorai but i can't figure out exactly what this operator aims and there are no examples in the repository "tests" of Aorai
For example, i wrote this formula
CALL(main) && _X_ (CALL(a) && _X_(RETURN(a) && _F_ (RETURN(b) && _X_ (RETURN(main)) ) ))
which says that in my program main, i have to call the function a() and after this i don't understand what happens with the operator fatally but it seems that it takes and accepts whatever we call after the function a() with no warning or error from Aorai. If anybody could help me or could give a right example about it.
For example, i have this program below which i would like to test with this formula above
void a()
{}
void b()
{}
int main()
{ a();
a();
b();
b();
a();
return 0;}
I type frama-c -aorai-ltl test.ltl test.c
Normally, there should be an error or warning from Aorai. No?

Your question is more about temporal logic than Frama-C/Aorai itself, but the meaning of this formula is that main must call a, then do whatever it wants, before calling b and returning just after that.
NB: note that Aorai only traces call and return events, so that e.g. "just after" here means that main cannot not call any function after its last call to b, but can still perform some actions, such as x++;.
Update
I've run your complete example on Frama-C. Indeed a post-condition is missing in the contract for main generated by Aorai, namely that the state of the generated automaton at the end of main (T0_S4) is supposed to be accepting, which is not the case here. This is a bug. If you write explicitely an equivalent automaton in the ya language, as
%init: S0;
%accept: Sf;
S0: { CALL(main) } -> S1;
S1: { [ a() ] } -> S2;
S2: { RETURN(b) } -> S3
| other -> S2;
S3: { RETURN(main) } -> Sf;
Sf: -> Sf;
Then the generated contract for main contains a requires \false;, which indeed indicates that the function is not conforming to the automaton, and Aoraï warns about that.
Please note however that in the general case, Aoraï will not emit any warning. It generates contracts that, if fulfilled, imply that the whole program is conforming to the automaton. The proof of the contract must be done by another plugin (e.g. WP or Value Analysis)

Related

Why is returning a cloned ndarray throwing an overflow error(exceeded max recursion limit)?

I'm currently trying to write a function that is generally equivalent to numpy's tile. Currently each time I try to return a (altered or unaltered) clone of the input array, I get a warning about an overflow, and cargo prompts me to increase the recursion limit. however this function isn't recursive, so I'm assuming its happening somewhere in the implementation.
here is the stripped down function, (full version):
pub fn tile<A, D1, D2>(arr: &Array<A, D1>, reps: Vec<usize>) -> Array<A, D2>
where
A: Clone,
D1: Dimension,
D2: Dimension,
{
let num_of_reps = reps.len();
//just clone the array if reps is all ones
let mut res = arr.clone();
let bail_flag = true;
for &x in reps.iter() {
if x != 1 {
bail_flag = false;
}
}
if bail_flag {
let mut res_dim = res.shape().to_owned();
_new_shape(num_of_reps, res.ndim(), &mut res_dim);
res.to_shape(res_dim);
return res;
}
...
//otherwise do extra work
...
return res.reshape(shape_out);
}
this is the actual error I'm getting on returning res:
overflow evaluating the requirement `&ArrayBase<_, _>: Neg`
consider increasing the recursion limit by adding a `#![recursion_limit = "1024"]` attribute to your crate (`mfcc_2`)
required because of the requirements on the impl of `Neg` for `&ArrayBase<_, _>`
511 redundant requirements hidden
required because of the requirements on the impl of `Neg` for `&ArrayBase<OwnedRepr<A>, D1>`rustcE0275
I looked at the implementation of Neg in ndarray, it doesn't seem to be recursive, so I'm a little confused as to what is going on.
p.s. I'm aware there are other errors in this code, as those appeared after I switched from A to f64(the actual type I plan on using the function with), but those are mostly trivial to fix. Still if you have suggestions on any error you see I appreciate them nonetheless.

Java 8 Functional Programming - Passing function along with its argument

I have a question on Java 8 Functional Programming. I am trying to achieve something using functional programming, and need some guidance on how to do it.
My requirement is to wrap every method execution inside timer function which times the method execution. Here's the example of timer function and 2 functions I need to time.
timerMethod(String timerName, Function func){
timer.start(timerName)
func.apply()
timer.stop()
}
functionA(String arg1, String arg2)
functionB(int arg1, intArg2, String ...arg3)
I am trying to pass functionA & functionB to timerMethod, but functionA & functionB expects different number & type of arguments for execution.
Any ideas how can I achieve it.
Thanks !!
you should separate it into two things by Separation of Concerns to make your code easy to use and maintaining. one is timing, another is invoking, for example:
// v--- invoking occurs in request-time
R1 result1 = timerMethod("functionA", () -> functionA("foo", "bar"));
R2 result2 = timerMethod("functionB", () -> functionB(1, 2, "foo", "bar"));
// the timerMethod only calculate the timing-cost
<T> T timerMethod(String timerName, Supplier<T> func) {
timer.start(timerName);
try {
return func.get();
} finally {
timer.stop();
}
}
IF you want to return a functional interface rather than the result of that method, you can done it as below:
Supplier<R1> timingFunctionA =timerMethod("A", ()-> functionA("foo", "bar"));
Supplier<R2> timingFunctionB =timerMethod("B", ()-> functionB(1, 2, "foo", "bar"));
<T> Supplier<T> timerMethod(String timerName, Supplier<T> func) {
// v--- calculate the timing-cost when the wrapper function is invoked
return () -> {
timer.start(timerName);
try {
return func.get();
} finally {
timer.stop();
}
};
}
Notes
IF the return type of all of your functions is void, you can replacing Supplier with Runnable and then make the timerMethod's return type to void & remove return keyword from timerMethod.
IF some of your functions will be throws a checked exception, you can replacing Supplier with Callable & invoke Callable#call instead.
Don't hold onto the arguments and then pass them at the last moment. Pass them immediately, but delay calling the function by wrapping it with another function:
Producer<?> f1 =
() -> functionA(arg1, arg2);
Producer<?> f2 =
() -> functionB(arg1, arg2, arg3);
Here, I'm wrapping each function call in a lambda (() ->...) that takes 0 arguments. Then, just call them later with no arguments:
f1()
f2()
This forms a closure over the arguments that you supplied in the lambda, which allows you to use the variables later, even though normally they would have been GC'd for going out of scope.
Note, I have a ? as the type of the Producer since I don't know what type your functions return. Change the ? to the return type of each function.
Introduction
The other answers show how to use a closure to capture the arguments of your function, no matter its number. This is a nice approach and it's very useful, if you know the arguments in advance, so that they can be captured.
Here I'd like to show two other approaches that don't require you to know the arguments in advance...
If you think it in an abstract way, there are no such things as functions with multiple arguments. Functions either receive one set of values (aka a tuple), or they receive one single argument and return another function that receives another single argument, which in turn returns another one-argument function that returns... etc, with the last function of the sequence returning an actual result (aka currying).
Methods in Java might have multiple arguments, though. So the challenge is to build functions that always receive one single argument (either by means of tuples or currying), but that actually invoke methods that receive multiple arguments.
Approach #1: Tuples
So the first approach is to use a Tuple helper class and have your function receive one tuple, either a Tuple2 or Tuple3:
So, the functionA of your example might receive one single Tuple2<String, String> as an argument:
Function<Tuple2<String, String>, SomeReturnType> functionA = tuple ->
functionA(tuple.getFirst(), tuple.getSecond());
And you could invoke it as follows:
SomeReturnType resultA = functionA.apply(Tuple2.of("a", "b"));
Now, in order to decorate the functionA with your timerMethod method, you'd need to do a few modifications:
static <T, R> Function<T, R> timerMethod(
String timerName,
Function<? super T, ? extends R> func){
return t -> {
timer.start(timerName);
R result = func.apply(t);
timer.stop();
return result;
};
}
Please note that you should use a try/finally block to make your code more robust, as shown in holi-java's answer.
Here's how you might use your timerMethod method for functionA:
Function<Tuple2<String, String>, SomeReturnType> timedFunctionA = timerMethod(
"timerA",
tuple -> functionA(tuple.getFirst(), tuple.getSecond());
And you can invoke timedFunctionA as any other function, passing it the arguments now, at invocation time:
SomeReturnType resultA = timedFunctionA.apply(Tuple2.of("a", "b"));
You can take a similar approach with the functionB of your example, except that you'd need to use a Tuple3<Integer, Integer, String[]> for the argument (taking care of the varargs arguments).
The downside of this approach is that you need to create many Tuple classes, i.e. Tuple2, Tuple3, Tuple4, etc, because Java lacks built-in support for tuples.
Approach #2: Currying
The other approach is to use a technique called currying, i.e. functions that accept one single argument and return another function that accepts another single argument, etc, with the last function of the sequence returning the actual result.
Here's how to create a currified function for your 2-argument method functionA:
Function<String, Function<String, SomeReturnType>> currifiedFunctionA =
arg1 -> arg2 -> functionA(arg1, arg2);
Invoke it as follows:
SomeReturnType result = currifiedFunctionA.apply("a").apply("b");
If you want to decorate currifiedFunctionA with the timerMethod method defined above, you can do as follows:
Function<String, Function<String, SomeReturnType>> timedCurrifiedFunctionA =
arg1 -> timerMethod("timerCurryA", arg2 -> functionA(arg1, arg2));
Then, invoke timedCurrifiedFunctionA exactly as you'd do with any currified function:
SomeReturnType result = timedCurrifiedFunctionA.apply("a").apply("b");
Please note that you only need to decorate the last function of the sequence, i.e. the one that makes the actual call to the method, which is what we want to measure.
For the method functionB of your example, you can take a similar approach, except that the type of the currified function would now be:
Function<Integer, Function<Integer, Function<String[], SomeResultType>>>
which is quite cumbersome, to say the least. So this is the downside of currified functions in Java: the syntax to express their type. On the other hand, currified functions are very handy to work with and allow you to apply several functional programming techniques without needing to write helper classes.

Why does asserting on the result of Deref::deref fail with a type mismatch?

The following is the Deref example from The Rust Programming Language except I've added another assertion.
Why does the assert_eq with the deref also equal 'a'? Why do I need a * once I've manually called deref?
use std::ops::Deref;
struct DerefExample<T> {
value: T,
}
impl<T> Deref for DerefExample<T> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
fn main() {
let x = DerefExample { value: 'a' };
assert_eq!('a', *x.deref()); // this is true
// assert_eq!('a', x.deref()); // this is a compile error
assert_eq!('a', *x); // this is also true
println!("ok");
}
If I uncomment the line, I get this error:
error[E0308]: mismatched types
--> src/main.rs:18:5
|
18 | assert_eq!('a', x.deref());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected char, found &char
|
= note: expected type `char`
found type `&char`
= help: here are some functions which might fulfill your needs:
- .to_ascii_lowercase()
- .to_ascii_uppercase()
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
First, let's spell out the generic types for your specific example: 'a' is char, so we have:
impl Deref for DerefExample<char> {
type Target = char;
fn deref(&self) -> &char {
&self.value
}
}
Notably, the return type of deref is a reference to a char. Thus it shouldn't be surprising that, when you use just x.deref(), the result is a &char rather than a char. Remember, at that point deref is just another normal method — it's just implicitly invoked as part of some language-provided special syntax. *x, for example, will call deref and dereference the result, when applicable. x.char_method() and fn_taking_char(&x) will also call deref some number of times and then do something further with the result.
Why does deref return a reference to begin with, you ask? Isn't that circular? Well, no, it isn't circular: it reduces library-defined smart pointers to the built-in type &T which the compiler already knows how to dereference. By returning a reference instead of a value, you avoid a copy/move (which may not always be possible!) and allow &*x (or &x when it's coerced) to refer to the actual char that DerefExample holds rather than a temporary copy.
See also:
Why is the return type of Deref::deref itself a reference?

Weird behaviour with struct constructors

I've written a basic Node struct in D, designed to be used as a part of a tree-like structure. The code is as follows:
import std.algorithm: min;
alias Number = size_t;
struct Node {
private {
Node* left, right, parent;
Number val;
}
this(Number n) {val = n;}
this(ref Node u, ref Node v) {
this.left = &u;
this.right = &v;
val = min(u.val, v.val);
u.parent = &this;
v.parent = &this;
}
}
Now, I wrote a simple function which is supposed to give me a Node (meaning a whole tree) with the argument array providing the leaves, as follows.
alias Number = size_t;
Node make_tree (Number[] nums) {
if (nums.length == 1) {
return Node(nums[0]);
} else {
Number half = nums.length/2;
return Node(make_tree(nums[0..half]), make_tree(nums[half..$]));
}
}
Now, when I try to run it through dmd, I get the following error message:
Error: constructor Node.this (ulong n) is not callable using argument types (Node, Node)
This makes no sense to me - why is it trying to call a one-argument constructor when given two arguments?
The problem has nothing to do with constructors. It has to do with passing by ref. The constructor that you're trying to use
this(ref Node u, ref Node v) {...}
accepts its arguments by ref. That means that they must be lvalues (i.e. something that can be on the left-hand side of an assignment). But you're passing it the result of a function call which does not return by ref (so, it's returning a temporary, which is an rvalue - something that can go on the right-hand side of an assignment but not the left). So, what you're trying to do is illegal. Now, the error message isn't great, since it's giving an error with regards to the first constructor rather than the second, but regardless, you don't have a constructor which matches what you're trying to do. At the moment, I can think of 3 options:
Get rid of the ref on the constructor's parameters. If you're only going to be passing it the result of a function call like you're doing now, having it accept ref doesn't help you anyway. The returned value will be moved into the function's parameter, so no copy will take place, and ref isn't buying you anything. Certainly, assigning the return values to local variables so that you can pass them to the constructor as it's currently written would lose you something, since then you'd be making unnecessary copies.
Overload the constructor so that it accepts either ref or non-ref. e.g.
void foo(ref Bar b) { ... }
void foo(Bar b) { foo(b); } //this calls the other foo
In general, this works reasonably well when you have one parameter, but it would be a bit annoying here, because you end up with an exponential explosion of function signatures as you add parameters. So, for your constructor, you'd end up with
this(ref Node u, ref Node v) {...}
this(ref Node u, Node v) { this(u, v); }
this(Node u, ref Node v) { this(u, v); }
this(Node u, Node v) { this(u, v); }
And if you added a 3rd parameter, you'd end up with eight overloads. So, it really doesn't scale beyond a single parameter.
Templatize the constructor and use auto ref. This essentially does what #2 does, but you only have to write the function once:
this()(auto ref Node u, auto ref Node v) {...}
This will then generate a copy of the function to match the arguments given (up to 4 different versions of it with the full function body in each rather than 3 of them just forwarding to the 4th one), but you only had to write it once. And in this particular case, it's probably reasonable to templatize the function, since you're dealing with a struct. If Node were a class though, it might not make sense, since templated functions can't be virtual.
So, if you really want to be able to pass by ref, then in this particular case, you should probably go with #3 and templatize the constructor and use auto ref. However, personally, I wouldn't bother. I'd just go with #1. Your usage pattern here wouldn't get anything from auto ref, since you're always passing it two rvalues, and your Node struct isn't exactly huge anyway, so while you obviously wouldn't want to copy it if you don't need to, copying an lvalue to pass it to the constructor probably wouldn't matter much unless you were doing it a lot. But again, you're only going to end up with a copy if you pass it an lvalue, since an rvalue can be moved rather than copied, and you're only passing it rvalues right now (at least with the code shown here). So, unless you're doing something different with that constructor which would involve passing it lvalues, there's no point in worrying about lvalues - or about the Nodes being copied when they're returned from a function and passed into the constructor (since that's a move, not a copy). As such, just removing the refs would be the best choice.

Go Syntax of calling a function with pointer receiver

In Go, if I define a function with pointer as the receiver, shouldn't it allow call to the function from a pointer only? Why is it ok to call this function from the value itself and have the same effect.
For example, in following program: m1.reset() & m2.reset() have the same effect. Even though m1 is a value and m2 is a pointer.
I'm a bit confused as there are two ways of doing the same thing and am not sure which one to follow. Though most of the code follows the convention of calling the function using pointer field. Am I missing something?
package main
import "fmt"
type MyStruct struct {
X int
}
func (m *MyStruct) reset() {
m.X = 0
}
func main() {
m1 := MyStruct{1}
m2 := &MyStruct{1}
fmt.Println(m1.X)
fmt.Println(m2.X)
m1.reset()
m2.reset()
fmt.Println(m1.X)
fmt.Println(m2.X)
}
#jnml offers the perfect doc spec explanation, but I wanted to add a code example based on yours. I think your focus should be less about "Why are there two ways to do the same thing" and more about when to use one vs the other. A method which has a pointer as the receiver has the ability to modify the values of that receiver, while a method which has a value as the receiver cannot. This is because the methods receive a copy of the receiver. When you get a copy of a pointer, you can still modify its value. When you receive a copy of the value, changes you make in that method only change the copy, and never the original:
package main
import "fmt"
type MyStruct struct {
X int
}
func (m *MyStruct) resetPtr() {
m.X = 0
}
func (m MyStruct) resetValue() {
m.X = 0
}
func main() {
m1 := MyStruct{1}
m2 := &MyStruct{1}
fmt.Println("Original Values:", m1.X, m2.X)
m1.resetPtr()
m2.resetPtr()
fmt.Println("After resetPtr():", m1.X, m2.X)
m1 = MyStruct{1}
m2 = &MyStruct{1}
m1.resetValue()
m2.resetValue()
fmt.Println("After resetValue():", m1.X, m2.X)
}
Output
Original Values: 1 1
After resetPtr(): 0 0
After resetValue(): 1 1
You can see that the way you access these variables isn't really the issue. Its more about what you can do with them inside of the method, and, how they are passed as arguments to other functions or methods (being copied).
Specs says:
The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T (that is, it also contains the method set of T).
The next piece of necessary info about method calls says:
A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m().
Put the two above things together and you get the behavior you see.
A short explanation is that the Go compiler behind the scenes automatically converts:
m1.reset()
m2.reset()
into:
(&m1).reset()
m2.reset()

Resources