examples/0000755000175000017500000000000011336572745011021 5ustar jocjocexamples/coin.pl0000600000175000017500000000034111310234265012254 0ustar jocjoc:- use_module(library(chr)). :- chr_constraint throw_coin/1. % One non-trivial overlap, leading to non-joinable critical pair % Program is not confluent. throw_coin(Coin) <=> Coin = head. throw_coin(Coin) <=> Coin = tail. examples/merge.pl0000600000175000017500000000041411334275200012424 0ustar jocjoc:- use_module(library(chr)). :- chr_constraint merge/3, globvars/1. merge([], L2, L3) <=> L2 = L3. merge(L1, [], L3) <=> L1 = L3. merge([X|R1], L2, L3) <=> L3 = [X|R3], merge(R1, L2, R3). merge(L1, [Y|R2], L3) <=> L3 = [Y|R3], merge(L1, R2, R3). examples/ufd_found_compr.pl0000600000175000017500000000373211334273236014513 0ustar jocjoc% ufd_found_compr.pl % % Parallelized optimal union-find % % CPS Thom Frühwirth: Parallelizing Union-Find in Constraint Handling % Rules Using Confluence Analysis, ICLP 2005, LNCS 3668 % % Rule Rule CPS Found by conflcheck % % findnode1 findnode1 1 yes % findnode1 findnroot1 1 yes % ! findroot1 findroot1 1 0, all joinable % % found1 found1 1 yes % found1 linkeq1c 2 yes % found1 linkleft1c 2 guard contains >= % found1 linkright1c 2 guard contains >= % % compress findnode1 1 yes % compress found1 1 yes % ! compress compress 3 4 * % % ! linkeq1c linkeq1c 18 6 ** % linkeq1c linkleft1c 39 guard contains >= % linkeq1c linkright1c 39 guard contains >= % linkleft1c linkleft1c 191 guard contains >= % linkleft1c linkright1c 193 guard contains >= % linkright1c linkright1c 191 guard contains >= % % * 1, 3, and 4: no rules applicable, % 2: no rules applicable after 1 application of compress % % ** 18 seems impossible. There are only 13 possible matchings of % head constraints. :- use_module(library(chr)). :- op(700, xfx, '~>'). :- chr_constraint (~>)/2, find/2, compr/2, root/2, found/2, foundc/2, link/2. findnode1 @ A ~> B \ find(A,X) <=> find(B,X), compr(A,X). findroot1 @ root(A,_) \ find(A,X) <=> found(A,X). found1 @ A ~> B \ found(A,X) <=> found(B,X), compr(A,X). compress @ foundc(C,X) \ A ~> B, compr(A,X) <=> A ~> C. linkeq1c @ found(A,X), found(A,Y), link(X,Y) <=> foundc(A,X), foundc(A,Y). linkleft1c @ found(A,X), found(B,Y), link(X,Y), root(A,N), root(B,M) <=> N>=M | foundc(A,X), foundc(B,Y), B ~> A, N1 is max(N,M+1), root(A, N1). linkright1c @ found(A,X), found(B,Y), link(Y,X), root(A,N), root(B,M) <=> N>=M | foundc(A,X), foundc(B,Y), B ~> A, N1 is max(N,M+1), root(A, N1). examples/ufd_basic1.pl0000600000175000017500000000173711334272635013347 0ustar jocjoc% ufd_basic1.pl % % Basic parallel union-find % % CPS Thom Frühwirth: Parallelizing Union-Find in Constraint Handling % Rules Using Confluence Analysis, ICLP 2005, LNCS 3668 % % Rule Rule CPS Found by conflcheck % % findnode findnode 1 yes % findnode findroot1 1 yes % linkeq1 linkeq1 6 yes % link1 linkeq1 13 yes % ! link1 link1 65 contains non-terminating computation % found link1 2 yes % found found 1 yes :- use_module(library(chr)). :- op(700, xfx, '~>'). :- chr_constraint find/2, found/2, (~>)/2, link/2, root/1. findnode @ A ~> B \ find(A,X) <=> find(B,X). findroot1 @ root(A) \ find(A,X) <=> found(A,X). found @ A ~> B \ found(A,X) <=> found(B,X). linkeq1 @ link(X,Y), found(A,X), found(A,Y) <=> true. link1 @ link(X,Y), found(A,X), found(B,Y), root(A), root(B) <=> B ~> A, root(A). examples/simple1.pl0000600000175000017500000000036411334256573012717 0ustar jocjoc:- use_module(library(chr)). :- chr_constraint p/0, q/0. % Most simple program. No overlap in between rules, only simple overlaps of % rules with themselves, leading to trivial critical pairs. % Program is confluent. p <=> true. q <=> true. examples/simple2.pl0000600000175000017500000000026211334271655012713 0ustar jocjoc:- use_module(library(chr)). :- chr_constraint p/0, q/0. % One overlap, leading to the non-joinable critical pair (q, false) % Program is not confluent. p <=> q. p <=> false. examples/twocoins.pl0000644000175000017500000000021711334272401013203 0ustar jocjoc:- use_module(library(chr)). :- chr_constraint throw_coin/2. throw_coin(X,Y) <=> X = head, Y = tail. throw_coin(X,Y) <=> X = tail, Y = head. examples/xor.pl0000600000175000017500000000117211301460126012134 0ustar jocjoc:- use_module(library(chr)). :- chr_constraint xor/1. % Multiple overlaps: The first rule overlaps with itself in six different ways, % leading to six critical pairs, all of them trivial. The second rule overlaps % with itself in three different ways, also leading to to three different % trivial critical pairs. The first and second rule overlaps in four different % ways which lead to four different non-trivial critical pairs. Two of those % critical pairs are duplicates of the other two, leading to a total of % thirteen critical pairs, two of them non-trivial and unique. xor(X), xor(X) <=> xor(0). xor(1) \ xor(0) <=> true. examples/ufd_rank.pl0000600000175000017500000000243411334273016013125 0ustar jocjoc% ufd_rank.pl % % Optimized union-find % % CPS Schrijvers, Frühwirth: Implementing and Analysing Union-Find in % CHR, Report CW 389, July 2004, K.U. Leuven % % Rule Rule CPS Found by conflcheck % % findroot linkleft 1 guard contains >= % findroot linkright 1 guard contains >= % findnode findnode 2 yes % findnode findroot 1 yes % % linkeq linkleft 1 guard contains >= % linkeq linkright 1 guard contains >= % linkleft linkleft 20 guard contains >= % linkleft linkright 26 guard contains >= % linkright linkright 20 guard contains >= :- use_module(library(chr)). :- op(700, xfx, '~>'). :- chr_constraint make/1, root/2, find/2, union/2, (~>)/2, link/2. make @ make(A) <=> root(A,0). union @ union(A,B) <=> find(A,X), find(B,Y), link(X,Y). findnode @ A ~> B, find(A,X) <=> find(B,X), A ~> X. findroot @ root(A,_) \ find(A,X) <=> X=A. linkqq @ link(A,A) <=> true. linkleft @ link(A,B), root(A,N), root(B,M) <=> N>=M | B ~> A, N1 is max(N,M+1), root(A,N1). linkright@ link(B,A), root(A,N), root(B,M) <=> N>=M | B ~> A, N1 is max(N,M+1), root(A,N1). examples/simple4.pl0000600000175000017500000000076411301460126012707 0ustar jocjoc:- use_module(library(chr)). :- chr_constraint p/1. % Guards: All rules overlap with each other, although the first and second rule % lead to an inconsistent built-in store and thus create no critical pair. The % first and third rule also lead to a unification which then leads to an % inconsistent built-in store. The second and third rule lead to an critical % pair as well as every rule does with itself. % The program is confluent p(X) <=> X = 1 | true. p(X) <=> X = 2 | true. p(2) <=> true. examples/simple3.pl0000600000175000017500000000037711301460126012706 0ustar jocjoc:- use_module(library(chr)). :- chr_constraint p/0, q/0, r/0. % One overlap between rules possible leading to a non-trivial critical pair. % Six more trivial critical pairs arise from the overlaps of the rules with % itself. p,q <=> true. q,r <=> true. examples/leq.pl0000600000175000017500000000036411334274300012112 0ustar jocjoc:- use_module(library(chr)). :- chr_constraint leq/2. reflexivity @ leq(X,X) <=> true. antisymmetry @ leq(X,Y), leq(Y,X) <=> X = Y. idempotence @ leq(X,Y) \ leq(X,Y) <=> true. transitivity @ leq(X,Y), leq(Y,Z) ==> leq(X,Z). examples/mem.pl0000600000175000017500000000015011301460126012075 0ustar jocjoc:- use_module(library(chr)). :- chr_constraint assign/2, cell/2. assign(V,N), cell(V,O) <=> cell(V,N). examples/ufd_basic.pl0000600000175000017500000000152611334272503013254 0ustar jocjoc% ufd_basic.pl % % Basic parallel union-find % % CPS Thom Frühwirth: Parallelizing Union-Find in Constraint Handling % Rules Using Confluence Analysis, ICLP 2005, LNCS 3668 % % Rule Rule CPS Found by conflcheck % % findnode findnode 1 yes % findnode findroot 1 yes % linkeq link 1 yes % findroot link 1 yes % link link 4 yes :- use_module(library(chr)). :- chr_constraint make/1, find/2, union/2, arrow/2, link/2, root/1. make @ make(A) <=> root(A). union @ union(A,B) <=> find(A,X), find(B,Y), link(X,Y). findnode @ arrow(A,B) \ find(A,X) <=> find(B,X). findroot @ root(B) \ find(B,X) <=> X=B. linkeq @ link(A,A) <=> true. link @ link(A,B), root(A), root(B) <=> arrow(B,A), root(A). chrlib.pl0000600000175000017500000001005611333306702010756 0ustar jocjoc/*============================================================================= File: chrlib.pl Author: Johannes Langbein, Îçҹ̽»¨, Germany, jolangbein at gmail dot com Date: 02-06-2010 Version: 1.0 Copyright: 2010, Johannes Langbein This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . =============================================================================*/ /*=============================== chrlib ====================================== This file defines a number of auxiliary predicates related to properties of CHR rules, programs, and states. Predicates in this file: ======================== builtins_failed/1 Inconsistent (failed) built-in store builtins_consistent/1 Consistent built-in store propagate_builtins/1 Unify variables in built-in store unifier/3 Calculate MGU of two terms ==============================================================================*/ :- module(chrlib, [ builtins_failed/1, builtins_consistent/1, propagate_builtins/1, unifier/3]). :- use_module(termlib, [tl_member/3, tl_filter/3]). %% builtins_failed(+B) % % This predicate succeeds iff the conjunction of the built-ins in the list B is % failed i.e. contains logical contradictions. This predicate does not bind any % variables occuring in B builtins_failed(B) :- \+ builtins_consistent(B). %% builtins_consistent(+B) % % This predicate succeeds, iff the conjunction of the built-ins in the list B % is consistent, i.e. contains no logical contradictions. This predicate does % not bind any variables occuring in B builtins_consistent(B) :- \+ tl_member(false, B, ==), tl_filter(B, \==(true), B1), equalities_consistent(B1). %% propagate_builtins(+B) % % This predicate takes a list of built-in constraints B and tries to unify % them according to the equalities. The predicate only succeeds if the % built-ins are consistent and fails if the built-ins in B contain logical % contradictions or the literal false. propagate_builtins([]). propagate_builtins([true|Bs]) :- propagate_builtins(Bs). propagate_builtins([B|Bs]) :- functor(B, =, 2), call(B), propagate_builtins(Bs). %% unifier(+Term1, +Term2, -Unifier) % % This predicate calculates the MGU (most general unifier) of the two terms % Term1 and Term2 according to the Herbrand Algorithm without occur check. If % Term1 and Term2 are not unifiable, unifier/3 fails. If they are unifiable, % Unifier is a list of =/2 terms, which represent the resulting MGU. This % predicate does not bind any variables occuring in Term1 or Term2. unifier(T1, T2, []) :- T1 == T2, !. unifier(T1, T2, [T1 = T2]) :- var(T1), !. unifier(T1, T2, [T2 = T1]) :- var(T2), !. unifier(T1, T2, U) :- compound(T1), compound(T2), functor(T1, F, N), functor(T2, F, N), T1 =.. [_|[X1|R1]], T2 =.. [_|[X2|R2]], unifier(X1, X2, U1), unifier(R1, R2, U2), append(U1, U2, U), equalities_consistent(U). % equalities_consistent(+E) % % This predicate succeeds, if all equalities (=/2 terms) in the list % E are logically consistent. This predicate does not bind any variables % occuring in E. equalities_consistent(E) :- copy_term(E, E1), equalities_consistent_aux(E1). equalities_consistent_aux([]). equalities_consistent_aux([E|R]) :- functor(E, =, 2), call(E), equalities_consistent_aux(R). chrparser.pl0000600000175000017500000002072211333364012011503 0ustar jocjoc/*============================================================================= File: chrparser.pl Authors: Johannes Langbein, Îçҹ̽»¨, Germany, jolangbein at gmail dot com (all predicates except read_file/2 and read_file_/1) Tom Schrijvers, K.U. Leuven, Belgium, tom.schrijvers at cs.kuleuven dot be (predicates read_file/2 and read_file_/1) Date: 02-06-2010 Version: 1.0 Copyright: 2010, Johannes Langbein, Tom Schrijvers This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . =============================================================================*/ /*============================== chrparser ==================================== The predicates in this file implement a very simple CHR parser. The parser only works correctly on syntactically correct files and provides no means for error handling. CHR programs should be checked for syntactical correctness by one of the established CHR systems before they are used with this parser. The parser ignores everything in the file expect CHR simplification and simpagation rules and the chr_constraint directive defining the CHR constraints and their arity. This means the file can contain arbitrary Prolog predicates, directives and CHR propagation rules as long as they are syntactical correct. The syntax of rules supported by this parser is given by the following EBNF grammar. Rule --> [rulename '@'] ActualRule ActualRule --> LHS '<=>' RHS LHS --> [KeptHead '\'] RemHead RHS --> [Guard '|'] Body KeptHead --> Constraints RemHead --> Constraints Guard --> Constraints Body --> Constraints Constraints --> constraint {',' Constraints} Shortly, a rule recognized by this parser is of the form name @ KH \ RM <=> G | B where name, KH, and G can be omitted, together with the according symbols. Predicates in this file: ======================== read_rules/3 Read rules and list of CHR constraints from a file. Datastructures used: ==================== rule(S, KH, RH, G, B) A term representing a CHR rule. S is the rule together with its name as string as it is represented in the source file. KH, RH, G, B are lists representing the kept head constraints, the removed head constraints, the guard and the body of the rule. KH, and G are possibly empty. con(F, N) A term representing a declaration of a CHR constraint. F is the name of the constraint and N is its arity. ==============================================================================*/ :- module(parser, [read_rules/3]). :- user:use_module(library(chr)). %% read_rules(+FileName, -Rules, -CHRC) % % This predicate which extracts all rules from a file with the given name. % The file name must be given as Prolog string, for example: 'src/program.pl' % Rules is unified with a list of terms of the form rule(S, N, KH, RH, G, B). % The list CHRC is the list of all CHR constraints appearing in the program. It % contains terms of the form con(F, N). read_rules(File, Rules, CHRC) :- read_file(File, Clauses), extract_constraint_list(Clauses, CHRC), extract_rules(Clauses, Rules). % read_file(+FileName -Clauses) % % This predicate reads a Prolog source file provided its file name and returns % a list of all clauses appearing in the source file. In case the source file % contains an operator precedence declaration, this precedence is set in the % runtime system read_file(File,Clauses) :- see(File), read_file_aux(Clauses), seen. % read_file_(-Clauses) % % This predicate returns a list of all clauses of the currently opened source % file. In case the source file contains an operator precedence declaration, % this precedence is set in the runtime system. read_file_aux([Clause|Clauses]) :- read(Clause), (Clause == end_of_file -> Clauses = [] ; (Clause = (:- op(A,B,C)) -> op(A,B,C) ; true ), read_file_aux(Clauses) ). % extract_rules(+Clauses, -Rules) % % Given a list of Prolog clauses, this predicate returns a list of rules in % the format described above. This predicate ignores all clauses % which are not built according to the aforementioned grammar. extract_rules([end_of_file|_], []) :- !. extract_rules([H|R], [Rule|Rules]) :- parse_rule(H, Rule), !, extract_rules(R, Rules). extract_rules([_|R], Rules) :- extract_rules(R, Rules). % parse_rule(+Term -Rule) % % This predicate succeeds if Term is a CHR rule according to the aforementioned % grammar. In this case, Rule is unified with a term of the form % rule(N, KH, RH, G, B) representing the rule. parse_rule(Term, rule(Term, KH, RH, G, B)) :- Term = (_@ActRule), !, parse_actrule(ActRule, KH, RH, G, B). parse_rule(Term, rule(Term, KH, RH, G, B)) :- parse_actrule(Term, KH, RH, G, B). % parse_actrule(+Term, -KH, -RH, -G, -B) % % This predicate succeeds if Term is constructed according to the grammar rule % for ActualRule in the aforementioned grammar. In this case, KH and RH are % unified with the list of kept and removed head constraints respectively, % while G and B are unified with the lists of constraints from the guard and % body of the rule, respectively. parse_actrule(Term, KH, RH, G, B) :- Term = (LHS<=>RHS), !, parse_lhs(LHS, KH, RH), parse_rhs(RHS, G, B). % parse_lhs(+LHS, -KH, -RH) % % This predicate succeeds, if LHS is the left-hand side of a CHR rule according % to the above grammar. In this case, KH is the list of kept head constraints, % RH is the list of removed head constraints. If the left-hand side of a % simplification rule is parsed, KH is the empty list. parse_lhs(LHS, KH, RH) :- LHS = (KHS\RHS),!, parse_constraints(KHS, KH), parse_constraints(RHS, RH). parse_lhs(LHS, [], RH) :- parse_constraints(LHS, RH). % parse_rhs(+RHS, -G, -B) % % This predicate succeeds, if RHS is the right-hand side of a CHR rule % according to the above grammar. In this case, G is the list of the built-in % constraints from the guard of the rule and B is the list containing the % constraints from the body of the rule. G is the empty list if the rule % contains no guard. parse_rhs(RHS, G, B) :- RHS = (GS|BS), !, parse_constraints(GS, G), parse_constraints(BS, B). parse_rhs(RHS, [], G) :- parse_constraints(RHS, G). % parse_constraints(+Term, -List) % % This predicate succeeds if term is an arbitrary term or a sequence of terms, % separated by (,). In this case List is the list containing all the terms % from the sequence. This predicate is used to parse the head, guard, or body % of a rule into a list of constraints. parse_constraints(Term, [C|Res]) :- Term = (C,CS), !, parse_constraints(CS, Res). parse_constraints(Term, [Term]). % extract_constraint_list(+Clauses ~CHRCons) % % This predicate takes a list of read-in Prolog clauses and extracts the list % of CHR constraints as defined by the directive ":- chr_constraints..." in % the source file. The resulting list CHRCons consists of terms of the form % (F, N), where F is the functor and N the arity of a CHR constraint as % defined by the directive. If no such directive is found in the list Clauses, % the predicate fails. extract_constraint_list([C|_], CHRC) :- C = (:- chr_constraint CS), !, parse_constraint_list(CS, CHRC). extract_constraint_list([_|R], CHRC) :- extract_constraint_list(R, CHRC). % parse_constraint_list(+ConList, ~CHRCons) % % This predicate parses the term ConList of the form (F1/N1, F2/N2, ...) where % the Fi's are functors and the Ni's are arities, into a list CHRCons of terms % of the form (Fi, Ni). parse_constraint_list(CL, [(F, A)|CHRC]) :- CL = (C,R), C = (F/A),!, parse_constraint_list(R, CHRC). parse_constraint_list(C, [(F, A)]) :- C = (F/A). conflcheck.pl0000600000175000017500000004663611335010143011620 0ustar jocjoc/*============================================================================= File: conflcheck.pl Authors: Johannes Langbein, Îçҹ̽»¨, Germany, jolangbein at gmail dot com Date: 02-07-2010 Version: 1.0 Copyright: 2010, Johannes Langbein This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . =============================================================================*/ /*=============================== confluence check =========================== The predicates in this file implement a confluence checker for CHR programs according to the definition of confluence in [Fru09]. There are two restrictions to the CHR programs that can be used with this confluence checker: 1.) No propagation rules: The CHR program to use with this file must not contain propagation rules. 2.) Restricted built-ins: Only = is allowed as built-in constraint. The most important predicate in this file is the predicate check_confluence/1. This predicate checks all CHR rules in a Prolog file and decides whether or not they are confluent. IMPORTANT NOTE: The predicates in this file write temporary files to your hard-drive. Thus, it needs to be executed in a directory with write access. All files are deleted after the execution. Predicates in this file: ======================== check_confluence/1 Checks confluence for a program check_confluence/2 Checks confluence for a program and returns the number of non-joinable critical pairs check_confluence/3 Checks confluence for two rules in a program check_confluence/4 Checks confluence for two rules in a program and returns the number or non-joinable critical pairs show_critical_pairs/1 Print non-trivial CPs of all rules in file show_critical_pairs/3 Print non-trivial CPs of a given rule pair show_all_critical_pairs/1 Print all CPs of all rules in file show_all_critical_pairs/3 Print all CPs of a given rule pair Datastructures used: ==================== state(G, B, V) A term representing a CHR state. G is a list of CHR constraints, represented as Prolog terms. B is a list of built-in constraints, represented as Prolog terms. V is the list of global variables, represented as unbound Prolog variables. This list must not contain duplicates. rule(S, KH, RH, G, B) A term representing a CHR rule. S is the rule together with its name as string as it is represented in the source file. KH, RH, G, B are lists representing the kept head constraints, the removed head constraints, the guard and the body of the rule. KH, and G are possibly empty. cp(S1, S2, R1, R2, O, CAS) A term representing a critical pair. S1 and S2 are the two states of the critical pair represented as state(...) terms according to the definition above. R1 and R2 are the CHR rules the critical pair is stemming from. They are represented as rule(...) terms according to the definition above. O is a list of tuples, consisting of pairs of constraints. Those pairs describe the overlap of the two rules which leads to the critical pair. The list [(a(X),a(Y)), (b(X),b(Y))] means, that the head constraint a(X) of the first rule is overlapped with the head constraint a(Y) of the second rule and also the head constraint b(X) of the first rules is overlapped with the head constraint b(Y) of the second rule. The list CAS contains the critical ancestor state of this critical pair. =============================================================================*/ :- module(conflcheck, [ check_confluence/1, check_confluence/2, check_confluence/3, check_confluence/4, show_critical_pairs/1, show_critical_pairs/3, show_all_critical_pairs/1, show_all_critical_pairs/3]). :- use_module(criticalpairs, [ critical_pairs/2, critical_pairs/4, show_critical_pairs/1, show_critical_pairs/3, show_all_critical_pairs/1, show_all_critical_pairs/3]). :- use_module(stateequiv, [equivalent_states/2]). :- use_module(termlib, [tl_member/3]). %% check_confluence(+FileName) % % This predicate checks all CHR rules in the file FileName for confluence and % prints the according output. If the program is not confluent, i.e. if % there are non-joinable critical pairs, for those critical pairs a message is % printed containing the critical pair, together with the according rules and % overlap. This predicate always succeeds, even if the program is not % confluent. The confluence check continues after the first non-joinable % critical pair is found. % % The predicate first calculates all critical pairs stemming from all possible % overlaps of the rules in the file specified by FileName. Second the % according outputs are made and flags are set before all critical pairs are % checked for joinability. At last, the final message is printed and the flags % are set back to their default values. check_confluence(FileName) :- critical_pairs(FileName, CPS), start_joinable_check(FileName), cps_joinable(CPS, FileName, NoOfFail), end_joinable_check(FileName, NoOfFail),!. %% check_confluence(+FileName, RuleName1, RuleName2) % % This predicate checks two Rules from the file specified by FileName for % confluence and prints the according output. The Name of the two rules is are % given as RuleName1 and RuleName2. To check of only one rule RuleName1 and % RuleName2 have to be the same. If a rule with the name RuleName1 or RuleName2 % does not exists in the program, nothing is checked. % If the program is not confluent, i.e. if there are non-joinable critical % pairs, for those critical pairs a message is printed containing the critical % pair, together with the according rules and overlap. This predicate always % succeeds, even if the program is not confluent. The confluence check % continues after the first non-joinable critical pair is found. % % The predicate first calculates all critical pairs stemming from all possible % overlaps of the two rules in the file specified by FileName. Second the % according outputs are made and flags are set before all critical pairs are % checked for joinability. At last, the final message is printed and the flags % are set back to their default values. check_confluence(FileName, RuleName1, RuleName2) :- critical_pairs(FileName, RuleName1, RuleName2, CPS), start_joinable_check(FileName), cps_joinable(CPS, FileName, NoOfFail), end_joinable_check(FileName, NoOfFail),!. %% check_confluence(+FileName, -NoOfFail) % % Like check_confluence/1 but without any output beeing printed and NoOfFail % being bound to the number of non-joinable critical pairs. check_confluence(FileName, NoOfFail) :- critical_pairs(FileName, CPS), set_prolog_flag(verbose, silent), style_check(-singleton), set_prolog_flag(chr_toplevel_show_store, false), cps_joinable_no_print(CPS, FileName, NoOfFail), set_prolog_flag(chr_toplevel_show_store, true), style_check(-singleton), set_prolog_flag(verbose, normal). %% check_confluence(+FileName, +RuleName1, +RuleName2, -NoOfFail) % % Like check_confluence/3 but without any output beeing printed and NoOfFail % being bound to the number of non-joinable critical pairs. check_confluence(FileName, RuleName1, RuleName2, NoOfFail) :- critical_pairs(FileName, RuleName1, RuleName2, CPS), set_prolog_flag(verbose, silent), style_check(-singleton), set_prolog_flag(chr_toplevel_show_store, false), cps_joinable_no_print(CPS, FileName, NoOfFail), set_prolog_flag(chr_toplevel_show_store, true), style_check(-singleton), set_prolog_flag(verbose, normal). %% cps_joinable(+CPS, +FileName, ~NoOfFail) % % This predicate checks joinability of critical pairs. All critical pairs in % the list CPS are checked for joinability. FileName specifies the file % containing the CHR rules the critical pairs stems from. NoOfFail is the % number of critical pairs in CPS which are not joinable. This predicate % succeeds no matter whether there are non-joinable critical pairs or not. cps_joinable([], _, 0). cps_joinable([cp(S1, S2, R1, R2, O, CAS)|CPS], FileName, N) :- (states_joinable(S1, S2, FileName) -> (N1 is 0) ; (print_not_joinable(cp(S1, S2, R1, R2, O, CAS)), N1 is 1) ), !, cps_joinable(CPS, FileName, N2), N is N1 + N2. %% cps_joinable_no_print(+CPS, +FileName, ~NoOfFail) % % Like cps_joinable/3 but with no output generated. cps_joinable_no_print([], _, 0). cps_joinable_no_print([cp(S1, S2, _, _, _, _)|CPS], FileName, N) :- (states_joinable(S1, S2, FileName) -> (N1 is 0) ; (N1 is 1) ), !, cps_joinable_no_print(CPS, FileName, N2), N is N1 + N2. %% states_joinable(+State1, +State2, +FileName) % % This predicate succeeds if the two states State1 and State2 are joinable % given the rules of the program in the file specified by FileName. Joinable in % this case means that the rules of the program applied until exhaustion lead % to two states which are equivalent according to the definition of state % equivalence given in [RBF09]. % % After merging CHR and built-in constraints together into one list and % converting this list into a goal, both resulting goals are posed as query to % the CHR runtime system. Each time before a query is posed to the CHR system, % the CHR program file is consulted in order to reset the CHR runtime system to % its original state. After each call, the final state is retrieved using % find_chr_constraints/2. Because of the independent calls for each state, the % global variables the states share have been disconnected. Thus, they are % reconnected by calling reconnect/6. The two final states are then % compared using equivalent_states/2. states_joinable(S1, S2, FileName) :- copy_term(S1, state(G1, B1, V1)), copy_term(S2, state(G2, B2, V2)), append(G1, B1, L1), append(G2, B2, L2), list_to_goal(L1, H1), list_to_goal(L2, H2), consult(FileName), call(H1), findall_chr_constraints(V1, Result1), consult(FileName), call(H2), findall_chr_constraints(V2, Result2), reconnect(Result1, Result2, G1n, G2n, V1n, V2n), equivalent_states(state(G1n, [], V1n), state(G2n, [], V2n)),!. % list_to_goal(+L, ~G) % % This predicate converts a list of constraints L (user-defined as well as % built-ins constraints) into a single goal which then can be executed using % the predicate call/1. list_to_goal([C], (C)). list_to_goal([C|R],(C,T)) :- list_to_goal(R, T). % findall_chr_constraints(+GlobVars, -Res) % % This predicate binds Res to the list of all CHR constraints in the store that % can be found using find_chr_constraint/1 from the CHR library. The list % GlobVars contains all the global variables appearing in the original query % which led to the result Res. This is needed to keep the global variables % connected to the result of the computation. % % This predicate temporarly save the CHR constraints into a file to keep the % variables connected. Thus it needs to be placed in a directory where the user % has write access. The filename is randomly generated and the file is deleted % after the computation. findall_chr_constraints(GlobVars, Res) :- create_file_name(Name), open(Name, write, Sout, [alias(output)]), ( ( find_chr_constraint(R), write(output, R), write(output, ', '), nl(output), fail ) ; ( true ) ), write(output, globs(GlobVars)), write(output, '.'), nl(output), close(Sout), open(Name, read, Sin, [alias(input)]), read(input, T), close(Sin), delete_file(Name), to_list(T, Res). % to_list(+Term, -List) % % This predicate converts the conjunction of terms T, ending with a globs(...) % term into a list, where each subterm is one element fo the list. % % Example: to_list((a(X),b(y,(c(Z)),globs([X,Y,Z])), R), yields % R = [a(X), b(y,(c(Z)), globs([X,Y,Z])] to_list(T, [H|Res]) :- T =.. [_,H,T1], to_list(T1, Res). to_list(T, [T]) :- T =.. [globs, _]. % create_file_name(-Name) % % This predicate randomly generates a filename. If a file with this name does % not exist in the execution directory, the filename is returned, otherwise a % different name is generated create_file_name(Name) :- random(X), string_to_atom(Name, X), (exists_file(Name) -> fail; true). % reconnect(+Res1, +Res2, -Goal1, -Goal2, -GlobVars1, -GlobVars2) % % This predicate seperates the results found by findall_chr_constraints/2 into % the actual goal store and the set of global variables. Furthermore, it % reconnects the two states by unifiying the global variables of the two states, % while keeping track, that a global variable from one state is only bound to % one global variable from another state (for details see reconnect_globs/3). % The lists Res1 and Res2 are the results found by findall_chr_constraints/2. % Goal1 and Goal2 are lists representing the respective goal stores while % GlobVars1 and GlobVars2 are lists containing the global variables. reconnect(R1, R2, G1, G2, V1, V2):- extract_globs(R1, G1, V1), extract_globs(R2, G2, V2), reconnect_globs(V1, V2). % extract_globs(+List, -Goal, -GlobVars) % % This predicate separates the list List generated by findall_chr_constraints/2 % into the goal store Goal and the list of global variables GlobVars. extract_globs([globs(V)], [], V). extract_globs([H|R], [H|G], V) :- extract_globs(R, G, V). % reconnect_globs(+V1, +V2) % % Auxilliary predicate, calls reconnect_globs(V1, V2, []). reconnect_globs(V1, V2) :- reconnect_globs(V1, V2, []). % reconnect_globs(+V1, +V2, S) % % This predicate reconnect the lists of global variables V1 and V2. This needs % to be done if the global variables originate from two states of a critical % pair that have been executed separately and thus have been disconnected. The % predicate makes sure, that every variable occuring in V1 is only unified with % one variable occuring in V2 and vice versa. This is needed to take into % account different variable bindings that may have occured during execution % of the states of the critical pair. If an already reconnected variable is % seen again, it needs to be bound to the same variable as before, otherwise % the predicate fails. S is a buffer variable wich needs to be instantiated to % the empty list when calling the predicate. % % Example 1: % reconnect_globs([X, Y, X], [A, B, A],[]) succeeds with X = A and Y = B. % % Example 2: % reconnect_globs([X, Y, X], [A, B, C],[]) fails. reconnect_globs([], [], _). reconnect_globs([V1|R1],[V2|R2], S) :- tl_member(V1, S, ==),!, V1 == V2, reconnect_globs(R1, R2, S). reconnect_globs([V1|R1],[V2|R2], S) :- tl_member(V2, S, ==),!, V1 == V2, reconnect_globs(R1, R2, S). reconnect_globs([V1|R1],[V2|R2], S) :- \+ tl_member(V1, S, ==), \+ tl_member(V2, S, ==), var(V1), var(V2), V1 = V2, reconnect_globs(R1, R2, [V1|S]). reconnect_globs([V1|R1],[V2|R2], S) :- compound(V1), compound(V2), V1 =..[_|T1], V2 =..[_|T2], append(T1, R1, L1), append(T2, R2, L2), reconnect_globs(L1, L2, S). reconnect_globs([V1|R1],[V2|R2], S) :- ground(V1), ground(V2), V1 == V2, reconnect_globs(R1, R2, S). % start_joinable_check(+FileName) % % This predicate prints a message saying that the confluence check for the % file specified by FileName has been started and sets three different flags. % Singleton variable warnings are turned of and Prolog as well as CHR execution % are turned silent. This way, no output is produced while the critical pairs % are checked for joinability. start_joinable_check(FileName) :- nl, print('Checking confluence of CHR program in '), print(FileName), print('...'), nl,nl, set_prolog_flag(verbose, silent), style_check(-singleton), set_prolog_flag(chr_toplevel_show_store, false). % end_joinable_check(+FileName, +NoOfFail) % % This predicate prints out the final message after the confluence check and % turns Prolog's verbosity back to normal. FileName again specifies the file for % which confluence has been checked while NoOfFail is an integer indicating the % number of non-joinable critical pairs. end_joinable_check(FileName, NoFail) :- print_end_result(FileName, NoFail), style_check(-singleton). % print_end_result(+FileName, +NoOfFail) % % This predicate prints the end result message after the confluence check is % done. FileName specifies the file name of the file which was checked. The % message printed is depending on the number of non-joinable critical pairs % found. print_end_result(FileName, 0) :- print('The CHR program in '), print(FileName), print(' is confluent.'), nl,nl. print_end_result(FileName, N) :- N > 0, print('The CHR program in '), print(FileName), print(' is NOT confluent! '), print(N), print(' non-joinable critical pair(s) found!'), nl. % print_not_joinable(+CP) % % This predicate generates a messages for a non-joinable critical pair. The % critical pair is printed together with the overlap and the rules it stems % from. print_not_joinable(cp(S1, S2, rule(N1, _, _, _, _), rule(N2, _, _, _, _), O, CAS)) :- numbervars(cp(S1, S2, rule(N1, _, _, _, _), rule(N2, _, _, _, _), O, CAS), 0, _E), write_term('===============================================================================', []),nl, write_term('The following critical pair is not joinable:', []),nl, write_term(S1, [numbervars(true)]),nl, write_term(S2, [numbervars(true)]),nl,nl, write_term('This critical pair stems from the critical ancestor state:', []),nl, write_term(CAS, [numbervars(true)]),nl,nl, write_term('with the overlapping part:', []),nl, write_term(O, [numbervars(true)]),nl,nl, write_term('of the following two rules: ', []),nl, write_term(N1, [numbervars(true)]), nl, write_term(N2, [numbervars(true)]), nl, write_term('===============================================================================', []),nl,nl. %%%%%%%%%%%%%%%%%%%%%%%%%%%% References %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % [Fru09] Thom Fruehwirth: Constraint Handling Rules, 2009, Cambridge % University Press % [RBF09] Frank Raiser, Hariolf Betz, and Thom Frühwirth: Equivalence of CHR % states revisited, 2009. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% criticalpairs.pl0000600000175000017500000004621611346730177012366 0ustar jocjoc/*============================================================================= File: criticalpairs.pl Authors: Johannes Langbein, Îçҹ̽»¨, Germany, jolangbein at gmail dot com Date: 02-07-2010 Version: 1.0 Copyright: 2010, Johannes Langbein This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . =============================================================================*/ /*============================ critical pairs ================================= The predicates in this file implement an algorithm to find overlaps of rules and create critical pairs from this overlap. The algorithm is loosely based on the section on confluence in [DSS07]. The input for this program is a file containing a CHR program. The file has to be syntactically correct in order for the program to work correctly, therefore loading the file into a CHR runtime system previous to running this program is highly recommended. IMPORTANT NOTE: The underlying constraint theory is restricted to CET, thus only = is allowed as built-in constraint in the rules. Predicates in this file: ======================== critical_pairs/2 Calculate non-trivial CPs of all rules in file critical_pairs/4 Calculate non-trivial CPs of a given rule pair all_critical_pairs/2 Calculate all CPs of all rules in file all_critical_pairs/4 Calculate all CPs of a given rule pair show_critical_pairs/1 Print non-trivial CPs of all rules in file show_critical_pairs/3 Print non-trivial CPs of a given rule pair show_all_critical_pairs/1 Print all CPs of all rules in file show_all_critical_pairs/3 Print all CPs of a given rule pair Datastructures used: ==================== state(G, B, V) A term representing a CHR state. G is a list of CHR constraints, represented as Prolog terms. B is a list of built-in constraints, represented as Prolog terms. V is the list of global variables, represented as unbound Prolog variables. This list must not contain duplicates. rule(S, KH, RH, G, B) A term representing a CHR rule. S is the rule together with its name as string as it is represented in the source file. KH, RH, G, B are lists representing the kept head constraints, the removed head constraints, the guard and the body of the rule. KH, and G are possibly empty. cp(S1, S2, R1, R2, O, CAS) A term representing a critical pair. S1 and S2 are the two states of the critical pair represented as state(...) terms according to the definition above. R1 and R2 are the CHR rules the critical pair is stemming from. They are represented as rule(...) terms according to the definition above. O is a list of tuples, consisting of pairs of constraints. Those pairs describe the overlap of the two rules which leads to the critical pair. The list [(a(X),a(Y)), (b(X),b(Y))] means, that the head constraint a(X) of the first rule is overlapped with the head constraint a(Y) of the second rule and also the head constraint b(X) of the first rules is overlapped with the head constraint b(Y) of the second rule. The list CAS contains the critical ancestor state of this critical pair. =============================================================================*/ :- module(criticalpairs, [ critical_pairs/2, critical_pairs/4, all_critical_pairs/2, all_critical_pairs/4, show_critical_pairs/1, show_critical_pairs/3, show_all_critical_pairs/1, show_all_critical_pairs/3]). :- use_module(chrparser, [read_rules/3]). :- use_module(termlib, [tl_member/3, tl_filter/3, tl_make_set/3]). :- use_module(chrlib, [builtins_consistent/1, unifier/3]). :- use_module(stateequiv, [equivalent_states/2]). %% critical_pairs(+FilePath, -CPS) % % This predicate calculates a duplicate free list of all non-trivial critical % pairs of all rules given in the file specified by the string FilePath. % This file can be any valid CHR program file. The elements of the list are % terms representing critical pairs in the way described above. critical_pairs(File, CPS) :- all_critical_pairs(File, CPSA), process_cps(CPSA, CPS). %% critical_pairs(+FilePath, +RuleName1, +RuleName2, -CPS) % % This predicate calculates a duplicate free list of all non-trivial critical % pairs of two rules given in the file specified by the string FilePath. % This file can be any valid CHR program file. The elements of the list are % terms representing critical pairs in the way described above. Critical pairs % are only calculated for the two rules whose names are given as % RuleName1 and RuleName2. To calculate the critical pairs of a rule with % itself RuleName1 and RuleName2 have to be the same. If a rule with the name % RuleName1 or RuleName2 does not exists in the program, the predicate returns % an empty list in CPS. critical_pairs(File, RuleName1, RuleName2, CPS) :- all_critical_pairs(File, RuleName1, RuleName2, CPSA), process_cps(CPSA, CPS). %% all_critical_pairs(+FilePath, -CPS) % This predicate calculates all critical pairs stemming from every possible % overlap of all rules in the CHR program file specified by the string % FilePath. This file can be any valid CHR program file The elements of the % list are terms representing critical pairs in the way described above. % % First, all rules are read from the file using the predicate read_rules/3 from % the module parser. The returned list of rules then is used to calculate all % possible rule pairs and the resulting critical pairs from every possible % overlap. all_critical_pairs(File, CPS) :- read_rules(File, R, CHRC), findall(CP, (pick_rule_pair(R, R1, R2), critical_pair(R1, R2, CHRC, CP)), CPS). %% all_critical_pairs(+FilePath, +RuleName1, +RuleName2, -CPS) % This predicate calculates all critical pairs stemming from every possible % overlap of two rules in the CHR program file specified by the string % FilePath. This file can be any valid CHR program file The elements of the % list are terms representing critical pairs in the way described above. % Critical pairs are only calculated for the two rules whose names are given as % RuleName1 and RuleName2. To calculate the critical pairs of a rule with % itself RuleName1 and RuleName2 have to be the same. If a rule with the name % RuleName1 or RuleName2 does not exists in the program, the predicate returns % an empty list in CPS. % % First, all rules are read from the file using the predicate read_rules/3 from % the module parser. The returned list of rules then is used to calculate all % possible rule pairs and the resulting critical pairs from every possible % overlap. all_critical_pairs(File, RuleName1, RuleName2, CPS) :- read_rules(File, R, CHRC), findall(CP, (pick_rule_pair(R, RuleName1, RuleName2, R1, R2), critical_pair(R1, R2, CHRC, CP)), CPS). %% show_critical_pairs(+File) % % This predicate prints a duplicate free list of all non-trivial critical % pairs of all rules given in the file specified by the string File. % This file can be any valid CHR program file. show_critical_pairs(File) :- critical_pairs(File, CPS), pretty_print(CPS), print_lenght(CPS). %% show_all_critical_pairs(+File) % % This predicate prints all critical pairs stemming from every possible % overlap of all rules in the CHR program file specified by the string % File. This file can be any valid CHR program file. show_all_critical_pairs(File) :- all_critical_pairs(File, CPS), pretty_print(CPS), print_lenght(CPS). % show_critical_pairs(+File, +RuleName1, +RuleName2) % % This predicate prints a duplicate free list of all non-trivial critical % pairs of two rules given in the file specified by the string File. % This file can be any valid CHR program file. Critical pairs % are only printed for the two rules whose names are given as % RuleName1 and RuleName2. To print the critical pairs of a rule with % itself RuleName1 and RuleName2 have to be the same. show_critical_pairs(File, RuleName1, RuleName2) :- critical_pairs(File, RuleName1, RuleName2, CPS), pretty_print(CPS), print_lenght(CPS). % show_all_critical_pairs(+File, +RuleName1, +RuleName2) % % This predicate prints all critical pairs stemming from every possible % overlap of two rules in the CHR program file specified by the string % File. This file can be any valid CHR program file. Critical pairs are % only printed for the two rules whose names are given as RuleName1 and % RuleName2. To print the critical pairs of a rule with itself RuleName1 % and RuleName2 have to be the same. show_all_critical_pairs(File, RuleName1, RuleName2) :- all_critical_pairs(File, RuleName1, RuleName2, CPS), pretty_print(CPS), print_lenght(CPS). % critical_pair(+Rule1, +Rule2, +CHRC -CP) % % This predicate calculates one critical pair, stemming from one possible % overlap of the two rules R1 and R2 according to the definition in [Fru09]. % To construct the critical pair correctly, the list CHRC contains the names of % all CHR constraints as specified by the directive :- chr_constraint in the % source file. % % Backtracking this predicate eventually reveals all possible critical pairs, % stemming from every possible overlap. % % The critical pair is calculated by first renaming the variables of the two % rules apart with a call of copy_term for each rule. After appending the kept % and removed head constraints into one list, a possible match is created % calling the predicate match/5 which reveals the equalities necessary to make % the overlapping part match, as well as the non-overlapping parts of the two % rules. The built-in store of the states in the critical pair consists of the % equality revealed by match in conjunction with the two guards of the two % rules. Finally, the two goal stores and the set of global variables are % calculated according to the definition in [DSS07]. critical_pair(R1, R2, CHRC, cp(state(GS1, BS1, VS), state(GS2, BS2, VS), R1, R2, O, CAS)) :- copy_term(R1, rule(_N1, KH1, RH1, G1, B1)), copy_term(R2, rule(_N2, KH2, RH2, G2, B2)), append(KH1, RH1, H1), append(KH2, RH2, H2), match(H1, H2, O, U, D1, D2), append([U, G1, G2], BS), builtins_consistent(BS), split_body(B1, CHRC, B1CHR, B1BI), split_body(B2, CHRC, B2CHR, B2BI), append([KH1, D2, B1CHR], GS1), append([KH2, D1, B2CHR], GS2), append(B1BI, BS, BS1), append(B2BI, BS, BS2), append([H1, H2, G1, G2], WS), term_variables(WS, VS), append([H1, D2, U, G1, G2], CAS). % match(+Head1, +Head2, -Overlap -Unifier, -Diff1, -Diff2) % % This predicate calculates an arbitrary non-empty matching of the two list of % constraints Head1 and Head2. The list Overlap consisting of pairs of % constraints indicating which head constraint have been matched. The % overlapping part of the two heads is not unified but the unifier needed for % the match is returned as a list of =/2 terms in Unifier. The lists Diff1, % and Diff2 contain all the constraints which are not part of the overlap of % Head1 and Head2, respectively. % % On backtracking, this predicate eventually calculates all possible non-empty % matches. % Example: match([a(X),b(Y),c(Z)], [b(V), c(W)], U, D1, D2, O) results in % % 1) Overlap: b(Y) = b(V) % O = [(b(Y),b(V))], U = [Y=V], % D1 = [a(X), c(Z)], D2 = [c(W)], % % 2) Overlap: b(Y) = b(V), c(Z) = c(W) % O = [(b(Y),b(V)),(c(Z),c(W))], U = [Y=V, Z=W], % D1 = [a(X)], D2 = [], % % 3) Overlap: c(Z) = c(W) % O = [(c(Z),c(W))], U = [Z=W], % D1 = [a(X), b(Y)], D2 = [b(V)], % % The predicate traverses the first list of constraints recursively and in % every step performs one of the following actions, in case they are possible. % 1) Match the first constraint from the first list against one from the second % list (In this case, this is the whole overlap). % 2) Match the first constraint from the first list against one from the second % list and continue recursively with the rest of the list. % 3) Ignore the first constraint of the first list (thus excluding it from the % match) and continue recursively with the rest of the list. match([H1|R1], L2, [(H1,M)], U, R1, R) :- match_one(H1, L2, M, U, R). match([H1|R1], L2, [(H1,M)|O], U, D1, D2) :- match_one(H1, L2, M, U1, S), match(R1, S, O, U2, D1, D2), append(U1, U2, U). match([H1|R1], L2, O, U, [H1|D1], D2) :- match(R1, L2, O, U, D1, D2). % match_one(+Head, +List, -Match -Unifier, -Rest) % % This predicate succeeds if the constraint Head can be matched against one % constraint in the list List. In this case, Match is the constraint which is % matched against Head, Unifier is a list of =/2 terms % containing the equations necessary to make Head and the according constraint % in List syntactically equal, while Rest is List without the matched % constraint. On backtracking, this predicate will reveal every possible % matching between Head and constraints in List. % % Example 1: match_one(c(X), [a(X), c(Y, Z), c(V)], M, U, R) succeeds and % results in M = c(V), U = [X=V], and R = [a(X), c(Y, Z)]. % % Example 2: match_once(X), [a(X), c(Y, Z), d(V)], M, U, R) fails. % % The predicate recursively traverses List and either calculates the unifier of % Head with the current head of List (if even possible) or continues % recursively with the rest of List. match_one(X, [H|R], H, U, R) :- unifier(X, H, U). match_one(X, [H|R], M, U, [H|R1]) :- match_one(X, R, M, U, R1). % split_body(+Body +LCHRCons, ~CHR, ~BI). % % This predicate splits the list Body, consisting of user-defined and built-in % constraints into two lists CHR and BI where CHR contains only user defined % and BI contains only built-in constraints. The list LCHRCons with terms of % the form cons(functor, arity) is used to determine if a member of the list % body is a user-defined constraint or not. If it appears in LCHRCons, it is % added to the list CHR, if not, it is added to the list BI. split_body([], _, [], []). split_body([C|R], CONS, [C|CHR], BI) :- functor(C, F, N), tl_member((F, N), CONS, ==), !, split_body(R, CONS, CHR, BI). split_body([C|R], CONS, CHR, [C|BI]) :- split_body(R, CONS, CHR, BI). % process_cps(+CPSA, -CPS) % % This predicate removes trivial and duplicate critical pairs from the list % CPSA of critical pairs and returns the result as CPS. A critical pair is % trivial if its two states are syntactically equal. Two pairs % cp(S1, S2, _, _, _, _) and cp(S3, S4, _, _, _, _) are duplicates if S1 % equals S3 and S2 equals S4 or if S1 equals S4 and S2 equals S3. process_cps(CPS, R) :- tl_filter(CPS, criticalpairs:non_trivial_cp, CPS1), tl_make_set(CPS1, criticalpairs:variant_equal_cp, R). % non_trivial_cp(+CP) % % This predicate is true if the critical pair CP is non-trivial, i.e. if its % two states are not equivalent. non_trivial_cp(cp(S1, S2, _, _, _, _)) :- \+equivalent_states(S1, S2). % variant_equal_cp(+CP1, +CP2) % % This predicate succeeds, iff the two critical pairs CP1 and CP2 are variants, % or if they are equal. Two pairs cp(S1, S2, _, _, _, _) and % cp(S3, S4, _, _, _, _) % are variants if S1 is a variant if S3 and S2 is a variant of S4 or if S1 is a % variant of S4 and S2 is a variant of S3. The two pairs are equal if % S1 == S3 and S2 == S4 or if S1 == S4 and S2 == S3, where == denotes state % equivalence. variant_equal_cp(cp(S1, S2, _, _, _, _), cp(S3, S4, _, _, _, _)) :- S1 =@= S3, S2 =@= S4. variant_equal_cp(cp(S1, S2, _, _, _, _), cp(S3, S4, _, _, _, _)) :- S1 =@= S4, S2 =@= S3. variant_equal_cp(cp(S1, S2, _, _, _, _), cp(S3, S4, _, _, _, _)) :- equivalent_states(S1, S3), equivalent_states(S2, S4). variant_equal_cp(cp(S1, S2, _, _, _, _), cp(S3, S4, _, _, _, _)) :- equivalent_states(S1, S4), equivalent_states(S2, S3). % pick_rule_pair(+R, -R1, -R2) % % This predicate takes a list of rules R and returns two rules R1 and R2 which % are both members of the list R. R1 and R2 are not necessarily different, but % it is guaranteed, that the R2 is at a same or higher list index than R1. % This avoids selecting (rule1, rule2) as well as (rule2, rule1). % % On backtracking, this predicate reveals all possible pairs of rules. % % Example: pick_rule_pair([rule1, rule2, rule3], R1, R2) results in % R1 = rule1 % R2 = rule1 % R1 = rule1 % R2 = rule2 % R1 = rule1 % R2 = rule3 % R1 = rule2 % R2 = rule2 % R1 = rule2 % R2 = rule3 % R1 = rule3 % R2 = rule3 pick_rule_pair(R, R1, R2) :- pick_first(R, R1, RS), pick_second(RS, R2). pick_first([H|R], H, [H|R]). pick_first([_|R], R1, RS) :- pick_first(R, R1, RS). pick_second([H|_], H). pick_second([_|R], R1) :- pick_second(R, R1). % pick_rule_pair(+R, ,+RN1, +RN2, -R1, -R2) % % This predicate takes a list of rules R and returns two rules R1 and R2 which % are both members of the list R and have the names RN1 and RN2 accordingly. If % a rule with the name RN1 or RN2 does not exist, the predicate fails. pick_rule_pair(R, RN1, RN2, R1, R2):- pick_by_name(R, RN1, R1), pick_by_name(R, RN2, R2). pick_by_name([rule(RN@RS, KH, RH, G, B)|_], RN, rule(RN@RS, KH, RH, G, B)) :-!. pick_by_name([rule(_, _, _, _, _)|Rules], RN, R) :- pick_by_name(Rules, RN, R). % pretty_print(+List) % % Writes every element of a list of ciritcal pairs list in a new line using % write/1. pretty_print([]). pretty_print([cp(S1, S2, R1, R2, O, CAS)|R]) :- numbervars(cp(S1, S2, R1, R2, O, CAS), 0, _E), write_term(S1, [numbervars(true)]), nl, write_term(S2, [numbervars(true)]), nl, write_term(R1, [numbervars(true)]), nl, write_term(R2, [numbervars(true)]), nl, write_term(O, [numbervars(true)]), nl, write_term(CAS, [numbervars(true)]), nl, nl, nl, pretty_print(R). % print_lenght(+List) % % Outputs the lenght of the list of critical pairs List. print_lenght(L) :- length(L,N), write(N), write(' critical pairs found'),nl,nl. %%%%%%%%%%%%%%%%%%%%%%%%%%%% References %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % [DSS07]: Gregory J. Duck, Peter J. Stuckey, Martin Sulzmann: Observable % confluence for constraint handling rules - Lecture Notes in Computer Science, % 2007 - Springer % [Fru09] Thom Fruehwirth: Constraint Handling Rules, 2009, Cambridge % University Press %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LICENSE0000644000175000017500000010451311334777015010207 0ustar jocjoc GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . MANUAL0000644000175000017500000001352411335014234010067 0ustar jocjoc ============================= CHR Confluence Checker Manual ============================= 1) LIMITATIONS a) The confluence checker only works for programs that do not contain CHR propagation rules as the propagation history is not considered. b) The only built-in constraint allowed is equality expressed using the = operator. This is because the theory for the built-in constraints is limited to CET. c) The confluence checker needs to be executed in directory with read and write access as it writes and reads temporary files to the hard-drive. d) No syntax check is performed. The program whose confluence should be checked needs to be a valid CHR program for the Prolog implementations of CHR. Thus, it is recommended to run the Program in a Prolog implementation of CHR first. 2) PREDICATES AND HOW TO USE THEM check_confluence(+FileName) Checks confluence for a program and writes every non-joinable critical pair to the output. The path to the program file is given as FileName. This file can be any valid CHR program in one of the common Prolog implementations of CHR. Example: check_confluence('examples/merge.pl') check_confluence(+FileName, +RuleName1, +RuleName2) Checks confluence for two rules in a program. Works exactly like check_confluence/1 but only considers critical pairs of two (not necessarily different) rules. The names of those rules are given as RuleName1 and RuleName2. Examples: check_confluence('ufd_basic.pl', link, link) check_confluence('ufd_basic.pl', findnode, findroot) show_critical_pairs(+FileName) Prints all non-trivial CPs of all rules in a file. The path to the program file is given as FileName. This file can be any valid CHR program in one of the common Prolog implementations of CHR. Example: show_critical_pairs('examples/merge.pl') show_critical_pairs(+FileName, +RuleName1, +RuleName2) Prints all non-trivial CPs of two rules in a file. Works exactly like show_critical_pairs/1 but only considers critical pairs of two (not necessarily different) rules. The names of those rules are given as RuleName1 and RuleName2. Examples: show_critical_pairs('ufd_basic.pl', link, link) show_critical_pairs('ufd_basic.pl', findnode, findroot) show_all_critical_pairs(+FileName) Prints all CPs of all rules in a file. Works exactly like show_critical_pairs/1 with the exception, that critical pairs are not filtered. This means, trivial critical pairs as well as syntactically equivalent critical pairs and critical pairs which are symmetric are not removed. Example: show_all_critical_pairs('examples/merge.pl') show_all_critical_pairs(+FileName, +RuleName1, +RuleName2) Prints all CPs of two rules in a file. Works exactly like show_critical_pairs/3 with the exception, that critical pairs are not filtered. This means, trivial critical pairs as well as syntactically equivalent critical pairs and critical pairs which are symmetric are not removed. Examples: show_all_critical_pairs('ufd_basic.pl', link, link) show_all_critical_pairs('ufd_basic.pl', findnode, findroot) 3) EXTENDING THE CONFLUENCE CHECKER AND USING IT WITH OTHER PROGRAMS a) Extending the confluence checker The confluence checker can be extended to implement different a filtering for the list of critical pairs. For example observable confluence could be implemented by filtering the list of the critical pairs accordingly. In order to do this, the predicate clean_cps/2 has to be changed. There needs to be a unary predicate my_predicate/1, which decides for a given critical pair whether it should be considered for the confluence analysis or not. If now the line tl_filter(CPSOld, my_predicate, CPSNew), is added to the predicate clean_cps/2, all critical pairs for which my_predicate fails are removed from the list CPSOld resulting in the list CPSNew. Using tl_make_set/3 instead of tl_filter/3 with a binary predicate comparing two critical pairs removes "redundant" critical pairs. The existing removals of trivial critical pairs and variants can be used as an example. b) Using the confluence checker from another program The confluence checker also provides predicates which produce no output but return results to their caller. For details see the documentation in the according source file. state_equivalence(+State1, +State2) Succeeds iff the two states are equivalent. critical_pairs(+FileName -NoCps) Like critical_pairs/1 but without output. NoCps is bound to the number of critical pairs found. critical_pairs(+FileName, RuleName1, RuleName2 -NoCps) Like critical_pairs/3 but without output. NoCps is bound to the number of critical pairs found. check_confluence(+FileName -NoCps) Like check_confluence/1 but without output. NoCps is bound to the number of non-joinable critical pairs found. check_confluence(+FileName, RuleName1, RuleName2 -NoCps) Like check_confluence/3 but without output. NoCps is bound to the number of non-joinable critical pairs found. stateequiv.pl0000600000175000017500000003565511333563334011727 0ustar jocjoc/*============================================================================= File: stateequiv.pl Authors: Johannes Langbein, Îçҹ̽»¨, Germany, jolangbein at gmail dot com Date: 02-07-2010 Version: 1.0 Copyright: 2010, Johannes Langbein This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . =============================================================================*/ /*=============================== state equivalence =========================== The predicates in this file implement the theorem giving a criterion for state equivalence presented in [RBF09]. The predicate equivalent_states/2 decides whether the two states. In other words, given two states state(G, B, V) and state(G', B', V'), the predicate succeeds iff Ex y (B' -> ((G = G') %% B)) && Ex y' (B -> ((G = G') %% B')) where y and y' are the renamed apart local variables of the two states. Furthermore the two sets of global variables V and V' have to be equal, when reduced to only those variables actually occurring in the two states. Predicates in this file: ======================== equivalent_states/2 Decides, whether two CHR states are equivalent. Datastructures used: ==================== state(G, B, V) A term representing a CHR state. G is a list of CHR constraints, represented as Prolog terms. B is a list of built-in constraints, represented as Prolog terms. V is the list of global variables, represented as unbound Prolog variables. This list must not contain duplicates. Example: the term state([c(X),[X=0],[X]) represents the CHR state ([c(X)], (X=0), {X}) according to the definition of CHR states in [RBF09]. =============================================================================*/ :- module(stateequiv, [equivalent_states/2]). :- use_module(termlib, [tl_member/3, tl_diff/4, tl_set_equality/3, tl_intersect/4]). :- use_module(chrlib, [ builtins_failed/1, propagate_builtins/1]). %% equivalent_states(+S1, +S2) % % This predicate succeeds if the two states S1 and S2, represented as terms of % the form state(...), are equivalent according to [RBF09]. This is the case if % either both built-in stores are failed or if the global variables are % equivalent and the built-ins of one state imply the buil-ins of the other one % as well as the equivalence of the goal store and vice versa. equivalent_states(state(_, B1, _), state(_, B2, _)) :- builtins_failed(B1), builtins_failed(B2). equivalent_states(S1, S2) :- eq_glob_vars(S1,S2), rename_states_apart(S1, S2, R1 ,R2), implies(R1, R2), implies(R2, R1). % implies(+S1, +S2) % % This predicate checks the implication B -> Ex y' ((G = G') && B') used in the % theorem in [RBF09] In other words, given two states state(G1, B1, V1) and % state(G2, B2, V2), it checks whether B1 -> Ex y (G1 = G2 && B2) where y are % the local variables of the state S2. The local variables of the two states % S1 and S2 have to be disjunct. % % Example 1: implies( state([c(2),c(Y)],[Y=1],[Y]), % state([c(X),c(Y)],[Y=1],[Y])) % is true, because Y=1 -> Ex X [c(2), c(Y)] = [c(X), c(Y)] && Y=1. % Example 2: implies( state([c(X),c(Y)],[Y=1],[]), % state([c(2),c(Z)],[Z=1],[])) % is false, because Y=1 -> Ex Z [c(X), c(Y)] = [c(2), c(Z)] && Z=1 does not % hold since Ex Z ([c(X), c(Y)] = [c(2), c(Z)]) is not true. % % Example 3: implies(state([c(X)], [], [X]), state([c(X)], [X=1], [X])) % is false, because true -> (([c(X)] = [c(X)]) && X=1) is false since % true -> X=1 does not hold. % % To check the implication, a copy of the two states is made. The built-ins of % the first state are propagated. After this, the built-ins of the second state % need to be implied as well as the equivalence of the goal stores. The global % variables of the second state are passed along to those checks to calculate % the set of local variables. implies(S1, S2) :- copy_term((S1, S2), (state(G1s, B1s, _), state(G2s, B2s, V2s))), propagate_builtins(B1s), builtins_implied(B2s, V2s), goal_eq_implied(G1s, G2s, V2s). % builtins_implied(+Bs, +Vs) % % This predicate is true iff the conjunction of built-ins is true. In other % words, the predicate checks, whether the formula % Ex Ls (b1 && b2 && ... && bn) holds. In this formula Ls is the list of the % local variables of Bs, i.e. all variables in B except those appearing in Vs % and [b1, .., bn] = B. % % Example 1: builtins_implied([X=1, X=Z, Y=Z], []) is true since the % formula Ex X,Y,Z (X=1 && X=Z && Y=Z) is true. % % Example 2: builtins_implied([X=1, X=Z, Y=Z], [Y,Z]) is false since the % formula Ex X (X=1 && X=Z && Y=Z) does not hold in general. builtins_implied([], _). builtins_implied([true|Bs], Vs) :- builtins_implied(Bs, Vs). builtins_implied([B|Bs], Vs) :- arg(1, B, X), arg(2, B, Y), local_vars(B, Vs, Ls), eq_term(Ls, X, Y), builtins_implied(Bs, Vs). % goal_eq_implied(+G1s, +G2s, +V2s) % % This predicate checks whether the two lists of constraints G1s and G2s are % "equal". The lists G1s and G2s are "equal" if there exists are permutation % of G1s such that all members of G1 and G2 are pairwise equal according to % eq_term/3. The list V2s contains the global variables of the state from % which G2s is taken. % % Example 1: goal_eq_implied([c(1), c(Y)], [c(Y), c(X)], [Y]) is true % since Ex X (c(1) = c(X) && c(Y) = c(Y)). % % Example 2: goal_eq_implied([c(1), c(Z)], [c(Y), c(X)], [Y]) is false % since Ex X (c(Y) = c(1) || c(Y) = c(Z)). goal_eq_implied([], [], _). goal_eq_implied([G1|G1s], G2s, V2s) :- remove_eq_goal(G1, G2s, V2s, H2s), goal_eq_implied(G1s, H2s, V2s). % remove_eq_goal(+G1, +G2s, +V2s ~Hs) % % This predicate removes the first constraint G2 from the list of constraints % G2s which is equal to the constraint G1 according to eq_term/3 and returns % the remaining list of constraints as Hs. The list V2s contains the global % variables of the state from which G2s is taken. % % Example 1: remove_eq_goal(c(2), [c(Y), c(X)], [Y], R) % results in R = [c(Y)] % % Example 1: remove_eq_goal(c(2), [c(Y), c(X)], [], R) % results in R = [c(X)] and R = [c(Y)] remove_eq_goal(G1, [G2|G2s], V2s, G2s) :- local_vars(G2, V2s, L2s), eq_term(L2s, G1, G2). remove_eq_goal(G1, [G2|G2s], V2s, [G2|Hs]) :- remove_eq_goal(G1, G2s, V2s, Hs). % eq_term(+Ls, +T1, +T2) % % This predicate checks whether two terms T1 and T2 are equivalent, given the % existential quantification of the variables in L. In other words, it checks % whether Ex L (T1 = T2) holds. % % Examples: Let t be an arbitrary Prolog term % % Example 1: eq_term([], t, t) is true, because the two terms are syntactically % equivalent. % % Example 2: eq_term([X], X, t) is true, because the formula Ex X (X=t) holds. % % Example 3: eq_term([Y], t, Y) is true, because the formula Ex Y (t=Y) holds. % % Example 4: eq_term([], X, t) is false, because the formula (X=t) does not % hold in general. % % Example 5: eq_term([X], f(X), f(t)) holds iff eq_terms([X], X, t) holds (see % Example 2). eq_term(_, T1, T2) :- T1 == T2, !. eq_term(Ls, T1, T2) :- var(T1), tl_member(T1, Ls, ==), T1 = T2, !. eq_term(Ls, T1, T2) :- var(T2), tl_member(T2, Ls, ==), T2 = T1, !. eq_term(Ls, T1, T2) :- compound(T1), compound(T2), T1 =.. [F1|U1s], T2 =.. [F2|U2s], F1 == F2, eq_term_list(Ls, U1s, U2s). % eq_term_list(+Ls, +T1s, T2s) % This predicate is true, if the two lists of terms T1s and T2s are pairwise % equal according to eq_term/3 under the existential quantification of the % variables in the variable list Ls. % % Example 1: eq_term_list([X], [X, f(X), 1], [Y, f(Y), 1]) is true. % % Example 1: eq_term_list([X], [X, f(X), 1], [Y, f(Y), Z]) is false since % eq_term([X], 1 Z) is false. eq_term_list(_, [], []). eq_term_list(Ls, [T1|T1s], [T2|T2s]) :- eq_term(Ls, T1, T2), eq_term_list(Ls, T1s, T2s). % local_vars(+T, +Vs, ~Ls) % % Auxiliary predicate to calculate the local variables of an arbitrary term. % This predicate calculates all variables of the term T, removes the ones % appearing in Vs and returns the result in Ls. local_vars(T, Vs, Ls) :- term_variables(T, TVs), tl_diff(TVs, Vs, ==, Ls). %%%%%%%%%%%%%%%%%%%%%%%% Equality of global variables %%%%%%%%%%%%%%%%%%%%%%%%% % The predicates in this section test, whether two sets of global variables are % "equal" according to the axiomatization introduced in [RBF09]. % In the predicates in this section, global variables are represented as lists, % although a set-based view of this list is assumed. This means those list must % not contain multiple occurrences of the same variable. Also, the order in % which the variables appear in the lists does not matter, for example the two % lists [X,Y] and [Y,X] are considered equal. % eq_glob_vars(+ST1, +ST2) % % This predicate is true, iff the set of global variables of the states ST1 and % ST2 are "equal" according to the axiomatization introduced in [RBF09]. This % means the predicate is true, iff the following condition holds: % The list of global variables of ST1, without those not appearing in the % goal or the built-in constraints of ST1, is a permutation % of the global variables of ST2, also without those not appearing in the % goal or the built-in constraints of ST2. % % Example 1: eq_glob_vars( state([c(X)],[X==0],[X]), % state([c(0)],[X==0],[X])) succeeds. % % Example 2: eq_glob_vars( state([c(0)],[],[X]), % state([c(0)],[],[])) succeeds. % % Example 3: eq_glob_vars( state([c(X)],[],[X]), % state([c(Y)],[],[Y])) fails. % % Checks whether the "cleaned up" versions of the global variables are a % permutation of each other calling eq_glob_vars_cleaned/2. The "cleaned up" % versions of the global variables are obtained by calling clean_glob_vars/2 % for each state. eq_glob_vars(state(G1s,B1s,V1s), state(G2s,B2s,V2s)) :- clean_glob_vars(state(G1s,B1s,V1s), W1s), clean_glob_vars(state(G2s,B2s,V2s), W2s), tl_set_equality(W1s,W2s, ==). % clean_glob_vars(+ST, ~Ws) % % This predicate is true, iff the list of variables Ws contains all global % variables of the state ST except those not appearing in the goal or built-in % constraints of ST. % % Example: clean_glob_vars(state([c(X)],[],[X,Y]), Ws) results in % VsNew = [X]. % % Calculates the list of all variables occurring in the goal and built-ins and % returns the intersection of the set of those variables with the set of global % variables. clean_glob_vars(state(Gs, Bs, Vs), Ws) :- term_variables((Gs,Bs), GBVs), tl_intersect(GBVs, Vs, ==, Ws). %%%%%%%%%%%%%%%%%%%% Renaming variables in states apart %%%%%%%%%%%%%%%%%%%%%%% % The predicates in this section are for renaming apart the variables in the % states for which equivalence is checked. The renaming preserves the naming of % global variables with the same name that occur in both states (for more % details, see rename_states_apart/4 below). % rename_states_apart(+S1, +S2, -R1, -R2). % % This predicate is true, iff the states R1 and R2 are the states S1 and % S2 respectively in which the local variables have been renamed apart % according to the precondition of the theorem in [RBF09]. % % This means that for the new states R1 and R2, the following holds: % 1. All variables are replaced by new ones with fresh names. % 2. All variables of the state S1 do not occur in R2 except for those which % are global variables of both states S1 and S2. This also holds vice % versa for the states S2 and R1. % 3. Variables occurring as global variables in both states S1 and S2 are % still named the same in both states R1 and R2. % % Example: rename_states_apart(state([c(X), c(Y)], [X=1], [X,Y]), % state([c(X), c(Y), c(Z)], [Y=1], [Z,X]), R1, R2). % will result in % % R1 = state([c(_A),c(_B)],[_A=1],[_A,_B]), % R2 = state([c(_A),c(_C),c(_D)],[_C=1],[_D,_A]) % % rename_states_apart first calls copy_term twice, once for each term % representing a state and then calls unify_varlists to unify the global % variables that occur in both states. rename_states_apart(state(G1s, B1s, V1s), state(G2s, B2s, V2s), state(H1s, C1s, W1s), state(H2s, C2s, W2s)) :- copy_term(state(G1s, B1s, V1s), state(H1s, C1s, W1s)), copy_term(state(G2s, B2s, V2s), state(H2s, C2s, W2s)), unify_varlists(V1s, V2s, W1s, W2s). % unify_varlist(+V1s, +V2s, +W1s, +W2s). % % This predicate is true, iff the following conditions hold for the list of % list of variables V1s, V2s, W1s, and W2s: % 1. If a variable appears in V1s at position n and in V2s at position m, then % the n-th variable in W1s is unified with the m-th variable of W2s. % 2. All other variables are not bound in any way. % % This predicate can be used to (re-) unify a list of variables, which have % been renamed apart but share some common members. Therefore, the original % list of variables are given as the two lists V1s and V2s. The predicate % unifies all variables which have been the same at some point. % If the two list V1s and V2s are disjunct, no unification will be preformed. % % Example: unify_varlist([X,Y,Z],[Y,Z],[A,B,C],[D,E]) results % in the unifications D = B and E = C. unify_varlists([], _, _, _). unify_varlists([V1|V1s], V2s, [W1|W1s], W2s) :- unify_var(V1, V2s, W1, W2s), unify_varlists(V1s, V2s, W1s, W2s). % unify_var(+X, +Vs, +Y, +Ws). % % This predicate is true iff the following condition holds for the variables % X and Y and the list of variables Vs and Ws: % If X occurs in the list Vs at position n, then Y is unified with the n-th % member of the list Ws. % % This predicate can be used to unify two variables which have been renamed % apart but had the same name originally. % % Example 1: unify_var(Y, [X,Y,Z], L, [A,B,C]) will perform the % unification B = L. % % Example 2: unify_var(X, [Y,Z], A, [B,C]) will not perform any unification. unify_var(_, [], _, _). unify_var(X, [V|_], Y, [W|_]) :- X == V, Y = W. unify_var(X, [V|Vs], Y, [_|Ws]) :- X \== V, unify_var(X, Vs, Y, Ws). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Literature %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % [RBF09] Frank Raiser, Hariolf Betz, and Thom Frühwirth: Equivalence of CHR % states revisited, 2009. termlib.pl0000755000175000017500000001435411333052120011161 0ustar jocjoc/*============================================================================= File: termlib.pl Author: Johannes Langbein, Îçҹ̽»¨, Germany, jolangbein at gmail dot com Date: 02-05-2010 Version: 1.0 Copyright: 2010, Johannes Langbein This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . =============================================================================*/ /*============================== termlib ====================================== This file defines a number of predicates for handling terms, as well as lists and sets of terms. Some of the predicates already exist in common implementations of Prolog although most of them do not work as intended if called with unbound variables or complex terms. For this purpose, every predicate whose implementation involves comparison of two terms is a higher-order predicate allowing the user to pass his own definition of equality as parameter to the predicate. All predicates are guaranteed to not alter any unbound variable occurring in the arguments Also, all predicates give a unique solution and thus are not backtrackable. Predicates in this file: ======================== tl_member/3 Element member of list tl_remove/4 Removes first occurence of element from list tl_member_remove/4 Removes first occurence of element from list if present tl_remove_all/4 Removes all occurences of element from list tl_filter/3 Filters list according to predicate tl_make_set/3 Turns list into set tl_set_equality/3 Decides whether two lists contain the same elements tl_intersect/4 Computes set intersection of two lists tl_diff/4 Computes set difference of two lists ==============================================================================*/ :- module(termlib, [ tl_member/3, tl_remove/4, tl_member_remove/4, tl_remove_all/4, tl_filter/3, tl_make_set/3, tl_set_equality/3, tl_intersect/4, tl_diff/4]). %% tl_member(+T, +L, +P) % % This predicate is true, iff the term T is equal to at least one member of L. % The equality is decided using the predicate P. Therefore P must be a % predicate of arity 2. tl_member(T, [H|_], P) :- call(P,T,H), !. tl_member(T, [_|R], P) :- tl_member(T, R, P). %% tl_remove(+T, +L, +P ~R) % % This predicate removes the first occurrence of a term in the list L which is % equal to the term T and returns the resulting List in R. The equality is % decided using the predicate P. Therefore P must be a predicate of arity 2. tl_remove(_, [], _, []) :- !. tl_remove(T, [H|R], P, R) :- call(P,T,H), !. tl_remove(T, [H|R], P, [H|R1]) :- tl_remove(T, R, P, R1). %% tl_member_remove(+T, +L, +P ~R) % % Combination of tl_member/3 and tl_remove/4, but more efficient than a % consecutive call. This predicate removes the first occurrence of a term in % the list L which is equal to the term T and returns the resulting List in R, % but only succeeds if such a term is found. Again, equality is decided using % the predicate P. Therefore P must be a predicate of arity 2. tl_member_remove(T, [H|R], P, R) :- call(P,T,H), !. tl_member_remove(T, [H|R], P, [H|R1]) :- tl_member_remove(T, R, P, R1). %% tl_remove_all(+T, +L, +P ~R) % % This predicate removes all occurrences of terms in the list L which are % equal to the term T and returns the resulting List in R. The equality is % decided using the predicate P. Therefore P must be a predicate of arity 2. tl_remove_all(_, [], _, []) :- !. tl_remove_all(T, [H|R], P, R1) :- call(P,T,H),!, tl_remove_all(T, R, P, R1). tl_remove_all(T, [H|R], P, [H|R1]) :- tl_remove_all(T, R, P, R1). %% tl_filter(+L, +P ~R) % % This predicate filters the list L according to the unary predicate P. The % list R contains all elements t of L for which P(i) is true. tl_filter([], _, []) :- !. tl_filter([H|R], P, [H|R1]) :- call(P, H), !, tl_filter(R, P, R1). tl_filter([_|R], P, R1) :- tl_filter(R, P, R1). %% tl_make_set(+L, +P, ~R) % % This predicate turns the list L into a set (i.e. removes duplicate % occurrences) and returns the result in R. The binary predicate P is used to % determine equivalence of two members of L. tl_make_set([], _, []) :- !. tl_make_set([T|R], P, [T|R2]) :- tl_remove_all(T, R, P, R1), !, tl_make_set(R1, P, R2). %% tl_set_equality(+L1, +L2, +P) % % Checks, whether the two sets L1 and L2 are equal, i.e. whether L1 is a % permutation of L2. The binary predicate P is used to compare the elements % of L1 and L2. tl_set_equality([], [], _) :- !. tl_set_equality([H1|R1], L2, P) :- tl_member_remove(H1, L2, P, L3), !, tl_set_equality(R1, L3, P). %% tl_intersect(+L1, +L2, +P ~R) % % Calculates the intersection of the two lists L1, L2 and returns the result % in R. The intersection R contains all elements that appear in L1 and L2. % The binary predicate P is used to decide equality between two elements of % L1 and L2. tl_intersect([], _, _, []) :- !. tl_intersect([H1|R1], L2, P, [H1|R]) :- tl_member(H1, L2, P), !, tl_intersect(R1, L2, P, R). tl_intersect([_|R1], L2, P, R) :- tl_intersect(R1, L2, P, R). %% tl_diff(+L1, +L2, +P, ~R) % % Calculates the difference L1-L2 of the two lists L1 and L2 and returns the % result in R. The binary predicate P is used to decide equality between two % elements of L1 and L2. tl_diff(L1, [], _, L1) :- !. tl_diff(L1, [H2|R2], P, R) :- tl_remove(H2, L1, P, S), !, tl_diff(S, R2, P, R). tests.pl0000600000175000017500000006630411350444254010670 0ustar jocjoc/*============================================================================= File: tests.pl Authors: Johannes Langbein, Îçҹ̽»¨, Germany, jolangbein at gmail dot com Date: 02-09-2010 Version: 1.0 Copyright: 2010, Johannes Langbein This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . =============================================================================*/ /*=================================== tests =================================== This file contains predicates for automated testing along with testcases for the implementation of the confluence checker. How to use the test framework: ============================== 1. Defining testcases. Testcases are defined using the predicate test/3. Each testcase consists of a identifier (for example a string describing the test), the goal to call (with all its arguments) and the expected outcome. This can be either the term "success" or the term "failure", depending on whether the goal is expected to succeed or fail. The goal can either be a single goal or a goal composed of multiple subgoals. In this case, the first subgoal has to be the goal to be tested. Those three components are the arguments of the predicate test/3, in this order. Example 1: test('plus success', plus(2, 3, 5), success). Example 2: test('plus fail', plus(2, 3, 3), failure). Example 3: test('plus success', (plus(2, 3, X), X = 5) success). Example 4: test('plus fail', (plus(2, 3, X), plus(X, 2, 7)), failure). 2. Executing the tests. Test can be executed using the predicate run_tests/1, which takes the name of a goal as argument and executes all test-cases containing this goal. This predicates also produces output about which test is run, what goal is executed, and what the expected and actual result is. After all tests are executed, the number of failed testcases is printed. Example: run_tests(equivalent_states) executes all test-cases defined for equivalent_states. Predicates in this file: ======================== test_equivalent_states/0 Executes all tests for the predicate equivalent_states from the modul stateequiv test_all_critical_pairs/0 Executes all tests for the predicate all_critical_pairs from the modul criticalpairs test_critical_pairs/0 Executes all tests for the predicate critical_pairs from the modul criticalpairs test_check_confluence/0 Executes all tests for the predicate check_confluence from the modul conflcheck run_tests/1 Runs tests for predicates whose names are given in the argument =============================================================================*/ :- module(tests, [ test_equivalent_states/0, test_all_critical_pairs/0, test_critical_pairs/0, test_check_confluence/0, run_tests/1]). :- use_module(stateequiv, [equivalent_states/2]). :- use_module(criticalpairs, [critical_pairs/2, all_critical_pairs/2]). :- use_module(conflcheck, [check_confluence/2, check_confluence/4]). :- use_module(library(lists)). /*================================== Tests ==================================*/ test_equivalent_states :- run_tests(equivalent_states). test_all_critical_pairs :- run_tests(all_critical_pairs). test_critical_pairs :- run_tests(critical_pairs). test_check_confluence :- run_tests(check_confluence). /*=============================== Testcases =================================*/ % To prevent warnings about singleton variables in testcases :- style_check(-singleton). % equivalent_states test( 'renaming local var', equivalent_states( state([c(X)], [], []), state([c(Y)], [], [])), success). test( 'replacing global var', equivalent_states( state([c(X)], [X==0], [X]), state([c(0)], [X==0], [X])), success). test( 'omitting global var', equivalent_states( state([c(0)], [], []), state([c(0)], [], [X])), success). test( 'renaming global var', equivalent_states( state([c(Y)], [], [Y]), state([c(X)], [], [X])), failure). test( 'function terms 1', equivalent_states( state([c(f(Y))], [], []), state([c(X)], [], [])), failure). test( 'function terms 2', equivalent_states( state([c(f(Y))], [], []), state([c(X)], [X = f(Y)], [])), success). test( 'local and global vars together 1', equivalent_states( state([c(X), c(Y)], [], [Y]), state([c(Y), c(Y)], [], [Y])), failure). test( 'local and global vars together 2', equivalent_states( state([c(Y), c(Y)], [], [Y]), state([c(X), c(Y)], [X = Y], [Y])), success). test( 'local and global vars together 3', equivalent_states( state([c(X), c(Y), c(Z)], [X = 1], [Y]), state([c(Z), c(Y), c(X)], [X = 1], [Y])), success). test( 'different built-ins', equivalent_states( state([c(X), c(Y), c(Z)], [X = 1, Y=0], [Y]), state([c(Z), c(Y), c(X)], [X = 1], [Y])), failure). test( 'different built-ins and function terms', equivalent_states( state([c(Z), c(Y), c(f(X))], [Z = f(1), X = 1], [Y]), state([c(f(V)), c(Y), c(f(Z))], [Z = 1, V = 1], [Y])), success). test( 'different number of arguments', equivalent_states( state([c(X,Y), c(Z)], [], []), state([c(Z,Y), c(V, W)], [], [])), failure). test( 'different number of constraints', equivalent_states( state([c(1), c(1)], [], []), state([c(1)], [], [])), failure). test( 'failed and implied built-in stores', equivalent_states( state([c(X)], [X = 1, X = 2], []), state([c(X)], [X = 1], [])), failure). test( 'both built-in stores failed', equivalent_states( state([c(X)], [X = 1, X = 2], []), state([c(X)], [X = 1, Z = 3, X = Z], [])), success). % all_ciritcal_pairs and critical_pairs test( 'simple1.pl: only two trivial critical pairs because the two rules only overlap with themselves', ( all_critical_pairs('examples/simple1.pl', Res), permutation(Res, [ cp( state([], [true], []), state([], [true], []), rule((p<=>true),[],[p],[],[true]), rule((p<=>true),[],[p],[],[true]), [(p,p)], [p]), cp( state([], [true], []), state([], [true], []), rule((q<=>true),[],[q],[],[true]), rule((q<=>true),[],[q],[],[true]), [(q,q)], [q])]) ), success). test( 'simple1.pl: no actual critical pairs', critical_pairs('examples/simple1.pl', []), success). test( 'simple2.pl: three critical pairs, one of each rule with itself (trivial) and one between the rules', ( all_critical_pairs('examples/simple2.pl', Res), permutation(Res, [ cp( state([q], [], []), state([q], [], []), rule((p<=>q), [], [p], [], [q]), rule((p<=>q), [], [p], [], [q]), [ (p, p)], [p]), cp( state([q], [], []), state([], [false], []), rule((p<=>q), [], [p], [], [q]), rule((p<=>false), [], [p], [], [false]), [ (p, p)], [p]), cp( state([], [false], []), state([], [false], []), rule((p<=>false), [], [p], [], [false]), rule((p<=>false), [], [p], [], [false]), [ (p, p)], [p])]) ), success). test( 'simple2.pl: one non-trivial critical pair', critical_pairs('examples/simple2.pl', [ cp( state([q], [], []), state([], [false], []), rule((p<=>q), [], [p], [], [q]), rule((p<=>false), [], [p], [], [false]), [ (p, p)], [p])]), success). test( 'simple3.pl: three trivial critical pairs from each rule with themselves and one non-trivial critical pair between the two rules', ( all_critical_pairs('examples/simple3.pl', Res), permutation(Res, [ cp( state([q], [true], []), state([q], [true], []), rule((p, q<=>true), [], [p, q], [], [true]), rule((p, q<=>true), [], [p, q], [], [true]), [ (p, p)], [p, q, q]), cp( state([], [true], []), state([], [true], []), rule((p, q<=>true), [], [p, q], [], [true]), rule((p, q<=>true), [], [p, q], [], [true]), [ (p, p), (q, q)], [p, q]), cp( state([p], [true], []), state([p], [true], []), rule((p, q<=>true), [], [p, q], [], [true]), rule((p, q<=>true), [], [p, q], [], [true]), [ (q, q)], [p, q, p]), cp( state([r], [true], []), state([p], [true], []), rule((p, q<=>true), [], [p, q], [], [true]), rule((q, r<=>true), [], [q, r], [], [true]), [ (q, q)], [p, q, r]), cp( state([r], [true], []), state([r], [true], []), rule((q, r<=>true), [], [q, r], [], [true]), rule((q, r<=>true), [], [q, r], [], [true]), [ (q, q)], [q, r, r]), cp( state([], [true], []), state([], [true], []), rule((q, r<=>true), [], [q, r], [], [true]), rule((q, r<=>true), [], [q, r], [], [true]), [ (q, q), (r, r)], [q, r]), cp( state([q], [true], []), state([q], [true], []), rule((q, r<=>true), [], [q, r], [], [true]), rule((q, r<=>true), [], [q, r], [], [true]), [ (r, r)], [q, r, q])]) ), success). test( 'simple3.pl: one non-trivial critical pair between the two rules', critical_pairs('examples/simple3.pl', [ cp( state([r], [true], []), state([p], [true], []), rule((p, q<=>true), [], [p, q], [], [true]), rule((q, r<=>true), [], [q, r], [], [true]), [ (q, q)], [p, q, r])]), success). test( 'simple4.pl: three trivial critical pairs (from the three rules with themselves) and one non-trivial critical pair stemming from the overlap of the second and third rule.', ( all_critical_pairs('examples/simple4.pl', Res), permutation(Res,[ cp( state([], [true, _X=_Y, _X=1, _Y=1], [_X, _Y]), state([], [true, _X=_Y, _X=1, _Y=1], [_X, _Y]), rule((p(_Z)<=>_Z=1|true), [], [p(_Z)], [_Z=1], [true]), rule((p(_Z)<=>_Z=1|true), [], [p(_Z)], [_Z=1], [true]), [ (p(_X), p(_Y))], [p(_X), _X=_Y, _X=1, _Y=1]), cp( state([], [true, _A=_B, _A=2, _B=2], [_A, _B]), state([], [true, _A=_B, _A=2, _B=2], [_A, _B]), rule((p(_C)<=>_C=2|true), [], [p(_C)], [_C=2], [true]), rule((p(_C)<=>_C=2|true), [], [p(_C)], [_C=2], [true]), [ (p(_A), p(_B))], [p(_A), _A=_B, _A=2, _Y=2]), cp( state([], [true, _D=2, _D=2], [_D]), state([], [true, _D=2, _D=2], [_D]), rule((p(_E)<=>_E=2|true), [], [p(_E)], [_E=2], [true]), rule((p(2)<=>true), [], [p(2)], [], [true]), [ (p(_D), p(2))], [p(_D), _D=2, _D=2]), cp( state([], [true], []), state([], [true], []), rule((p(2)<=>true), [], [p(2)], [], [true]), rule((p(2)<=>true), [], [p(2)], [], [true]), [ (p(2), p(2))], [p(2)])]) ), success). test( 'simple4.pl: no non-trivial critical pair', critical_pairs('examples/simple4.pl', []), success). test( 'xor.pl: six trivial critical pairs from the first rule with itself, three from the second rule with itself. Four critical pairs between first and second rule', ( all_critical_pairs('examples/xor.pl', Res), permutation(Res,[ cp( state([xor(_A), xor(0)], [_B=_A], [_B, _A]), state([xor(_B), xor(0)], [_B=_A], [_B, _A]), rule((xor(_C), xor(_C)<=>xor(0)), [], [xor(_C), xor(_C)], [], [xor(0)]), rule((xor(_C), xor(_C)<=>xor(0)), [], [xor(_C), xor(_C)], [], [xor(0)]), [ (xor(_B), xor(_A))], [xor(_B), xor(_B), xor(_A), _B=_A]), cp( state([xor(_D), xor(0)], [_F=_D], [_F, _D]), state([xor(_F), xor(0)], [_F=_D], [_F, _D]), rule((xor(_G), xor(_G)<=>xor(0)), [], [xor(_G), xor(_G)], [], [xor(0)]), rule((xor(_G), xor(_G)<=>xor(0)), [], [xor(_G), xor(_G)], [], [xor(0)]), [ (xor(_F), xor(_D))], [xor(_F), xor(_F), xor(_D), _F=_D]), cp( state([xor(0)], [_H=_I, _H=_I], [_H, _I]), state([xor(0)], [_H=_I, _H=_I], [_H, _I]), rule((xor(_J), xor(_J)<=>xor(0)), [], [xor(_J), xor(_J)], [], [xor(0)]), rule((xor(_J), xor(_J)<=>xor(0)), [], [xor(_J), xor(_J)], [], [xor(0)]), [ (xor(_H), xor(_I)), (xor(_H), xor(_I))], [xor(_H), xor(_H), _H=_I, _H=_I]), cp( state([xor(0)], [_K=_L, _K=_L], [_K, _L]), state([xor(0)], [_K=_L, _K=_L], [_K, _L]), rule((xor(_M), xor(_M)<=>xor(0)), [], [xor(_M), xor(_M)], [], [xor(0)]), rule((xor(_M), xor(_M)<=>xor(0)), [], [xor(_M), xor(_M)], [], [xor(0)]), [ (xor(_K), xor(_L)), (xor(_K), xor(_L))], [xor(_K), xor(_K), _K=_L, _K=_L]), cp( state([xor(_N), xor(0)], [_O=_N], [_O, _N]), state([xor(_O), xor(0)], [_O=_N], [_O, _N]), rule((xor(_P), xor(_P)<=>xor(0)), [], [xor(_P), xor(_P)], [], [xor(0)]), rule((xor(_P), xor(_P)<=>xor(0)), [], [xor(_P), xor(_P)], [], [xor(0)]), [ (xor(_O), xor(_N))], [xor(_O), xor(_O), xor(_N), _O=_N]), cp( state([xor(_Q), xor(0)], [_R=_Q], [_R, _Q]), state([xor(_R), xor(0)], [_R=_Q], [_R, _Q]), rule((xor(_S), xor(_S)<=>xor(0)), [], [xor(_S), xor(_S)], [], [xor(0)]), rule((xor(_S), xor(_S)<=>xor(0)), [], [xor(_S), xor(_S)], [], [xor(0)]), [ (xor(_R), xor(_Q))], [xor(_R), xor(_R), xor(_Q), _R=_Q]), cp( state([xor(0), xor(0)], [_T=1], [_T]), state([xor(1), xor(_T)], [true, _T=1], [_T]), rule((xor(_U), xor(_U)<=>xor(0)), [], [xor(_U), xor(_U)], [], [xor(0)]), rule((xor(1)\xor(0)<=>true), [xor(1)], [xor(0)], [], [true]), [ (xor(_T), xor(1))], [xor(_T), xor(_T), xor(0), _T=1]), cp( state([xor(1), xor(0)], [_V=0], [_V]), state([xor(1), xor(_V)], [true, _V=0], [_V]), rule((xor(_W), xor(_W)<=>xor(0)), [], [xor(_W), xor(_W)], [], [xor(0)]), rule((xor(1)\xor(0)<=>true), [xor(1)], [xor(0)], [], [true]), [ (xor(_V), xor(0))], [xor(_V), xor(_V), xor(1), _V=0]), cp( state([xor(0), xor(0)], [_X=1], [_X]), state([xor(1), xor(_X)], [true, _X=1], [_X]), rule((xor(_Y), xor(_Y)<=>xor(0)), [], [xor(_Y), xor(_Y)], [], [xor(0)]), rule((xor(1)\xor(0)<=>true), [xor(1)], [xor(0)], [], [true]), [ (xor(_X), xor(1))], [xor(_X), xor(_X), xor(0), _X=1]), cp( state([xor(1), xor(0)], [_Z=0], [_Z]), state([xor(1), xor(_Z)], [true, _Z=0], [_Z]), rule((xor(_E), xor(_E)<=>xor(0)), [], [xor(_E), xor(_E)], [], [xor(0)]), rule((xor(1)\xor(0)<=>true), [xor(1)], [xor(0)], [], [true]), [ (xor(_Z), xor(0))], [xor(_Z), xor(_Z), xor(1), _Z=0]), cp( state([xor(1), xor(0)], [true], []), state([xor(1), xor(0)], [true], []), rule((xor(1)\xor(0)<=>true), [xor(1)], [xor(0)], [], [true]), rule((xor(1)\xor(0)<=>true), [xor(1)], [xor(0)], [], [true]), [ (xor(1), xor(1))], [xor(1), xor(0), xor(0)]), cp( state([xor(1)], [true], []), state([xor(1)], [true], []), rule((xor(1)\xor(0)<=>true), [xor(1)], [xor(0)], [], [true]), rule((xor(1)\xor(0)<=>true), [xor(1)], [xor(0)], [], [true]), [ (xor(1), xor(1)), (xor(0), xor(0))], [xor(1), xor(0)]), cp( state([xor(1), xor(1)], [true], []), state([xor(1), xor(1)], [true], []), rule((xor(1)\xor(0)<=>true), [xor(1)], [xor(0)], [], [true]), rule((xor(1)\xor(0)<=>true), [xor(1)], [xor(0)], [], [true]), [ (xor(0), xor(0))], [xor(1), xor(0), xor(1)])]) ), success). test( 'xor.pl: Two non-trivial critical pairs between first and second rule', critical_pairs('examples/xor.pl', [ cp( state([xor(0), xor(0)], [_T=1], [_T]), state([xor(1), xor(_T)], [true, _T=1], [_T]), rule((xor(_U), xor(_U)<=>xor(0)), [], [xor(_U), xor(_U)], [], [xor(0)]), rule((xor(1)\xor(0)<=>true), [xor(1)], [xor(0)], [], [true]), [ (xor(_T), xor(1))], [xor(_T), xor(_T), xor(0), _T=1])]), success). test( 'mem.pl: Three overlaps of the rule with itself.', ( all_critical_pairs('examples/mem.pl', Res), permutation(Res,[ cp( state([cell(_A, _B), cell(_C, _D)], [_C=_A, _D=_E], [_C, _D, _F, _A, _E, _B]), state([cell(_C, _F), cell(_A, _E)], [_C=_A, _D=_E], [_C, _D, _F, _A, _E, _B]), rule((assign(_G, _H), cell(_G, _I)<=>cell(_G, _H)), [], [assign(_G, _H), cell(_G, _I)], [], [cell(_G, _H)]), rule((assign(_G, _H), cell(_G, _I)<=>cell(_G, _H)), [], [assign(_G, _H), cell(_G, _I)], [], [cell(_G, _H)]), [ (assign(_C, _D), assign(_A, _E))], [assign(_C, _D), cell(_C, _F), cell(_A, _B), _C=_A, _D=_E]), cp( state([cell(_J, _K)], [_J=_L, _K=_M, _J=_L, _N=_O], [_J, _K, _N, _L, _M, _O]), state([cell(_L, _M)], [_J=_L, _K=_M, _J=_L, _N=_O], [_J, _K, _N, _L, _M, _O]), rule((assign(_P, _Q), cell(_P, _R)<=>cell(_P, _Q)), [], [assign(_P, _Q), cell(_P, _R)], [], [cell(_P, _Q)]), rule((assign(_P, _Q), cell(_P, _R)<=>cell(_P, _Q)), [], [assign(_P, _Q), cell(_P, _R)], [], [cell(_P, _Q)]), [ (assign(_J, _K), assign(_L, _M)), (cell(_J, _N), cell(_L, _O))], [assign(_J, _K), cell(_J, _N), _J=_L, _K=_M, _J=_L, _N=_O]), cp( state([assign(_S, _T), cell(_U, _V)], [_U=_S, _W=_X], [_U, _V, _W, _S, _T, _X]), state([assign(_U, _V), cell(_S, _T)], [_U=_S, _W=_X], [_U, _V, _W, _S, _T, _X]), rule((assign(_Y, _Z), cell(_Y, _ZZ)<=>cell(_Y, _Z)), [], [assign(_Y, _Z), cell(_Y, _ZZ)], [], [cell(_Y, _Z)]), rule((assign(_Y, _Z), cell(_Y, _ZZ)<=>cell(_Y, _Z)), [], [assign(_Y, _Z), cell(_Y, _ZZ)], [], [cell(_Y, _Z)]), [ (cell(_U, _W), cell(_S, _X))], [assign(_U, _V), cell(_U, _W), assign(_S, _T), _U=_S, _W=_X])]) ), success). test( 'mem.pl: Two actual critical pairs.', ( critical_pairs('examples/mem.pl', Res), permutation(Res,[ cp( state([cell(_A, _B), cell(_C, _D)], [_C=_A, _D=_E], [_C, _D, _F, _A, _E, _B]), state([cell(_C, _F), cell(_A, _E)], [_C=_A, _D=_E], [_C, _D, _F, _A, _E, _B]), rule((assign(_G, _H), cell(_G, _I)<=>cell(_G, _H)), [], [assign(_G, _H), cell(_G, _I)], [], [cell(_G, _H)]), rule((assign(_G, _H), cell(_G, _I)<=>cell(_G, _H)), [], [assign(_G, _H), cell(_G, _I)], [], [cell(_G, _H)]), [ (assign(_C, _D), assign(_A, _E))], [assign(_C, _D), cell(_C, _F), cell(_A, _B), _C=_A, _D=_E]), cp( state([assign(_S, _T), cell(_U, _V)], [_U=_S, _W=_X], [_U, _V, _W, _S, _T, _X]), state([assign(_U, _V), cell(_S, _T)], [_U=_S, _W=_X], [_U, _V, _W, _S, _T, _X]), rule((assign(_Y, _Z), cell(_Y, _ZZ)<=>cell(_Y, _Z)), [], [assign(_Y, _Z), cell(_Y, _ZZ)], [], [cell(_Y, _Z)]), rule((assign(_Y, _Z), cell(_Y, _ZZ)<=>cell(_Y, _Z)), [], [assign(_Y, _Z), cell(_Y, _ZZ)], [], [cell(_Y, _Z)]), [ (cell(_U, _W), cell(_S, _X))], [assign(_U, _V), cell(_U, _W), assign(_S, _T), _U=_S, _W=_X])]) ), success). % check_confluence test( 'coin.pl', check_confluence('examples/coin.pl', 1), success). test( 'leq.pl', check_confluence('examples/leq.pl', 0), success). test( 'mem.pl', check_confluence('examples/mem.pl', 2), success). test( 'merge.pl', check_confluence('examples/merge.pl',1), success). test( 'twocoins.pl', check_confluence('examples/twocoins.pl', 1), success). test( 'xor.pl', check_confluence('examples/xor.pl',0), success). test( 'simple1.pl', check_confluence('examples/simple1.pl',0), success). test( 'simple2.pl', check_confluence('examples/simple2.pl',1), success). test( 'simple3.pl', check_confluence('examples/simple3.pl',1), success). test( 'simple4.pl', check_confluence('examples/simple4.pl',0), success). :- style_check(+singleton). /*============================= General predicates ==========================*/ % run_tests(+GoalName) % This predicate executes all testcases for the goal whose name is given as the % argument GoalName. % Simply calls run_tests/2 with an initial number of 0 failed testcases and all % testcases with the according GoalName found in this file. run_tests(GoalName) :- findall(Test, find_test(GoalName, Test), Tests), run_tests(Tests, 0). % find_test(+GoalName, ~Test) % This predicate unifies Test with a testcase from the database whose goal is % a term whose functor is GoalName or is composed of multiple sub-goals of % which the first one has a functor called GoalName. find_test(GoalName, Test) :- test(Id, Goal, ExpRes), functor(Goal, GoalName, _), Test = test(Id, Goal, ExpRes). find_test(GoalName, Test) :- test(Id, Goal, ExpRes), Goal =.. [','|[G|_]], functor(G, GoalName, _), Test = test(Id, Goal, ExpRes). % run_tests(+Tests, +FailedCases) % This predicate executes all testcases given in the list of testcase Tests. % Furthermore it counts the number of already failed testcases % in FailedCases in order to generate a report of success or failure after all % testcases have been executed. run_tests([], 0) :- write('All tests passed successfully'), nl,!. run_tests([], X) :- write(X), write(' Test(s) failed!'), nl,!. run_tests([T|TS], FC) :- run_test(T, Res), (Res -> FC1 is FC ; FC1 is FC + 1),!, run_tests(TS, FC1). % run_test(+Test, ~Res) % This predicate runs the testcase Tes and returns the outcome % bound to the variable Res. Res is true iff the test had the expected outcome. run_test(test(Id, Goal, ExpRes), Res) :- output_pre_test(Id, Goal, ExpRes), execute(Goal, ActRes), ( ExpRes == ActRes -> ( output_success(ActRes), Res = true ) ; ( output_failure(ActRes), Res = false ) ). % execute(+Goal, +ExpectedResult) % Checks if Goal succeeds or fails. execute succeeds either when Goal succeeds % and ExpectedResult is bound to the term "success" or if Goal fails and % ExpectedResult is bound to failure. execute(Goal, success) :- call(Goal). execute(Goal, failure) :- call(\+ Goal). % output_pre_test(+Id, +Goal, +ExpRes) % This predicate creates the output displayed before the test is run. It % generates the following output: % "Test \Id" % " Calling \Goal, expected result \ExpRes". output_pre_test(Id, Goal, ExpRes) :- write('Test '), write(Id), nl, write('Calling '), write(Goal), write(', expected result: '), write(ExpRes), write('...'), nl. % output_success(+ActualResult) % This predicate prints the string % "Test successful with result: \ActualResult" output_success(ActRes) :- write('Test successful with result: '), write(ActRes), nl, nl. % output_failure(+ActualResult) % This predicate prints the string % "Test NOT successful with result: \ActualResult" output_failure(ActRes) :- write('Test NOT successful with result: '), write(ActRes), nl, nl. /* t1 :- check_confluence('examples/ufd_basic.pl'). t2 :- check_confluence('examples/ufd_basic1.pl', link1, linkeq1). t3 :- check_confluence('examples/ufd_found_compr.pl', compress, compress). t4 :- check_confluence('examples/ufd_found_compr.pl', linkeq1c, linkeq1c). t5(N) :- check_confluence('examples/ufd_basic.pl', N). t6(N) :- check_confluence('examples/ufd_basic.pl', link, link, N). */