Alloy assertion does not work as expected - assertion

Here is my alloy code:
one sig Library {
books: set Book, // set of the library's books
patrons: set Patron, // set of the library's patrons
circulation: Patron lone -> some Book // books in circulation
}
// set of books in the Library
sig Book {
}
// set of patrons
sig Patron {
curbooks: set Book // books currently checked out by a patron
}
So I want to add an assert that two Patron cannot currently have the same book. Here is the assertion I came with:
assert sameBook2Patrons {
all disj p, p': Patron | all b: p.curbooks | b not in p'.curbooks
}
So when check the assertion with:
check sameBook2Patrons{} for exactly 2 Book, exactly 2 Patron
Alloy does not find any counter-example. But when I use the run command, Alloy gives me plenty of counter example:
run{} for exactly 2 Book, exactly 2 Patron
Also, I read that adding a fact with the negation of a valid assertion is supposed to give no instance. I added that:
fact sameBook2Patrons {
not (all disj p, p': Patron | all b: p.curbooks | b not in p'.curbooks)
}
When I run the model, Alloy finds valid instance.
What am I doing wrong? Thank you.

You are using the check command wrongly. To check the assertion sameBook2Patrons you should instead use
check sameBook2Patrons for exactly 2 Book, exactly 2 Patron
i.e, without curly braces. If you put the braces, the assertion to be checked is the expression inside the braces (in your case, empty, which is equivalente to true) and sameBook2Patrons is just the name of the command.

Related

Create a list using SWI-cpp.h

I'm trying to use the SWI-PL engine in C++ using SWI-cpp.h.
I don't have any tutorial, I'm only using this reference and I'm looking in GitHub repos for some examples.
My code works fine, except for one thing; calling this definition:
foo([bar]).
As you can see, the definition requires a list.
Since I can't put a PlTermv in a PlTermv, I have no idea how to construct a list. I could use a PlTail, but I only know a way in which I have to add an empty head.
This is my CPP code so far:
PlTermv av(1);
// Load external pl file that contaions the foo definition.
PlCall("consult", PlTerm("foobar.pl"));
PlAtom bar = PlAtom("hello");
// I want Prolog to return a list with this compound.
av[0] = PlCompound("foo", PlTermv(bar));
PlCall("call", av); // So that this statement returns 'true' instead of 'false'.
How could I change this code in a way that PlCall("call",av); returnstrue?
Creating lists in Prolog can be done using the atomic_list_concat/3 predicate.
This means PlCall has to be called one more time in the code and it's result has to be stored in a PlTerm:
PlTermv av(1);
// Load external pl file that contaions the foo definition.
PlCall("consult", PlTerm("foobar.pl"));
PlTerm list;
// Use space as separator. Sets the value of 'list' to '[bar]'.
PlCall("atomic_list_concat", PlTermv(list, " ", "bar"));
av[0] = PlCompound("foo", PlTermv(list));
PlCall("call", av); // returns 'true'

C++ Running actual code from file without compiling it [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am trying to make a program which can read code from a file (similar to an interpretor but not as complex) store it into a linear list and then execute it when needed.
This is what i want this "interpretor" to know:
variable declaration
array declaration
for, while, if control structures
input and output files (output files can be opened in append mode)
non recursive functions
Because i execute it command by command i can stop/start at a specific number of commands executed which is helpful when trying to do more at the same time (similar to multithreading) and for this reason, i will name the class _MINI_THREAD. Here are the declarations of the struct COMMAND and class _MINI_THREAD:
struct COMMAND
{
unsigned int ID;
char command_text[151];
COMMAND* next;
COMMAND* prev;
};
class _MINI_THREAD
{
public:
void allocate_memory()
{
while (start_of_list == NULL)
start_of_list = new (std::nothrow) COMMAND;
while (end_of_list == NULL)
end_of_list = new (std::nothrow) COMMAND;
start_of_list -> prev = NULL;
start_of_list -> next = end_of_list;
end_of_list -> prev = start_of_list;
end_of_list -> next = NULL;
}
void free_memory()
{
for(COMMAND* i=start_of_list -> next;i!=end_of_list;i=i->next)
delete i -> prev;
delete end_of_list -> prev;
delete end_of_list;
}
bool execute_command(unsigned int number_of_commands)
{
for(unsigned int i=0;i<number_of_commands;i++)
{
/*match id of current command pointed by the cursor with a function from the map*/
if (cursor==end_of_list) return false;
else cursor=cursor->next;
}
return true;
}
bool if_finished()
{
if (cursor==end_of_list)return true;
else return false;
}
unsigned int get_ticks()
{
return ticks_per_loop;
}
void set_ticks(unsigned int ticks)
{
ticks_per_loop = ticks;
}
private:
unsigned int ticks_per_loop;
COMMAND* cursor=NULL;
COMMAND* start_of_list=NULL;
COMMAND* end_of_list=NULL;
};
I also try to keep the syntax of the "invented code" from the source files as close as possible to the c/c++ syntax but sometimes i placed a new parameter because it makes verification a lot easier. Please notice that even the while has a name so that i can manage nested loops faster.
Here is an example i came up with:
Source_file.txt
int a;
input_file fin ("numbers.in");
output_file fout ("numbers.out");
while loop_one ( fin.read(a,int,skipws) )
{
fout.print(a,int);
fout.print(32,char); /*prints a space after each number*/
}
close_input_file fin;
close_output_file fout;
/*This code is supposed to take all numbers from the input file and */
/* move them into the output file */
In the real program the object thread1 of class _MINI_THREAD contains a dinamically allocated list (i will display it as an array for simple understanding)
_MINI_THREAD thread1;
/*read from Source_file.txt each command into thread1 command array*/
thread1.commandarr={
define_integer("a"),
open_input_file("numbers.in",fin),
open_output_file("numbers.out",fout),
define_label_while("loop_one",fin.read()), /*if the condition is false the `cursor` will jump to labe_while_end*/
type_to_file(fout,a,int),
type_to_file(fout,32,char),
label_while_return("loop_one"), /*returns the cursor to the first line after the while declaration*/
label_while_end("loop_one"), /*marks the line after the while return point*/
close_input_file("numbers.in",fin),
close_output_file("numbers.out",fout),
};
/*the cursor is already pointing at the first command (define_integer("a"))*/
/*this will execute commands until the cursor reaches the end_of_list*/
while(thread1.execute_commands(1))NULL;
thread1.free_memory();
Now my problem is actually implementing the IF_CONTROL_STRUCTURE. Because you may want to type if (a==b) or if (foo()) etc... and i don't know how can i test all this stuff.
I somehow managed to make the cursor move accordingly to any structure (while,do ... while,for etc) with the idea of labels but still i cannot check the condition each structure has.
You really want to write some interpreter (probably using some bytecode). Read more about semantics.
Writing well a good interpreter is not a trivial task. Consider using some existing one, e.g. Lua, Guile, Neko, Python, Ocaml, .... and take some time to study their free software implementation.
Otherwise, spend several months reading stuff, notably:
SICP is an absolute must to read (and freely downloadable).
the Dragon Book
Programming Language Pragmatics
Lisp In Small Pieces
about the SECD machine
the GC handbook
Notice that an entire book (at least) is needed to explain how an interpreter works. See also relevant SIGPLAN conferences.
Many (multi-thread friendly) interpreters have some GIL. A genuinely multi-threaded interpreter (without any GIL) is very difficult to design (what exactly would be its REPL ???), and a multi-threaded garbage collector is also very difficult to implement and debug (consider using an existing one, perhaps MPS or Boehm's GC).
So "your simple work" could require several years of full-time work (and could get you a PhD).
a simpler approach
After having read SICP and becoming familiar with some Lisp-like language (probably some Scheme, e.g. thru Guile), you could decide on some simpler approach (basically a tiny Lisp interpreter which you could code in a few hundred lines of C++; not as serious as full-fledged interpreters mentioned before).
You first need to define on paper, at least in English, the syntax and the semantics of your scripting language. Take a strong inspiration from Lisp and its S-expressions. You probably want your scripting language to be homoiconic (so your AST would be values of your languages), and it would have (like Lisp) only expressions (and no statements). So the conditional is ternary like C++ ? :
You would represent the AST of your scripting language as some C++ data structure (probably some class with a few virtual methods). Parsing some script file into an AST (or a sequence of AST, maybe feed to some REPL) is so classical that I won't even explain; you might use some parser generator -improperly called compiler-compilers (like bison or lemon).
You would then at least implement some eval function. It takes two arguments Exp and Env: the first one, Exp, is the AST of the expression to be evaluated, and the second one, Env is some binding environment (defining the binding of local variables of your scripting language, it could be as simple as a stack of mapping from variables to values). And that eval function returns some value. It could be a member function of your AST class (then Exp is this, the receiver ....). Of course ASTs and values of your scripting language are some tagged union (which you might, if so wished, represent as a class hierarchy).
Implementing recursively such an eval in C++ is quite simple. Here is some pseudo code:
eval Exp Env :
if (Exp is some constant) {
return that constant }
if (Exp is a variable Var) {
return the bounded value of that Var in Env }
if (Exp is some primitive binary operator Op /* like + */
with operands Exp1 Exp2) {
compute V1 = eval Exp1 Env
and V2 = Exp2 Env
return the application of Op /* eg addition */ on V1 and V2
}
if (Exp is a conditional If Exp1 Exp2 Exp3) {
compute V1 = eval Exp1 Env
if (V1 is true) {
compute V2 = eval Exp2 Env
return V2
} else { /*V1 is false*/
compute V3 = eval Exp3 Env
return V3
}
}
.... etc....
There are many other cases to consider (e.g. some While, some Let or LetRec which probably would augment Env, primitive operations of different arities, Apply of an arbitrary functional value to some sequence of arguments, etc ...) that are left as an exercise to the reader. Of course some expressions have side effects when evaluated.
Both SICP and Lisp In Small Pieces explain the idea quite well. Read about meta-circular evaluators. Don't code without having read SICP ...
The code chunk in your question is a design error (even the MINI_THREAD thing is a mistake). Take a few weeks to read more, throw your code to the thrash bin, and start again. Be sure to use some version control system (I strongly recommend git).
Of course you want to be able to interpret recursive functions. There are not harder to interpret than non-recursive ones.
PS. I am very interested by your work. Please send me some email, and/or publish your tentative source code.

Could anyone please explain me this part of a code?

I stumbled on this syntax while learning file handling.
while(fp.read((char*)&st,sizeof(student)) && found==0)
{
if(strcmpi(st.retadmno(),n)==0)
{
st.show_student();
cout<<"\nEnter The New Details of student"<<endl;
st.modify_student();
int pos=-1*sizeof(st);
fp.seekp(pos,ios::cur);
fp.write((char*)&st,sizeof(student));
cout<<"\n\n\t Record Updated";
found=1;
}
}
Many articles only gave the generic syntax of this comparison but i couldn't find the actual meaning of it. THe syntax is followed by an if statement and is as follows.
Thanks!
This line:
while(fp.read((char*)&st,sizeof(student)) && found==0)
reads a from the file, and if that is successful [1], checks that found is still zero, and enters the rest of the loop.
I personally would do:
while(!found && fp.read(reinterpret_cast<char*>&st, sizeof(student))
instead. That way, you don't read an extra student after writing.
[1] The sucess here is judged by the fact that fp.read returns the istream object that it operates on, and this can be converted to void * (pre-C++11) or bool (C++11 onwards) which reflects the status of fp.good(). In other words, the file is in a state where you can read more from it.

How replace If-else block condition

In my code I have an if-else block condition like this:
public String method (Info info) {
if (info.isSomeBooleanCondition) {
return "someString";
}
else if (info.isSomeOtherCondition) {
return "someOtherString";
}
else if (info.anotherCondition) {
return "anotherStringAgain";
}
else if (lastCondition) {
return "string ...";
}
else return "lastButNotLeastString";
}
Each conditional branch returns a String.
Since if-else statements are difficult to read, test and maintain, how can I replace?
I was thinking to use Chain Of Responsability Pattern, is it right in this case?
Is there any other elegant way that I can do that?
I am left to assume that your code does not exist in the Info class as it is passed in an referenced for all but that last condition. My first instinct would be to make String OtherClass.method(Info) into String Info.method() and have it return the appropriate string.
Next, I would take a look at the conditions. Are they really conditions or can they be mapped to a table. Whenever I see code performing a lookup, such as this, I tend to fall back on attempting to fit into a dictionary or map so I can perform a lookup for the value.
If you are left with conditions that must be checked then I would begin thinking about lambdas, delegates or custom interface. A series of if..then across the same type could easily be represented. Next, you would collect them and execute accordingly. IMO, this would make the if..then bunch much clearer. It is more code by is secondary at this point.
interface IInfoCheck
{
bool TryCheck(Info info, out string);
}
public OtherClass()
{
// Setup checks
CheckerCollection.add(new IInfoCheck{
public String check(out result) {
// check code
}
});
}
public String method(Info info) {
foreach (IInfoCheck ic in CheckerCollection)
{
String result = null;
if (ic.TryCheck(out result))
{
return result;
}
}
}
The problem statement does not fit into an ideal chain of responsibility scenario because it is either/or kind or conditions which look 'chained' but is actually 'not'. Reason - one processes all the chain-links in the chain of responsibility pattern irrespective of what happened in the previous links, i.e. no chain-links are skipped(although you can configure which chain links to process and which not - but still the execution of a chain-link is not dependent on the outcome of a previous chain-link). However, in this if-else-if* scenario - once an if statement condition matches, the further conditions are not evaluated.
I have thought of an alternative design which achieves the above without if-else, but it is lengthier but at the same time more flexible.
Lets say we have a FunctionalInterface IfElseReplacer which takes 'info' as input and gives 'String' output.
public Interface IfElseReplacer(){
public String executeCondition(Info);
}
Then the above conditions can be re-phrased as lambda expressions would look like -
"(Info info) -> info.someCondition ? someString"
"(Info info) -> info.anotherCondition ? someOtherString"
and so on...
Then we need a processConditons method to process these Lambdas- it could be a default method in ifElseReplacer -
default String processConditions(List<IfElseReplacer> ifElseReplacerList, Info info){
String strToReturn="lastButNotLeastString";
for(IfElseReplacer ifElseRep:ifElseReplacerList){
strToReturn=ifElseRep.executeCondition(info);
if(!"lastButNotLeastString".equals(strToReturn)){
break;//if strToReturn's value changes i.e. executeCondition returns a String valueother than "lastButNotLeastString" then exit the for loop
}
return strToReturn;
}
What remains now is to (I am skipping the code for this - please let me know if you need it then will write this also) -
From wherever the if-else conditions need to be checked there -
Create an array of lambda expressions as explained above assigning them to IfElseReplacer interfaces while adding them to a list of type IfElseReplacer.
Pass this list to the default method processConditions() along with an instance of Info.
Default method would return the String value which we would be same as the result of if-else-if* block given in the problem statement.
I'd simply factor out the returns:
return
info.isSomeBooleanCondition ? "someString" :
info.isSomeOtherCondition ? "someOtherString" :
info.anotherCondition ? "anotherStringAgain" :
lastCondition ? "string ..." :
"lastButNotLeastString"
;
From the limited information about the problem, and the code given, it looks like this a case of type-switching. The default solution would be to use a inheritance for that:
class Info {
public abstract String method();
};
class BooleanCondition extends Info {
public String method() {
return "something";
};
class SomeOther extends Info {
public String getString() {
return "somethingElse";
};
Patterns which are interesting in this case are Decorator, Strategy and Template Method. Chain of Responsibility has another focus. Each element in the chain implement logic to process some commands. When chained, an object forwards the command if it cannot process it. This implements a loosly coupled structure to process commands where no central dispatch is needed.
If computing the string on the conditions is an operation, and from the name of the class I am guessing that it is probably an expression tree, you should look at the Visitor pattern.

Display valid LR(0) items

I have to create a C++ program to display the valid LR(0) items in SLR parsing in compiler design. Till now I am able to take the grammar as an input from the user and find its closure. But i am not able to proceed further with the goto implementation in SLR. Can anyone please provide me the links or code as to how to display the valid LR(0) items of a grammar.
-Thanks in advance
You're able to take the closure of the grammar? Technically, the closure function is defined on sets of items (which are sets of productions with a position associated with each production).
Now, you ask for how to display the valid LR(0) items of a grammar. You either mean displaying all the items, as defined in the paragraph above, or displaying all states of the LR(0) automaton. The first is trivial because all possible items are valid, so I'm guessing you want all states. This is what you do (straight from the dragon book).
SetOfItems getValidStates(Grammar G) {
// S' -> S is the "first" production of G (which must be augmented)
SetOfItems C = {[S' -> *S]};
do {
bool added = false;
for (Item I : C) {
for (Symbol X : G) {
L = GOTO(I, X);
if (L.size() > 0 && !C.contains(L)) {
added = true;
C.add(L);
}
}
}
} while (added);
return C;
}
The only question is how to implement GOTO(SetOfItems, Symbol).
So,
SetOfItems GOTO(SetOfItems S, Symbol X) {
SetOfItems ret = {}
for (Item I : S)
if (I.nextSymbol().equals(X))
ret.add(I.moveDotByOne())
return closure(ret);
}
Each item in the set has the form [A -> a*Yb], where A is the head of some production and aXb is the body of the production (a and b are just a string of grammar symbols, Y is a single symbol). The '*' is just the position I mentioned - it's not in the grammar, and [A->a*Yb].nextSymbol() is Y. Basically, Item.nextSymbol() just returns whatever symbol is to the right of the dot. [A->a*Yb].moveDotByOne() returns [A->aY*b].
Now, I just finished the parsing chapter in the compiler book, and I'm not completely happy with my understanding, so be careful with what I've written.
As for a link to real code: http://ftp.gnu.org/gnu/bison/ is where you'll find bison's source, but that's a LALR parser generator, and I don't think it implements LR(0).