for (expr1;expr2;expr3) {
< loop_body >
}
expr1;
loop: if expr2 == 0 goto out
< loop_body>
expr3;
goto loop
out: ...
Give the operational semantics description for the following:
expr1;
do{
< body >
expr2;
}while(expr3);
Answer
expr1;
loop: <body>
expr2;
if expr3 == 0 goto out;
goto loop;
out: ....
or
expr1;
loop: <body>
expr2;
if expr3 == 1 goto loop;
....
Give the operational semantics description for the following:
switch(expr1)
{
case const1:
< body1 >
break;
case const2:
< body2 >
break;
default:
< body3 >
break;
}
Answer:
if expr1 == const1 goto L1;
if expr2 == const2 goto L2;
<body3>;
goto out;
L1: <body1>
goto out;
L2: <body2>
goto out;
out: ....
For the grammar:
The denotational mappings are:
For the grammar:
The denotational mapping is:
Writen as
$$\frac{S1,S2,S3,...Sn}{S}$$
Meaning if $S1,S2,...,$ and $Sn$ are all true, then we can infer $S$ is true.
An axiom is a rule that is assumed to be true. For example just $S$.
Precondition can be stregthed, post condition can always be weakened.
$$\frac{\{P\}S\{Q\}, P' \Rightarrow P, Q \Rightarrow Q'}{\{P'\}S\{Q'\}}$$For example, given:
{ x > 3} x = x $-$ 3 {x > 0}
We can prove that { x > 5} x = x $-$ 3 {x > 0} is valid
$$\frac{\{x>3\}x=x-3\{x>0\}, \{x > 5\} \Rightarrow \{x > 3\}, \{x > 0\} \Rightarrow \{x > 0 \}}{\{x > 5\}x=x-3\{x > 0\}}$$Given the statements
{P1} S1 {P2}
{P2} S2 {P3}
We can use the following inference rule:
$$\frac{\{P1\}S1\{P2\}, \{P2\}S2\{P3\}}{\{P1\}S1,S2\{P3\}}$$Compute weakest precondition
The precondition is then $y > 6 - \frac{x}{2}$
The inference rule for a conditional statement such as
if B then S1 else S2
is as follows
$$\frac{\{B \, \textrm{and} \, P\}S1\{Q\}, \{(\textrm{not}\, B) \, \textrm{and} \, P\}S2\{Q\}}{\{P\}\textrm{if B then S1 else S2}\{Q\}}$$Find the weakest precondition for the statement below
if x > 0 then
y = y - 1
else
y = y + 1
{y > 0}
Because there is an if statement, we need to evaluate the postcondition for all possible paths of execution
$$ y = y - 1\\ \{y > 0\}\\ y - 1 > 0\\ y > 1 $$AND
$$ y = y + 1\\ \{y > 0\}\\ y + 1 > 0\\ y > -1 $$Our two possible preconditions are then $y > 1$ or $y > -1$. Our job is to pick the one that will make the postcondition of $\{y > 0\}$ no matter which branch of the if-statement is evaluated.
By substituting in each possible value in each branch, we find that only $y > 1$ causes the postcondition to always be true, so that is the precondition for the entire if-statement