Why this precondition will be fail,I don't understand well - dafny

datatype message = Nil | Aenc(aencMsg:message,aencKey:message) | Senc(m1:message,m2:message) | K(r1:role,r2:role) | Pk(r:role) | Sk(r:role) | Str(r:role) | Var(n:role) | Concat(array<message>)
type channel = array<message>
method ReceiveMsgFromChannel(c:channel) returns (m:message)
requires c.Length > 0
requires c[0] != Nil
ensures c[0] == Nil
// requires verify(c)
modifies c
{
m:=c[0];
c[0]:=Nil;
}
method AliceSendMsg_1(c:channel)
requires c.Length > 0
modifies c
{
var aencMsg:=new message[2];
aencMsg[0]:=Var("Na");
aencMsg[1]:=Str("A");
var m :=Aenc(Concat(aencMsg),Pk("B"));
c[0] :=m;
assert m.aencKey == Pk("B");
}
method Test(ch1:channel)
requires ch1.Length>0
requires forall i:int :: 0<=i<ch1.Length ==> ch1[i]==Nil
modifies ch1
{
AliceSendMsg_1(ch1);
var m1:=ReceiveMsgFromChannel(ch1);
}
This is part of my code.I try to define two entities in protocol,One sends message,another receives message.And there AliceSendMsg_1 represent Alice sends the msg of aenc not Nil.Then Bob receives the Msg from Channel.But the message can not be Nil.Why the precondtion fails.Any help in getting this to verify is appreciated. Thank you!

The body of Test first executes,
AliceSendMsg_1(ch1);
Furthermore, AliceSendMsg_1 is marked with modifies ch1 but does not give any postcondition. Therefore, when Dafny reasons about the method Test, it knows absolutely nothing about the contents of ch1 after the call to AliceSendMsg_1. Remember that when Dafny is verifying Test, it does not look into the body of AliceSendMsg_1. All it knows about AliceSendMsg_1 is whatever is in the signature of that method.
You can fix this by simply adding the property you need to the signature of AliceSendMsg_1.
method AliceSendMsg_1(c:channel)
requires c.Length > 0
ensures c[0] != Nil // add this line
modifies c

Related

How to check this sequence element is equal to that sequence element in Dafny

I have 2 sequences a:seq and b:seq, I wonder if we use the function, how we can determine that the element at this index in seq a is equal to element at this index in seq b
function test(s:seq<nat>, u:seq<nat>): nat
ensures |s|>0
ensures |u|>0
ensures |s| == |u|
{
// Code
}
method Testing()
{
var sys:seq<nat> := [4,2,9,3,1];
var usr:seq<nat> := [1,2,3,4,5];
assert test(sys, usr) == 1
// The element at the index 2 of sys and usr are equal, so it have 1 element that match in both 2 sequence
}
Because of the function I could not create a while loop, so I can not do the basic logic on that, so I wonder if there's something that fit the requirement.
After researching and working by Python to find the recursion in Python, finally I found the answer for this:
function bullspec(s:seq<nat>, u:seq<nat>): nat
requires |s| > 0
requires |u| > 0
requires |s| == |u|
{
var index:=0;
if |s| == 1 then (
if s[0]==u[0]
then 1 else 0
) else (
if s[index] != u[index]
then bullspec(s[index+1..],u[index+1..])
else 1+bullspec(s[index+1..],u[index+1..])
)
}
This is a wonderful problem to solve with Dafny.
Let me state the problem in clear:
Given two sequences of the same length, find the first index at which these sequences are equal. Otherwise return the length of the sequences.
That formulation makes it possible to not require that sequences are non-empty.
Thus, we can start with the following definition
function bullspec(s:seq<nat>, u:seq<nat>): (r: nat)
requires |s| == |u|
// Ensures r is either a sequence index or the sequence length
ensures r <= |s|
// All the elements before r are different
ensures forall i: nat | i < r :: s[i] != u[i]
// Either r is the sequence length or the elements at index r are equal
ensures r == |s| || s[r] == u[r]
{
Now, if you manage to prove this function, you will have prove that this function does what you want it to do.
To obtain the body of the function, you usually have to check whether the sequence if empty. In our case, we can return 0, which is the length of the sequence.
if |s| == 0 then 0 else
If the sequence is not empty, then we can compare the first elements. If they are equal, then we return the index 0
if s[0] == u[0] then 0 else
Otherwise, what happens if we recurse into bullspec(s[1..],u[1..])? We will obtain an index that is offset by 1 ! So we only need to add 1 to it.
1 + bullspec(s[1..],u[1..])
}
With this, you can verify that your function does exactly what you intended it to do.

Testing for identical objects in Dart

According to the documentation, the function identical checks whether two references are to the same object.
With that in mind, I don't understand why the following is the case:
int a = 1;
int b = 1;
print(identical(a, b)); // prints 'true'
Map c = { 1: 'y' };
Map d = { 1: 'y' };
print(identical(c, d)); // prints 'false'
I'd expect both calls to return 'false'.
identical compares references. a and b are references to a compile time literal 1. Thus they are identical.

Getting a SimpleHellaCacheIF exception when making two memory accesses from the same instruction

I am trying to modify the accumulator generator example to load two accesses at once, for example to load two indices from one array. All I changed is that when the first memory response comes in, I increment a counter and send out another. But I get a cache exception. My code for the accelerator is below. It only has a few changes from the accumulator.
What’s confusing too me is that the first access works and I get the data, and for now, I’m using the same address with the second access. So why wouldn’t this work?
val regfile = Mem(4, UInt(width = 16.W))
val busy = Reg(init = Vec.fill(4){Bool(false)})
val cmd = Queue(io.cmd)
val funct = cmd.bits.inst.funct
val addr = cmd.bits.rs2(log2Up(4)-1,0)
val doLoad = funct === UInt(0)
val doRead = funct === UInt(1)
val doWrite = funct === UInt(2)
val doAccum = funct === UInt(3)
val memRespTag = io.mem.resp.bits.tag
// datapath
val addend = cmd.bits.rs1
val accum = regfile(addr)
val wdata = Mux(doWrite, addend, accum + addend)
val counter = RegInit(0.U)
when (cmd.fire() && (doWrite || doAccum)) {
regfile(addr) := wdata
}
when (io.mem.resp.valid) {
regfile(memRespTag) := io.mem.resp.bits.data
busy(memRespTag) := Bool(false)
when(counter === 0.U) {
counter := 1.U
}
}
// control
when (io.mem.req.fire()) {
busy(counter) := Bool(true)
}
val doResp = cmd.bits.inst.xd
val stallReg = busy(counter)
val stallLoad = doLoad && !io.mem.req.ready
val stallResp = doResp && !io.resp.ready
cmd.ready := !stallReg && !stallLoad && !stallResp // command resolved if no stalls AND not issuing a load that will need a request
// PROC RESPONSE INTERFACE
io.resp.valid := cmd.valid && doResp && !stallReg && !stallLoad
// valid response if valid command, need a response, and no stalls
io.resp.bits.rd := cmd.bits.inst.rd
// Must respond with the appropriate tag or undefined behavior
io.resp.bits.data := accum
// Semantics is to always send out prior accumulator register value
io.busy := cmd.valid || busy.reduce(_||_)
// Be busy when have pending memory requests or committed possibility of pending requests
io.interrupt := Bool(false)
// Set this true to trigger an interrupt on the processor (please refer to supervisor documentation)
io.mem.req.valid := ((cmd.valid && doLoad) || counter === 1.U ) && !stallReg && !stallResp
io.mem.req.bits.addr := addend
io.mem.req.bits.tag := addr
io.mem.req.bits.cmd := M_XRD // perform a load (M_XWR for stores)
io.mem.req.bits.size := log2Ceil(8).U
io.mem.req.bits.signed := Bool(false)
io.mem.req.bits.data := Bits(0) // we're not performing any stores...
io.mem.req.bits.phys := Bool(false)
I managed to read multiple locations from io.mem interface but still struggling with multiple writes.
Initially, i also faced same exception because i provided invalid memory address (no memory was existed with that address) at the time of io.mem request is triggered.
Here, in your case after toggling counter to value 1 from 0. It remains high. So there is no control from cmd.valid. In this case cmd.valid is important as value (addend) assigned to io.mem.req.bits.addr signal is only valid when cmd.valid is high. You can make interface independent of cmd.valid.You have to modify interface accordingly.
So, conclusion is,Sample valid address for io.mem.req interface.From my experience you can read as many locations as you want with single custom command.
Thanks & Regards,
Sanket,

How to match a variable to a token in javacc?

I am trying to match a variable (a string) to one of my defined tokens in JAVACC. The pseudocode for what I am trying to do is...
String x;
if (x matches <FUNCTIONNAME>) {...}
How would I go about achieving this?
Thank you
Here is one way to do it. Use the STATIC==false option. The following code should do what you need
public boolean matches( String str, int k ) {
// Precondition: k should be one of the integers
// given a name in XXXConstants
// Postcondition: result is true if and only if str would be lexed by
// the lexer as a single token of kind k possibly
// preceeded and followed by any number of skipped and special tokens.
StringReader sr = new StringReader( str ) ;
SimpleCharStream scs = new SimpleCharStream( sr ) ;
XXXTokenManager lexer = new XXXTokenManager( scs );
boolean matches = false ;
try {
Token a = lexer.getNextToken() ;
Token b = lexer.getNextToken() ;
matches = a.kind == k && b.kind == 0 ; }
catch( Throwable t ) {}
return matches ;
}
One problem with this is that it will skip tokens declared as SKIP or SPECIAL_TOKEN. E.g. if I use a Java lexer then "/*hello*/\tworld // \n" will still match JavaParserConstants.ID. If you don't want this, you need to do two things. First go into the .jj file and convert any SKIP tokens to SPECIAL_TOKENS. Second add checks that there no special tokens were found
matches = a.kind == k && b.kind == 0 && a.specialToken == null && b.specialToken == null ;

Weird antlr grammar rule

I have found an old file that define antlr grammar rules like that:
rule_name[ ParamType *param ] > [ReturnType *retval]:
<<
$retval = NULL;
OtherType1 *new_var1 = NULL;
OtherType2 *new_var2 = NULL;
>>
subrule1[ param ] > [ $retval ]
| subrule2 > [new_var2]
<<
if( new_var2 == SOMETHING ){
$retval = something_related_to_new_var2;
}
else{
$retval = new_var2;
}
>>
{
somethingelse > [new_var_1]
<<
/* Do something with new_var_1 */
$retval = new_var_1;
>>
}
;
I'm not an Antlr expert and It's the first time that i see this kind of semantic for a rule definition.
Does anybody know where I can find documentation/informations about this?
Even a keyword for a google search is welcome.
Edit:
It should be ANTLR Version 1.33MR33.
Ok, I found! Here is the guide:
http://www.antlr2.org/book/pcctsbk.pdf
I quote the interesting part of the pdf that answer to my question.
1) Page 47:
poly > [float r]
: <<float f;>>
term>[$r] ( "\+" term>[f] <<$r += f;>> )*
;
Rule poly is defined to have a return value called $r via the "> [float r]" notation; this is similar to the output redirection character of UNIX shells. Setting the value of $r sets the return value of poly. he first action after the ":" is an init-action (because it is the first action of a rule or subrule). The init-action defines a local variable called f that will be used in the (...)* loop to hold the return value of the term.
2) Page 85:
A rule looks like:
rule : alternative1
| alternative2
...
| alternativen
;
where each alternative production is composed of a list of elements that can be references to rules, references to tokens, actions, predicates, and subrules. Argument and return value definitions looks like the following where there are n arguments and m return values:
rule[arg1,...,argn] > [retval1,...,retvalm] : ... ;
The syntax for using a rule mirrors its definition:
a : ... rule[arg1,...,argn] > [v1,...,vm] ...
;
Here, the various vi receive the return values from the rule rule, each vi must be an l-value.
3) Page 87:
Actions are of the form <<...>> and contain user-supplied C or C++ code that must be executed during the parse.

Resources