in - web.sec.uni-passau.deweb.sec.uni-passau.de/papers/leanea.pdfev olving algebras eas gurevic h...

34

Upload: others

Post on 20-Oct-2019

4 views

Category:

Documents


0 download

TRANSCRIPT

leanEA

A Poor Man�sEvolving Algebra Compiler

Bernhard BeckertJoachim Posegga

Interner Bericht �����

Universit�at Karlsruhe

Fakult�at f�ur Informatik

leanEA� A Poor Man�s Evolving Algebra Compiler

Bernhard Beckert � Joachim Posegga

Universit�at KarlsruheInstitut f�ur Logik� Komplexit�at und Deduktionssysteme

���� Karlsruhe� GermanyEmail� fbeckert�poseggag�ira�uka�de

WWW� http���i��www�ira�uka�de��posegga�leanea�

May ��� ��

Abstract

The Prolog program

�termexpansiondefine C as A with B�� C� A��B�����

termexpansiontransition E if C then D��

transition E���C���B�A�transition ��� ��

serializeD�B�A��

serializeE�F��C�D��A�B�� �� serializeE�C�B�� serializeF�D�A��

serializeF��G� �G�� ��E��F����C�D��D� �B�A����C�B��� assertaA� E���

�G�H�� ��E�F� �� G��E� G����C�D��D� �B�A����C�B��A� E�� ��H� �F�

��� ����

A��B �� �A�B�� ��D�C�� D��C��

implements a virtual machine for evolving algebras� It o�ers an e�cient and very

�exible framework for their simulation�

Computation models and speci�cation methods seem to be worlds apart� The evolvingalgebra project started as an attempt to bridge the gap by improving on Turing�s thesis�

�Gurevich� ���

� Introduction

Evolving algebras �EAs� �Gurevich� ����� Gurevich� ����� are abstract machines usedmainly for formal specication of algorithms The main advantage of EAs over classicalformalisms for specifying operational semantics� like Turing machines for instance� is thatthey have been designed to be usable by human beings� whilst the concrete appearance ofa Turing machine has a solely mathematical motivation� EAs try to provide a user friendlyand natural�though rigorous�specication tool The number of specications using EAsis rapidly growing�� examples are specications of the languages ANSI C �Gurevich Hug�gins� ����� and ISO Prolog �B�orger Rosenzweig� ������ and of the virtual architecture

�There is a collection of papers on evolving algebras and their application on the World Wide Web athttp���www�engin�umich�edu��huggins�EA�

� leanEA� A Poor Man�s Evolving Algebra Compiler

APE �B�orger et al�� ����b� EA specications have also been used to validate languageimplementations �eg� Occam �B�orger et al�� ����a�� and distributed protocols �Gurevich Mani� �����

When working with EAs� it is very handy to have a simulator at hand for running thespecied algebras This observation is of course not new and implementations of abstractmachines for EAs already exist� Angelica Kappel describes a Prolog�based implementationin �Kappel� ������ and Jim Huggins reports an implementation in C Both implementationsare quite sophisticated and o�er a convenient language for specifying EAs

In this paper� we describe an approach to implementing an abstract machine for EAswhich is di�erent� in that it emphasizes on simplicity and elegance of the implementation�rather than on sophistication We present a simple� Prolog�based approach for executingEAs The underlying idea is to map EA specications into Prolog programs Ratherthan programming a machine explicitly� we turn the Prolog system itself into a virtualmachine for EA specications� this is achieved by changing the Prolog reader� such thatthe transformation of EAs into Prolog code takes place whenever the Prolog system readsinput As a result� evolving algebra specications can be treated like ordinary Prologprograms

The main advantage of our approach� which we call leanEA� is its �exibility� the Prologprogram we discuss in the sequel can easily be understood and extended to the needsof concrete specication tasks �non�determinism� special handling of undened functions�etc� Furthermore� its �exibility allows to easily embed it into� or interface it with othersystems

The paper is organized as follows� in Section �� we start with explaining how a deter�ministic� untyped EA can be programmed in leanEA� this section is written pragmatically�in the sense that we do not present a mathematical treatment� but explains what a userhas to do in order to use EAs with leanEA The implementation of leanEA is explained inparallel In Section � we give some hints for programming in leanEA Rigorous denitionsfor vigorous readers can be found in Section �� where the semantics of leanEA programs arepresented Extensions of leanEA are described in Section �� these include purely syntacticalextensions made just for the sake of programming convenience� as well as more semanticalextensions like including typed algebras� or implementing non�deterministic evolving alge�bras Section � introduces modularized EAs� where Prolog�s concept of modules is used tostructure the specied algebras Finally� we draw conclusions from our research in Section �An extended example of using leanEA is given in Appendix A

Through the paper we assume the reader to be familiar with the basic ideas behindevolving algebras� and with the basics of Prolog

� Programming Evolving Algebras in leanEA

��� The Basics of leanEA

An algebra can be understood as a formalism for describing static relations between things�there is a universe consisting of the objects we are talking about� and a set of functionsmapping members of the universe to other members Evolving algebras o�er a formalismfor describing changes as well� an evolving algebra �moves� from one state to another� whilefunctions are changed

Bernhard Beckert � Joachim Posegga

Programming Evolving Algebras in leanEA �

leanEA is a programming language that allows to program this behavior From a decla�rative point of view� a leanEA program is a specication of an EA Here� however� we willnot argue declaratively� but operationally by describing how statements of leanEA set upan EA and how it moves from one state to another A declarative description of leanEA

can be found in Section �

��� Overview

leanEA is an extension of standard Prolog� thus a leanEA program can be treated like anyother Prolog program� ie� it can be loaded �or compiled� into the underlying Prolog system�provided leanEA itself has been loaded before�

leanEA has two syntactical constructs for programming an EA� the rst are functionde�nitions of the form

define Location as Value with Goal�

which specify the initial state of an EA

The second construct are transition de�nitions which dene the EA�s evolving� ie� themapping from one state to the next�

transition Name if Condition then Updates�

The signature of EAs is in our approach the set of all ground Prolog terms The �single�universe� that is not sorted� consists of ground Prolog terms� too� it is not specied explicitly

Furthermore� the nal state�s� of the EA are not given explicitly in leanEA Instead� astate S is dened to be nal if no transition is applicable in S or if a transition res thatuses undened functions in its updates

The computation of the specied evolving algebra is started by calling the Prolog goal

transition �

which recursively searches for the applicable transitions and executes them until no moretransitions are applicable

��� leanEA�s Operators

For implementing the syntax for function and transition denitions outlined above� a coupleof Prolog operators have to be dened with appropriate preferences� they are shown inFigure �� Lines ���

Note� that the preferences of operators �those pre�dened by leanEA as well as othersused in a leanEA program� can in�uence the semantics of Prolog goals included in leanEA

programs

��� Representation of States in leanEA

Before explaining how function denitions set up the initial state of an EA� we take a lookat the leanEA internals for representing states� A state is given by the mapping of locationsto their values� ie� elements of the universe A location f�u�� � � � � un�� n � �� consists ofa functor f and arguments u�� � � � � un that are members of the universe

Universit�at Karlsruhe

� leanEA� A Poor Man�s Evolving Algebra Compiler

� �� op���fy�transition�� op�����xfx�if��

� op��� fy�define�� op�����xfy�with��

� op����xfy�as�� op�����xfx�then��

� op���xfx����� op���xfx������

� op���xfx����� op���xfx�����

� op����fx�����

� �� multifile ����� �

� �� dynamic ����� �

term�expansion��define Location as Value with Goal�

� ��Location �� Value� �� Goal����

�� term�expansion��transition Name if Condition then Updates�

�� �transition�Name� ��

�� �Condition�FrontCodeBackCodetransition������ ��

�� serialize�UpdatesFrontCodeBackCode��

�� serialize��AB��FrontAFrontB��BackBBackA�� ��

�� serialize�AFrontABackA�

�� serialize�BFrontBBackB��

�� serialize��LocTerm �� Expr�

� ��Expr� ��� �Val� LocTerm ��� �Func�Args�

� Args ��� ArgVals Loc ����Func�ArgVals��

�� asserta�Loc �� Val���

�� ��H�T� ��� �HVal�TVal�� ��

�� � H � �HVal

�� � H ��� �Func�Args� Args ��� ArgVals

�� H� ��� �Func�ArgVals� H� �� HVal

�� ��

�� T ��� TVal�

�� �� ��� ���

� �S �� T� �� ��ST� ��� �Val�Val �� Val� �� Val �

Figure �� leanEA� the Program

Bernhard Beckert � Joachim Posegga

Programming Evolving Algebras in leanEA �

Example �� Assume� for instance� that there is a partial function denoted by f that mapsa pair of members of the universe to a single element� and that and � are members ofthe universe The application of f to and � is denoted by the Prolog term f� �� Thislocation can either have a value in the current state� or it can be undened

A state in leanEA is represented by the values of all dened locations Technically�this is achieved by dening a Prolog predicate ��� �� that behaves as follows� The goal�Loc �� Val� succeeds if Loc is bound to a ground Prolog term that is a location in thealgebra� and if a value is dened for this location� then Val is bound to that value Thegoal fails if no value is dened for Loc in the current state of the algebra

To evaluate a function call like� for example� f�f� ����� leanEA uses ���� as anevaluation predicate� the relation t ��� v holds for ground Prolog terms t and v if the valueof t�where t is interpreted as a function call�is v �in the current state of the algebra�

In general� the arguments of a function call are not necessarily elements of the universe�contrary to the arguments of a location�� but are expressions that are recursively evaluatedIt is possible to use members of the universe in function calls explicitly� these can be denotedby preceding them with a backslash ���� this disables the evaluation of whatever Prologterm comes after the backslash We will refer to this as quoting in the sequel

For economical reasons� the predicate ���� actually maps a list of function calls to alist of values Figure �� Lines ������ shows the Prolog code for ���� which is more or lessstraightforward� if the term to be evaluated �bound to the rst argument of the predicate�is preceded with a backslash� the term itself is the result of the evaluation� otherwise� allarguments are recursively evaluated and the value of the term is looked up with the predicate��� Easing the evaluation of the arguments of terms is the reason for implementing ���

over lists The base step of the recursion is the identity of the empty list �Line ��� ���

fails if the value of the function call is undened in the current state

Example �� Consider again the binary function f� and assume it behaves like addition inthe current state of the algebra Then both the goals

�f���� �� ��� �X� and �f�f������� �� ��� �X�

succeed with binding X to � The goal

�f��f����� �� ��� �X� �

however� will fail since addition is undened on the term f����� which is not an integerbut a location Analogously�

�f�f����� �� ��� �X�

will fail� because � and � are undened constants ���ary functions�

After exploring the leanEA internals for evaluating expressions� we come back to pro�gramming in leanEA The rest of this section will explain the purpose of function andtransition denitions� and how they a�ect the internal predicates just explained

�Note� that ���� is de�ned to be dynamic such that it can be changed by transitions �Fig� �� Line ���

Universit�at Karlsruhe

� leanEA� A Poor Man�s Evolving Algebra Compiler

��� Function De�nitions

The initial state of an EA is specied by a sequence of function denitions They dene theinitial values of locations by providing Prolog code to compute these values A constructof the form

define Location as Value with Goal�

gives a procedure for computing the value of a location that matches the Prolog termLocation� if Goal succeeds� then Value is taken as the value of this location Functiondenitions set up the predicate �� �and thus ���� in the initial state One function denitioncan specify values for more than one functor of the algebra It is possible in principle�although quite inconvenient� to dene all functors within a single function denition Thevalue computed for a location may depend on the additional Prolog code in a leanEA�program �code besides function and transition denitions�� since Goal may call any Prologpredicate If several function denitions dene values for a single location� the �textually�rst denition is chosen

����� Implementation of Function De�nitions

A function denition is translated into the Prolog clause

�Location �� Value� �� Goal��

Since each denition is mapped into one such clause� Goal must not contain a cut ����otherwise� the cut might prevent Prolog from considering subsequent �� clauses that matcha certain location

The translation of a dene statement to a �� clause is implemented by modifying theProlog reader as shown in Figure �� Lines ����

����� Examples for Function De�nitions

Constants A denition of the form

define register� as � with false�

introduces the constant ���ary function� register� with an undened value Such a de�nition is actually redundant� since all Prolog terms belong to the signature of the speciedEA and will be undened unless an explicit value has been dened

A denition of the form

define register� as � with true�

assigns the value � to the constant register�The denition

define register� as register� with true�

denes that the value of the function call register� is register� Thus evaluating�register� and register� will produce the same result

�In most Prolog dialects �e�g�� SICStus Prolog and Quintus Prolog� the Prolog reader is changed byadding clauses for the term expansion�� predicate� If a term t is read� and term expansiontS� succeedsand binds the variable S to a term s� then the Prolog reader replaces t by s�

Bernhard Beckert � Joachim Posegga

Programming Evolving Algebras in leanEA �

Prolog Data Types Prolog Data Types can be easily imported into the algebra Lists�for instance� are introduced by a denition of the form

define X as X with X���� X��H�T��

This denes that all lists evaluate to themselves� thus a list in an expression denotes thesame list in the universe and it is not necessary to quote it with a backslash Similarly�

define X as X with integer�X��

denes that Prolog integers evaluate to themselves in the algebra

Evaluating Functions by Calling Prolog Predicates The following are example de�nitions that interface Prolog predicates with an evolving algebra�

define X�Y as Z with Z is X�Y�

define append�XY� as Result with append�XYResult��

Input and Output Useful denitions for input and output are

define read as X with read�X��

define output�X� as X with write�X��

Whilst the purpose of read should be immediate� the returning of the argument of outputmight not be clear� the idea is that the returned value can be used in expressions Thatis� an expression of the form f���output�� �� will evaluate to the value of the locationf�� � and� as a side e�ect� write on the screen

A similar� often more useful version of output is

define output�FormatX� as X with format�Format�X���

which allows to format output and include text

����� Necessary Conditions for Function De�nitions

The design of leanEA constrains function denitions in several ways� the conditions func�tion denitions have to meet are not checked by leanEA� but must be guaranteed by theprogrammer In particular� the programmer has to ensure that�

� The computed values are ground Prolog terms� and the goals for computing themeither fail or succeed �ie� terminate� for all possible instantiations that might appearProlog exceptions that terminate execution have to be avoided as well It is thereforeadvisable� for instance� to formulate the denition of � as�

define X�Y as Z with integer�X� integer�Y� Z is X�Y�

� The goals do not change the Prolog data base or have any other side e�ects �sidee�ects that do not in�uence other computations are harmless and often useful� anexample are the denitions for input and output in Section ����

� The goals do not �syntactically� contain a cut ���

� The goals do not call the leanEA internal predicates transition��� ���� � and ���

Violating these requirements does not necessarily mean that leanEA will not functionproperly anymore� however� unless the programmer is very well aware of what he�she isdoing� we strongly recommend against breaking these rules

Universit�at Karlsruhe

� leanEA� A Poor Man�s Evolving Algebra Compiler

�� Transition De�nitions

Transitions specify the evolving of an evolving algebra A transition� if applicable� mapsone state of an EA to a new state by changing the value of certain locations Transitionshave the following syntax�

transition Name if Condition then Updates�

where

Name is an arbitrary Prolog term �usually an atom�

Condition is a Prolog goal that determines when the transition is applicable Conditionsusually contain calls to the predicate ��� �see Section ��� below�� and often usethe logical Prolog operators �� �conjunction�� ��� �disjunction�� ���� �implication��and ���� �negation�

Updates is a comma�separated sequence of updates of the form

f��r��� � � � � r�n�� �� v�

fk�rk�� � � � � rknk� �� vk

An update fi�ri�� � � � � rini� �� vi �� � i � k� changes the value of the location that consistsof �a� the functor fi and �b� the elements of the universe that are the values of the functioncalls ri�� � � � � rini� the new value of this location is determined by evaluating the functioncall vi All function calls in the updates are evaluated simultaneously �ie� in the old state�If one of the function calls is undened� the assignment fails

If the left�hand side of an update is quoted by a preceding backslash� the update willhave no e�ect besides that the right�hand side is evaluated� the meaning of the backslashcannot be changed

A transition is applicable �res� in a state� if Condition succeeds For calculating thesuccessor state� the �textually� rst applicable transition is selected Then the Updates ofthe selected transition are executed If no transition res or if one of the updates of the rstring transition fails� the new state cannot be computed In that case� the evolving algebraterminates� ie� the current state is nal Else the computation continues iteratively withcalculating further states of the algebra

����� Implementation of Transition De�nitions

leanEA maps a transition

transition Name if Condition then Updates�

into a Prolog clause

transition�Name� ��

Condition �

UpdateCodetransition� ��

Bernhard Beckert � Joachim Posegga

Hints for Programmers �

Likewise to function denitions� this is achieved by modifying the Prolog reader as shownin Figure �� Lines �����

Since the updates in transitions must be executed simultaneously� all function callshave to be evaluated before the rst assignment takes place The auxiliary predicateserialize�� �Lines ������ serves this purpose� it splits all updates into evaluation code�that uses the predicate ���� � and into code for storing the new values by asserting anappropriate ��� clause

����� The Equality Relation

Besides logical operators� leanEA allows in the condition of transitions the use of thepre�dened predicate ��� �Fig �� Line ��� implementing the equality relation� the goal�s �� t� succeeds if the function calls s and t evaluate �in the current state� to the sameelement of the universe It fails� if one of the calls is undened or if they evaluate to di�erentelements

�� An Example Algebra

We conclude this section with considering an example of an evolving algebra�

Example �� The leanEA program shown in Figure � species an EA for computing n�The constant state is used for controlling the ring of transitions� in the initial state�only the transition start res and reads an integer� it assigns the input value to reg�The transition step iteratively computes the faculty of reg��s value by decrementing reg�

and storing the intermediate results in reg If the value of reg� is �� the computation iscomplete� and the only applicable transition result prints reg After this� the algebrahalts since no further transition res and a nal state is reached

� Hints for Programmers

This section lists a couple of programming hints that have shown to be useful when spe�cifying EAs with leanEA

Final States� leanEA does not have an explicit construct for specifying the nal state of anEA By denition� the algebra reaches a nal state if no more transition is applicable�but is is often not very declarative to use this feature As the algebra can also behalted by trying to evaluate an undened expression� a construct of the form

stop �� stop�

in an update can increase the readability of specications a lot If stop is undened�the EA will halt if this assignment is to be carried out

Tracing Transitions� It is highly unlikely that a programmer is able to write down aspecication of an EA without errors directly Programming in leanEA is just likeprogramming in Prolog and usually requires debugging the code one has writtendown

Universit�at Karlsruhe

�� leanEA� A Poor Man�s Evolving Algebra Compiler

define state as initial with true�

define readint as X with read�X� integer�X��

define write�X� as X with write�X��

define X as X with integer�X��

define X�Y as R with integer�X�integer�Y�R is X�Y�

define X�Y as R with integer�X�integer�Y�R is X�Y�

transition step

if state �� �running ���reg� �� ��

then reg� �� reg���

reg �� �reg �reg���

transition start

if state �� �initial

then reg� �� readint

reg �� �

state �� �running�

transition result

if state �� �running reg� �� �

then reg �� write�reg �

state �� �final�

Figure �� An Evolving Algebra for Computing n�

Bernhard Beckert � Joachim Posegga

Semantics ��

For tracing transitions� it is often useful to include calls to write or trace at the endof conditions� the code will be executed whenever the transition res and it allows toprovide information about the state of the EA

Another� often useful construct is a denition of the form

define break�FormatX� as X with format�Format�X��break�

Tracing the Evaluation of Terms� A denition of the form

define f�X� as with write�f�X�� fail�

is particularly useful for tracing the evaluation of functions� if the above functiondenition precedes the �actual� denition of f�X�� it will print the expression to beevaluated whenever the evaluation takes place

Examining States� All dened values of locations in the current state can be listed bycalling the Prolog predicate listing���� Note� that this does not show any defaultvalues

� Semantics

This section formalizes the semantics of leanEA programs� in the sense that it explains indetail which evolving algebra is specied by a concrete leanEA�program

Definition �� Let P be a leanEA�program� then DP denotes the sequence of functiondenitions in P �in the order in which they occur in P �� TP denotes the sequence of transitiondenitions in P �in the order in which they occur in P �� and CP denotes the additionalProlog�code in P � ie� P without DP and TP

The function denitions DP �that may call predicates from CP � specify the initial stateof an evolving algebra� whereas the transition denitions specify how the algebra evolvesfrom one state to another

The signature of evolving algebras is in our approach the set GTerms of all groundProlog terms The �single� universe� that is not sorted� is a subset of GTerms

Definition �� GTerms denotes the set of all ground Prolog terms� it is the signature ofthe evolving algebra specied by a leanEA program

We represent the states S of an algebra �including the initial state S�� by an evaluationfunction �� S � mapping locations to the universe Section �� explains how �� S � ie� theinitial state� is derived from the function denitions D In what way the states evolveaccording to the transition denitions in T �which is modeled by altering �� � is the subjectof Section ��

The nal state�s� are not given explicitly in leanEA Instead� a state S is dened to benal if no transition is applicable in S or if a transition res that uses undened functioncalls in its updates �Def ����

�The user may� however� explicitly terminate the execution of a leanEAprogram �see Section ��

Universit�at Karlsruhe

�� leanEA� A Poor Man�s Evolving Algebra Compiler

��� Semantics of Function De�nitions

A function denition �define F as R with G�� gives a procedure for calculating thevalue of a location f�t�� � � � � tn� �n � �� Procedurally� this works by instantiating F tothe location and executing G If G succeeds� then R is taken as the value of the locationIf several denitions provide values for a single location� we use the rst one Note� thatthe value of a location depends on the additional Prolog code CP in a leanEA�program P �since G may call predicates from CP

Definition �� Let D be a sequence of function denitions and C be additional Prolog codeA function denition

D ! define F as R with G�

in D is succeeding for t � GTerms with answer r ! R� � if

� there is a �most general� substitution � such that F� ! t�

� G� succeeds �possibly using predicates from C��

� � is the answer substitution of G� �the rst answer substitution if G� is not deter�ministic�

If no matching substitutions � exists or if G� fails� D is failing for tThe partial function

�� D�C � GTerms �� GTerms

is dened by��t

D�C ! r �

where r is the answer �for t� of the rst function denition D � D succeeding for t If nofunction denition D � D is succeeding for t� then ��t

D�C is undened

The following denition formalizes the conditions function denitions have to meet �seeSection �����

Definition � A sequence D of function denitions and additional Prolog code C are wellde�ning if

� no function denition Di � D is for some term t � GTerms neither succeeding norfailing �ie� not terminating�� unless there is a denition Dj � D� j � i� in front ofDi that is succeeding for t�

� if D � D is succeeding for t � GTerms with answer r� then r � GTerms�

� D does not �syntactically� contain a cut �����

� the goals in D and the code C

�a� do not change the Prolog data base or have any other side e�ects�

�b� do not call the leanEA internal predicates transition��� ���� � and ���

�Prolognegation and the Prologimplication ���� are allowed�

Bernhard Beckert � Joachim Posegga

Semantics ��

Proposition � If a sequence D of function denitions and additional Prolog code C arewell dening� then ��

D�C is a well dened partial function on GTerms �a term mapping�

A well�dened term mapping �� is the basis for dening the evaluation function of anevolving algebra� that is the extension of �� to function calls that are not a location�

Definition �� Let �� be a well dened term mapping The partial function

�� � � GTerms �� GTerms

is dened for t ! f�r�� � � � � rn� � GTerms �n � �� as follows�

��t � !

�s if t ! �s

��f���r� �� � � � � ��rn �� otherwise

��� The Universe

A well�dened term mapping �� DP �CP

enumerates the universe UP of the evolving algebraspecied by P � in addition� UP contains all quoted terms �without the quote� occurringin P �

Definition ��� If P is a leanEA program� and �� DP �CP

is a well dened term mapping�then the universe UP is the union of the co�domain of ��

DP �CP� ie�

��GTerms DP �CP

! f��t DP �CP

� t � GTerms� ��t DP �CP

�g �

and the set

ft � t � GTerms� �t occurs in P g �

Note� that �obviously� the co�domain of �� � is a subset of the universe� ie�

��GTerms �DP �CP

� UP �

The universe UP as dened above is not necessarily decidable In practice� however�one usually uses a decidable universe� ie� a decidable subset of GTerms that is a supersetof UP �eg GTerms itself� This can be achieved by adding function denitions and thusexpanding the universe

��� Semantics of Transition De�nitions

After having set up the semantics of the function denitions� which constitute the initialevaluation function and thus the initial state of an evolving algebra� we proceed with thedynamic part

The transition denitions TP of a leanEA�program P specify how a state S of the evolvingalgebra represented by P maps to a new state S �

�It is also possible to change De�nition � � that� in its current form� de�nes the minimal version of theuniverse�

Universit�at Karlsruhe

�� leanEA� A Poor Man�s Evolving Algebra Compiler

Definition ��� Let S be a state of an evolving algebra corresponding to a well denedterm mapping �� S � and let T be a sequence of transition denitions

A transitiontransition Name if Condition then Updates

is said to �re� if the Prolog goal Condition succeeds in state S �possibly using the predi�cate ��� � Def ���

Letf��r��� � � � � r�n�� �� v�

fk�rk�� � � � � rknk� �� vk

�k � �� ni � �� be the sequence Updates of the rst transition in T that res Then theterm mapping �� S� and thus the state S� are dened by

��t S� !

�����

��vi �

S if there is a smallest i� � � i � k�such that t ! fi���ri�

S � � � � � ��rini �

S�

��t S otherwise

If �� �S is undened for one of the terms rij or vi� � � i � k� � � j � ni of the rst transitionin T that res� or if no transition res� then the state S is �nal and �� S� is undened

Proposition ��� If �� S� is a well dened term mapping� then �� S� �as dened in Def ���is well dened

��� The Equality Relation

Besides �� �and�� ��� �or�� ���� �negation�� and ���� �implication� leanEA allows in con�ditions of transitions the pre�dened predicate ��� � that implements the equality relationfor examining the current state�

Definition ��� In a state S of an evolving algebra �that corresponds to the well denedterm mapping �� S�� for all t�� t� � GTerms� the relation t� �� t� holds i�

� ��t� �

S � and ��t� �

S ��

� ��t� �

S ! ��t� �

S

��� Runs of leanEA�programs

A run of a leanEA�program P is a sequence of states S�� S�� S�� � � � of the specied evolvingalgebra Its initial state S� is given by

�� S ! �� DP �CP

�Def �� The following states are determined according to Denition �� and using

Sn� ! �Sn�� �n � �� �

This process continues iteratively until a nal state is reached

Bernhard Beckert � Joachim Posegga

Extensions ��

Proposition ��� leanEA implements the semantics as described in this section� ie� pro�vided ��

DP �CPis well dened�

� in each state S of the run of a leanEA�program P the Prolog goal ��t� ��� �X��succeeds and binds the Prolog variable X to u i� ��t �S ! u�

� the execution of P terminates in a state S i� S is a nal state�

� the predicate �� implements the equality relation

�� Some Remarks Regarding Semantics

����� Relations

There are no special pre�dened elements denoting true and false in the universe Thevalue of the relation �� �and similar pre�dened relations� see Section ��� is representedby succeeding �resp failing� of the corresponding predicate

����� Unde�ned Function Calls

Similarly� there is no pre�dened element undef in the universe� but evaluation fails if novalue is dened This� however� can be changed by adding

define � as undef with true�

as the last function denition

����� Internal and External Functions

In leanEA there is no formal distinction between internal and external functions Functiondenitions can be seen as giving default values to functions� if the default values of a functionremain unchanged� then it can be regarded external �pre�dened� If no default value isdened for a certain function� it is classically internal If the default value of a location ischanged� this is what is called an external location in �Gurevich� ����� The relation ��

�and similar predicates� are staticSince there is no real distinction� it is possible to mix internal and external functions in

function calls

����� Importing and Discarding Elements

leanEA does not have constructs for importing or discarding elements The latter is notneeded anyway If the former is useful for an application� the user can simulate �importv� by �v �� import�� where import is dened by the function denition

define import as X with gensym�fX���

����� Local Nondeterminism

If the updates of a ring transition are inconsistent� ie� several updates dene a newvalue for the same location� the rst value is chosen �this is called local nondeterminism in�Gurevich� ������

�The Prolog predicate gensym generates a new atom every time it is called�

Universit�at Karlsruhe

�� leanEA� A Poor Man�s Evolving Algebra Compiler

� Extensions

��� The let Instruction

It is often useful to use local abbreviations in a transition The possibility to do so can beimplemented by adding a clause

serialize��let Var � Term���Term� ��� �Val� Var � �Val�true��

to leanEA� Then� in addition to updates� instructions of the form

let x � t

can be used in the update part of transitions� where x is a Prolog variable and t a Prologterm This allows to use x instead of t in subsequent updates �and let instructions� of thesame transition A variable x must be dened only once in a transition using let Note�that x is bound to the quoted term ���t �� thus� using an x inside another quoted term maylead to undesired results �see the rst part of Example ���

Example ��� �let X � �a reg �� �f�X�� is equivalent to �reg �� �f��a��� �whichis di�erent from �reg �� �f�a����

let X � �b

let Y � f�XX�

reg� �� g�YY�

reg �X� �� X�

is equivalent to

reg� �� g�f��b�b�f��b�b��

reg ��b� �� �b�

Using let not only shortens updates syntactically� but also enhances e"ciency� becausefunction calls that occur multiply in an update do not have to be re�evaluated

��� Additional Relations

The Prolog predicate ��� that implements the equality relation �Def ���� is the only onethat can be used in the condition of a transition �besides the logical operators� It ispossible to implement similar relations using the leanEA internal predicate ��� to evaluatethe arguments of the relation�

A predicate p�t�� � � � � tn�� n � �� is implemented by adding the code

p�t�� � � � � tn� ��

�t�� � � � � tn� ��� �x�� � � � � xn�

Code�

to leanEA Then the goal �p�t�� � � � � tn�� can be used in conditions of transitions insteadof p��t�� � � � � tn� �� true�� where p� is dened by the function denition

�And de�ning the operator let by adding ��� op ��fxlet�����x�� � � � � xn must be n distinct Prolog variables and must not be instantiated when ��� is called� Thus�

�S �� T� �� �ST� ��� �VV��� must not be used to implement ��� but �S �� T� �� �ST� ���

�V�V��� V� �� V����

Bernhard Beckert � Joachim Posegga

Modularized Evolving Algebras ��

define p��x�� � � � � xn� as true with Code�

�which is the standard way of implementing relations using function denitions� Note�that p fails� if one of ��t�

S � � � � � ��tn �S is undened in the current state S

Example ��� The predicate �� implements the is�not�equal relation� t� �� t� succeeds i���t�

� �� ��t� � �� and ��t�

� �! ��t� � �� is implemented by adding the clause

�A �� B� �� ��AB� ��� �Val�Val � Val� ��� Val ��

to leanEA

��� Non�determinism

It is not possible to dene non�deterministic EAs in the basic version of leanEA If morethan one transition re in a state� the rst is chosen

This behavior can be changed � such that non�deterministic EAs can be executed �in the following way�

The cut from Line �� has to be removed Then� further ring transitions are executedif backtracking occurs

A �retract on backtrack� has to be added to the transitions to remove the e�ect oftheir updates and restore the previous state if backtracking occurs Line �� has to bechanged to

� asserta�Loc �� Val� � �retract�Loc �� Val�fail� ��

Now� leanEA will enumerate all possible sequences of transitions Backtracking is in�itiated� if a nal state is reached� ie� if the further execution of a leanEA program fails

The user has to make sure that there is no innite sequence of transitions �eg� byimposing a limit on the length of sequences�

Note� that usually the number of possible transition sequences grows exponentially intheir length� which leads to an enormous search space if one tries to nd a sequence thatends in a �successful� state by enumerating all possible sequences

Modularized Evolving Algebras

One of the main advantages of EAs is that they allow a problem�oriented formalizationThis means� that the level of abstraction of an evolving algebra can be chosen as needed Inthe example algebra in Section �� �p �� for instance� we simply used Prolog�s arithmeticsover integers and did not bother to specify what multiplication or subtraction actuallymeans In this section� we demonstrate how such levels of abstraction can be integratedinto leanEA� the basic idea behind it is to exploit the module�mechanism of the underlyingProlog implementation

Universit�at Karlsruhe

�� leanEA� A Poor Man�s Evolving Algebra Compiler

algebra fak��N��reg ��

using �mult�

start reg� �� N

reg �� �

stop reg� �� ��

define readint as X with read�X� integer�X��

define write�X� as X with write�X��

define X as X with integer�X��

define X�Y as R with integer�X�integer�Y�R is X�Y�

define X�Y as R with mult��XY��R���

transition step

if ���reg� �� ��

then reg� �� �reg����

reg �� �reg �reg���

Figure �� A Modularized EA for Computing n�

�� The Algebra Declaration Statement

In the modularized version of leanEA� each specication of an algebra will become a Prologmodule� therefore� each algebra must be specied in a separate le For this� we add analgebra declaration statement that looks as follows�

algebra Name�InOut�using �Include�List�start Updatesstop Guard�

Name is an arbitrary Prolog atom that is used as the name of the predicate for runningthe specied algebra� and as the name of the module It is required that Name�plis also the le name of the specication and that the algebra�statement is the rststatement in this le

In� Out are two lists containing the input and output parameters of the algebra Theelements of Out will be evaluated if the algebra reaches a nal state �see below�

Include�List is a list of names of sub�algebras used by this algebra

Updates is a list of updates� it species that part of the initial state of the algebra �seeSection ��� p ��� that depends on the input In

Guard is a condition that species the nal state of the evolving algebra If Guard issatised in some state� the computation is stopped and the algebra is halted �seeSection ��� p ��

Bernhard Beckert � Joachim Posegga

Modularized Evolving Algebras ��

algebra mult��XY��result��

using ��

start reg� �� X

reg �� Y

result �� �

stop reg� �� ��

define write�X� as X with write�X��

define X as X with integer�X��

define X�Y as R with integer�X�integer�Y�R is X�Y�

define X�Y as R with integer�X�integer�Y�R is X�Y�

transition step

if ���reg� �� ��

then reg� �� �reg����

result �� �result�reg ��

Figure �� A Modularized EA for Multiplication

Example �� As an example consider the algebra statement in Figure �� an algebra fak isdened that computes n� This is a modularized version of the algebra shown in Section ��on page � The transitions start and result are now integrated into the algebra statement

The last function denition in the algebra is of particular interest� it shows how thesub�algebra mult� included by the algebra statement� is called Where the earlier algebrafor computing n� on page � used Prolog�s built�in multiplication� a sub�algebra for carryingout multiplication is called Its denition can be found in Figure �

�� Implementation of Modularized EAs

The basic di�erence between the basic version of leanEA and the modularized version is thatthe algebra�statement at the beginning of a le containing an EA specication is mappedinto appropriate module and use module statements in Prolog Since the algebra willbe loaded within the named module� we also need an evaluation function that is denedinternally in this module This allows to use functions with the same name in di�erentalgebras without interference

Figure � �p ��� lists the modularized program It denes four additional operators�algebra� start� stop� and using� that are needed for the algebra statement The rstterm expansion clause �Lines ����� translates such a statement into a Prolog moduleheader� declares ��� to be dynamic in the module� and denes the evaluation predicate��� for this module�� The e�ect of the term expansion�statement is probably best seenat an example� the module declaration in Figure �� for instance� is mapped into

�This implementation is probably speci�c for SICStus Prolog and needs to be changed to run on otherProlog systems� The �Name��pre�x is required in SICStus� because a ��� module�� ���declaration becomes e�ective after the current term was processed�

Universit�at Karlsruhe

�� leanEA� A Poor Man�s Evolving Algebra Compiler

� �� op���fy�transition�� op�����xfx�if��

� op��� fy�define�� op�����xfy�with��

� op����xfy�as�� op�����xfx�then��

� op���xfx����� op���xfx������

� op���xfx����� op���xfx�����

� op����fx���� op���fx�algebra��

� op����xfy�start�� op�����xfx�stop��

� op�����xfy�using���

term�expansion��algebra Head using Include�list

� start Updates stop Guard�

�� ���� module�Name�Name� ���

�� Name���� use�module�Include�list��

�� ��� dynamic�Name������ ��

�� Name����H�T� ��� �HVal�TVal�� ��

�� � H � �HVal

�� � H ��� �Func�Args� Args ��� ArgVals

�� H� ��� �Func�ArgVals� H� �� HVal��

�� T ��� TVal�

� Name���� ��� ���

� Name���A �� B� �� ��AB� ��� �Val�Val ��

�� Val� �� Val �

�� Name��NewHead �� FrontCodeBackCode�

�� �transition ��Out ��� Value�

�� Name��transition�result� �� �Guard�������

�� Head ����NameInOut� NewHead ����NameInValue�

�� serialize�UpdatesFrontCodeBackCode��

�� term�expansion��define Location as Value with Goal�

�� ��Location �� Value� �� Goal����

� term�expansion��transition Name if Condition then Updates�

� �transition�Name� ��

�� �Condition�FrontCodeBackCodetransition������ ��

�� serialize�UpdatesFrontCodeBackCode��

�� serialize��AB��FrontAFrontB��BackBBackA�� ��

�� serialize�AFrontABackA�

�� serialize�BFrontBBackB��

�� serialize��LocTerm �� Expr�

�� ��Expr� ��� �Val� LocTerm ��� �Func�Args�

�� Args ��� ArgVals Loc ����Func�ArgVals��

� asserta�Loc �� Val���

Figure �� Modularized EAs� the Program

Bernhard Beckert � Joachim Posegga

Conclusion ��

�� module�fak�fak� ���

fak����use module��mult����

�� dynamic fak������ �

plus the usual denition of ����

�� Running Modularized EAs

In contrast to the basic version of the EA interpreter� a modularized EA has a denedinterface to the outside world� The algebra�statement denes a Prolog predicate that canbe used to run the specied EA Thus� the user does not need to start the transitionsmanually Furthermore� the run of a modularized EA does not end with failure of thestarting predicate� but with success This is the case since a modularized EA has a denednal state If the predicate succeeds� the nal state has been reached

For the example algebra above �Figure ��� the run proceeds as follows�

� �� �ea��

�consulting ea�pl����

�ea�pl consulted �� msec � bytes�

yes

� �� �fak��

�consulting fak�pl����

�consulting mult�pl����

�consulted mult�pl in module mult � msec ���� bytes�

�consulted fak�pl in module fak �� msec ���� bytes�

yes

� �� fak� Result��

Result � � � �

yes

� ��

After loading�� the EA interpreter� the EA of Figure � is loaded from the le fak�pl Thusloads in turn the algebra for multiplication in mult�pl The algreba is then started andthe result of �� is returned

Conclusion

We presented leanEA� an approach to implementing an abstract machine for evolving al�gebras The underlying idea is to modifying the Prolog reader� such that loading a speci�cation of an evolving algebra means compiling it into Prolog clauses Thus� the Prologsystem itself is turned into an abstract machine for running EAs The contribution of ourwork is twofold�

��For more complex computations it is of course advisable to compile� rather than to load the Prologcode�

Universit�at Karlsruhe

�� leanEA� A Poor Man�s Evolving Algebra Compiler

Firstly� leanEA o�ers an e"cient and very �exible framework for simulating EAs leanEA

is open� in the sense that it is easily interfaced with other applications� embedded into othersystems� or adapted to concrete needs We believe that this is a very important featurethat is often underestimated� if a specication system is supposed to be used in practice�then it must be embedded in an appropriate system for program development leanEA�as presented in this paper� is surely more a starting point than a solution for this� but itdemonstrates clearly one way for proceeding

Second� leanEA demonstrates that little e�ort is needed to implement a simulator forEAs This supports the claim that EAs are a practically relevant tool� and it shows a clearadvantage of EAs over other specication formalisms� these are often hard to understand�and di"cult to deal with when implementing them EAs� on the other hand� are easilyunderstood and easily used Thus� leanEA shows that one of the major goals of EAs� namelyto �bridge the gap between computation models and specication methods� �followingGurevich �������� was achieved

A An Extended Example� First Order Semantic Tableaux

A�� An Evolving Algebra Description of Semantic Tableaux

The following is a leanEA specication of semantic tableaux for rst order logic It is adeterministic version of the algebra described in �B�orger Schmitt� ����� We assume thereader to be familiar with free variable semantic tableau �Fitting� �����

We use Prolog syntax for rst�order formulae� atoms are Prolog terms� ��� is negation���� disjunction� and �� conjunction Universal quantication is expressed as all�XF��where X is a Prolog variable and F is the scope� similarly� existential quantication isexpressed as ex�XF�

Example �� �p���all�N��p�N��p�s�N����� stands for p��� ��n��p�n� p�s�n�����

Since formulae have to be represented by ground terms� the variables are instantiatedwith !"VAR!���� !"VAR!� �� etc using numbervars��

A branch is represented as a �Prolog� list of the formulae it contains� a tableau isrepresented as a list of the branches it consists of

The external functions nxt�fml� nxt�branch� update�branch� and update�tableau

are only described declaratively in �B�orger Schmitt� ������ they determine in whichorder formulae and branches are used for expansion of a tableau A simple version ofthese functions has been implemented �see below�� that nevertheless is quite e"cient Itimplements the same tableau procedure that is used in the tableau based theorem proverleanTAP �Beckert Posegga� �����

A�� Preliminaries

First� library modules are included that are used in the function denitions�� The usageof the included predicates is described below

��numbervars�Term�N�M� uni�es each of the variables in term Term with a special term ��VAR�i��where i ranges from N to M� �� N must be instantiated to an integer� write� format� and listing print thespecial terms as variable names A� B� � � � � Z� A�� B�� etc�

��These are modules from the SICStus Prolog library� They might be named di�erently and�or behavedi�erently in other Prolog systems�

Bernhard Beckert � Joachim Posegga

An Extended Example� First Order Semantic Tableaux ��

� �� use�module�library�charsio��format�to�chars��

� open�chars�stream�����

� �� use�module�library�lists��append�����

� �� use�module�unify�unify� ���

The formula Fml to be proven to be inconsistent is given as a Prolog fact formula�Fml��which is additional Prolog code�� Fml has to be a closed formula� and the same variablemust not be bound by more than one quantier In Fml the Prolog variables are not yetreplaced by ground terms

� formula��all�X��p�X��p�f�X����p�a��p�f�f�a������

A�� Function De�nitions

A���� Initial Values of Internal Constants

The constant tmode �called mode in �B�orger Schmitt� ������ denes the mode of thetableau prover which is either close �the next transition will check for closure of thecurrent tableau�� expand �the next transition tries to expand the tableau�� failure �thetableau is not closed and cannot be expanded�� or success �the tableau is closed� ie� aproof has been found� The initial value of tmode is close�

� define tmode as close�

The current branch cbranch initially contains only the formula to be proven to beinconsistent The variables in this formula are instantiated with !"VAR!���� !"VAR!� ��etc using numbervars� such that �Formula� becomes a ground term

� define cbranch as �Formula� with formula�Formula�

� numbervars�Formula����

The current tableau ctab is initially a list containing the initial current branch �descri�bed above� as its single element

define ctab as ��Formula�� with formula�Formula�

� numbervars�Formula����

The current formula cfml is initially set to ��nxtfml�cbranch� �� where the externalfunction nxtfml �see Sec A��� chooses the next formula from a branch to be expandedSince the function nxtfml cannot be called immediately��� the predicate nxtfml�impl� thatimplements nxtfml� is used instead

�� define cfml as Cfml with formula�Formula�

�� numbervars�Formula���

�� nxtfml�impl��Formula�Cfml��

varcount is the number of variables already used in the proof �plus one� Its initialvalue is the number of �di�erent� variables in the initial current formula �plus one�

�� define varcount as Count with formula�Formula�

�� numbervars�Formula�Count��

��It is not possible in leanEA to use a function of the speci�ed algebra in the Prolog code of functionde�nitions�

Universit�at Karlsruhe

�� leanEA� A Poor Man�s Evolving Algebra Compiler

The constant fcount contains the number of Skolem function symbols already alreadyused �plus one� Its initial value is ��

�� define fcount as ��

A���� De�nitions of External Functions

The function rename�FmlCount� replaces the atom !"VAR!��� � which is a place holderfor the special variable that is called v in �B�orger Schmitt� ����� � in Fml by !"VAR!�n��where n is the integer Count is bound to !"VAR!�n� is the place holder for the nth variablerename is implemented using the predicate replace �see Section A��

�� define rename�FmlCount� as Newfml with

�� replace�Fml!"VAR!���!"VAR!�Count�Newfml��

The function inst is similar to rename� but instead of inserting a new variable for theatom !"VAR!���� it is replaced by a Skolem term The Skolem term is composed of thefunctor f� the number that is bound to Fcount �which makes the Skolem terms di�erentfor di�erent values of Fcount�� and �the place holders of� the rst Varcount variables �thepredicate freevars is described in Section A��

� define inst�FmlFcountVarcount� as Newfml with

� freevars�VarcountFree�

�� Skolem ��� �fFcount�Free�

�� replace�Fml!"VAR!���SkolemNewfml��

The value of the function exhausted is � if the tableau T bound to Tab is exhausted� elseit is � A tableau is exhausted� if no next branch can be chosen� ie� if ��nxtbranch�T� !bottom

�� define exhausted�Tab� as � with nxtbranch�impl�Tabbottom��

�� define exhausted��� as ��

succ is the successor function on integers�

�� define succ�X� as X� with integer�X� X� is X���

update�branch removes the old formula Old�fml from the branch Old�branch� ifOld�fml is a ��formula� it is then appended at the end of the branch New formulaeare added to the beginning of the branch There are two versions of this function� for onenew formula ������� and one for two new formulae ������� Note� that Old�fml is never aliteral

In combination with the implementation of nxtfml that always chooses the �rst non�literal formula� update�branch implements branches as queues� which leads to a completetableau proof procedure

�� define update�branch�Old�branchOld�fmlNew�fml� as New�branch with

�� remove�Old�branchOld�fmlTmp�branch�

�� � fmltype�impl�Old�fmlgamma� ��

� append��New�fml�Tmp�branch��Old�fml�New�branch�

� � New�branch � �New�fml�Tmp�branch�

�� ��

Bernhard Beckert � Joachim Posegga

An Extended Example� First Order Semantic Tableaux ��

�� define update�branch�Old�branchOld�fmlNew�fml��New�fml� � as

�� New�branch with

�� remove�Old�branchOld�fmlTmp�branch�

�� � fmltype�impl�Old�fmlgamma� ��

�� append��New�fml��New�fml� �Tmp�branch�

�� �Old�fml�New�branch�

�� � New�branch � �New�fml��New�fml� �Tmp�branch�

� ��

The function update�tabl removes the old branch from the tableau and appends thenew branch�es� to the end of the tableau There are two version of this function� for onenew branch and for two new branches

� define update�tabl�Old�tablOld�branchNew�branch� as New�tabl with

�� remove�Old�tablOld�branchTmp�tabl�

�� append�Tmp�tabl�New�branch�New�tabl��

�� define update�tabl�Old�tablOld�branch

�� New�branch��New�branch� � as

�� New�tabl with

�� remove�Old�tablOld�branchTmp�tabl�

�� append�Tmp�tabl�New�branch��New�branch� �New�tabl��

In �B�orger Schmitt� ����� the value of the function clsubst is a list of the closingsubstitutions of a tableau But� since we only need to know whether there is a closingsubstitution or not� the value of clsubst is in our version just empty or nonempty Thepredicate is�closed� that checks whether a tableau is closed� is described in Section A�

�� define clsubst�T� as nonempty with is�closed�T��

� define clsubst��� as empty�

The function nxtfml chooses the rst formula on the branch that is not a literal� ifno such formula exists� its value is bottom The predicate nxtfml�impl is described inSection A�

� define nxtfml�B� as Next with nxtfml�impl�BNext��

nxtbranch chooses the rst branch of a tableau that is expandable� ie� the rstbranch B such that ��nxtfml�B� is not bottom The predicate nxtbranch�impl is de�scribed in Section A�

�� define nxtbranch�T� as Next with nxtbranch�impl�TNext��

The function fmltype determines the type of a formula� which is one of alpha� beta�gamma� delta� and lit �for literals� The predicate fmltype�impl is described in Sec�tion A�

�� define fmltype�Fml� as Type with fmltype�impl�FmlType��

The function fst�comp�Fml� ������� computes the rst formula that is the result ofapplying the appropriate tableau rule to Fml� if the rule application results in two newformulae� snd�comp�Fml� returns the second formula In �B�orger Schmitt� ����� the ��

Universit�at Karlsruhe

�� leanEA� A Poor Man�s Evolving Algebra Compiler

and ��rules are dened in such a way that the atom !"VAR!���� which is the place holderfor the special variable v� is substituted for the bound variable The substitution is doneusing the predicate replace �see below� v is replaced by the appropriate term �a newvariable or a Skolem term� in the transitions gamma and delta� respectively

�� define fst�comp�Fml� as First with

�� � Fml � �F�� �� First � F

�� � Fml � ���F���� �� First � �F

�� � Fml � ����F�� �� First � F

�� � Fml � ���F��� �� First � �F

�� � Fml � �F��� �� First � F

� � Fml � all�XF� �� replace�FX!"VAR!���First�

� � Fml � ��ex�XF�� �� replace���F�X!"VAR!���First�

�� � Fml � ��all�XF�� �� replace���F�X!"VAR!���First�

�� � Fml � ex�XF� �� replace�FX!"VAR!���First�

�� ��

�� define snd�comp�Fml� as Second with

�� � Fml � ��F� �� Second � F

�� � Fml � �����F�� �� Second � �F

�� � Fml � ����F�� �� Second � F

�� � Fml � ����F�� �� Second � �F

� � Fml � ���F� �� Second � F

� ��

A�� Additional Code Used in the Function De�nitions

The predicate nxtfml�impl implements the function nxtfml� it chooses the rst formulaon a tableau branch that is not a literal If no such formula exists� the value of nxtfml isbottom� the value of nxtfml�bottom� is bottom as well

�� nxtfml�impl�bottombottom��

�� nxtfml�impl���bottom��

�� nxtfml�impl��First���Fml� ��

�� ���fmltype�impl�Firstlit���Fml�First�

�� nxtfml�impl����Rest�Next� �� nxtfml�impl�RestNext��

The predicate nxtbranch�impl implements the function nxtbranch� it chooses the rstbranch of a tableau that is expandable� ie� the rst branch that contains a formula thatis not a literal If no such branch exists� the value of nxtbranch is bottom

�� nxtbranch�impl���bottom��

�� nxtbranch�impl��First���Branch� ��

�� ���nxtfml�impl�Firstbottom���Branch�First�

� nxtbranch�impl����Rest�Next� �� nxtbranch�impl�RestNext��

The predicate fmltype�impl implements the function fmltype �in the obvious way�

� fmltype�impl�FmlType� ��

�� � Fml � ���� �� Type � alpha

Bernhard Beckert � Joachim Posegga

An Extended Example� First Order Semantic Tableaux ��

�� � Fml � �������� �� Type � alpha

�� � Fml � ������� �� Type � alpha

�� � Fml � ������� �� Type � beta

�� � Fml � ����� �� Type � beta

�� � Fml � all���� �� Type � gamma

�� � Fml � ��ex����� �� Type � gamma

�� � Fml � ��all����� �� Type � delta

� � Fml � ex���� �� Type � delta

� Type � lit

� ��

replace��Term�Old�NewNew�term� replaces all occurrences of Old in Term by NewThe result is bound to New�term replace�list��List�Old�NewNew�list� does thesame for a list List of terms

� replace�TermOldNewNew� ��

� Term �� Old

� ��

� replace�TermOldNewNTerm� ��

� Term ��� �F�Args�

� replace�list�ArgsOldNewNArgs�

� NTerm ��� �F�NArgs��

replace�list���������

� replace�list��H�T�OldNew�NH�NT�� ��

�� replace�HOldNewNH�

�� replace�list�TOldNewNT��

The predicate freevars��N�List�� generates a list of the place holders for the rstn variables� where n is the integer N is bound to

�� freevars����� �� ��

�� freevars�N�!"VAR!�N���Free�� ��

�� integer�N�

�� N� is N��

�� freevars�N�Free��

remove��Old�list�Elem�New�list� removes all occurrences of the term Elem fromthe list Old�list� the result is bound to New�list

�� remove��������

� remove��H�T�ElemNew� ��

�� remove�TElemNT�

��� � H �� Elem ��

��� New � NT

��� � New � �H�NT�

��� �

��� ��

The predicate is�closed��T� �Lines �������� checks whether the tableau bound to T

is closed First� the predicate denumbervars is called �described below�� that replaces

Universit�at Karlsruhe

�� leanEA� A Poor Man�s Evolving Algebra Compiler

the variable place holders by Prolog variables� then the predicate is�closed� ���������is called� which closes the branches of a tableau �containing Prolog variables as objectvariables� one after the other using close�branch

close�branch ��������� negates the rst formula on the branch �and further formulaeif backtracking occurs� and tries to unify this negation with another formula on the branch

is�closed and the predicates it calls heavily depend on backtracking for nding a singlesubstitution that closes all branches of the tableau simultaneously

��� is�closed�T� ��

��� denumbervars�TT��

��� is�closed� �T��

�� ��

�� is�closed� �����

��� is�closed� ��First�Rest�� ��

��� close�branch�First�

��� is�closed� �Rest��

��� close�branch��H�T�� ��

��� �H � �Neg� �H � Neg� ��

��� member�unify�NegT��

��� close�branch����T�� �� close�branch�T��

member�unify is the same as member� except that is uses sound unication �with occurcheck�

��� member�unify�X�H�T�� ��

�� � unify�XH�

�� � member�unify�XT�

��� ��

The predicate denumbervars replaces the place holders of the form !"VAR!�n� by�new� Prolog variables It is the most system dependent predicate in the denition ofthis evolving algebra It works by writing the tableau to a �character stream� usingformat�to�chars����� which replaces the place holders by Prolog variables�� and thenre�reading the tableau from the �character stream��� append�Chars� #�CharsPoint�

adds a period ��� to the term such that it becomes a Prolog fact

��� denumbervars�TT�� ��

��� format�to�chars�$%p$�T�Chars�

��� append�Chars� #�CharsPoint�

��� open�chars�stream�CharsPointreadStream�

��� read�StreamT��

��� close�Stream��

��format to chars�Format�Arguments�Chars� prints Arguments into a list of character codes usingformat�� �which in this case just prints the term�� Chars is uni�ed with the list�

��See Footnote �� on Page �����open chars stream�Charsread�Stream� opens Stream as an input stream to an existing list of cha

racter codes� The stream may be read with the Stream IO predicates and must be closed using close���

Bernhard Beckert � Joachim Posegga

An Extended Example� First Order Semantic Tableaux ��

A�� Transition De�nitions

The main di�erence to the original version of the EA as described in �B�orger Schmitt������ is that instead of using an additional transition

transition enter�closure

if tmode �� �expand

then tmode �� �close�

the closure mode is entered explicitly at the end of each of the expanding transitions alpha�beta� gamma and delta Using the transition enter�closure would make the EA non�deterministic� because it res whenever one of the expanding transitions res

If the EA is in closure mode� there are three transitions that might apply�

� If the current tableau is closed� transition success ��������� res and tmode is setto success Then� the EA is in a nal state� because no further transition res

� If the tableau is not closed but expandable� transition closure ��������� res� tmodeis set to expand� and the tableau will be expanded in the next step

� If the current tableau is neither closed nor expandable� transition failure ���������res It sets tmode to fail� and the EA reaches a nal state

��� transition success

�� if tmode �� �close

�� clsubst�ctab� �� �empty

��� then tmode �� �success�

��� transition closure

��� if tmode �� �close

��� clsubst�ctab� �� �empty

��� exhausted�ctab� �� ��

��� then tmode �� �expand�

��� transition failure

��� if tmode �� �close

�� clsubst�ctab� �� �empty

�� exhausted�ctab� �� ��

��� then tmode �� �fail�

There are four transitions for expanding the current tableau� one for each possible typeof the current formula �which is never a literal� The denitions of these transitions makeuse of the let construct �Sec ���

The transition alpha rst stores the two formulae that are the result of the rule applica�tion to the current formula in F� and F � respectively These two formulae are added to thecurrent branch �and the old current formula is removed�� the new branch� that is stored in B

is added to the current tableau �and the old branch is removed� The resulting tableau T

becomes the next current tableau� and the next current branch and current formula arechosen from T

��� transition alpha

Universit�at Karlsruhe

�� leanEA� A Poor Man�s Evolving Algebra Compiler

��� if tmode �� �expand

��� fmltype�cfml� �� �alpha

��� then let F� � fst�comp�cfml�

��� let F � snd�comp�cfml�

��� let B � update�branch�cbranchcfmlF�F �

��� let T � update�tabl�ctabcbranchB�

�� ctab �� T

�� cbranch �� nxtbranch�T�

��� cfml �� nxtfml�nxtbranch�T��

��� tmode �� �close�

The transition beta� too� stores the two formulae that are the result of the rule appli�cation to the current formula in F� and F � respectively But contrary to the transitionalpha� it generates two new branches B� and B by adding the new formulae separately tothe current branch Both new branches are added to the current tableau �the old branch isremoved� The resulting tableau T becomes the next current tableau� and the next currentbranch and current formula are chosen from T

��� transition beta

��� if tmode �� �expand

��� fmltype�cfml� �� �beta

��� then let F� � fst�comp�cfml�

��� let F � snd�comp�cfml�

��� let B� � update�branch�cbranchcfmlF��

�� let B � update�branch�cbranchcfmlF �

�� let T � update�tabl�ctabcbranchB�B �

��� ctab �� T

��� cbranch �� nxtbranch�T�

��� cfml �� nxtfml�nxtbranch�T��

��� tmode �� �close�

The transition gamma rst stores the result of applying fst�cmp to the current formulain F� which is the scope of the quantication with the bound variable replaced by the specialvariable v �resp its place holder !"VAR!���� v is then replaced by a new free variable usingrename The resulting formula F� is added to the current branch and the new branch isadded to the current tableau �replacing the old branch� The next current branch andcurrent formula are chosen� and varcount is increased by one

��� transition gamma

��� if tmode �� �expand

��� fmltype�cfml� �� �gamma

��� then let F � fst�comp�cfml�

�� let F� � rename�Fvarcount�

�� let B � update�branch�cbranchcfmlF��

��� let T � update�tabl�ctabcbranchB�

��� ctab �� T

��� cbranch �� nxtbranch�T�

��� cfml �� nxtfml�nxtbranch�T��

��� varcount �� succ�varcount�

Bernhard Beckert � Joachim Posegga

An Extended Example� First Order Semantic Tableaux ��

��� tmode �� �close�

The transition delta is very similar to the transition gamma The only di�erences arethat the variable v is replaced by a Skolem term �instead of a free variable� using inst� andthat fcount is increased instead of varcount

��� transition delta

��� if tmode �� �expand

�� fmltype�cfml� �� �delta

� then let F � fst�comp�cfml�

�� let F� � inst�Ffcountvarcount�

�� let B � update�branch�cbranchcfmlF��

�� let T � update�tabl�ctabcbranchB�

�� ctab �� T

�� cbranch �� nxtbranch�T�

�� cfml �� nxtfml�nxtbranch�T��

�� fcount �� succ�fcount�

�� tmode �� �close�

References

Beckert Bernhard � Posegga Joachim ���� leanTAP � Lean Tableau�based De�duction Journal of Automated Reasoning To appear

B�orger Egon � Rosenzweig Dean ���� A Mathematical Denition of Full PrologScience of Computer Programming

B�orger Egon � Schmitt Peter H� ���� A Description of the Tableau Method UsingEvolving Algebras

B�orger Egon Durdanovic Igor � Rosenzweig Dean ����a Occam� Speci�cation and Compiler Correctness Pages ����� of� Montanari U� � Olderog

E��R� �eds�� Proceedings� IFIP Working Conference on Programming Concepts� Me�thods and Calculi PROCOMET ��� North�Holland

B�orger Egon Del Castillo Giuseppe Glavan P� � Rosenzweig Dean ����bTowards a Mathematical Specication of the APE��� Architecture� The APESE Mo�del Pages ������ of� Pehrson B� � Simon I� �eds�� Proceedings� IFIP ��thWorld Computer Congress� vol � Amsterdam� Elsevier

Fitting Melvin C� ���� First�Order Logic and Automated Theorem Proving Springer�Verlag

Gurevich Yuri ���� Evolving Algebras A Tutorial Introduction Bulletin of theEATCS� ��� �������

Gurevich Yuri ���� Evolving Algebras ����� Lipari Guide In� B�orger E� �ed��Speci�cation and Validation Methods Oxford University Press

Universit�at Karlsruhe

�� leanEA� A Poor Man�s Evolving Algebra Compiler

Gurevich Yuri � Huggins Jim ���� The Semantics of the C Programming LanguagePages ������ of� Proceedings� Computer Science Logic CSL� LNCS ��� Springer

Gurevich Yuri � Mani Raghu ���� Group Membership Protocol� Specicationand Verication In� B�orger E� �ed�� Speci�cation and Validation Methods OxfordUniversity Press

Kappel Angelica M� ���� Executable Specications based on Dynamic Algebras Pages������ of� Proceedings� �th International Conference on Logic Programming andAutomated Reasoning LPAR�� St� Petersburg� Russia LNCS ��� Springer

Bernhard Beckert � Joachim Posegga