How to implement repeat untill (condition) loop in promela? - promela

Which would be right approach to do :
repeat{
...
} until(<condition>)
in Promela ?
I have tried :
do::
//..
(condition) -> break;
od
and
do ::
//..
if::(condition) -> break;
else
fi;
od

Your first attempt is incorrect, because if <condition> is not true the process will simply block forever.
Your second attempt is functionally correct. Personally, I would prefer a minor variant to your solution which does not drop the true entry condition for executing the bulk code.
Given
repeat{
// bulk code
} until(<condition>)
you have the following options:
do:
do
:: true ->
// bulk code
if
:: <condition> ->
break;
:: else;
fi;
od;
or
do
:: true ->
// bulk code
if
:: ! <condition>;
:: else ->
break;
fi;
od;
goto:
L1:
// bulk code
if
:: <condition>;
:: else
-> goto L1;
fi;
or
L1:
// bulk code
if
:: ! <condition>
-> goto L1;
:: else;
fi;
unless (do not use!):
do
:: true ->
d_step {
// bulk code
}
od unless { <condition> };
Note that there are two catches with this approach:
it assumes that the value of <condition> is altered within // bulk code and not anywhere else in the code (e.g. by some other process)
depending on the content of // bulk code, it might not possible to use d_step at all.
Only in the case in which the instruction altering the evaluation of <condition> is precisely the last one inside // bulk code then one is allowed to drop d_step without affecting the semantics.
To see why this is the case, observe the behaviour of Spin on the following code example:
active proctype example()
{
int cc = 0;
do
:: true ->
printf("before %d\n", cc);
cc++;
printf("after %d\n", cc);
od unless { cc == 3 };
}
which has the following output:
~$ spin test.pml
before 0
after 1
before 1
after 2
before 2
1 process created
since cc++ alters the evaluation of cc == 3 but is not the last instruction of the code sequence, the statement after 3 is never printed on screen.
EDIT:
Of course one could also try another variant of code with the unless statement, e.g.
bool flag;
do
:: true ->
// bulk code
flag = true;
flag = false;
od unless { flag && <condition> };
This is obviously always correct, even in the general case, but it clogs the source code with additional variables that are not part of the original problem, so I would still discourage the use of unless to replace do/until.
Here is an example of how to use it:
active proctype example()
{
int cc = 0;
bool flag = false;
do
:: true ->
printf("before %d\n", cc);
cc++;
printf("after %d\n", cc);
flag = true;
flag = false;
od unless { flag && (cc == 3) };
}
and indeed it yields the correct output:
~$ spin test.pml
before 0
after 1
before 1
after 2
before 2
after 3
1 process created

Related

Change an Int variable value in LLDB

Environment: Xcode 11.3.1/Swift 5
Here is the function:
func lldbTest() {
var switchInt = 1
...// do something and set a break point here
if switchInt == 1 {
print("switchInt == 1")
} else if switchInt == 2 {
print("switchInt == 2")
}
}
I debug before enter the if statement, and I change switchInt to 2 in lldb
e switchInt = 2
p switchInt
(Int) $R4 = 2
but it still print "switchInt == 1"
result
I guess the behavior is because the compiler has already evaluated the if statement "if switchInt == 1" because there's no code that changes the value of switchInt before that line. I tried the below and was able to get the behavior desired.
var switchInt = 1
for i in 0..<10 {
switchInt = 0
}
if switchInt == 1 { -> Put a break point here and use (lldb) e switchInt=2
print("switchInt == 1")
} else if switchInt == 2 {
print("switchInt == 2")
}
Now execute the command p switchInt and it will have the value 2. Step through the breakpoint and it will print switchInt == 2.
Setting variables from the debugger in Swift is somewhat hit and miss. Because swift uses so many wrapped objects (Int's for instance are actually a "struct"), the compiler has to do a fair amount of optimization even at -Onone or the code will run unacceptably slowly.
The debugger is often told only about a shadow copy of the variable, and not the location that is actually being used in code. You can try various tricks like Felix suggests, but at present you're not guaranteed to succeed...
This is a known bug, but for technical reasons is one that is tricky to solve.

What is the correct use of select statement in Go?

Good Day everyone
I have been learning the fundaments of go and how to use its channel-based concurrency paradigm.
However, while playing with some code I wrote focusing on the select statement I found a strange behavior:
func main() {
even := make(chan int)
odd := make(chan int)
quit := make(chan bool)
//send
go send(even, odd, quit)
//receive
receive(even, odd, quit)
fmt.Println("Exiting")
}
func send(e, o chan<- int, q chan<- bool) {
for i := 0; i < 100; i++ {
if i%2 == 0 {
e <- i
} else {
o <- i
}
}
close(e)
close(o)
q <- true
close(q)
}
func receive(e, o <-chan int, q <-chan bool) {
for cont, i := true, 0; cont; i++ {
fmt.Println("value of i", i, cont)
select {
case v := <-e:
fmt.Println("From even channel:", v)
case v := <-o:
fmt.Println("from odd channel:", v)
case v := <-q:
fmt.Println("Got exit message", v)
// return // have also tried this instead
cont = false
}
}
}
when I run this simple program sometimes the i accumulator ends up with more than a 100 being printed to the console, and instead of finishing up with a "from odd channel: 99", the for loop continues on outputting one or more zeroes from even/odd channels randomly, as if the quit channel's message was being somewhat being delayed onto its case and instead the odd/even channels were sending more integers thus quitting the for loop not exactly after the odd/even channels have been closed.
value of i 97 true
from odd channel: 97
value of i 98 true
From even channel: 98
value of i 99 true
from odd channel: 99
value of i 100 true
From even channel: 0
value of i 101 true
From even channel: 0
value of i 102 true
from odd channel: 0
value of i 103 true
From even channel: 0
value of i 104 true
Got exit message true
Exiting
I have tried to search for the correct use of the case statement but I haven´t been able to find the problem with my code.
It seems like the same behavior can be reproduced on the go playground: my code
thanks for your attention put on my question.
The program is printing 0 because receive on a closed channel returns the zero value. Here's one way to accomplish your goal.
First, eliminate the q channel. Closing the o and e channels is sufficient to indicate that the sender is done.
func send(e, o chan<- int, q chan<- bool) {
for i := 0; i < 100; i++ {
if i%2 == 0 {
e <- i
} else {
o <- i
}
}
close(e)
close(o)
}
When receiving values, use the two value receive to detect when the zero value is returned because the channel is closed. Set the channel to nil when the channel is closed. Receive on a nil channel does not yield a value. Loop until both channels are nil.
func receive(e, o <-chan int, q <-chan bool) {
for e != nil && o != nil {
select {
case v, ok := <-e:
if !ok {
e = nil
continue
}
fmt.Println("From even channel:", v)
case v, ok := <-o:
if !ok {
o = nil
continue
}
fmt.Println("From odd channel:", v)
}
}
}
playground example

swift 3 variable used before begin initialized

I have an issue with my n variable. I cannot use n in for loop. Why? n was initialized before for loop. Please, help.
import Foundation
var n: Int
var t: Int
while(true){
var tt = readLine()
t = Int(tt!)!
if (t==0){
break
}
else if ( t < 0){
n = t*(-1)
}
else if(t > 0){
n = t
}
var arr : [[String]] = []
for i in 0..<n*2{
for y in 0..<n*2{
arr[i][y] = "."
}
}
}
A variable may be declared and not immediately initialized, as long as initialization is guaranteed before first use
The error is more subtle than at first glance. You may actually declare a property without initializing it, as long as all program flows leading to its first use ascertain initialization of it.
The issue is with the if, else if and else if block:
var n: Int // declaration
// ...
if (t == 0) {
break
}
else if (t < 0) {
n = t*(-1)
}
else if (t > 0){
n = t
}
// first use
for i in 0..<n*2 { /* ... */ }
Swift cannot not infer that this block is in fact exhaustive, and believes that there is a possibility that none of the above if statements holds, which, in the eyes of the compiler, would lead to the following program state:
program flow has not been broken (break)
and n has not been instantiated
As humans, however, we know that the if - else if - else if block above is indeed exhaustive, and can help the compiler out by simply changing the last if else statement to a simple else statement.
if (t == 0) {
break
}
else if (t < 0) {
n = t*(-1)
}
// if none of the above, t > 0
else {
n = t
}
On another note, the nested array access of non-existing array elements, arr[i][y] = "." will lead to a runtime exception, but this is another issue. In its current form, it looks as if the intent with the nested loops could be replaced with a nested array instantiation:
var arr = [[String]](repeating: [String](repeating: ".", count: 2*n), count: 2*n)
or,
var arr = (0..<2*n).map { _ in [String](repeating: ".", count: 2*n) }
The variable n is only declared, not initialized.
To initialize the variables:
var n: Int = 0
var t: Int = 0

expectationForPredicate Fails test case

Recently started working on XCode UI test with SWIFT.
My problem is I need to wait until a element appears on iPhone screen.
I found a solution with '''expectationForPredicate''' and '''waitForExpectationsWithTimeout''' but the problem this is this methods are designed to fail test case if expected predicate not matched within timeout.
I need a code which can wait for element to appear on screen if the element did not appear and timeout exceeded then I don't want test case to fail. rather I would like to return true (element exists) / false (not exists)
I found a solution by avoiding the above mentioned functions as those are failing my tests instead of returning true or false
Below is the method i created
func waitForElementToAppear(element: XCUIElement, file: String = #file, line: UInt = #line) -> Bool {
let TIMEOUT: Double = 120 ;
var isFound = false;
let start = NSDate();
var diff : Double = 0;
repeat{
print("Is element \(element) found : \(element.exists)")
print("Printing debugDescription -> ")
print(XCUIApplication().debugDescription)
if(element.exists){
isFound = true;
break;
}
print("Waiting for element to exists... Time counter :\(diff)")
sleep(1)
let end = NSDate();
diff = end.timeIntervalSinceDate(start);
}while(diff <= TIMEOUT);
return isFound;
}
I hope this will help others, But if you still have any other better solution please answer here.

Does a break statement break from a switch/select?

I know that switch/select statements break automatically after every case. I am wondering, in the following code:
for {
switch sometest() {
case 0:
dosomething()
case 1:
break
default:
dosomethingelse()
}
}
Does the break statement exit the for loop or just the switch block?
Break statements, The Go Programming Language Specification.
A "break" statement terminates execution of the innermost "for",
"switch" or "select" statement.
BreakStmt = "break" [ Label ] .
If there is a label, it must be that of an enclosing "for", "switch"
or "select" statement, and that is the one whose execution terminates
(§For statements, §Switch statements, §Select statements).
L:
for i < n {
switch i {
case 5:
break L
}
}
Therefore, the break statement in your example terminates the switch statement, the "innermost" statement.
A hopefully illustrative example:
loop:
for {
switch expr {
case foo:
if condA {
doA()
break // like 'goto A'
}
if condB {
doB()
break loop // like 'goto B'
}
doC()
case bar:
// ...
}
A:
doX()
// ...
}
B:
doY()
// ....
Yes, break breaks the inner switch.
https://play.golang.org/p/SZdDuVjic4
package main
import "fmt"
func main() {
myloop:
for x := 0; x < 7; x++ {
fmt.Printf("%d", x)
switch {
case x == 1:
fmt.Println("start")
case x == 5:
fmt.Println("stop")
break myloop
case x > 2:
fmt.Println("crunching..")
break
default:
fmt.Println("idling..")
}
}
}
0idling..
1start
2idling..
3crunching..
4crunching..
5stop
Program exited.
This question might be too old already but I still think label makes our code become harder to read.
Instead of breaking the for inside select, just set a flag for the loop and handle it inside select-case before invoking break.
For example:
loop := true
for loop {
select {
case <-msg:
// do your task here
case <-ctx.Done():
loop = false
break
}
}
Updated: Totally agree with Vaelin in the comment. Declaring that flag inside the scope of the for loop can avoid memory leak and conflict with other variables in current scope, just in case we have a same variable name already.
for loop := true; loop; {
}
Just from a switch block. There's plenty of examples in Golang own code you can examine (compare inner break with outer break).
this should explain it.
for{
x := 1
switch {
case x >0:
fmt.Println("sjus")
case x == 1:
fmt.Println("GFVjk")
default:
fmt.Println("daslkjh")
}
}
}
Runs forever
for{
x := 1
switch {
case x >0:
fmt.Println("sjus")
break
case x == 1:
fmt.Println("GFVjk")
default:
fmt.Println("daslkjh")
}
}
}
Again, runs forever
BUT
package main
import "fmt"
func main() {
d:
for{
x := 1
switch {
case x >0:
fmt.Println("sjus")
break d
case x == 1:
fmt.Println("GFVjk")
default:
fmt.Println("daslkjh")
}
}
}
will print sjus
... clear ?
http://play.golang.org/p/GOvnfI67ih
It only exits the switch block.