1
The asmerl states from Abstract State Machines in Erlang. The ASM is a methodology of creating specification executable, which I respect. Erlang, except Tcl and Rust, is my favorite programming language. I combined this two ideas in a program which is subject of development of the testing ASM and generating test cases from them.
The asmerl is designed for software developers who want to ensure that specification of their project does not introduce hidden bugs. To learn about the asmerl the briefly Python programming is sufficient. To understand the examples in last sections of this page the knowledge of test driven development and refactoring is necessary.
Key features of the asmerl are:
The asmerl is currently available via this web page for testing. Two restriction are set. First the maximum size of input file is limited to 128Kib. Second, the maximum of heap size of interpreter is set to 100Mb. If the former will be exceeded the program exits and dumps a core.
The web page contains description of the language of the asmerl and its features. If you are looking for links to the subjects covered by this page the last section contains them.
In the asmerl the main role plays functions. Even entities which are used as variables are functions with zero arity. Contrary to typical programming languages, functions values are not computed but defined. Here are some examples of definitions of functions.
cardNumber := 0011223344 pin(0011223344) := 1234 allowed(1234,0011223344) := falseWe say that function has assigned value and call the statement defining value an assignment.
The functions are called as in other languages and the basic expression in the asmerl is nested function evaluation. It is presented on listing bellow.
allowed(pin(cardNumber),cardNumber)Under the definitions from the beginning of this section, the value of expression above is equal to
false.
The algorithm of value computation is greedy. For a given function call all arguments are evaluated to the limit to ensure that the function call will be evaluated at as low level as possible. The algorithm is used also during the assignment. The arguments of function which is defined are also reduced before this statement is done.
That must be pointed, that all literals used in the asmerl consist of: numbers, small letters, large letters and the sign of underscore. So it is possible to have, for example, a name of a function starting with number.
The assignments are grouped in sets. Two basic are called: the State set and the Update set. Here we interest the former. If the assignment are processed they are collected in update set. We say that there is a conflict in the update set when there are collected two assignments with the same name of function, the same arguments and the different values. For example:
allowed(1234,0011223344) := false allowed(1234,0011223344) := trueThe update set without conflicts is called consistent. Programming in the asmerl is concentrated on obtaining consistent update sets from the code.
There is a special notion in the asmerl for creating many update sets from a single statement. It is shown on listing bellow.
allowed(1234,0011223344) := false, trueIt creates two update sets one with assignment:
allowed(1234,0011223344) := falseand one with:
allowed(1234,0011223344) := trueTwo of such statements:
cardNumber := 0011223344, 1122334455 pin := 1234, 2345, 3456creates the six update sets with the proper values assigned to two functions.
The second base concept of the asmerl is the state set. This is a set of assignments which is consistent and represent the state of computation. Update sets are applied to state set creating new state sets. This is done by merging them in the following way. There are three cases:
Let us see it in practice. Click on the button "Load an example to the editor" above.
The code in the editor consists of two parts. First (lines 1-4) the
state clause is written and defines the initial state set of the computation using
assignment statements.
Second, (lines: 6-10) two rules are written to describe the update set.
If you click Run button just above the editor the example will be evaluated. You can see
in the result window (bellow editor) two state sets. First is initial, the second is after applying the update set.
After them update sets are printed. In both case they consist of the same assignments.
The computation is interrupted because of the third state set is identical to second one and there are no new
state sets to proceed.
We will use states and updates for abbreviation of state sets and update sets, from this point.
Note that, in the asmerl conflicts are checked on two levels. First, updates generated by all rules must be free of conflicts. Second, all such updates summed up must be consistent, too.
You can play with this example adding assignments and testing results.
Basic notion of lists is identical to the common programming languages. The listing bellow shows two examples of list assignments.
accountNumbers := [0011223344, 1122334455] empty := []Lists can be processed with use of the predefined deterministic functions. That means that they are not defined but computed traditional way. They are described bellow.
hd(List)
The function returns a head of the List or undefined when the List is empty.
tl(List)
The function returns a tail of the List or undefined when the List is empty.
last(List)
The function returns a last element of the List or undefined when the List is empty.
append(Element,List)
The function returns a new list with the Element on first position and the former List as a tail.
prepend(Element,List)
The function returns a new list with Element on the last position and the List on the beginning.
delete(Element,List)
The function returns a new list with all occurrences of Element removed from the List.
length(List)
The function returns the length of the List.
uniq(List)
The function return List with removed repetitive elements.
choose(List)
The function returns a random element from the List or undefined when the List is empty.
shuffle(List)
The function returns a new list with all elements from the List shuffled.
perm(List)
It is the special function. It creates a new update set for any permutation of the List. Please note that the number of permutation of a N element list is N!. The web interface to the asmerl has restriction of a size of the heap set to 100Mb. Setting long list as argument to perm ends with a program crash.
The first example (click left button above) shows described functions in work. If you click
Run button, it creates a new update and state with values of them assigned to functions named
from 'a' to 'j'. Functions from 'k' to 'n' are producing the undefined values as
they have the empty List as an argument.
The second example (click right button above) creates large number of states. As the state
clause can be treated as an application of updates to the empty state, 120 states are created.
Because the rule empty produces an empty update there is no other states computed.
Both examples uses if statement which will be explained in next section.
The basic logical expression is the nested function call if it evaluates to logical value. Having two
nested function calls one can use comparison operators to produce logical value. Mostly used are == for equality,
!= for inequality. You can use also use <, >, <=
and >= for value comparison. In that cases results are always defined because computation uses standard
Erlang operators. The membership of element to list is tested with the in operator. The contrary situation,
lack of membership, is tested by the ni one. If the values are integers the comparison is evaluated after
translation to numeric values. Such logical expressions could be joined using standard logical operators and,
or and not. The priority of operators is preserved. One can also use brackets to change default priorities.
if logical_expression:
statements then block
else:
statements else block
If statement is also similar to one from common programming languages. The logical expression
controls update creation of statement blocks. The resulting update is produced by the statements
then block if logical_expression evaluates to the true and
the statements else block in case of the false. The other values of logical_expression
interrupts computation with an error. The else clause is optional.
for function in list:
statements
The for clause produces update in the following way. For any item in the list the assignment
function := itemis temporary added to state. Then the
statements are used to
compute update. All such updates are merged to final update of the statement. Note that check of conflicts
is turned on during this computation.
par:
statements
Parallel execution is turned on by the par statement.
Statements are computed during update creation with the state applied to all statements independently.
To explain it there is valuable to see example of swap. It is assumed that both x and y
are defined in the state. The example looks like:
x := y y := xIt works because the state applied to each command is the same.
seq:
statements
The statement seq is used to execute statements in sequential manner. This is probably the way you
understand the execution of the code. Each time statement is evaluated the resulting update is stored in the state. So the code:
color := red
light(color) := on
if light(color) == on:
out := light_defined
will evaluate without an error. The cost of using this way of computation is dependency between statements which
are evaluated. But the advantage is the simple understanding of such a code.
By default the sequential execution is turned on during processing state clause. During rule
processing the parallel execution is present. This is done because the sequential processing is more suitable
during configuration of states using if statements controlled by small number of configuration assignments.
The parallel processing is more suitable during refactoring the code of rules when changing order of statements is valuable.
Procedures are defined as in other programming languages as it is shown on listing bellow.
proc name(arg1,arg2,...,argN):
statements
They have name, a zero or a number of arguments and a list of statements.
The update set of the procedure call
proc(function1,function2,...,functionN)is computed as follows. First for any actual parameter
functionI and
argument of procedure argI the assignment:
argI := functionIis added temporary to the state. Then
statements are evaluated to compute
update of procedure. By default the parallel code execution is turned on during statements evaluation.
The recurrent call of procedures is prohibited and causes an error when detected.
Standard refactorings of condition statements are valuable during reorganization of the asmerl code. But the most valuable refactoring is "Replace else by not condition". It transforms:
if logical_expression:
then statements
else:
else statements
to:
if logical_expression:
then statements
if not logical_expression:
else statements
Writing else clauses is more suitable during working with the code. But this refactoring allows
to move statements, change the condition arrangement and merge they with other ones. Then, one could
extract procedures of the form:
proc name(args):
if logical_expression:
statements
which is useful to make code readable.
Standard output of the asmerl consists of enumerated states and updates from them. This can be changed using report facility. There can be many report clauses in the code. Each of them has the form presented bellow.
report logical_expression [[ string ]]After the keyword
report the logical_expression is placed. Then the arbitrary string
should be written. It starts with the [[ and can contains any chars without the sequence
]] witch ends it. If there is one update from the given state reports are processed.
This means that there exists exactly one so called next state in this situation.
If the logical_expression with the given state evaluates to true the string is processed.
The logical_expression can be splited on multiple lines when it is joined by and operator. The
example of such code is presented bellow.
report logical_expression_1 and logical_expression_2 and logical_expression_3 [[ string ]]
The string can contains function calls from the state and the next state. The function
is evaluated with the state when is annotated with the sign of dollar and curly braces as shown bellow.
${function()}
When the function is annotated with the sign at and curly braces like:
@{function()}
it is evaluated with the next state. In both cases function can be arbitrary
nested functions calls with the list expressions and functions inside or outside them.
The state contains also the function nr which contains the unique number of the state processed.
Reports are not executed by default. To see them you need to change value of the select box above editor window to Process reports.
The code of the model in the asmerl has following order.
state:
statements
proc name(args):
statements
rule name:
statements
report condition [[
string
]]
The code starts with the state clause which must have at least one assignment. Next the procedures
are defined. There can be no procedure defined in the code. Next rules are written. There must be at least one
rule defined in the code. It is convenient that there exists one rule which contains model whereas other ones
contains sanity checks, tests and other tasks. The code ends with report clauses. They are optional and could
be omitted.
The indentation of code has two modes. One could use tabulator or for spaces for the indent. The chosen mode should be preserved in the whole code.
The example presented here shows reason why I am interesting in this topic and why the asmerl is written.
The code in editor presents street light example. Lines 1-5 established the initial state of computation.
There is the green light turned on, the other lights are turned off. Lines 7-20 contains rule process.
It changes the lights in the common manner. The green changes to the yellow then to the red next is the red with
the yellow and finally green. Lines 22-27 contains the rule correct. It checks that lights of each
colors are turned on or off. Lines 29-33 contains report which generates the unit tests for the Erlang eunit package.
Because of the Erlang pattern matching feature the implementation of it is extremely simple. But in this example
the derivation of unit tests is important.
Two topics shown in this example are crucial and leads to two questions.
To partially answer to the questions set in previous section one can examine formalized method of systems specification called Given-When-Then, and the relationship between them and the asmerl models.
There is one to one relationship between the Given-When-Then style of specification and modeling the asmerl code. It means that having formalized specification of system in this method one could write a model. Conversely having the model one could create the specification. The key tool to establish this relation is refactoring. Virtually any code in asmerl should be refactored to the form where procedures looks like on listing bellow.
proc name(args):
if given_condition:
if when_condition:
then_code
and the rule clause which has form of sequence of such procedures calls.
The given_condition establish the conditions of the system,
when_condition relate to action taken on it and then_code
is a set of assignments. Such code could be source of acceptance tests using dedicated
testing software. It is also possible to write test cases using the asmerl's report facility,
setting given_condition and when_condition as logical_expression of report
and examining when_condition and then_code in a generated test cases.
The example code (left button above) shows the model of a cash machine in the asmerl. The refactored
version (right button) contains 6 procedures each of them is a valid Given-When-Then specification snipped.
The sequence of report clauses in that example defines unit tests written with eunit and meck modules. You can
observe that the atomic elements of logical condition corresponds to the statements in test cases. The outer calls
from the model are translated to mocked calls of back-end module bank_service. The
when_condition is equivalent to call of a cash_machine - module which is defined by tests.
Repetitions of test cases are removed from the code using the nr function calls.
My personal interest in Abstract State Machines have been started when I have bought a book: "Abstract State Machines. A method for high-level system design and analysis" by Egon Börger and Robert Stärk. You can buy it here. Complete description you can found on the Wikipedia article on this topic. You could be interested on XASM full features functional and open source ASM implementation of ASML language from Microsoft. Contrary to this implementation the asmerl is tiny and procedural.
My favorite book on the unit testing is: "Test-Driven Development: A practical guide" by David Astels. After many years it is still on sale. You can read in it about the unit testing, the refactoring and mock objects. This topic is also covered by many newer books and articles. See the Wikipedia article. The start point of reading about the refactoring is Martin Fowler's refactoring.com where one can read a web edition of the "Refactoring. Improving the design of existed code.". You can also buy this book on many internet bookstores.
Given-When-Then is practice introduced in the behavior driven development. Its implementations concentrate on natural language usage on unit/acceptance test creation. You could consult the page cucumber.io for information about BDD and the tool implemeting such a method of development. In my opinion the formalized version of Given-When-Then is suitable to be a vital point of the specification development. You could also read the Wikipedia article.
The Erlang language runtime environment could be downloaded from www.erlang.org. On that page you can download also some introduction articles and books on programming in this language. The documentation of runtime environment contains description of leex, yecc and eunit - standard modules used in the asmerl development. The meck module is available from the GitHub repository.