I am trying to simulate some simple asm code using Prolog. (32 bit)
I am new in Prolog and I am stucked in some problems without any solutions.
Basically if here is the code:
...
add eax, 1
...
and I want to simulate in this way:
...
EAX is EAX - 1,
...
and swipl will generate errors like :
Call: (7) 1 is 1-1 ? creep
Fail: (7) 1 is 1-1 ? creep
....
false
I know basically I could do like this:
EAX_temp is EAX + 1
But how can I keep manipulate EAX in next instructions..?
Could any one give me some help..? Thank you!
The "Prolog" way would be to actually maintain the state of all your registers in a term which you pass along the main predicate that runs the simulation. So, for example:
But please note: this is not a predicate (hence the missing dot at the end)! This is a term, and it will be initialized to all zeros (I am assuming here):
So at the beginning of your program you can initialize your registers with:
You can leave it at this, or you can have a helper predicate that provides access to the one register you need, for example:
And to set a register:
which you can then use like this to define your
apply_instruction/3
:The sort of predicates,
reg_eax
andset_reg_eax
can be automatically generated by a library,library(record)
(see here), with the initial idea proposed by Richard o'Keefe in his book "The Craft of Prolog" for doing exaclty this sort of stuff. If you use the libary, you don't need to write all the access and set predicates yourself.If you are using SWI-Prolog, however, you can also make use of
Dicts
; see here. This is part of the current development version of SWI-Prolog (version 7) and makes dealing with structures with named arguments much easier.There are probably several good ways to do this. And the answer might further be refined by your context which is currently not clear.
One way, is you could create dynamic facts for register values:
Then do:
To read a register, you would just use, for example:
The main drawback of
assert
andretract
is that they take a lot more CPU time than list manipulation. But I think they make sense for this kind of application where you have a CPU "state" that is represented by several register values.