KeY struggles to handle ternary operator - key-formal-verification

I am playing around with KeY (https://www.key-project.org) for a teaching project.
On one hand I was happy that KeY easily proves correctness of the following jml annotated java code
/*# ensures ((\result == a) || (\result == b));
# ensures ((\result >= a) && (\result >= b));
*/
public int max(int a, int b) {
if(a <= b)
return b;
else
return a;
}
but on the other hand I was surprisingly not enable to prove correctness of the following equivalent program
/*# ensures ((\result == a) || (\result == b));
# ensures ((\result >= a) && (\result >= b));
*/
public int max(int a, int b) {
return (a <= b) ? b : a;
}
Does somebody know whether I am missing something?

Thanks for checking out KeY.
The stated examples verify automatically in no time with KeY 2.6.3 on my PC.
KeY has a number of settings upon which the verification engine depends. Perhaps some of these settings make KeY fail.
You should press the button "Choose Predef" from the "Proof Search Strategy" panel and
try again. It should work then.
You might also consider removing the directory ".key" in your home
directory to fully reset the settings of KeY. Perhaps some settings
prevents the tool from succeeding.
Hope this helps!

Related

Conditional Statement with Decision variables and Multiple relations

This is from CPLEX.
I tried doing this but getting no results. Basically my model need a forall statement with these two conditions using decision variables and multiple relations under that. All the equality constraints. Can anyone explain what is the problem in my syntax.
Error : Function operator<(dvar float+,float) not available in context CPLEX.
Some of the screenshots and actual equation from the document is provided alongwith the problem.
Regards,
Debtirthaenter image description here
// code from the model.
enter image description here
forall (a in A, j in Ji[a], n in N: j==jbreak)
{Ts[a][j][n] < tbreak && Tf[a][j][n] > tbreak} => (yvr1[j][n] == yv[j][n]);// && wvr1[a][n] == wv[a][n] && Balr1[a][j][n] == Bal[a][j][n] && Tsr1[a][j][n] == Ts[a][j][n] &&Tfr1[a][j][n] == Tf[a][j][n]);
forall (b in B: b==jbreak,i in Ij[b], n in N) ctTBRD[i][b][n]:
Tsr1[i][b][n] >= tbreak + tmaint;
}
strict inequality is not allowed so can you change
Tf[a][j][n] > tbreak
into
Tf[a][j][n] >= tbreak+1
?
Expanding on Alex's answer: the problem is indeed that strict inequality is not supported. However, Alex's solution will only work if tbreak is an integer variable. According to your error message, tbreak is a float+ variable, though. So the fix should be something like this:
Ts[a][j][n] <= tbreak - eps
where eps is a small constant, like 1e-6.
However, working with these tolerances is always a bit shaky, so you may want to double-check whether you can get around this. For example, by making tbreak an integer variable or by reverting the condition so that a strict less-than becomes a greater-than-or-equal (not sure this can be done but it is worth thinking about).

Never claim does not work in promela model

Consider this simple PROMELA model:
#define p (x!=4)
int x = 0;
init {
do
:: x < 10 ->
x++;
od
}
I wanted to verify this model with this simple claim, which was generated by using spin -f:
never { /* []p */
accept_init:
T0_init:
do
:: ((p)) -> goto T0_init
od;
}
However, the verification using
spin -a model.pml
cc -o pan pan.c
./pan
yields no result. Trying the -a option also does not deliver results.
Any random simulation shows, that obviously p is false at some point, so why does the never claim not work, despite I generated it with spin?
Am I missing something fundamental?
If you want to check []p, you will need to construct a never claim for ![]p.
From the reference:
To translate an LTL formula into a never claim, we have to consider first whether the formula expresses a positive or a negative property. A positive property expresses a good behavior that we would like our system to have. A negative property expresses a bad behavior that we claim the system does not have. A never claim is normally only used to formalize negative properties (behaviors that should never happen), which means that positive properties must be negated before they are translated into a claim.
put the claim in the source code (say, check.pml)
int x = 0;
init {
do
:: x < 10 ->
x++;
od
}
ltl { [] (x != 4) }
then
spin -a check.pml
cc pan.c -o pan
./pan -a
this gives
pan:1: assertion violated !( !((x!=4))) (at depth 16)
pan: wrote check.pml.trail
you can watch the trail with
./pan -r -v
IMHO, using an extra tool to construct the automaton from the claim is terribly inconvenient and often confusing.

Is it possible to create a OR test with only IFs and equality tests?

I'm working with a templating language that is constrained in its ability to handle conditionals. I have IFs and I can test for truth.
I know that I can emulate if A && B if I use:
IF A
IF B
// A && B here
END IF
END IF
But is there a way that I can emulate an OR? Asking around my colleagues, nobody can think of a way. Is there a way to demonstrate that it is or is not possible?
EDIT
I could do it this way:
IF A
IF !B
// A && !B here
END IF
IF B
// (A && B + !A && B) here
END IF
This simplifies to A || B and only runs one of the blocks of code
You can do it you use an extra variable. Duplicating the code doesn't work, because then it runs twice if they're both true.
AorB=false
if A; then AorB=true; fi
if B; then AorB=true; fi
if AorB; then
// A || B
fi
Also note that our conditionals are testing for truth, not for equality. Equality is a binary operator, like A == B. You should write it as NOT(A == 0) if you want to use only equality tests.

SPIN: Visit statements infinitely often

I'm wondering whether it's possible to verify an LTL property in a program with a fairness constraint that states that multiple statements must be executed infinitely often.
E.g.:
bool no_flip;
bool flag;
active[1] proctype node()
{
do
:: skip -> progress00: no_flip = 1
:: skip -> progress01: flag = 1
:: !no_flip -> flag = 0
od;
}
// eventually we have flag==1 forever
ltl p0 { <> ([] (flag == 1)) }
This program is correct iff eventually the no_flip flag becomes true and flag becomes true.
However, running both 'pan -a' and 'pan -a -f' (weak fairness) yields a cycle through the no_flip=1 statement and the acceptance state (from LTL formula).
I thought the progress labels would enforce that the execution passed through them infinitely often, but that doesn't seem to be the case.
So, is it possible to add such kind of fairness constraints?
Thanks,
Nuno
Just the inclusion of a progress label itself does not guarantee that the execution will be limited to non-progress cases. You need to add 'non-progress' somewhere in your ltl or never claim.
As a never claim you enforce progress with <>[](np_) (using spin -p '<>[](np_)' to generate the never claim itself). A possible ltl form for your verification is:
ltl { []<>!(np_) && <>[](flag==1) }
Also note that making 'progress' does not mean visiting each progress label infinitely often; it means visiting any progress label infinitely often. So, when enforcing progress, a viable path through your code is the first do option - which is not what you expect.
Answering my own question, for this simple example, I can split each loop branch into separate processes. Then by running pan in weak fairness mode, I have the guarantee that each process will be scheduled eventually.
However, this "solution" is not very interesting for my case, since I have a model with dozens of branches in each process.. Any other ideas?
bool no_flip;
bool flag;
active[1] proctype n1()
{
do
:: skip -> no_flip = 1
od;
}
active[1] proctype n2()
{
do
:: skip -> flag = 1
od;
}
active[1] proctype n3()
{
do
:: !no_flip -> flag = 0
od;
}
// eventually we have flag==1 forever
ltl p0 { <>[] (flag == 1) }

How can I write like "x == either 1 or 2" in a programming language? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why do most programming languages only have binary equality comparison operators?
I have had a simple question for a fairly long time--since I started learning programming languages.
I'd like to write like "if x is either 1 or 2 => TRUE (otherwise FALSE)."
But when I write it in a programming language, say in C,
( x == 1 || x == 2 )
it really works but looks awkward and hard to read. I guess it should be possible to simplify such an or operation, and so if you have any idea, please tell me. Thanks, Nathan
Python allows test for membership in a sequence:
if x in (1, 2):
An extension version in C#
step 1: create an extension method
public static class ObjectExtensions
{
public static bool Either(this object value, params object[] array)
{
return array.Any(p => Equals(value, p));
}
}
step 2: use the extension method
if (x.Either(1,2,3,4,5,6))
{
}
else
{
}
While there are a number of quite interesting answers in this thread, I would like to point out that they may have performance implications if you're doing this kind of logic inside of a loop depending on the language. A far as for the computer to understand, the if (x == 1 || x == 2) is by far the easiest to understand and optimize when it's compiled into machine code.
When I started programming it seemed weird to me as well that instead of something like:
(1 < x < 10)
I had to write:
(1 < x && x < 10)
But this is how most programming languages work, and after a while you will get used to it.
So I believe it is perfectly fine to write
( x == 1 || x == 2 )
Writing it this way also has the advantage that other programmers will understand easily what you wrote. Using a function to encapsulate it might just make things more complicated because the other programmers would need to find that function and see what it does.
Only more recent programming languages like Python, Ruby etc. allow you to write it in a simpler, nicer way. That is mostly because these programming languages are designed to increase the programmers productivity, while the older programming languages' main goal was application performance and not so much programmer productivity.
It's Natural, but Language-Dependent
Your approach would indeed seem more natural but that really depends on the language you use for the implementation.
Rationale for the Mess
C being a systems programming language, and fairly close to the hardware (funny though, as we used to consider a "high-level" language, as opposed to writing machine code), it's not exactly expressive.
Modern higher-level languages (again, arguable, lisp is not that modern, historically speaking, but would allow you to do that nicely) allow you to do such things by using built-in constructs or library support (for instances, using Ranges, Tuples or equivalents in languages like Python, Ruby, Groovy, ML-languages, Haskell...).
Possible Solutions
Option 1
One option for you would be to implement a function or subroutine taking an array of values and checking them.
Here's a basic prototype, and I leave the implementation as an exercise to you:
/* returns non-zero value if check is in values */
int is_in(int check, int *values, int size);
However, as you will quickly see, this is very basic and not very flexible:
it works only on integers,
it works only to compare identical values.
Option 2
One step higher on the complexity ladder (in terms of languages), an alternative would be to use pre-processor macros in C (or C++) to achieve a similar behavior, but beware of side effects.
Other Options
A next step could be to pass a function pointer as an extra parameter to define the behavior at call-point, define several variants and aliases for this, and build yourself a small library of comparators.
The next step then would be to implement a similar thing in C++ using templates to do this on different types with a single implementation.
And then keep going from there to higher-level languages.
Pick the Right Language (or learn to let go!)
Typically, languages favoring functional programming will have built-in support for this sort of thing, for obvious reasons.
Or just learn to accept that some languages can do things that others cannot, and that depending on the job and environment, that's just the way it is. It mostly is syntactic sugar, and there's not much you can do. Also, some languages will address their shortcomings over time by updating their specifications, while others will just stall.
Maybe a library implements such a thing already and that I am not aware of.
that was a lot of interesting alternatives. I am surprised nobody mentioned switch...case - so here goes:
switch(x) {
case 1:
case 2:
// do your work
break;
default:
// the else part
}
it is more readable than having a
bunch of x == 1 || x == 2 || ...
more optimal than having a
array/set/list for doing a
membership check
I doubt I'd ever do this, but to answer your question, here's one way to achieve it in C# involving a little generic type inference and some abuse of operator overloading. You could write code like this:
if (x == Any.Of(1, 2)) {
Console.WriteLine("In the set.");
}
Where the Any class is defined as:
public static class Any {
public static Any2<T> Of<T>(T item1, T item2) {
return new Any2<T>(item1, item2);
}
public struct Any2<T> {
T item1;
T item2;
public Any2(T item1, T item2) {
this.item1 = item1;
this.item2 = item2;
}
public static bool operator ==(T item, Any2<T> set) {
return item.Equals(set.item1) || item.Equals(set.item2);
}
// Defining the operator== requires these three methods to be defined as well:
public static bool operator !=(T item, Any2<T> set) {
return !(item == set);
}
public override bool Equals(object obj) { throw new NotImplementedException(); }
public override int GetHashCode() { throw new NotImplementedException(); }
}
}
You could conceivably have a number of overloads of the Any.Of method to work with 3, 4, or even more arguments. Other operators could be provided as well, and a companion All class could do something very similar but with && in place of ||.
Looking at the disassembly, a fair bit of boxing happens because of the need to call Equals, so this ends up being slower than the obvious (x == 1) || (x == 2) construct. However, if you change all the <T>'s to int and replace the Equals with ==, you get something which appears to inline nicely to be about the same speed as (x == 1) || (x == 2).
Err, what's wrong with it? Oh well, if you really use it a lot and hate the looks do something like this in c#:
#region minimizethisandneveropen
public bool either(value,x,y){
return (value == x || value == y);
}
#endregion
and in places where you use it:
if(either(value,1,2))
//yaddayadda
Or something like that in another language :).
In php you can use
$ret = in_array($x, array(1, 2));
As far as I know, there is no built-in way of doing this in C. You could add your own inline function for scanning an array of ints for values equal to x....
Like so:
inline int contains(int[] set, int n, int x)
{
int i;
for(i=0; i<n; i++)
if(set[i] == x)
return 1;
return 0;
}
// To implement the check, you declare the set
int mySet[2] = {1,2};
// And evaluate like this:
contains(mySet,2,x) // returns non-zero if 'x' is contained in 'mySet'
In T-SQL
where x in (1,2)
In COBOL (it's been a long time since I've even glanced briefly at COBOL, so I may have a detail or two wrong here):
IF X EQUALS 1 OR 2
...
So the syntax is definitely possible. The question then boils down to "why is it not used more often?"
Well, the thing is, parsing expressions like that is a bit of a bitch. Not when standing alone like that, mind, but more when in compound expressions. The syntax starts to become opaque (from the compiler implementer's perspective) and the semantics downright hairy. IIRC, a lot of COBOL compilers will even warn you if you use syntax like that because of the potential problems.
In .Net you can use Linq:
int[] wanted = new int{1, 2};
// you can use Any to return true for the first item in the list that passes
bool result = wanted.Any( i => i == x );
// or use Contains
bool result = wanted.Contains( x );
Although personally I think the basic || is simple enough:
bool result = ( x == 1 || x == 2 );
Thanks Ignacio! I translate it into Ruby:
[ 1, 2 ].include?( x )
and it also works, but I'm not sure whether it'd look clear & normal. If you know about Ruby, please advise. Also if anybody knows how to write this in C, please tell me. Thanks. -Nathan
Perl 5 with Perl6::Junction:
use Perl6::Junction 'any';
say 'yes' if 2 == any(qw/1 2 3/);
Perl 6:
say 'yes' if 2 == 1|2|3;
This version is so readable and concise I’d use it instead of the || operator.
Pascal has a (limited) notion of sets, so you could do:
if x in [1, 2] then
(haven't touched a Pascal compiler in decades so the syntax may be off)
A try with only one non-bitwise boolean operator (not advised, not tested):
if( (x&3) ^ x ^ ((x>>1)&1) ^ (x&1) ^ 1 == 0 )
The (x&3) ^ x part should be equal to 0, this ensures that x is between 0 and 3. Other operands will only have the last bit set.
The ((x>>1)&1) ^ (x&1) ^ 1 part ensures last and second to last bits are different. This will apply to 1 and 2, but not 0 and 3.
You say the notation (x==1 || x==2) is "awkward and hard to read". I beg to differ. It's different than natural language, but is very clear and easy to understand. You just need to think like a computer.
Also, the notations mentioned in this thread like x in (1,2) are semantically different then what you are really asking, they ask if x is member of the set (1,2), which is not what you are asking. What you are asking is if x equals to 1 or to 2 which is logically (and semantically) equivalent to if x equals to 1 or x equals to 2 which translates to (x==1 || x==2).
In java:
List list = Arrays.asList(new Integer[]{1,2});
Set set = new HashSet(list);
set.contains(1)
I have a macro that I use a lot that's somewhat close to what you want.
#define ISBETWEEN(Var, Low, High) ((Var) >= (Low) && (Var) <= (High))
ISBETWEEN(x, 1, 2) will return true if x is 1 or 2.
Neither C, C++, VB.net, C#.net, nor any other such language I know of has an efficient way to test for something being one of several choices. Although (x==1 || x==2) is often the most natural way to code such a construct, that approach sometimes requires the creation of an extra temporary variable:
tempvar = somefunction(); // tempvar only needed for 'if' test:
if (tempvar == 1 || tempvar == 2)
...
Certainly an optimizer should be able to effectively get rid of the temporary variable (shove it in a register for the brief time it's used) but I still think that code is ugly. Further, on some embedded processors, the most compact and possibly fastest way to write (x == const1 || x==const2 || x==const3) is:
movf _x,w ; Load variable X into accumulator
xorlw const1 ; XOR with const1
btfss STATUS,ZERO ; Skip next instruction if zero
xorlw const1 ^ const2 ; XOR with (const1 ^ const2)
btfss STATUS,ZERO ; Skip next instruction if zero
xorlw const2 ^ const3 ; XOR with (const2 ^ const3)
btfss STATUS,ZERO ; Skip next instruction if zero
goto NOPE
That approach require two more instructions for each constant; all instructions will execute. Early-exit tests will save time if the branch is taken, and waste time otherwise. Coding using a literal interpretation of the separate comparisons would require four instructions for each constant.
If a language had an "if variable is one of several constants" construct, I would expect a compiler to use the above code pattern. Too bad no such construct exists in common languages.
(note: Pascal does have such a construct, but run-time implementations are often very wasteful of both time and code space).
return x === 1 || x === 2 in javascript