scieee AI-readable full text Open interactive document viewer

Term rewriting systems .net framework

Arnal Julián, Salvador

Abstract

[EN] This thesis presents the implementation of a framework to work with term rewriting systems. Term rewriting systems provide a complete computational model which is very close to functional programming. Its formulation is equational logic and it can also be used to reason about program properties, not only of functional programs but also of programs written in other programming languages. Our framework has been implemented in a tool called TRS.Tool (built on .Net and available at http://TRS.JarCode.Net) that covers three main objectives: - Determine the basic properties of a given term rewriting system (signature, set of rules conservativeness, linearity, etc…). - Calculate the critical pairs of the term rewriting system and determine its orthogonality. - Apply the rewriting rules over a given term. The tool is available as a web based application created using this framework

Full text

Ocial Master's Degree in Software Engineering, Formal Methods and Information Systems Universitat Politècnica de València Departamento de Sistemas Informáticos y Computación Term Rewriting Systems .Net Framework Author: Supervisor: Arnal Julián, Salvador Lucas Alba, Salvador Academic Year 2012/2013 I To Loanny, the reason I smile each day since we met each other. ABSTRACT This thesis presents the implementation of a framework to work with term rewriting systems. Term rewriting systems provide a complete computational model which is very close to functional programming. Its formulation is equational logic and it can also be used to reason about program properties, not only of functional programs but also of programs written in other programming languages. Our framework has been implemented in a tool called TRS.Tool (built on .Net and available at http://TRS.JarCode.Net ) that covers three main objectives: 1. Determine the basic properties of a given term rewriting system (signature, set of rules conservativeness, linearity, etc...). 2. Calculate the critical pairs of the term rewriting system and determine its orthogonality. 3. Apply the rewriting rules over a given term. The tool is available as a web based application created using this framework. II RESUMEN Esta tesis presenta la implementación de un marco para trabajar con sistemas de reescritura de términos. Los sistemas de reescritura de términos proporcionan un modelo de cómputo completo que es muy cercano a la programación funcional. Su formulación es la de la lógica ecuacional y puede ser utilizado también para razonar sobre las propiedades de los programas, no solo de los programas funcionales, sino también de programas escritos en otros lenguajes de programación. Nuestro marco que ha sido implementado en una herramienta llamada TRS.Tool (creada en .Net y disponible en http://TRS.JarCode.Net ) que cubre tres objetivos principales: 1. Determinar las propiedades básicas de un sistema de reescritura de términos dado (signatura, conjunto de reglas, conservativo, lineal, etc...). 2. Calcular los pares críticos del sistema de reescritura de términos y determinar su ortogonalidad. 3. Aplicar las reglas de reescritura sobre un término dado. La herramienta está disponible como una aplicación web creada utilizando este marco. III ACKNOWLEDGMENTS Writing this master thesis would have been impossible without the help and support of the kind people around me. Here I can give particular mention to some of them only. It is a dicult task to acknowledge all people who inuenced my life and contributed, in dierent ways, to this thesis. I am very grateful to all my friends and colleagues. However, I would like to add some personal words. First and foremost I oer my sincerest gratitude to my supervisor Prof. Salvador Lucas, I appreciate his vast knowledge and skill in many areas. Without his assistance and guidance this thesis wouldn't be possible. A very special thanks goes out to my family, my brother and my parents, for their support during my entire life and, in particular, I must acknowledge Loanny, my friend, my love, my partner, my life: you came into my life recently but without your love, kindness and encouragement I would not have nished this master. I would like to acknowledge my friends for their moral support and motivation, which drives me to give my best. Alejandro, Ana, Carolina, Elena, Jorge, Luis, Mario, Max, Pedro, Pilar, Rodrigo, Silvia, ...the list is endless. I know most of you will never understand a word of this thesis, but you all made it possible. Thanks to one and all. Boro Arnal IV CONTENTS Abstract II Resumen III Acknowledgments IV Contents V List of Figures VIII List of Tables XII List of Examples XV 1 Introduction 1 1.1 Objectives............................. 5 1.2 PlanoftheThesis......................... 5 2 Preliminaries 7 V CONTENTS VI 2.1 Basicconcepts........................... 7 2.1.1 Signature, variables and terms . . . . . . . . . . . . . . 7 2.1.2 Substitutions, matching and unication . . . . . . . . . 11 2.1.3 Rewrite Rules and Term Rewriting Systems . . . . . . 12 2.2 Conuence............................. 15 2.2.1 Local conuence and Conuence . . . . . . . . . . . . . 15 2.2.2 Critical pairs . . . . . . . . . . . . . . . . . . . . . . . 16 2.2.3 Orthogonality . . . . . . . . . . . . . . . . . . . . . . . 18 2.2.4 Decidability........................ 20 3 Framework Model 22 3.1 Term Rewriting System Module . . . . . . . . . . . . . . . . . 24 3.1.1 SymbolClass ....................... 26 3.1.2 TermClass ........................ 28 3.1.3 RuleClass......................... 29 3.1.4 TermRewritingSystem Class . . . . . . . . . . . . . . . 31 3.2 Critical Pair Module . . . . . . . . . . . . . . . . . . . . . . . 35 3.2.1 Substitution Class . . . . . . . . . . . . . . . . . . . . 35 3.2.2 Position Class . . . . . . . . . . . . . . . . . . . . . . . 36 3.2.3 CriticalPair Class . . . . . . . . . . . . . . . . . . . . . 37 3.3 ExecutionModule......................... 38 3.3.1 Execution Tree Class . . . . . . . . . . . . . . . . . . . 38 3.3.2 ExecutionNode Class . . . . . . . . . . . . . . . . . . . 40 4 Implementation 47 4.1 Unication............................. 47 4.2 Matching ............................. 51 CONTENTS VII 4.3 Conuence decision . . . . . . . . . . . . . . . . . . . . . . . . 54 5 TRS.Tool 60 5.1 TPDBFormat........................... 61 5.2 UseExample ........................... 63 5.2.1 InputData ........................ 64 5.2.2 Terms ........................... 66 5.2.3 Matching and unication . . . . . . . . . . . . . . . . . 68 5.2.4 Rules............................ 69 5.2.5 CriticalPairs ....................... 70 5.2.6 Term Execution . . . . . . . . . . . . . . . . . . . . . . 75 6 Testing the framework 84 7 Conclusions 89 Bibliography 91 LIST OF FIGURES 1 Term tree structure . . . . . . . . . . . . . . . . . . . . . . . . 11 2 Local conuence and Conuence . . . . . . . . . . . . . . . . . 16 3 CriticalPairgraph ........................ 18 4 Critical Pair convergence graph . . . . . . . . . . . . . . . . . 20 5 Term Rewriting System Module Diagram . . . . . . . . . . . . 23 6 Critical Pair Module Diagram . . . . . . . . . . . . . . . . . . 23 7 Execution Module Diagram . . . . . . . . . . . . . . . . . . . 24 8 Term Rewriting System Module Class Diagram . . . . . . . . 25 9 SymbolClass ........................... 26 10 Symbol inheritance structure . . . . . . . . . . . . . . . . . . . 27 11 TermClass ............................ 28 12 RuleClass............................. 30 13 TermRewritingSystem Class . . . . . . . . . . . . . . . . . . . 31 14 Term Rewriting System in memory representation . . . . . . . 34 15 Critical Pair Module Class Diagram . . . . . . . . . . . . . . . 35 VIII LIST OF EXAMPLES XV 16 Termination Analysis. . . . . . . . . . . . . . . . . . . . . . . . . . 81 CHAPTER 1 INTRODUCTION In Software Engineering and Programming, formal methods are understood as a collection of mathematical techniques for developing software and hardware systems. In software engineering they can be used to exploit the power of mathematical notations and proofs. Formal methods cover hundreds of methodologies, languages and notations that can be used to specify and verify properties. Some formal methods rely on the use of Term Rewriting Systems ( TRSs ). There are various areas where the term rewriting systems play an important role in the study of computational procedures. Rewrite rules can be used to specify properties and requirements of programs. And using the theory of rewriting systems, we can check them. We all have used rewriting systems, without knowing it, since school. When we simplify an arithmetic equation, we can do it as follows: (3 + 4) ·(4 + 2) →7·(4 + 2) →7·6→42 (1) We can see this sequence as performing elementary simplication steps within some context. The elementary steps are the basic operations of addition and multiplication that we can easily represent by means of simple rules like ( 0 + 1 →1,0 + 2 →2,0 + 3 →3,...,0·1→0,0·2→0, . . . ). The contexts are arithmetic expressions with a `hole' where the elementary step 1 2 is done. On the rst step of the sequence (1) the context is ·(4 + 2) , where  denotes the hole, and 3+4→7 is the elementary step. This means that  is 3+4 before and 7 after. We are applying a sequence of elementary steps, till we obtain a term (i.e., 42 ) that can't be reduced anymore: this is the normal form. Some important properties of this system are: • Non deterministic : there are steps where we can choose dierent rules to be applied, for instance: (3+4)·(4+2) →7·(4+2) →7·4+7·2→7·4+14 →28+14 →42 (2) It's another valid rewrite sequence. In general, the rewriting process is non-deterministic . • Uniqueness of normal forms : all possible dierent rewrite sequences will always produce the same normal form. • Terminating : Every rewrite sequence can be extended to reach a normal form. This property is not easy to check. Note that we have excluded the usual commutative property of addition and product to make it terminating. Otherwise we could have a sequences like 0+1 → 1+0→0+1→. . . • Conuent : Divergent sequences starting from a given expression admit a join into a common expression. Each of those properties can be used to investigate how to choose nite computation sequences (normalization), the absence of innite computations (termination), the determinism of computations (conuence), the possibility of obtain completely dened information at the end of the computations (completely denedness), etc... Two of these properties are specially important for what they represent: conuence and termination. Termination ensures that there is no innite computation and some outcome will be obtained in nite time from an initial expression. Conuence guarantees that such an outcome will be unique if computations are exhaustive i.e., they stop yielding a normal form. Overall, we can think of such rewriting computations (to normal form) as being deterministic. 3 Decidability of these properties is a main problem, so most studies in the eld restrict the attention to specic classes of term rewriting systems (left-linear, ground, growing,...) to develop decision methods. Term rewriting systems can be used to model algorithms and then study their properties or check their correctness. In the following we show two simple examples that illustrates the importance of the properties of conuence and termination, and why having tools to automatically check them is useful. Example 1: Conuence. Consider the following term rewriting system 1 R : add(0, x)→x (3) add(s(x), y)→s(add(x, y)) (4) prod(0, x)→0 (5) prod(s(x), y)→add(y, prod(x, y)) (6) fact(0) →s(0) (7) fact(s(x)) →prod(s(x), fact(x)) (8) It implements the computation of the factorial of a number. The natural numbers are represented in Peano notation, i.e. with a constant symbol 0 and a function symbol s (called successor ), we write 0 for 0, s(0) for 1 , s(s(0)) for 2 ,..., and so on. In general n∈N is represented as the n−th application of s to 0 (written sn(0) ). This rewrite system is terminating and conuent, so we will always get a result (a normal form) from the evaluation of an expression like fact(sn(0)) and this result will always be the same (namely, sn!(0) , i.e., the Peano representation of n! ), disregarding of the particular choice of reduction sequence. We can try to improve the algorithm by adding a new rule to try to speed up the execution by reducing the number of steps that are needed to obtain the solution 2 : prod(s(0), y)→y (9) This new rule represents the property 1·y=y . If we study the properties 1 You can test it with TRS.Tool: http://TRS.JarCode.Net/?t=-1 2 You can test it with TRS.Tool: http://TRS.JarCode.Net/?t=-2 4 of the new system, now it is not conuent. This means that we may get dierent answers depending on the reduction sequence. Example 2: Termination. Consider now the following term rewriting system 3 R : add(0, x)→x (10) add(s(x), y)→s(add(x, y)) (11) prod(0, x)→0 (12) prod(s(x), y)→add(y, prod(x, y)) (13) that implements the addition and multiplication operations. We can prove it terminating and conuent. We can try to improve it adding by a new rule 4 : add(x, x)→prod(s(s(0)), x)) (14) Which represents the fact x+x= 2 ·x . What we are trying to do with this new rule is to reduce the number of rewriting steps by transforming the addition of a number to itself, into the multiplication of that number by 2. Unfortunately, again we have obtained a worse system, because now it is not terminating nor conuent. As a conclusion of these examples, we can say that when designing or optimizing rewrite systems, we greatly benet from having appropriate analysis tools available. Our TRS.Tool, whose design and use is described in this document, is able to prove that the TRS R in Example 1 is conuent before adding the optimizing rule (9). Furthermore, TRS.Tool can also prove that the extended TRS R0 which is obtained after adding the rule (9) to R fails to be conuent. With regard to the TRS R in Example 2, termination tools like MUTERM 5 can prove termination of R before adding the rule (14). And tools like AProVE 6 are able to disprove termination of the extended TRS. Furthermore, TRS.Tool can be used to show not only that R is conuent, but also that R0 is neither conuent nor terminating. 3 You can test it with TRS.Tool: http://TRS.JarCode.Net/?t=-3 4 You can test it with TRS.Tool: http://TRS.JarCode.Net/?t=-4 5 http://zenon.dsic.upv.es/muterm/ 6 http://aprove.informatik.rwth-aachen.de/ 1.1. Objectives 5 1.1 Objectives The main goal of this thesis is the implementation of a framework that enables the user (programmer, software developer, or interested searcher) to work with term rewriting systems. This framework provides for three main functionalities: 1. Determine the basic structure of a given term rewriting system: signature, arity functions, set of rules and syntactic properties like conservativeness, linearity, etc .... 2. Compute the critical pairs of the term rewriting system and determine its orthogonality. 3. Apply the rewriting rules over a given term. Because of my personal experience with programing languages I decided to implement it using C#.Net as it provides some benets over other languages and technologies as: total object orientation, a complete class library, fully integrated IDE, ...and the library created can be used directly in F#, a functional language integrated in the .Net framework. We have also developed a web tool using this framework to show how does it work. The tool is suitable to be used in teaching the main concepts ans notions of term rewriting as done in several courses of the Master of Software Engineering, Formal Methods and Information Systems like: • 32574 / FSA / Fundamentos de Ingeniería del Sofware Automática. • 32582 / DLP / Diseño de Lenguajes de Programación. • 32576 / TEP / Terminación de Programas. • 30184 / TSD / Tecnología Software Declarativa. • 32575 / ATM / Métodos Ágiles y Tecnología Multiparadigma. 1.2 Plan of the Thesis This thesis is organized in the following chapters: 1.2. Plan of the Thesis 6 • Chapter 2 : we present a brief introduction to term rewriting theory. We present the basic concepts and the notation used. • Chapter 3 : we explain the implementation model of our framework to work with term rewriting systems. • Chapter 4 : we explain in detail the main algorithms implemented in the framework. • Chapter 5 : we present the web tool created with the use of the framework. • Chapter 6 : we conclude with the analysis of the framework created and the future work that can be done to made it more powerful. CHAPTER 2 PRELIMINARIES This is a brief introduction to the theory of term rewriting. We present the basic concepts and the notation used. More detailed information can be found in [1, 2, 6] 2.1 Basic concepts 2.1.1 Signature, variables and terms A signature F is a nite set of function symbols {f, g, h . . .} , each having a xed arity , which establishes the number of its `arguments', given by a mapping ar :F → N . A function symbol a with arity of 0 ( ar(a) = 0 ) is called a constant . Let X be a countable innite set of variables {x, y, z, . . .} where F ∩ X =∅ . The set of terms over F and X , denoted by T(F,X) , is the least set satisfying: 1. All variables are terms: if x∈ X , then x∈ T (F,X) , 2. All constants are terms: if {a∈ F ∧ ar(a) = 0} , then a∈ T (F,X) , 7 2.1. Basic concepts 8 3. A function call is a term if all the parameters are terms: if {f∈ F ∧ ar(f) = k > 0∧ti∈ T (F,X)∀i∈[1, k]} , then f(t1, . . . , tk)∈ T (F,X) . For any term t∈ T (F,X) , the set of variables occurring in t is denoted as Var(t) . If Var(t)=0 , then we say that t is ground . The set of ground terms is denoted by T(F) (rather than T(F,∅) ). A term is said to be linear if it has no multiple occurrences of a single variable. The symbol labeling the root of t is denoted as Root(t) : 1. The root of a variable x is x : if x∈ X , then Root(x) = x , 2. The root of a constant a is a : if {a∈ F ∧ ar(a) = 0} , then Root(a) = a , 3. The root of a term f(t1, . . . , tk) is f : Root(f(t1, . . . , tk)) = f . Positions are represented by a (possibly empty) sequence of natural numbers. The empty sequence Λ denotes the root position of a term. The length of a position p is |p| . p∈ Pos ={Λ}∪{i.q |i∈N>0∧q∈ Pos} (15) Pos(t) denotes the set of positions in t, and refer to sub-trees in the syntactic (tree) structure of the terms. We write t|p to denote the sub-term of t at position p . The depth of sub-term s=t|p is the length |p| of p . Pos(t) = ({Λ} if t∈ X (16a) {Λ} ∪ [1≤i≤ki.Pos(ti) if t=f(t1, . . . , tk) (16b) Positions of non-variable symbols in t are denoted as PosF(t) , and PosX(t) are the positions of variables. PosF(t) = {p∈ Pos(t)|Root(t|p)∈ F} (17) PosX(t) = {p∈ Pos(t)|Root(t|p)∈ X } (18) Example 3: Signature, variables and terms. 2.1. Basic concepts 9 Let F={f, g, h, a, b} be a set of symbols such that ar(f) = 2, ar(g) = 1, ar(h)=3, ar(a) = 0, ar(b)=0 . Let X={x, y, z} be a set a variables. The following terms do not belong to T(F,X) : f(a) (19) g (20) x(b) (21) h(f(a, b), a) (22) j(a, b) (23) Functions f , g and h are used with a wrong arity on (19), (20) and (22) respectively. On (21) the symbol x is used as a function when it is a variable and on (23), the symbol j does not belongs to F . The following terms belong to T(F,X) : t1=f(x, b) (24) t2=g(b) (25) t3=f(a, f(g(x), f(h(f(x, b), a, g(y)), g(b)))) (26) t4=h(f(a, b), g(x), a) (27) t5=h(f(a, z), g(x), a) (28) t6=h(f(x, b), a, g(y)) (29) t7=x (30) t8=b (31) t9=f(g(a), a) (32) 2.2. Confluence 16 t ∗  t ∗  s ??  u s ∗?? ∗ u t0 ∗ ?? t0 ∗ ?? Figure 2: Local conuence and Conuence 2.2.2 Critical pairs Let l→r and l0→r0 be two rules of a term rewriting system and suppose these rules share no variables ( Var(l)∩ Var(l0) = ∅ ). If lp is a subterm of l at position p ( lp=l|p ) such that lp is not a variable ( lp/∈ X ), and lp and l0 unify with mgu σ ( σ(lp) = σ(u) ), then the pair hσ(l)[σ(r0)]p, σ(r)i is called the critical pair and p is called critical or overlapping position of the pair. A critical pair hs, ti is convergent if there is a term u such that s→∗u and t→∗u Example 6: Critical Pais. The term rewriting system in the Example 2 5, has four critical pairs: 1. Rule (61) with rule (58) at position 1 . 2. Rule (57) with rule (59) at position Λ . 3. Rule (57) with rule (63) at position Λ . 4. Rule (63) with rule (59) at position Λ . Let's study the rst critical pair: l→r= (61) = f(g(x), a)→g(g(x)) (64) l0→r0= (58) = g(x0)→f(a, x0) (65) 2 You can test it with TRS.Tool: http://TRS.JarCode.Net/?t=-5 2.2. Confluence 17 Notice that l and l0 should not share any variable, because that, we must rename the variables in l0 and r0 p= 1 (66) lp=l|1=g(x) (67) σ={x0→x} (68) σ is the m.g.u. of lp and l0 ( σ(lp) = σ(l0) = g(x) ). σ(l) = f(g(x), a) (69) σ(r0) = f(a, x) (70) σ(r) = g(g(x)) (71) s=σ(l)[σ(r0)]p=f(f(a, x), a)[f(a, x)]1=f(f(a, x), a) (72) Now we have the two terms that form the critical pair: h(72),(71)i , i.e.: hf(f(a, x), a), g(g(x))i (73) The study of critical pairs is essential for the analysis of conuence of term rewriting systems. The existence of a critical pair implies a point of divergence in the rewriting computation, i.e. the same redex can be rewritten in dierent ways. As we said before, a critical pair represents a divergence. For instance, the critical pair (73) is the result of the divergence that exist when we try to reduce the term σl =f(g(x), a) : we have two choices: either using the rule (61) at position Λ or else use the rule (58) at position 1 . If we try both rules, we will get f(f(a, x), a) and g(g(x)) respectively, this is the critical pair. 2.2. Confluence 18 f(f(a, x), a) f(g(x), a) (115) 77 (118) ''g(g(x)) Figure 3: Critical Pair graph 2.2.3 Orthogonality There are two kinds of critical pairs that are relevant for the analysis of local conuence: • When the critical position is the root position ( p= Λ ) the critical pair is an overlay . • When the two terms of the critical pair are equal, the critical pair is called trivial . Note that trivial critical pairs are trivially convergent A critical pair with both properties is called a trivial overlay . A suitable criterion to determine the conuence of a term rewriting system relies on the notions of orthogonality. A left-linear term rewriting system is: • Orthogonal if it has no critical pair. • Almost orthogonal if its critical pairs are trivial overlays. • Weakly orthogonal if its critical pairs are trivial. An Orthogonal term rewriting system is almost orthogonal, and almost orthogonal term rewriting systems are weakly orthogonal. The interest of orthogonality for proving conuence is due to Huet and Lévy's theorem [4]: Weakly orthogonal term rewriting systems are conuent. (74) 2.2. Confluence 19 If a term rewriting system has nontrivial critical pairs, we can study their convergence. According to Huet's theorem [3]: A Term rewriting system is locally conuent if only if all its critical pairs are convergent. (75) If all critical pairs of a TRS R are convergent, then R is locally conuent. Obviously, conuence implies local conuence, but the opposite claim is not true. Example 7: Critical Pairs convergence. Consider again the critical pair (73) in Example 6. This critical pair is not trivial. We must try to test it for convergence. If the term rewriting system is terminating we only need to apply rules until we get to the normal forms. Otherwise we must apply the rules carefully to avoid entering into a loop. For the rst term f(f(a, x), a) , we have this rewriting sequence: f(f(a, x), a) (76) 1 −−−−−→ f(a,x)→aσ= (77) f(a, a) (78) Λ −−−−−→ f(y,y)→yσ={y→a} (79) a (80) And for the second one, g(g(x)) , the rewriting sequence is: g(g(x)) (81) Λ −−−−−−−→ g(x)→f(a,x)σ={x→g(x)} (82) f(a, g(x)) (83) Λ −−−−−→ f(a,x)→aσ={x→g(x)} (84) a (85) 2.2. Confluence 20 So, the critical pair is convergent f(f(a, x), a) ∗ %% f(g(x), a) (115) 77 (118) '' a g(g(x)) ∗ 99 Figure 4: Critical Pair convergence graph The rest of critical pairs are: ha, h(a, a, a)i (86) ha, h(x, x, a)i (87) ha, ai (88) Critical pair (88) is trivial, hence convergent. The other two critical pairs ((86) and (87)) are not trivial, but they are convergent. Huet's Theorem ensures that the system is locally conuent because all critical pairs are convergent. 2.2.4 Decidability The problem of checking conuence of a term rewriting system is undecidable, but it is decidable for some special cases. The Newman's lemma , states that: A terminating term rewriting system is conuent if it is locally conuent. (89) As a consequence of Huet's Theorem and Newman's Lemma, we have the following secidability result for terminating term rewriting systems [5]: Conuence of terminating term rewriting systems with a nite number of rules is decidable. (90) 2.2. Confluence 21 Given a terminating and nite term rewriting system, as the number of rules is nite, the number of critical pairs will be nite too. If not all the critical pairs are trivial, as the term rewriting system is terminating, we can reduce the terms to its canonical forms, in nite time, and determine whether the critical pairs are convergent or not by just checking the obtained normal forms for equality. CHAPTER 3 FRAMEWORK MODEL The Framework is divided into three main submodules: • Term Rewriting System Module : This module is the responsible to store the data structure representing a term rewriting system. • Critical Pair Module : Contains the necessary classes to calculate and manage the critical pairs of a term rewriting system. • Execution Module : It is used to trace the execution of a term rewriting system over a term. 22 23 Term Rewriting System Signature 0..* Arguments 0..* 0..1 1 0..* 0..* 2 TermRewritingSystem Symbol Term Rule Figure 5: Term Rewriting System Module Diagram Critical Pair 1 2 1 2 0..* 0..* CriticalPair Position Substitution Symbol Term Rule Figure 6: Critical Pair Module Diagram 3.1. Term Rewriting System Module 24 Execution 1 0..* 0..* 11 1 1 ExecutionNode ExecutionTree Position Rule Substitution Term TermRewritingSystem Figure 7: Execution Module Diagram Additionally there is an auxiliary class, Parser , which is responsible to parse the .trs les and build a TermRewritingSystem object. 3.1 Term Rewriting System Module The Term Rewriting System Module is the core of the framework. It represents the data structure that stores a term rewriting system and allows access to its properties. The data structure which has been chosen to represent a Term is based on the syntactic tree. Each Term object represents a node in that tree, and has a reference to Symbol on it. This representation is show more clear in gure 14. Each symbol on the term rewriting system is represented by one (and only one) Symbol object, and it stores a list of all the nodes on the trees where it is used. The reason for proceeding in this way was that this makes the code for the implementation of the matching, unication and substitution algorithms clearer. The implementations has been done in the recursive mode, and the cost for all of them is linear (see Chapter 4). 3.1. Term Rewriting System Module 25 Signature 0..* Arguments 0..* 0..1 1 0..* 0..* 2 TermRewritingSystem Comments: String[] IsCollapsing: Bool IsConservative: Bool IsDestructive: Bool IsDuplicating: Bool IsLeftLinear: Bool IsLinear: Bool IsRightLinear: Bool Symbol Arity: Int Name: String Notation: FunctionNotation Type: TermType Term IsLinear: Bool GetRedexes(term: Term): Position[] GetSubTerm(pos: Position): Term Matching(term: Term): Substitution Replace(term: Term, pos: Position):Term Unication(term: Term): Substitution Rule HasExtraVariables: Bool IsCollapsing: Bool IsDestructive: Bool IsDuplicating: Bool IsLeftLinear: Bool IsLinear: Bool IsRightLinear: Bool Figure 8: Term Rewriting System Module Class Diagram 3.1. Term Rewriting System Module 32 • List of Constants : A dictionary storing the Symbol objects representing each constant used in the term rewriting system. The constants are accessible by the string representing its name ( .Constants[“a”], .Constants[“b”], .Constants[“c”], ... ) The signature of the term rewriting system is represented by the union of the collections Constants and Functions . The object also has methods to inform about the main term rewriting system (Collapsing, Conservative, Destructive, ...). The methods Instantiate , NewRule and NewSymbol are used to create new objects of type Term , Rule or Symbol in the current TermRewritingSystem object. Example 8: Term Rewriting System Representation. This example illustrates the source code which is needed to build a term rewriting system and the representation in memory of the created structure. Consider the following term rewriting system with only one rule: f(a, x)→f(g(a), b) (91) // Create the TRS TermRewritingSystem trs = new TermRewritingSystem(); // Create the Symbols Symbol s_a = new Symbol(TermType.Constant, "a"); Symbol s_b = new Symbol(TermType.Constant, "b"); Symbol s_f = new Symbol(TermType.Function, "f", FunctionNotation.Prefix, 2); Symbol s_g = new Symbol(TermType.Function, "g", FunctionNotation.Prefix, 1); Symbol s_x = new Symbol(TermType.Variable, "x"); // Add Symbols to the TRS trs.Constants.Add(s_a); trs.Constants.Add(s_b); trs.Functions.Add(s_f); trs.Functions.Add(s_g); trs.Variables.Add(s_x); // Create the left term Term t_f1 = new Term(s_f); s_f.Instances.Add(t_f1); // f(?, ?) Term t_a1 = new Term(s_a); s_a.Instances.Add(t_a1); t_f1.Arguments.Add(t_a1); t_a1.Parent = t_f1; // f(a, ?) Term t_x1 = new Term(s_x); 3.1. Term Rewriting System Module 33 s_x.Instances.Add(t_x1); t_f1.Arguments.Add(t_x1); t_x1.Parent = t_f1; // f(a, x) // Create the right term Term t_f2 = new Term(s_f); s_f.Instances.Add(t_f2); // f(?, ?) Term t_g1 = new Term(s_g); s_g.Instances.Add(t_g1); t_f2.Arguments.Add(t_g1); t_g1.Parent = t_f2; // f(g(?), ?) Term t_a2 = new Term(s_a); s_a.Instances.Add(t_a2); t_g1.Arguments.Add(t_a2); t_a2.Parent = t_g1; // f(g(a), ?) Term t_b1 = new Term(s_b); s_b.Instances.Add(t_b1); t_f2.Arguments.Add(t_b1); t_b1.Parent = t_f2; // f(g(a), b) // Create the rule Rule r1 = new Rule(); // ? -> ? r1.Left = t_f1; // f(a, x) -> ? r1.Left = t_f2; // f(a, x) -> f(g(a), b) // Add the rule to the TRS trs.Rules.Add(r1); This code includes all the steps which are necessary to create the term rewriting system, but in the framework there are methods that automatize most of the work. The following code is a more compact but equivalent version of the previous one. // Create the TRS TermRewritingSystem trs = new TermRewritingSystem(); // Create the symbols trs.NewSymbol(TermType.Constant, "a") trs.NewSymbol(TermType.Constant, "b") trs.NewSymbol(TermType.Function, "f", 2) trs.NewSymbol(TermType.Function, "g") trs.NewSymbol(TermType.Variable, "x") // Create the left Term Term t_f1 = trs.Instantiate("f"); // f(?, ?) trs.Instantiate("a", t_f1); // f(a, ?) trs.Instantiate("x", t_f1); // f(a, x) // Create the right Term Term t_f2 = trs.Instantiate("f"); // f( ? , ?) Term t_g1 = trs.Instantiate("g", t_f2); // f(g(?), ?) trs.Instantiate("a", t_g1); // f(g(a), ?) 3.1. Term Rewriting System Module 34 trs.Instantiate("b", t_f2); // f(g(a), b) // Create the Rule trs.NewRule(t_f1, t_f2); // f(a, x) -> f(g(a), b) The long version of the code has been included to clarify how the objects and links between them are created, but the short version must be used because it builds the correct structure automatically. In fact, the Symbol , Term and Rule constructors are private to the package, and can be called only through the correspondent TermRewritingSystem object method ( NewSymbol , Instantiate and NewRule respectively). There is an even more compact version for creating terms, using the Parse method. The way this method can be used to build the terms is: // Create the left Term Term t_f1 = trs.Parse("f(a,x)"); // f(a, x) // Create the right Term Term t_f2 = trs.Parse("f(g(a),b)"); // f(g(a), b) "a" "x" "f" "g" "b" t_a2 t_g1 t_b1 t_f2t_f1 t_x1t_a1 r1 trs Figure 14: Term Rewriting System in memory representation 3.2. Critical Pair Module 35 Figure 14 represents the objects structure created with the previous code. Blue balloons are Terms and the red ones are the Symbols . The white balloon is the TermRewritingSystem object and the green one is the Rule object. In order to make the graph more clear, the link between the Symbols and the TermRewritingSystem object is not represented. 3.2 Critical Pair Module This module stores the information concerning with a Critical Pair. 1 2 1 0..* 0..* 2 CriticalPair IsTrivial: Bool IsOverLay: Bool IsTrivialOverLay: Bool IsConvergent: YesNo CheckConvergence(int MaxIterations): Bool Position Position: Int[] Append(i: Int) Current(): Int MoveNext(): Int Reset() Substitution AddBinding(Symbol: v, Term: t) Apply(Term: t): Term Rule Symbol Term Figure 15: Critical Pair Module Class Diagram 3.2.1 Substitution Class The Substitution class is a list of bindings , i.e., pairs Variable-Term. Each pair is internally named binding , the method AddBinding is used to add new bindings to the substitution, as it takes a Symbol object and a Term object as arguments. The method checks its type (must be Variable ); If it fails, an exception is raised. 3.2. Critical Pair Module 36 Substitution Bindings: SortedList<Symbol, Term> Clone(): Substitution Apply(Term: t): Term AddBinding(Symbol: v, Term: t) ToString(): String Figure 16: Substitution Class The method Apply takes a Term as argument and returns a new Term as the result of applying the substitution to the term. The original Term is not modied. 3.2.2 Position Class Position is an auxiliary class that indicates a position of a symbol into a term. Internally it is an array of integers, and implements the interfaces Enumerable<int> and IEnumerator<int> , so it makes easier for the rest of algorithms to explore a term. A Position object has no a reference to any object of the tree structure of a Term ; it only stores a position which is not associated to any Term , e.g. 1.2.2.1.3. Position Pos: List<Int> Current: Int Clone(): Position Current(): Int MoveNext(): Bool Reset() Append(i: Int) ToString(): String Figure 17: Position Class 3.2. Critical Pair Module 37 3.2.3 CriticalPair Class This class is the main one in the module, as it is used to store the elements that dene a critical pair, i.e.: • an ordered pair of Rules , • a Position , on the left-hand side of the rst Rule , • a Substitution , that unies the subterm of the left-hand side of the rst Rule at the specied Position with the left side of the second Rule . Here, we asume that both rules share no variables. • an ordered pair of Terms , CriticalPair FirstRule: Rule FirstTerm: Term IsTrivial: Bool IsOverLay: Bool IsTrivialOverLay: Bool IsConvergent: YesNo Pos: Postition SecondRule: Rule SecondTerm: Term Sigma: Substitution CheckConvergence(int MaxIterations): Bool Clone(): CriticalPair ToString(): String Figure 18: CriticalPair Class The class has a main method: CheckConvergence . It tries to check whether the two Terms that form the critical pair converge to the same term. As we don't know if the term rewriting system is terminating, the method tries `all' the possible of rewritings of each term. To avoid an innite loop, MaxIterations bouns the number of iterations before stopping the search for convergence. If the method does not nd an answer and reaches the maximum iterations, the method will return false ; otherwise it will return true . 3.3. Execution Module 38 The data type of IsConvergent is an enumeration whose possible values are [ Yes , No , DontKnow ]. It will take the value DontKnow when the method CheckConvergence is unable to determine whether the critical pair converges or not. 3.3 Execution Module The execution module is used to trace the rewriting steps over a term by a term rewriting system. An execution covers all possible rewritings over a term. The tree structure is used to represent all possible substitutions we can make. Each node represents one step of the rewriting process, and each dierent rewrite possibility generates a new branch on the tree. 0..* 0..* 1 11 1 1 ExecutionNode Explode(): ExecutionNode[] GetTrace(): ExecutionNode[] ExecutionTree NextStep(): ExecutionNode[] Position Rule Substitution Term TermRewritingSystem Figure 19: Execution Module Diagram 3.3.1 Execution Tree Class ExecutionTree is the entry point for building a trace for the rewrites over a term. It contains references to two objects: 3.3. Execution Module 39 • Root: The ExecutionNode root of the tree. It stores the starting Term which is used for the substitution. • TRS: The term rewriting system which is used in the rewrite process. ExecutionTree has three collections of ExecutionNode : •Nodes : All the execution nodes generated during the execution process. •CanonicalNodes : The nodes with a Term in normal form, that is, no rule from the TermRewritingSystem , can be applied. •NewNodes : Nodes that were created in a previous iteration of the execution process and are waiting to be processed. ExecutionTree CanonicalNodes: List<ExecutionNode> Nodes: List<ExecutionNode> NewNodes: List<ExecutionNode> Root: ExecutionNode TRS: TermRewritingSystem NextStep(): List<ExecutionNode> Find(t: Term): ExecutionNode Figure 20: ExecutionTree Class The way this class works is: 1. When an object is created, the root node is stored on CanonicalNodes or NewNodes depending if the root Term is in normal form or not. 2. Now we begin an iterative process: each step is launched by calling the NextStep method. 3. When the NextStep method is called, it takes an ExecutionNode out from the NewNodes list and calls the Explode method on it. 4. Every ExecutionNode which is returned by the Explode method is stored in the Nodes list. 3.3. Execution Module 40 5. Any ExecutionNode which is returned by the Explode method with a Term in normal form is stored in the CanonicalNodes list. 6. The rest of ExecutionNode which are not added on a previous iteration to the Nodes list are stored in the NewNodes list. The ExecutionNode not added to NewNodes list are agged as Deforested 7. The end of the iterative process is reached when the NextStep method returns a Null value. This means that there is no node on the NewNodes list. If the term rewriting system is not terminating, we can fall in an eternal loop, and never get out from the iterative process. If the terms generated in the rewriting process are nite, even though the term rewriting system is not terminating, the iterative process will nish. 3.3.2 ExecutionNode Class A ExecutionNode object stores a single step in the rewrite process. The properties of the objecs are: •Term : Is the current term. •Deforest : Is a boolean that indicates the current Term has been generated before on another ExecutionNode from the same ExecutionTree . If it is true , it is not necessary to continue the rewrite process from this point because we will generate the same branches. •Childs and Parent : Links to parent and child ExecutionNode in the tree structure. The Child list will be empty until the Explode method is called. •Pos , Rule , Sigma : Those are the Rule , Position and Substitution that used over the Term from the parent ExecutionNode generates the current Term . 3.3. Execution Module 41 ExecutionNode Deforested: Bool Childs: List<ExecutionNode> IsCanonical: YesNo Parent: ExecutionNode Pos: Position Rule: Rule Sigma: Substitution Term: Term Explode(): List<ExecutionNode> GetTrace(): List<ExecutionNode> Figure 21: ExecutionNode Class The method Explode calculates all child ExecutionNodes resulting from the application of all possible rules to the current Term . Method GetTrace returns an ordered list of all the ExecutionNodes from the root to the current node. Example 9: Execution Module. This example traces how the execution module works. Given the term rewriting system from the Example 1 5: f(a, x)→h(x, x, a) (92) g(x)→f(a, x) (93) f(y, y)→y (94) h(x, y, a)→g(x) (95) f(g(x), a)→g(g(x)) (96) b→a (97) f(a, x)→a (98) Let's trace how the ExecutionTree is built for Term : f(g(x), a) (99) We assume that the trs object is created according to the term rewriting system denition 1 You can test it with TRS.Tool: http://TRS.JarCode.Net/?t=-5 4.1. Unification 48 3. The current symbol on both terms are dierent and at least one of them is a variable. Then, add a new binding to the substitution with the variable and the sub-term. Now: (a) If the variable is also used on σ and the new binding is dierent from the one on σ , then the unication fails. (b) If the variable is used on the right side of the new binding, then the unication fails. (c) If the variable is not used on σ , we apply the new binding to the right side of all bindings on σ . Then we continue with the unication. Note that when both symbols are variables, we can create the rule in one direction or another. The original Paterson-Wegman algorithm has some errors that were discovered and xed by D.D. Champeaux [7]. We have taken them into account in the algorithm that we implement here. 1. Each node has a list with the number of occurrences of each variable on it. The unication is possible only if the variable of the substitution if not used on it. 2. Each time a new binding is added to the substitution, it is applied to all existing bindings in the substitution. With those changes the algorithm is still linear (with respect to the sum of nodes and edges in the tree graph of the terms). Example 10: Unication algorithm example traces. Let f(a, x) and f(a, g(x)) be two terms that we want to unify. The algorithm starts with σ= and pointers to the respective roots of the term (marked in red on the gures). 4.1. Unification 49 f ag x f a x Figure 32: Unication example 1, step 1 As both nodes have the same symbol, we continue with the exploration of the tree: f ag x f a x Figure 33: Unication example 1, step 2 Again, the nodes have the same symbol, and because we are in a leaf of the tree, we must do backtracking to explore the other branch. f ag x f a x Figure 34: Unication example 1, step 3 In this case, the nodes are dierent, one has the subterm x and the second g(x) . Since one of the terms is a variable, we must create a new binding which is added to the substitution: x7→ g(x) . However, since the variable x is used in g(x) , the unication fails. And this means that both terms does not unify. 4.1. Unification 50 Let's see another example: Let f(x, y) and f(g(y), a) be two terms that we want to unify. The algorithm starts with σ= and pointers to the roots of each term. f xy f g y a Figure 35: Unication example 2, step 1 We continue with the exploration. f xy f g y a Figure 36: Unication example 2, step 2 As in the previous example, the nodes are dierent, one has the subterm x and the second g(y) , since one of the terms is a variable, we must create a new binding: x7→ g(y) . Now variable x is not used in g(y) and the unication can continue. We add the new binding to the substitution: σ=∪ {x7→ g(y)} f xy f g y a Figure 37: Unication example 2, step 3 4.2. Matching 51 Again we have dierent nodes: one with sub-term y and the other one with sub-term a , since one of the terms is a variable, we must create a new binding: y7→ a . Before adding the new binding to the substitution, we apply the new binding to the existing one in the substitution. The substitution becomes: σ={x7→ g(a), y 7→ a} We have nished the tree exploration: both terms unify with σ={x7→ g(a), y 7→ a} 4.2 Matching The matching algorithm can be considered as a particular case of the unication algorithm because the way they work is the same, with the difference that the unication is done in both directions and matching is only one direction. As in the unication, the algorithm explores both terms in parallel using a depth-rst exploration. The algorithm starts with an empty substitution σ= . On each exploration step there are three possible cases: • The current symbol on both terms are equal: continue with the matching. • The current symbol on both terms are dierent: the rst term is not a variable: the matching fails. • The current symbol on both terms are dierent and the rst term is a variable: we are going to add a new binding to the substitution with the variable part from the rst term and the term part from the second one. Now:  If the variable is also used in σ and the new binding is dierent from the one in σ , the matching fails.  If the variable is not used in σ , we continue with the matching. Note that in this case the substitution is always made in the same direction, so the variable must be allocated on the rst term. Example 11: Matching algorithm example traces. 4.2. Matching 52 We are going to illustrate the matching algorithm with the same terms from Example 10 Let f(a, x) and f(a, g(x)) be two terms that we want to match. The algorithm starts with σ= and pointers to the roots of each term. f ag x f a x Figure 38: Matching example 1, step 1 As both nodes have the same symbol, we continue with the tree exploration: f ag x f a x Figure 39: Matching example 1, step 2 Again, the nodes have the same symbol. Since we are in a leaf of the tree, we must do backtracking to explore the other branch. f ag x f a x Figure 40: Matching example 1, step 3 4.2. Matching 53 In this case, the nodes are dierent, one has the subterm x and the second g(x) . Since one of the terms is a variable, we must create a new binding: x7→ g(x) . In the matching algorithm we don't have the restriction that the variable of the binding can't be used in the term part so we add the new binding to the substitution. Since we end the exploration, the term f(a, x) matches with the term f(a, g(x)) with the substitution σ={x7→ g(x)} . Let's see the second example: Let f(x, y) and f(g(y), a) be two terms that we want to match. The algorithm starts with σ= and pointers to the roots of each term. f xy f g y a Figure 41: Matching example 2, step 1 We continue with the exploration. f xy f g y a Figure 42: Matching example 2, step 2 The nodes are dierent, one has the subterm x and the other g(y) . Since the rst is a variable, we must create a new binding: x7→ g(y) . So we add it to the substitution: σ={x7→ g(y)} 4.3. Confluence decision 54 f xy f g y a Figure 43: Matching example 2, step 3 Again we have dierent nodes, one with y and the other with a . We create the binding y7→ a , and add it to the substitution: σ={x7→ g(y), y 7→ a} We have nished the tree exploration: the term f(x, y) matches with the term f(g(y), a) with the substitution σ={x7→ g(y), y 7→ a} . 4.3 Conuence decision Figure 44 shows the ow chart for studying conuence of a term rewriting system on the basis of the analysis of its critical pairs. 4.3. Confluence decision 55 Is left-linear? Has critical pairs? Are all trivial overlay? Are all trivial? Are all critical pairs convergent? Is orthogonal Is almost orthogonal Is weakly orthogonal Is locally conuent Is con- uent Is not conuent Is the TRS terminating? Conuence unknown No Yes No Yes Yes No Yes No Yes No Yes No Unknown Figure 44: Conuence algorithm ow chart If the term rewriting system is not orthogonal (or almost/weakly orthogonal), because it is not left-linear or some of its critical pairs is not trivial, we must check the convergence of the critical pairs. This point is critical, because, right now, the framework does not provide any method to determine if the term rewriting system is terminating or not. The method which is used to check for convergence of critical pairs is quite simple: the execution module is used to try all possible rewrites over each term in the critical pair, and then checking for an eventual equality of the results waiting at some point. The problem is that, if the term rewiring 4.3. Confluence decision 56 system is not terminating, then the module could be running forever without reaching this point. Since the exploration of the reduction space of a term can be limited by using an additional counter which is a parameter of the process, if the process reaches this limit without any convergence, the critical pair is agged as convergence unknown. There are tree particular cases where we can obtain useful information when such conuence unknown state is obtained: • If exploring any of the terms in the critical pair we get two (or more) dierent normal forms, then we can conclude that the term rewriting system is not conuent , regardless of the result for the convergence of the critical pair and the local conuence property. • If, while looking for convergence of a critical pair, any of the terms has exhausted the exploration of its reduction space before reaching the specied limit of rewrite steps without obtaining a normal form, then the term rewriting system is nonterminating. This is because the execution tree has all its leaves deforested, and there are loops to other terms in the execution tree, so there are innite loops. • If, while looking for a convergence point for a critical pair, a loop has been detected, i.e., any term contains a subterm that previously occurs in the rewrite sequence, we can conclude that the term rewriting system is nonterminating (see the denition of looping TRS in page 13). In the following, we illustrate these remarks with some corresponding examples: Example 12: Non conuence. Consider the following rewriting system 1 : b→a (100) b→c (101) c→b (102) c→d (103) One of its critical pairs is: hc, ai (104) 1 You can test it with TRS.Tool: http://TRS.JarCode.Net/?t=-8 4.3. Confluence decision 57 The critical pair is convergent because: c→b→a (105) But this is the execution tree created while looking for this convergence: c b ac d Figure 45: Non conuence example The tree has two dierent normal forms (the green ones), so the term rewriting system is not conuent. Example 13: Non termination, rst case. Consider the following rewriting system 2 : + (0, x)→x (106) + (−(x), x)→0 (107) + (+(x, y), z)→+(x, +(y, z)) (108) + (x, y)→+(y, x) (109) −(0) →0 (110) −(−(x)) →x (111) −(+(x, y)) →+(−(x),−(y)) (112) One of its critical pairs is: <−(+(y, x)),+(−(x),−(y)) > (113) If we explore all possible rewrites over the rst term −(+(y, x)) we will get this tree: 2 You can test it with TRS.Tool: http://TRS.JarCode.Net/?t=-6 5.2. Use Example 64 5.2.1 Input Data Shows the same information introduced by the user. The main purpose is to check that all data have been correctly parsed. Figure 53: Input data tab The information that is shown here is organized into four tables: • TRS.ToString() : uses the ToString method of the TermRewritingSystem Object created to print out the term rewriting system in TPDB format, see Table 1. 5.2. Use Example 65 Table 1: TRS.ToString() • Variables and Signature : Shows the set of variables and the signature (function symbols and arity functions), see Table 2 5.2. Use Example 66 Table 2: Variables and signature • Terms : Lists all terms with labels to be used in the rest of the tabs. The terms from the rules are numbered from 0 to n , and marked with "L" or "R", so the term T0L is the left-hand side of the rst rule, the term T3R is the right-hand side of the fourth rule, and so on..., see Table 3 Table 3: Variables and signature 5.2.2 Terms It draws the tree structure for each term and its basic properties. 5.2. Use Example 67 Figure 54: Terms tab As an example, this is the information for terms t and T3L Table 4: Term t analysis 5.2. Use Example 68 Table 5: Term T3L analysis Each symbol in the tree is represented as a cell in the table, with the position it has inside the term. At the bottom of the tree there is the set of variables and the properties the terms satisfy: linear, ground, etc ... 5.2.3 Matching and unication Test the matching and unication among all terms. Figure 55: Matching and unication It contains two tables, one for matching and another for unication: 5.2. Use Example 69 Figure 56: Matching table detail Figure 57: Unication table detail For each pair of terms such that the matching or unication is possible, the table contains the substitution σ that makes it possible. If a pair of terms do not unify or match, they are not included in the corresponding table. 5.2.4 Rules Analyses of the properties of the rules. Figure 58: Rules tab There is a table for each rule that indicates its properties. Here are the tables for R1 and R2 : 5.2. Use Example 70 Table 6: Rule R1 analysis Table 7: Rule R2 analysis 5.2.5 Critical Pairs This option obtains and analyses the critical pairs. 5.2. Use Example 71 Figure 59: Critical pair tab There are four tables on this tab: • Critical pair calculation : There is a cell for each critical pair. Table 8: Critical pair calculation Here is the outcome for the rst and second critical pairs: 5.2. Use Example 72 Figure 60: First critical pair calculation Figure 61: Second critical pair calculation • Critical pair convergence : For nontrivial critical pairs the tool tries to test their convergence: 5.2. Use Example 73 Table 9: Critical pair convergence If the critical pair converges, the rewrite sequence is detailed for each part of the critical pair. Here is the detail for checking convergence of the second and fourth critical pairs: Figure 62: First critical pair convergence 5.2. Use Example 80 Figure 74: Example 1 optimized version The TRS.Tool nds a non convergent critical pair, so the term rewriting system is not conuent. Table 13: Example 1 optimized version critical pairs 5.2. Use Example 81 Table 14: Example 1 optimized version properties Example 16: Termination Analysis. Consider again the term rewriting system in Example 2: add(0, x)→x (126) add(s(x), y)→s(add(x, y)) (127) prod(0, x)→0 (128) prod(s(x), y)→add(y, prod(x, y)) (129) You can test it with TRS.Tool at: http://TRS.JarCode.Net/?t=-3 5.2. Use Example 82 Figure 75: Example 2 If we test the term rewriting system with TRS.Tool, we can check that it has no critical pairs and it is actually conuent, due to its orthogonality. Table 15: Example 2 properties Now, if we add the new rule (14): http://TRS.JarCode.Net/?t=-4 5.2. Use Example 83 Figure 76: Example 2 optimized version The TRS.Tool nds a non convergent critical pair, so the term rewriting system is not conuent. Table 16: Example 2 optimized version critical pairs Furthermore, TRS.Tool detects the new system is nonterminating. Table 17: Example 2 optimized version properties CHAPTER 6 TESTING THE FRAMEWORK In order to test the correct functionality of the framework, we have decided to use the set of term rewriting systems from the Conuence Competition 1 . For this test we have set 500 as the limit of rewrites. The test set contains 216 term rewriting system tagged with their properties. After trying them with TRS.Tool, we obtain the following results for conuence and local conuence: CoCo Tag TRS.Tool Success ratio Conuent 171 5 2.9 % Non Conuent 27 14 51.9 % Success 198 19 9.6 % Unknown 18 199 Total 216 216 Table 18: Conuence property test These results are not so impressive because, currently, TRS.Tool has only one way to check conuence of a system: the check for orthogonality properties (and in the set of problems there are only 5 orthogonal systems). 1 http://termcomp-devel.uibk.ac.at/hzankl/cops/ 84 85 CoCo Tag TRS.Tool Success ratio Locally Conuent 163 201 123.3 % Non Locally Conuent 12 12 100.0 % Success 175 213 121.7 % Unknown 9 3 Total 216 216 Table 19: Locally Conuence property test The target of the Conuence Competition is proving conuence rather than local conuence. In contrast, TRS.Tool determines the local conuence of some systems that have this information missed on the set. TRS.Tool determines the local conuence of 38 systems that are not tagged as locally conuent: • 31 (1, 19, 20, 22...): Tagged as conuent, but not as locally conuent. Probably, since conuence implies local conuence, the tagging for local conuence was just missed as directly entailed from positive conuence tag. • 2 (126, 216): Have no tags about conuence or local conuence, but in the comments it is said that they are conuent. • 3 (21, 212, 214): Tagged as nonconuent and not as locally conuent. • 2 (62, 175): No tag about conuence nor local conuence. CoCo Tag TRS.Tool Success ratio Terminating 35 0 0.0 % Non Terminating 181 129 71.3 % Success 216 129 59.7 % Unknown 0 87 Total 216 216 Table 20: Terminating property test TRS.Tool implements a method to detect nonterminating systems (see section 4.3 and Examples 13 and 14), and it was able to discover 71.3% of them. 86 A detailed report of the test can be viewed on the website: http://TRS.JarCode.Net/Test.html Here you can see the individual result for each test, and the result for each of those properties: conuence, nonconuence, local conuence, nonlocal conuence, termination and nontermination. Figure 77: Test detailed report If you click on the name of one le tested, you can test it again with TRS.Tool. Figure 78: 5.trs test loaded The column Seconds indicates the amount of time the analysis of the term rewriting system takes. As the precision of the Stopwatch object 87 from .Net which is used to measure the time is 1 millisecond, and some tests take less than that, we have done each test 10 times and calculate the average time. The last column Rewrites indicates how many rewrites were necessary to determine the (non)convergence of all critical pairs. We have removed system number 15 from the test, because it is a complex term rewriting system with 15 critical pairs, and some of them reach the limit of 500 rewrites without any convergence. The time for this one took almost 2 hours and the TRS.Tool couldn't determine any property. It will be necessary to create a timer to cut the execution of the process and give a timeout exception. Figure 79: 15.trs results At the end of the table there is a row with the total values. The average time for the 215 systems was 239 milliseconds. This value could be lower, because of the educational objective of the tool, it analyses all the critical pairs. But this is not necessary: if we nd a notconvergent critical pair, then it is not necessary to check the rest and we can get an answer early. Figure 80: Test total values Here is a dispersion graph of the time which is necessary to get the result in milliseconds. Note that only 5 examples required more than 1 second. 88 Figure 81: Test dispersion graph CHAPTER 7 CONCLUSIONS The main goal of this thesis is the implementation of a framework that enables the user to work with term rewriting systems, providing these functionalities: 1. Determine the basic structure and syntactic properties of a given term rewriting system. 2. Compute the critical pairs of the term rewriting system and determine its orthogonality, local conuence and conuence. 3. Compute resolution sequences for term rewriting. Another important target of the thesis is the development of a web tool which if suitable to be used in teaching the main rewriting concepts. Our implementation ts the goals, but there are lot of additional developments that can be included and on some points can be optimized. One of the rst targets that should be addressed in the future is the optimization of the execution module to make it more smart. Currently, almost all branches of the execution tree are explored and the deforestation method is quite poor. It should be improved to detect loops of non terminating term rewriting systems. As a second step in the optimization of the execution 89