From d19a79bd6394cc5726f9cd9e7e8a9391c9a8d27a Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Wed, 16 Mar 2016 23:27:45 +0100 Subject: [PATCH 01/57] finite closure greater smaller funktioniert jetzt auch mit wildcards (muss noch getestet werden) --- .../unify/model/FiniteClosure.java | 69 ++++++++++++++++--- test/unify/FiniteClosureTest.java | 10 +-- 2 files changed, 66 insertions(+), 13 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index e618482d..977f36ee 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -1,5 +1,7 @@ package de.dhbwstuttgart.typeinference.unify.model; +import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Optional; @@ -57,12 +59,30 @@ public class FiniteClosure implements IFiniteClosure { */ @Override public Set smaller(Type type) { - if(!inheritanceGraph.containsKey(type)) - return new HashSet<>(); - - Set result = inheritanceGraph.get(type).getContentOfDescendants(); + Set result = inheritanceGraph.containsKey(type) ? inheritanceGraph.get(type).getContentOfDescendants() : new HashSet<>(); result.add(type); + if(type.getTypeParams().size() == 0) + return result; + + ArrayList> paramCandidates = new ArrayList<>(); + for(Type param : type.getTypeParams()) { + if(param instanceof ExtendsType || param instanceof SuperType) { + Set pc = param.smArg(this); + paramCandidates.add(pc); + } else { + HashSet pc = new HashSet<>(); + pc.add(param); + paramCandidates.add(pc); + } + } + + Set permResult = new HashSet<>(); + permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); + + for(TypeParams newParams : permResult) + result.add(type.setTypeParams(newParams)); + return result; } @@ -72,11 +92,30 @@ public class FiniteClosure implements IFiniteClosure { */ @Override public Set greater(Type type) { - if(!inheritanceGraph.containsKey(type)) - return new HashSet<>(); - - Set result = inheritanceGraph.get(type).getContentOfPredecessors(); + Set result = inheritanceGraph.containsKey(type) ? inheritanceGraph.get(type).getContentOfPredecessors() : new HashSet<>(); result.add(type); + + if(type.getTypeParams().size() == 0) + return result; + + ArrayList> paramCandidates = new ArrayList<>(); + for(Type param : type.getTypeParams()) { + if(param instanceof ExtendsType || param instanceof SuperType) { + Set pc = param.grArg(this); + paramCandidates.add(pc); + } else { + HashSet pc = new HashSet<>(); + pc.add(param); + paramCandidates.add(pc); + } + } + + Set permResult = new HashSet<>(); + permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); + + for(TypeParams newParams : permResult) + result.add(type.setTypeParams(newParams)); + return result; } @@ -213,4 +252,18 @@ public class FiniteClosure implements IFiniteClosure { return new HashSet<>(); return strInheritanceGraph.get(typeName).stream().map(x -> x.getContent()).collect(Collectors.toCollection(HashSet::new)); } + + protected void permuteParams(ArrayList> candidates, int idx, Set result, Type[] current) { + if(candidates.size() == idx) { + result.add(new TypeParams(Arrays.copyOf(current, current.length))); + return; + } + + Set localCandidates = candidates.get(idx); + + for(Type t : localCandidates) { + current[idx] = t; + permuteParams(candidates, idx+1, result, current); + } + } } diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index 9b5c72e6..7b1b6664 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -1,15 +1,11 @@ package unify; -import java.util.HashSet; -import java.util.Set; - import org.junit.Test; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; import de.dhbwstuttgart.typeinference.unifynew.TypeFactory; -import de.dhbwstuttgart.typeinference.unify.model.Type; public class FiniteClosureTest { @@ -37,10 +33,14 @@ public class FiniteClosureTest { @Test public void testSmaller() { - IFiniteClosure fc = new FiniteClosureBuilder().getCollectionExample(); + FiniteClosureBuilder fcb = new FiniteClosureBuilder(); TypeFactory tf = new TypeFactory(); + fcb.add(tf.getSimpleType("Integer"), tf.getSimpleType("Number")); + IFiniteClosure fc = fcb.getCollectionExample(); + System.out.println("\n\n----- Smaller Test -----"); + System.out.println("Smaller(List) = " + fc.smaller(tf.getSimpleType("List", tf.getExtendsType(tf.getSimpleType("Number"))))); System.out.println("Smaller(List) = " + fc.smaller(tf.getSimpleType("List", "T"))); System.out.println("Smaller(TreeSet) = " + fc.smaller(tf.getSimpleType("TreeSet", "T"))); System.out.println("Smaller(Collection) = " + fc.smaller(tf.getSimpleType("Collection"))); From fa9627b8835580217217a74f0b128b00c9961b11 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Thu, 17 Mar 2016 16:35:33 +0100 Subject: [PATCH 02/57] unify case 1 --- .../unify/model/FiniteClosure.java | 4 ++ .../typeinference/unifynew/Unify.java | 61 ++++++++++--------- test/unify/UnifyTest.java | 2 +- 3 files changed, 36 insertions(+), 31 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 977f36ee..516d85fe 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -144,6 +144,7 @@ public class FiniteClosure implements IFiniteClosure { return new HashSet(); Set result = new HashSet(); + result.add(type); Type t = type.getExtendedType(); @@ -158,6 +159,7 @@ public class FiniteClosure implements IFiniteClosure { return new HashSet(); Set result = new HashSet(); + result.add(type); Type t = type.getSuperedType(); @@ -194,6 +196,7 @@ public class FiniteClosure implements IFiniteClosure { return new HashSet(); Set result = new HashSet(); + result.add(type); Type t = type.getExtendedType(); @@ -213,6 +216,7 @@ public class FiniteClosure implements IFiniteClosure { return new HashSet(); Set result = new HashSet(); + result.add(type); Type t = type.getSuperedType(); diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java index 548340b3..ce7e13c4 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java @@ -232,38 +232,39 @@ public class Unify { Set set = new HashSet<>(); IUnify unify = new MartelliMontanariUnify(); - //Set cs = fc.getAllTypes(rhsType.getName()); - Type c = rhsType; + Set cs = fc.getAllTypes(rhsType.getName()); - //Set thetaQs = cs.stream().flatMap(x -> fc.smaller(x).stream()).collect(Collectors.toCollection(HashSet::new)); - Set thetaQs = fc.smaller(c); - - Set thetaQPrimes = new HashSet<>(); - - TypeParams cParams = c.getTypeParams(); - if(cParams.size() == 0) - thetaQPrimes.add(c); - else { - ArrayList> candidateParams = new ArrayList<>(); - for(Type param : cParams) - candidateParams.add(fc.grArg(param)); - Set permutations = new HashSet(); - permuteParams(candidateParams, 0, permutations, new Type[candidateParams.size()]); + Set thetaQs = cs.stream().flatMap( + x -> fc.smaller(x).stream().filter(y -> y.getTypeParams().arePlaceholders()) + ).collect(Collectors.toCollection(HashSet::new)); + + for(Type c : cs) { + Set thetaQPrimes = new HashSet<>(); + TypeParams cParams = c.getTypeParams(); + if(cParams.size() == 0) + thetaQPrimes.add(c); + else { + ArrayList> candidateParams = new ArrayList<>(); + for(Type param : cParams) + candidateParams.add(fc.grArg(param)); + Set permutations = new HashSet(); + permuteParams(candidateParams, 0, permutations, new Type[candidateParams.size()]); + + for(TypeParams tp : permutations) + thetaQPrimes.add(c.setTypeParams(tp)); + } - for(TypeParams tp : permutations) - thetaQPrimes.add(c.setTypeParams(tp)); - } - - for(Type tqp : thetaQPrimes) { - Optional opt = unify.unify(tqp, thetaPrime); - if(opt.isPresent()) { - Unifier unifier = opt.get(); - Set> substitutions = unifier.getSubstitutions(); - for(Entry sigma : substitutions) - set.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); - for(Type tq : thetaQs) { - Set smaller = fc.smaller(unifier.apply(tq)); - smaller.stream().map(x -> new MPair(lhsType, x, PairOperator.EQUALSDOT)).forEach(x -> set.add(x)); + for(Type tqp : thetaQPrimes) { + Optional opt = unify.unify(tqp, thetaPrime); + if(opt.isPresent()) { + Unifier unifier = opt.get(); + Set> substitutions = unifier.getSubstitutions(); + for(Entry sigma : substitutions) + set.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + for(Type tq : thetaQs) { + Set smaller = fc.smaller(unifier.apply(tq)); + smaller.stream().map(x -> new MPair(lhsType, x, PairOperator.EQUALSDOT)).forEach(x -> set.add(x)); + } } } } diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 8524c1dc..1b120dae 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -38,7 +38,7 @@ public class UnifyTest extends Unify { eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Integer")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Number")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Integer")), tf.getSimpleType("Vector", "C"), PairOperator.SMALLERDOT)); - eq.add(new MPair(tf.getPlaceholderType("A"), tf.getSimpleType("List", tf.getSimpleType("Number")), PairOperator.SMALLERDOT)); + eq.add(new MPair(tf.getPlaceholderType("A"), tf.getSimpleType("Number"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getSimpleType("Number"), tf.getPlaceholderType("A"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getPlaceholderType("A"), tf.getPlaceholderType("C"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getSimpleType("Double"), tf.getPlaceholderType("B"), PairOperator.SMALLERDOT)); From 299f8f56cada9e6c1744a16c8a1dd9647905c2a9 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Sun, 20 Mar 2016 15:09:12 +0100 Subject: [PATCH 03/57] added missing cases --- .../unify/interfaces/IFiniteClosure.java | 2 +- .../unify/model/FiniteClosure.java | 71 ++++- .../typeinference/unify/model/Unifier.java | 2 +- .../unifynew/MartelliMontanariUnify.java | 6 +- .../typeinference/unifynew/Unify.java | 278 +++++++++++++----- test/unify/FiniteClosureTest.java | 28 +- test/unify/UnifyTest.java | 8 +- 7 files changed, 301 insertions(+), 94 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java index 62b65b27..3af29411 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java @@ -50,5 +50,5 @@ public interface IFiniteClosure { public Set smArg(PlaceholderType type); public Optional getGenericType(String typeName); - public Set getAllTypes(String typeName); + public Set getAllTypesByName(String typeName); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 516d85fe..64fb6862 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -9,13 +9,19 @@ import java.util.Set; import java.util.stream.Collectors; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; +import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; +import de.dhbwstuttgart.typeinference.unifynew.MartelliMontanariUnify; public class FiniteClosure implements IFiniteClosure { private HashMap> inheritanceGraph; private HashMap>> strInheritanceGraph; + public FiniteClosure() { + + } + public FiniteClosure(Set pairs) { inheritanceGraph = new HashMap>(); @@ -52,16 +58,34 @@ public class FiniteClosure implements IFiniteClosure { strInheritanceGraph.get(key.getName()).add(inheritanceGraph.get(key)); } } - + /** * Returns all types of the finite closure that are subtypes of the argument. * @return The set of subtypes of the argument. */ @Override public Set smaller(Type type) { + // - if(T < T') then T <=* T' Set result = inheritanceGraph.containsKey(type) ? inheritanceGraph.get(type).getContentOfDescendants() : new HashSet<>(); result.add(type); + // if T1 <=* T2 then sigma1(T1) <=* sigma1(T2) + // where foreach type var a in T2: + // sigma1(T1) <=* sigma2(T2) + /*if(strInheritanceGraph.containsKey(type.getName())) { + IUnify unify = new MartelliMontanariUnify(); + HashSet> candidateNodes = strInheritanceGraph.get(type.getName()); + for(Node candidateNode : candidateNodes) { + Type theta2 = candidateNode.getContent(); + Optional sigma2 = unify.unify(theta2, type); + if(!sigma2.isPresent()) + continue; + for(Type sigma1theta1 : candidateNode.getContentOfDescendants()) { + Type theta1 = sigma2.get().apply(sigma1theta1); + } + } + }*/ + if(type.getTypeParams().size() == 0) return result; @@ -86,6 +110,37 @@ public class FiniteClosure implements IFiniteClosure { return result; } + /** + * @param t1 + * @param t2 + * @return + */ + protected Optional match(Type t1, Type t2) { + if(!t1.getName().equals(t2.getName())) + return Optional.empty(); + + TypeParams t1Params = t1.getTypeParams(); + TypeParams t2Params = t2.getTypeParams(); + + if(t1Params.size() != t2Params.size()) + return Optional.empty(); + + Unifier result = new Unifier(); + for(int i = 0; i < t1Params.size(); i++) { + Type t1i = t1Params.get(i); + Type t2i = t2Params.get(i); + + boolean equal = t1i.equals(t2i); + if(!equal && !(t2i instanceof PlaceholderType)) + return Optional.empty(); + + if(!equal && t2i instanceof PlaceholderType) + result.Add((PlaceholderType) t2i, t1i); + } + + return Optional.of(result); + } + /** * Returns all types of the finite closure that are supertypes of the argument. * @return The set of supertypes of the argument. @@ -170,7 +225,11 @@ public class FiniteClosure implements IFiniteClosure { @Override public Set grArg(PlaceholderType type) { - return new HashSet<>(); + HashSet result = new HashSet<>(); + result.add(type); + result.add(new SuperType(type)); + result.add(new ExtendsType(type)); + return result; } @Override @@ -231,7 +290,11 @@ public class FiniteClosure implements IFiniteClosure { @Override public Set smArg(PlaceholderType type) { - return new HashSet<>(); + HashSet result = new HashSet<>(); + result.add(type); + result.add(new SuperType(type)); + result.add(new ExtendsType(type)); + return result; } @Override @@ -251,7 +314,7 @@ public class FiniteClosure implements IFiniteClosure { } @Override - public Set getAllTypes(String typeName) { + public Set getAllTypesByName(String typeName) { if(!strInheritanceGraph.containsKey(typeName)) return new HashSet<>(); return strInheritanceGraph.get(typeName).stream().map(x -> x.getContent()).collect(Collectors.toCollection(HashSet::new)); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java index 0a1fde25..add681e5 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java @@ -5,7 +5,7 @@ import java.util.Map.Entry; import java.util.Set; import java.util.function.Function; -public class Unifier implements Function { +public class Unifier implements Function /*, Set*/ { // TODO set implementieren private HashMap substitutions = new HashMap<>(); public static Unifier IDENTITY = new Unifier(); diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java b/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java index 6db1a512..d15fefdd 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java @@ -101,12 +101,12 @@ public class MartelliMontanariUnify implements IUnify { TypeParams rhsTypeParams = rhs.getTypeParams(); TypeParams lhsTypeParams = lhs.getTypeParams(); + if(!rhs.getName().equals(lhs.getName()) || rhsTypeParams.size() != lhsTypeParams.size()) + return null; // conflict + if(rhsTypeParams.size() == 0 || lhsTypeParams.size() == 0) return Optional.empty(); - if(!rhs.getName().equals(lhs.getName()) || rhsTypeParams.size() != lhsTypeParams.size()) - return null; // conflict - for(int i = 0; i < rhsTypeParams.size(); i++) result.add(new MPair(rhsTypeParams.get(i), lhsTypeParams.get(i), PairOperator.EQUALSDOT)); diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java index ce7e13c4..807c8d7f 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java @@ -227,105 +227,223 @@ public class Unify { Type rhsType = pair.getRhsType(); // Case 1: (a <. Theta') - if(pairOp == PairOperator.SMALLERDOT && lhsType instanceof PlaceholderType) { - Type thetaPrime = pair.getRhsType(); - Set set = new HashSet<>(); - IUnify unify = new MartelliMontanariUnify(); - - Set cs = fc.getAllTypes(rhsType.getName()); - - Set thetaQs = cs.stream().flatMap( - x -> fc.smaller(x).stream().filter(y -> y.getTypeParams().arePlaceholders()) - ).collect(Collectors.toCollection(HashSet::new)); - - for(Type c : cs) { - Set thetaQPrimes = new HashSet<>(); - TypeParams cParams = c.getTypeParams(); - if(cParams.size() == 0) - thetaQPrimes.add(c); - else { - ArrayList> candidateParams = new ArrayList<>(); - for(Type param : cParams) - candidateParams.add(fc.grArg(param)); - Set permutations = new HashSet(); - permuteParams(candidateParams, 0, permutations, new Type[candidateParams.size()]); - - for(TypeParams tp : permutations) - thetaQPrimes.add(c.setTypeParams(tp)); - } - - for(Type tqp : thetaQPrimes) { - Optional opt = unify.unify(tqp, thetaPrime); - if(opt.isPresent()) { - Unifier unifier = opt.get(); - Set> substitutions = unifier.getSubstitutions(); - for(Entry sigma : substitutions) - set.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); - for(Type tq : thetaQs) { - Set smaller = fc.smaller(unifier.apply(tq)); - smaller.stream().map(x -> new MPair(lhsType, x, PairOperator.EQUALSDOT)).forEach(x -> set.add(x)); - } - } - } - } - - result.add(set); - } + if(pairOp == PairOperator.SMALLERDOT && lhsType instanceof PlaceholderType) + result.add(unifyCase1((PlaceholderType) pair.getLhsType(), pair.getRhsType(), fc)); // Case 2: (a <.? ? ext Theta') - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof ExtendsType){ - throw new NotImplementedException(); // TODO - } + else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof ExtendsType) + result.add(unifyCase2((PlaceholderType) pair.getLhsType(), (ExtendsType) pair.getRhsType(), fc)); // Case 3: (a <.? ? sup Theta') - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof SuperType) { - Set set = new HashSet<>(); - for(Type theta : fc.smArg(rhsType)) - set.add(new MPair(lhsType, theta, PairOperator.EQUALSDOT)); - result.add(set); - } + else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof SuperType) + result.add(unifyCase3((PlaceholderType) lhsType, (SuperType) rhsType, fc)); // Case 4: (a <.? Theta') - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType) { - Set set = new HashSet<>(); - set.add(new MPair(lhsType, rhsType, PairOperator.EQUALSDOT)); - result.add(set); - } + else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType) + result.add(unifyCase4((PlaceholderType) lhsType, rhsType, fc)); // Case 5: (Theta <. a) - else if(pairOp == PairOperator.SMALLERDOT && rhsType instanceof PlaceholderType) { - Set set = new HashSet<>(); - for(Type thetaS : fc.greater(lhsType)) - set.add(new MPair(rhsType, thetaS, PairOperator.EQUALSDOT)); - result.add(set); - } + else if(pairOp == PairOperator.SMALLERDOT && rhsType instanceof PlaceholderType) + result.add(unifyCase5(lhsType, (PlaceholderType) rhsType, fc)); // Case 6: (? ext Theta <.? a) - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof ExtendsType && rhsType instanceof PlaceholderType) { - Set set = new HashSet<>(); - for(Type thetaS : fc.grArg(lhsType)) - set.add(new MPair(rhsType, thetaS, PairOperator.EQUALSDOT)); - result.add(set); - } - + else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof ExtendsType && rhsType instanceof PlaceholderType) + result.add(unifyCase6((ExtendsType) lhsType, (PlaceholderType) rhsType, fc)); + // Case 7: (? sup Theta <.? a) - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof SuperType && rhsType instanceof PlaceholderType) { - throw new NotImplementedException(); // TODO - } + else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof SuperType && rhsType instanceof PlaceholderType) + result.add(unifyCase7((SuperType) lhsType, (PlaceholderType) rhsType, fc)); // Case 8: (Theta <.? a) - else if(pairOp == PairOperator.SMALLERDOTWC && rhsType instanceof PlaceholderType) { - Set set = new HashSet<>(); - for(Type thetaS : fc.grArg(lhsType)) - set.add(new MPair(rhsType, thetaS, PairOperator.EQUALSDOT)); - result.add(set); + else if(pairOp == PairOperator.SMALLERDOTWC && rhsType instanceof PlaceholderType) + result.add(unifyCase8(lhsType, (PlaceholderType) rhsType, fc)); + } + + return result; + } + + protected Set unifyCase1(PlaceholderType a, Type thetaPrime, IFiniteClosure fc) { + Set result = new HashSet<>(); + IUnify unify = new MartelliMontanariUnify(); + + Set cs = fc.getAllTypesByName(thetaPrime.getName()); + + for(Type c : cs) { + + // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? + Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + thetaQs.add(c); // reflexive + + Set thetaQPrimes = new HashSet<>(); + TypeParams cParams = c.getTypeParams(); + if(cParams.size() == 0) + thetaQPrimes.add(c); + else { + ArrayList> candidateParams = new ArrayList<>(); + for(Type param : cParams) + candidateParams.add(fc.grArg(param)); + + for(TypeParams tp : permuteParams(candidateParams)) + thetaQPrimes.add(c.setTypeParams(tp)); + } + + for(Type tqp : thetaQPrimes) { + Optional opt = unify.unify(tqp, thetaPrime); + if (!opt.isPresent()) + continue; + + Unifier unifier = opt.get(); + Set> substitutions = unifier.getSubstitutions(); + for (Entry sigma : substitutions) + result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + for (Type tq : thetaQs) { + Set smaller = fc.smaller(unifier.apply(tq)); + smaller.stream().map(x -> new MPair(a, x, PairOperator.EQUALSDOT)) + .forEach(x -> result.add(x)); + } + } } return result; } - protected void permuteParams(ArrayList> candidates, int idx, Set result, Type[] current) { + protected Set unifyCase2(PlaceholderType a, ExtendsType extThetaPrime, IFiniteClosure fc) { + Set result = new HashSet<>(); + IUnify unify = new MartelliMontanariUnify(); + + Type thetaPrime = extThetaPrime.getExtendedType(); + Set cs = fc.getAllTypesByName(thetaPrime.getName()); + + for(Type c : cs) { + + // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? + Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + thetaQs.add(c); // reflexive + + Set thetaQPrimes = new HashSet<>(); + TypeParams cParams = c.getTypeParams(); + if(cParams.size() == 0) + thetaQPrimes.add(c); + else { + ArrayList> candidateParams = new ArrayList<>(); + for(Type param : cParams) + candidateParams.add(fc.grArg(param)); + + for(TypeParams tp : permuteParams(candidateParams)) + thetaQPrimes.add(c.setTypeParams(tp)); + } + + for(Type tqp : thetaQPrimes) { + Optional opt = unify.unify(tqp, thetaPrime); + if (!opt.isPresent()) + continue; + + Unifier unifier = opt.get(); + Set> substitutions = unifier.getSubstitutions(); + for (Entry sigma : substitutions) + result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + for (Type tq : thetaQs) { + ExtendsType extTq = new ExtendsType(tq); + Set smaller = fc.smaller(unifier.apply(extTq)); + smaller.stream().map(x -> new MPair(a, x, PairOperator.EQUALSDOT)) + .forEach(x -> result.add(x)); + } + + } + } + + return result; + } + + protected Set unifyCase3(PlaceholderType a, SuperType subThetaPrime, IFiniteClosure fc) { + Set result = new HashSet<>(); + for(Type theta : fc.smArg(subThetaPrime)) + result.add(new MPair(a, theta, PairOperator.EQUALSDOT)); + return result; + } + + protected Set unifyCase4(PlaceholderType a, Type thetaPrime, IFiniteClosure fc) { + Set result = new HashSet<>(); + result.add(new MPair(a, thetaPrime, PairOperator.EQUALSDOT)); + return result; + } + + protected Set unifyCase5(Type theta, PlaceholderType a, IFiniteClosure fc) { + Set result = new HashSet<>(); + for(Type thetaS : fc.greater(theta)) + result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + return result; + } + + protected Set unifyCase6(ExtendsType extTheta, PlaceholderType a, IFiniteClosure fc) { + Set result = new HashSet<>(); + for(Type thetaS : fc.grArg(extTheta)) + result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + return result; + } + + protected Set unifyCase7(SuperType supTheta, PlaceholderType a, IFiniteClosure fc) { + Set result = new HashSet<>(); + IUnify unify = new MartelliMontanariUnify(); + + Type theta = supTheta.getSuperedType(); + Set cs = fc.getAllTypesByName(theta.getName()); + + for(Type c : cs) { + + // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? + Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + thetaQs.add(c); // reflexive + + Set thetaQPrimes = new HashSet<>(); + TypeParams cParams = c.getTypeParams(); + if(cParams.size() == 0) + thetaQPrimes.add(c); + else { + ArrayList> candidateParams = new ArrayList<>(); + for(Type param : cParams) + candidateParams.add(fc.grArg(param)); + + for(TypeParams tp : permuteParams(candidateParams)) + thetaQPrimes.add(c.setTypeParams(tp)); + } + + for(Type tqp : thetaQPrimes) { + Optional opt = unify.unify(tqp, theta); + if (!opt.isPresent()) + continue; + + Unifier unifier = opt.get(); + Set> substitutions = unifier.getSubstitutions(); + for (Entry sigma : substitutions) + result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + for (Type tq : thetaQs) { + Set smaller = fc.smaller(unifier.apply(tq)); + smaller.stream().map(x -> new MPair(a, new SuperType(x), PairOperator.EQUALSDOT)) + .forEach(x -> result.add(x)); + } + + } + } + + return result; + } + + protected Set unifyCase8(Type theta, PlaceholderType a, IFiniteClosure fc) { + Set result = new HashSet<>(); + for(Type thetaS : fc.grArg(theta)) + result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + return result; + } + + protected Set permuteParams(ArrayList> candidates) { + Set result = new HashSet<>(); + permuteParams(candidates, 0, result, new Type[candidates.size()]); + return result; + } + + private void permuteParams(ArrayList> candidates, int idx, Set result, Type[] current) { if(candidates.size() == idx) { result.add(new TypeParams(Arrays.copyOf(current, current.length))); return; diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index 7b1b6664..073b4a94 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -1,13 +1,39 @@ package unify; +import org.junit.Assert; import org.junit.Test; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; +import de.dhbwstuttgart.typeinference.unify.model.Type; import de.dhbwstuttgart.typeinference.unifynew.TypeFactory; -public class FiniteClosureTest { +public class FiniteClosureTest extends FiniteClosure { + + @Test + public void testMatch() { + TypeFactory tf = new TypeFactory(); + + Type a = tf.getPlaceholderType("a"); + Type b = tf.getPlaceholderType("b"); + Type c = tf.getPlaceholderType("c"); + + Type A = tf.getSimpleType("A"); + Type B = tf.getSimpleType("B"); + Type C1 = tf.getSimpleType("C", a, b, c); + Type C2 = tf.getSimpleType("C", a, A, b); + Type C3 = tf.getSimpleType("C", A, B, A); + Type D1 = tf.getSimpleType("D", C1, a, b, c); + Type D2 = tf.getSimpleType("D", C3, A, B, A); + + System.out.println(match(C2, C1)); + System.out.println(match(C3, C1)); + System.out.println(match(D2, D1)); + Assert.assertFalse(match(C3, C2).isPresent()); + Assert.assertFalse(match(C1, C2).isPresent()); + } @Test public void testGreater() { diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 1b120dae..5c3ad04e 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -25,6 +25,7 @@ public class UnifyTest extends Unify { //fcb.add(tf.getSimpleType("Number"), tf.getSimpleType("Object")); fcb.add(tf.getSimpleType("Integer"), tf.getSimpleType("Number")); fcb.add(tf.getSimpleType("Double"), tf.getSimpleType("Number")); + fcb.add(tf.getSimpleType("MyList"), tf.getSimpleType("List", tf.getSimpleType("Integer"))); //fcb.add(tf.getSimpleType("List", "T")); IFiniteClosure fc = fcb.getCollectionExample(); @@ -35,10 +36,10 @@ public class UnifyTest extends Unify { // Number <. A // Double <. B // B <. Object - eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Integer")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); + //eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Integer")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Number")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Integer")), tf.getSimpleType("Vector", "C"), PairOperator.SMALLERDOT)); - eq.add(new MPair(tf.getPlaceholderType("A"), tf.getSimpleType("Number"), PairOperator.SMALLERDOT)); + eq.add(new MPair(tf.getPlaceholderType("A"), tf.getSimpleType("List", "A"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getSimpleType("Number"), tf.getPlaceholderType("A"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getPlaceholderType("A"), tf.getPlaceholderType("C"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getSimpleType("Double"), tf.getPlaceholderType("B"), PairOperator.SMALLERDOT)); @@ -80,8 +81,7 @@ public class UnifyTest extends Unify { candidates.add(p2); candidates.add(p3); - Set result = new HashSet<>(); - permuteParams(candidates, 0, result, new Type[candidates.size()]); + Set result = permuteParams(candidates); System.out.println(result); } From 21c6aef7fd8a8268c05837f739d192abb55a6f7a Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Sun, 20 Mar 2016 18:05:34 +0100 Subject: [PATCH 04/57] =?UTF-8?q?cartesische=20produkte=20=C3=BCberarbeite?= =?UTF-8?q?t?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../typeinference/unifynew/Unify.java | 111 ++++++++++-------- test/unify/UnifyTest.java | 6 +- 2 files changed, 65 insertions(+), 52 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java index 807c8d7f..ae702fba 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java @@ -57,33 +57,48 @@ public class Unify { * mit dem geordneten Tripel (a,b,c), wodurch das kartesische Produkt auch assoziativ wird." - Wikipedia */ - // All Sets - List> sets = new ArrayList>(); + // There are up to 10 toplevel set. 8 of 10 are the result of the + // cartesian product of the sets created by pattern matching. + List>> topLevelSets = new ArrayList<>(); - if(eq1s.size() != 0) - sets.add(eq1s); // Add Eq1' + if(eq1s.size() != 0) { + Set> wrap = new HashSet<>(); + wrap.add(eq1s); + topLevelSets.add(wrap); // Add Eq1' + } // Add the set of [a =. Theta | (a=. Theta) in Eq2'] Set bufferSet = eq2s.stream() .filter(x -> x.getPairOp() == PairOperator.EQUALSDOT && x.getLhsType() instanceof PlaceholderType) .collect(Collectors.toSet()); - if(bufferSet.size() != 0) - sets.add(bufferSet); + if(bufferSet.size() != 0) { + Set> wrap = new HashSet<>(); + wrap.add(bufferSet); + topLevelSets.add(wrap); + } // Sets that originate from pair pattern matching // Sets of the "second level" - - sets.addAll(calculatePairSets(eq2s, fc)); + Set>> secondLevelSets = calculatePairSets(eq2s, fc); /* Up to here, no cartesian products are calculated. - * Around here, filters for pairs and sets can be applied */ + * filters for pairs and sets can be applied here */ ISetOperations setOps = new GuavaSetOperations(); - // Calculate the cartesian products - Set> result = setOps.cartesianProduct(sets).stream() - .map(x -> new HashSet(x)).collect(Collectors.toCollection(HashSet::new)); + // Sub cartesian products of the second level (pattern matched) sets + for(Set> secondLevelSet : secondLevelSets) { + List> secondLevelSetList = new ArrayList<>(secondLevelSet); + topLevelSets.add(setOps.cartesianProduct(secondLevelSetList) + .stream().map(x -> new HashSet<>(x)) + .collect(Collectors.toCollection(HashSet::new))); + } + + // Cartesian product over all (up to 10) top level sets + Set>> eqPrimeSet = setOps.cartesianProduct(topLevelSets) + .stream().map(x -> new HashSet<>(x)) + .collect(Collectors.toCollection(HashSet::new)); //System.out.println(result); /* @@ -91,38 +106,41 @@ public class Unify { */ /* - * TODO - * Im Paper wird Eq'' genannt, es wird also von einer Menge in einer Menge in einer Menge ausgegangen. - * Durch das flache Kartesische Produkt gibt es hier aber nur Mengen in Mengen. - * Richtig so? + * TODO hier das ergebnis schonh flach machen? (wird im unify old (glaub ich) so gemacht) */ + Set> eqPrimeSetFlat = new HashSet<>(); + for(Set> setToFlatten : eqPrimeSet) { + Set buffer = new HashSet<>(); + setToFlatten.stream().forEach(x -> buffer.addAll(x)); + eqPrimeSetFlat.add(buffer); + } IRuleSet rules = new RuleSet(fc); Set> changed = new HashSet<>(); - Set> unchanged = new HashSet<>(); + Set> eqPrimePrimeSet = new HashSet<>(); - for(Set eqss : result) { - Optional> newEqss = rules.subst(eqss); - if(newEqss.isPresent()) - changed.add(newEqss.get()); - else - unchanged.add(eqss); + for(Set eqPrime : eqPrimeSetFlat) { + Optional> eqPrimePrime = rules.subst(eqPrime); + + if(eqPrimePrime.isPresent()) + changed.add(eqPrimePrime.get()); + else + eqPrimePrimeSet.add(eqPrime); } - /* * Step 6 a) Restart for pairs where subst was applied * b) Build the union over everything */ - for(Set eqss : changed) - unchanged.addAll(this.unify(eqss, fc)); + for(Set eqss : changed) { + eqPrimePrimeSet.addAll(this.unify(eqss, fc)); + } /* - * Step 7: Filter result for solved pairs TODO wie? + * Step 7: Filter result for solved pairs */ - - return unchanged; + return eqPrimePrimeSet; } @@ -217,8 +235,12 @@ public class Unify { } - protected List> calculatePairSets(Set eq2s, IFiniteClosure fc) { - List> result = new ArrayList>(); + protected Set>> calculatePairSets(Set eq2s, IFiniteClosure fc) { + List>> result = new ArrayList<>(); + + // Init all 8 cases + for(int i = 0; i < 8; i++) + result.add(new HashSet<>()); for(MPair pair : eq2s) { @@ -228,38 +250,38 @@ public class Unify { // Case 1: (a <. Theta') if(pairOp == PairOperator.SMALLERDOT && lhsType instanceof PlaceholderType) - result.add(unifyCase1((PlaceholderType) pair.getLhsType(), pair.getRhsType(), fc)); + result.get(0).add(unifyCase1((PlaceholderType) pair.getLhsType(), pair.getRhsType(), fc)); // Case 2: (a <.? ? ext Theta') else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof ExtendsType) - result.add(unifyCase2((PlaceholderType) pair.getLhsType(), (ExtendsType) pair.getRhsType(), fc)); + result.get(1).add(unifyCase2((PlaceholderType) pair.getLhsType(), (ExtendsType) pair.getRhsType(), fc)); // Case 3: (a <.? ? sup Theta') else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof SuperType) - result.add(unifyCase3((PlaceholderType) lhsType, (SuperType) rhsType, fc)); + result.get(2).add(unifyCase3((PlaceholderType) lhsType, (SuperType) rhsType, fc)); // Case 4: (a <.? Theta') else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType) - result.add(unifyCase4((PlaceholderType) lhsType, rhsType, fc)); + result.get(3).add(unifyCase4((PlaceholderType) lhsType, rhsType, fc)); // Case 5: (Theta <. a) else if(pairOp == PairOperator.SMALLERDOT && rhsType instanceof PlaceholderType) - result.add(unifyCase5(lhsType, (PlaceholderType) rhsType, fc)); + result.get(4).add(unifyCase5(lhsType, (PlaceholderType) rhsType, fc)); // Case 6: (? ext Theta <.? a) else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof ExtendsType && rhsType instanceof PlaceholderType) - result.add(unifyCase6((ExtendsType) lhsType, (PlaceholderType) rhsType, fc)); + result.get(5).add(unifyCase6((ExtendsType) lhsType, (PlaceholderType) rhsType, fc)); // Case 7: (? sup Theta <.? a) else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof SuperType && rhsType instanceof PlaceholderType) - result.add(unifyCase7((SuperType) lhsType, (PlaceholderType) rhsType, fc)); + result.get(6).add(unifyCase7((SuperType) lhsType, (PlaceholderType) rhsType, fc)); // Case 8: (Theta <.? a) else if(pairOp == PairOperator.SMALLERDOTWC && rhsType instanceof PlaceholderType) - result.add(unifyCase8(lhsType, (PlaceholderType) rhsType, fc)); + result.get(7).add(unifyCase8(lhsType, (PlaceholderType) rhsType, fc)); } - return result; + return result.stream().filter(x -> x.size() > 0).collect(Collectors.toCollection(HashSet::new)); } protected Set unifyCase1(PlaceholderType a, Type thetaPrime, IFiniteClosure fc) { @@ -456,13 +478,4 @@ public class Unify { permuteParams(candidates, idx+1, result, current); } } - - private Set getAllInstantiations(Type t, IFiniteClosure fc) { - Set result = new HashSet<>(); - result.add(t); - return result; - - // TODO - } - } diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 5c3ad04e..ae219dd2 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -36,10 +36,10 @@ public class UnifyTest extends Unify { // Number <. A // Double <. B // B <. Object - //eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Integer")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Number")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); + eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Integer")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); + eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Number")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Integer")), tf.getSimpleType("Vector", "C"), PairOperator.SMALLERDOT)); - eq.add(new MPair(tf.getPlaceholderType("A"), tf.getSimpleType("List", "A"), PairOperator.SMALLERDOT)); + //eq.add(new MPair(tf.getPlaceholderType("A"), tf.getSimpleType("List", "A"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getSimpleType("Number"), tf.getPlaceholderType("A"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getPlaceholderType("A"), tf.getPlaceholderType("C"), PairOperator.SMALLERDOT)); //eq.add(new MPair(tf.getSimpleType("Double"), tf.getPlaceholderType("B"), PairOperator.SMALLERDOT)); From 47c9be54881d99c5facca963a9364aafdca79efd Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Tue, 22 Mar 2016 13:17:56 +0100 Subject: [PATCH 05/57] =?UTF-8?q?Aufr=C3=A4umen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/de/dhbwstuttgart/syntaxtree/Class.java | 17 +++++++++-------- .../syntaxtree/factory/UnifyTypeFactory.java | 5 +++-- src/de/dhbwstuttgart/syntaxtree/type/Type.java | 6 +++++- .../typeinference/unify/model/SimpleType.java | 2 +- .../typeinference/unify/model/TypeParams.java | 9 +++++++++ test/unify/GenerateFiniteClosure.java | 6 +++++- 6 files changed, 32 insertions(+), 13 deletions(-) diff --git a/src/de/dhbwstuttgart/syntaxtree/Class.java b/src/de/dhbwstuttgart/syntaxtree/Class.java index 006e3537..a044a288 100755 --- a/src/de/dhbwstuttgart/syntaxtree/Class.java +++ b/src/de/dhbwstuttgart/syntaxtree/Class.java @@ -214,7 +214,7 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I private Menge fielddecl = new Menge(); private GenericDeclarationList genericClassParameters; private int offset; - private Type superClass; + private RefType superClass; // ino.method.Class.23041.definition @@ -240,7 +240,7 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I * @param modifiers * @param supertypeGenPara - Eine Liste von Namen, welche die Generischen Parameter der Klasse darstellen. */ - public Class(String name, Type superClass, Modifiers modifiers, Menge supertypeGenPara) { + public Class(String name, RefType superClass, Modifiers modifiers, Menge supertypeGenPara) { this(name,superClass,modifiers,0); if(supertypeGenPara == null)return; Menge gtvs = new Menge<>(); @@ -261,7 +261,7 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I this.setGenericParameter(new GenericDeclarationList(gtvs,0)); } - public Class(String name, Type superClass, Modifiers mod, int offset){ + public Class(String name, RefType superClass, Modifiers mod, int offset){ this(name,mod,offset); if(superClass == null)this.superClass = new Class("java.lang.Object",-1).getType(); else this.superClass = superClass; @@ -293,14 +293,14 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I public Class(String name2, Modifiers object, ClassBody classBody, Menge containedTypes2, Menge typeMenge, Menge paraMenge, int offset2) { - this(name2, object, classBody, containedTypes2,(Type)null, typeMenge, paraMenge, offset2); + this(name2, object, classBody, containedTypes2,(RefType)null, typeMenge, paraMenge, offset2); } private static Menge usedIdToRefType(Menge superif2) { Menge ret = new Menge<>(); for(UsedId id : superif2)ret.add(usedIdToRefType(id)); return ret; } - private static Type usedIdToRefType(UsedId superclass2) { + private static RefType usedIdToRefType(UsedId superclass2) { RefType ret = new RefType(superclass2.getSimpleName(), null, superclass2.getOffset()); ret.set_ParaList(superclass2.get_ParaList()); return ret; @@ -314,7 +314,7 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I // ino.end // ino.method.Class.23047.definition public Class(String name, Modifiers mod, ClassBody cb, Menge ct, - Type superclass, Menge Menge, Menge paralist, int offset) + RefType superclass, Menge Menge, Menge paralist, int offset) // ino.end // ino.method.Class.23047.body { @@ -671,7 +671,8 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I //ConstraintsSet oderConstraints = this.TYPE(this.getMethodList(), fieldInitializers, assumptions); - this.superClass = this.superClass.TYPE(assumptions, this); + //Gibt es hier eine ClassCastException stimmt etwas grundsätzlich nicht! + this.superClass = (RefType)this.superClass.TYPE(assumptions, this); for(Field f:this.getFields()){ oderConstraints.add(f.TYPE(assumptions)); @@ -1028,7 +1029,7 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I * Die Super Klasse dieser Klasse. * @return null für Klasse Object */ - public Type getSuperClass(){ + public RefType getSuperClass(){ return this.superClass; } @Override diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index c718a7bf..6d2503f8 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -20,6 +20,7 @@ import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.SimpleType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; +import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public class UnifyTypeFactory { @@ -28,7 +29,7 @@ public class UnifyTypeFactory { HashSet pairs = new HashSet<>(); for(ClassAssumption cAss : fromAss.getClassAssumptions()){ UnifyType tl = UnifyTypeFactory.convert(cAss.getAssumedClass().getType()); - Type superClass = cAss.getAssumedClass().getSuperClass(); + RefType superClass = cAss.getAssumedClass().getSuperClass(); if(superClass != null){ UnifyType tr = UnifyTypeFactory.convert(superClass); pairs.add(smaller(tl, tr)); @@ -57,7 +58,7 @@ public class UnifyTypeFactory { for(Type pT : t.getParaList()){ params.add(UnifyTypeFactory.convert(pT)); } - ret = new SimpleType(t.get_Name(),params.toArray()); + ret = new SimpleType(t.get_Name(),new TypeParams(params)); }else{ ret = new SimpleType(t.get_Name()); } diff --git a/src/de/dhbwstuttgart/syntaxtree/type/Type.java b/src/de/dhbwstuttgart/syntaxtree/type/Type.java index 5959f52f..7d57e1e9 100755 --- a/src/de/dhbwstuttgart/syntaxtree/type/Type.java +++ b/src/de/dhbwstuttgart/syntaxtree/type/Type.java @@ -17,7 +17,11 @@ import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.DebugException; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; - +class Test { + void methode(ArrayList t){ + + } +} //TODO: Die Klasse Type muss abstract werden! // ino.class.Type.26716.declaration diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java b/src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java index a8997439..62d3ca1c 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java @@ -9,7 +9,7 @@ public final class SimpleType extends UnifyType { super(name, new TypeParams(typeParams)); } - private SimpleType(String name, TypeParams params) { + public SimpleType(String name, TypeParams params) { super(name, params); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java b/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java index a95a1b43..294df4b4 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java @@ -3,9 +3,18 @@ package de.dhbwstuttgart.typeinference.unify.model; import java.util.Arrays; import java.util.Iterator; +import de.dhbwstuttgart.typeinference.Menge; + public final class TypeParams implements Iterable{ private final UnifyType[] typeParams; + public TypeParams(Menge types){ + typeParams = new UnifyType[types.size()]; + for(int i=0;i test = fc.getAllTypes(importClass); + assertTrue(test.size()>0); } } From 0e524caae759156fc0e4569f68a5512d8ea9774c Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Tue, 22 Mar 2016 20:41:24 +0100 Subject: [PATCH 06/57] Added missing rules --- .../unify/interfaces/IRuleSet.java | 8 ++ .../typeinference/unifynew/RuleSet.java | 98 +++++++++++++++++++ 2 files changed, 106 insertions(+) diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java index 840d7259..d86ebdd8 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java @@ -16,6 +16,14 @@ public interface IRuleSet { public Optional> reduce1(MPair pair); public Optional> reduce2(MPair pair); + public Optional reduceWildcardLow(MPair pair); + public Optional reduceWildcardLowRight(MPair pair); + public Optional reduceWildcardUp(MPair pair); + public Optional reduceWildcardUpRight(MPair pair); + public Optional reduceWildCardLowUp(MPair pair); + public Optional reduceWildcardUpLow(MPair pair); + public Optional reduceWildcardLeft(MPair pair); + public boolean erase1(MPair pair); public boolean erase2(MPair pair); public boolean erase3(MPair pair); diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java index e41525f5..11138a47 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java @@ -559,4 +559,102 @@ public class RuleSet implements IRuleSet{ return applied ? Optional.of(new HashSet<>(result)) : Optional.empty(); } + + @Override + public Optional reduceWildcardLow(MPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + Type lhsType = pair.getLhsType(); + Type rhsType = pair.getRhsType(); + if(!(lhsType instanceof ExtendsType) || !(rhsType instanceof ExtendsType)) + return Optional.empty(); + + return Optional.of(new MPair(((ExtendsType) lhsType).getExtendedType(), ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT)); + } + + @Override + public Optional reduceWildcardLowRight(MPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + Type lhsType = pair.getLhsType(); + Type rhsType = pair.getRhsType(); + if((lhsType instanceof ExtendsType) || !(rhsType instanceof ExtendsType)) + return Optional.empty(); + + return Optional.of(new MPair(lhsType, ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT)); + } + + @Override + public Optional reduceWildcardUp(MPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + Type lhsType = pair.getLhsType(); + Type rhsType = pair.getRhsType(); + if(!(lhsType instanceof SuperType) || !(rhsType instanceof SuperType)) + return Optional.empty(); + + return Optional.of(new MPair(((SuperType) rhsType).getSuperedType(), ((SuperType) lhsType).getSuperedType(), PairOperator.SMALLERDOT)); + } + + @Override + public Optional reduceWildcardUpRight(MPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + Type lhsType = pair.getLhsType(); + Type rhsType = pair.getRhsType(); + if((lhsType instanceof SuperType) || !(rhsType instanceof SuperType)) + return Optional.empty(); + + return Optional.of(new MPair(((SuperType) rhsType).getSuperedType(), lhsType, PairOperator.SMALLERDOT)); + } + + @Override + public Optional reduceWildCardLowUp(MPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + Type lhsType = pair.getLhsType(); + Type rhsType = pair.getRhsType(); + if(!(lhsType instanceof ExtendsType) || !(rhsType instanceof SuperType)) + return Optional.empty(); + + return Optional.of(new MPair(((ExtendsType) lhsType).getExtendedType(), ((SuperType) rhsType).getSuperedType(), PairOperator.EQUALSDOT)); + } + + @Override + public Optional reduceWildcardUpLow(MPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + Type lhsType = pair.getLhsType(); + Type rhsType = pair.getRhsType(); + if(!(lhsType instanceof SuperType) || !(rhsType instanceof ExtendsType)) + return Optional.empty(); + + return Optional.of(new MPair(((SuperType) lhsType).getSuperedType(), ((ExtendsType) rhsType).getExtendedType(), PairOperator.EQUALSDOT)); + } + + @Override + public Optional reduceWildcardLeft(MPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + Type rhsType = pair.getRhsType(); + if((rhsType instanceof SuperType) || (rhsType instanceof ExtendsType)) + return Optional.empty(); + + Type lhsType = pair.getLhsType(); + + if(lhsType instanceof SuperType) + return Optional.of(new MPair(((SuperType) lhsType).getSuperedType(), rhsType, PairOperator.EQUALSDOT)); + + if(lhsType instanceof ExtendsType) + return Optional.of(new MPair(((ExtendsType) lhsType).getExtendedType(), rhsType, PairOperator.EQUALSDOT)); + + return Optional.empty(); + } } From 14e00913e89e49288964f29ef46d8ccf6ce264a2 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Tue, 22 Mar 2016 20:47:39 +0100 Subject: [PATCH 07/57] application of new rules --- .../typeinference/unify/interfaces/IRuleSet.java | 2 +- src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java | 2 +- src/de/dhbwstuttgart/typeinference/unifynew/Unify.java | 7 +++++++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java index d86ebdd8..c4de888d 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java @@ -20,7 +20,7 @@ public interface IRuleSet { public Optional reduceWildcardLowRight(MPair pair); public Optional reduceWildcardUp(MPair pair); public Optional reduceWildcardUpRight(MPair pair); - public Optional reduceWildCardLowUp(MPair pair); + public Optional reduceWildcardLowUp(MPair pair); public Optional reduceWildcardUpLow(MPair pair); public Optional reduceWildcardLeft(MPair pair); diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java index 11138a47..52239af4 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java @@ -613,7 +613,7 @@ public class RuleSet implements IRuleSet{ } @Override - public Optional reduceWildCardLowUp(MPair pair) { + public Optional reduceWildcardLowUp(MPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java index ae702fba..6e6fe376 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java @@ -178,6 +178,13 @@ public class Unify { Optional opt = rules.reduceUpLow(pair); opt = opt.isPresent() ? opt : rules.reduceLow(pair); opt = opt.isPresent() ? opt : rules.reduceUp(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardLow(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardLowRight(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardUp(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardUpRight(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardLowUp(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardUpLow(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardLeft(pair); // One of the rules has been applied if(opt.isPresent()) { From 88726ccb7059078f3e1b972ef50e41339a883c98 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Wed, 23 Mar 2016 09:45:36 +0100 Subject: [PATCH 08/57] added funN --- .../unify/interfaces/IFiniteClosure.java | 4 +++ .../unify/model/FiniteClosure.java | 14 +++++++- .../typeinference/unify/model/FunNType.java | 34 +++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java index 3af29411..0bba681f 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java @@ -4,6 +4,7 @@ import java.util.Optional; import java.util.Set; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; +import de.dhbwstuttgart.typeinference.unify.model.FunNType; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.SimpleType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; @@ -49,6 +50,9 @@ public interface IFiniteClosure { public Set grArg(PlaceholderType type); public Set smArg(PlaceholderType type); + public Set grArg(FunNType type); + public Set smArg(FunNType type); + public Optional getGenericType(String typeName); public Set getAllTypesByName(String typeName); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 64fb6862..27827dbe 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -8,6 +8,7 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; @@ -193,6 +194,11 @@ public class FiniteClosure implements IFiniteClosure { return result; } + @Override + public Set grArg(FunNType type) { + throw new NotImplementedException(); + } + @Override public Set grArg(ExtendsType type) { if(!inheritanceGraph.containsKey(type.getExtendedType())) @@ -249,7 +255,13 @@ public class FiniteClosure implements IFiniteClosure { return result; } - + + @Override + public Set smArg(FunNType type) { + throw new NotImplementedException(); + } + + @Override public Set smArg(ExtendsType type) { if(!inheritanceGraph.containsKey(type.getExtendedType())) return new HashSet(); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java b/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java new file mode 100644 index 00000000..a6068c84 --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java @@ -0,0 +1,34 @@ +package de.dhbwstuttgart.typeinference.unify.model; + +import java.util.Set; + +import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; + +public class FunNType extends Type { + + public FunNType(TypeParams p) { + super("FuN", p); + } + + @Override + public Type setTypeParams(TypeParams newTp) { + return new FunNType(newTp); + } + + @Override + Set smArg(IFiniteClosure fc) { + return fc.smArg(this); + } + + @Override + Set grArg(IFiniteClosure fc) { + return fc.grArg(this); + } + + @Override + Type apply(Unifier unif) { + // TODO Auto-generated method stub + return null; + } + +} From 11bcf5735a68b878090c31c266072a9f3ab0a86a Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Wed, 23 Mar 2016 10:59:41 +0100 Subject: [PATCH 09/57] freshPlaceholder Method // funN rules (not implemented yet) --- .../unify/interfaces/IRuleSet.java | 10 ++++++++ .../unify/model/PlaceholderType.java | 24 +++++++++++++++++++ .../typeinference/unify/model/TypeParams.java | 2 +- .../typeinference/unifynew/RuleSet.java | 18 ++++++++++++++ 4 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java index c4de888d..23c444e0 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java @@ -16,6 +16,9 @@ public interface IRuleSet { public Optional> reduce1(MPair pair); public Optional> reduce2(MPair pair); + /* + * Missing Rules + */ public Optional reduceWildcardLow(MPair pair); public Optional reduceWildcardLowRight(MPair pair); public Optional reduceWildcardUp(MPair pair); @@ -24,6 +27,13 @@ public interface IRuleSet { public Optional reduceWildcardUpLow(MPair pair); public Optional reduceWildcardLeft(MPair pair); + /* + * FunN Rules + */ + public Optional> reduceFunN(MPair pair); + public Optional> greaterFunN(MPair pair); + public Optional> smallerFunN(MPair pair); + public boolean erase1(MPair pair); public boolean erase2(MPair pair); public boolean erase3(MPair pair); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java index 5a3d5341..b5a0fe1e 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java @@ -1,13 +1,37 @@ package de.dhbwstuttgart.typeinference.unify.model; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Random; import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; public final class PlaceholderType extends Type{ + protected static final HashSet EXISTING_PLACEHOLDERS = new HashSet(); + protected static String nextName = "gen_"; + public PlaceholderType(String name) { super(name); + EXISTING_PLACEHOLDERS.add(name); + } + + public static PlaceholderType freshPlaceholder() { + String name = nextName + randomChar(); + + while(EXISTING_PLACEHOLDERS.contains(name)); + nextName += randomChar(); + + return new PlaceholderType(name); + } + + /** + * Returns random char between 'a' and 'z' + * @return + */ + private static char randomChar() { + return (char) (new Random().nextInt(22) + 97); } @Override diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java b/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java index 966a561b..a7393508 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java @@ -5,7 +5,7 @@ import java.util.Iterator; public final class TypeParams implements Iterable{ private final Type[] typeParams; - + public TypeParams(Type... types) { typeParams = types; } diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java index 52239af4..4232a692 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java @@ -657,4 +657,22 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); } + + @Override + public Optional> reduceFunN(MPair pair) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Optional> greaterFunN(MPair pair) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Optional> smallerFunN(MPair pair) { + // TODO Auto-generated method stub + return null; + } } From a5b86dc84c5f9614f96e08fb58d4b60787eccffe Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Wed, 23 Mar 2016 11:44:31 +0100 Subject: [PATCH 10/57] freshPlaceholder / implemented funn rules --- .../typeinference/unify/model/FunNType.java | 10 +++ .../unify/model/PlaceholderType.java | 1 - .../typeinference/unifynew/RuleSet.java | 75 +++++++++++++++++-- 3 files changed, 79 insertions(+), 7 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java b/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java index a6068c84..bb74d39e 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java @@ -8,13 +8,21 @@ public class FunNType extends Type { public FunNType(TypeParams p) { super("FuN", p); + if(p.size() == 0) + throw new IllegalArgumentException("Function types need at least one type parameter"); } @Override public Type setTypeParams(TypeParams newTp) { + if(newTp.size() == 0) + throw new IllegalArgumentException("Function types need at least one type parameter"); return new FunNType(newTp); } + public int getN() { + return typeParams.size()-1; + } + @Override Set smArg(IFiniteClosure fc) { return fc.smArg(this); @@ -31,4 +39,6 @@ public class FunNType extends Type { return null; } + // TODO equals und hashcode + } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java index b5a0fe1e..8a7769de 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java @@ -28,7 +28,6 @@ public final class PlaceholderType extends Type{ /** * Returns random char between 'a' and 'z' - * @return */ private static char randomChar() { return (char) (new Random().nextInt(22) + 97); diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java index 4232a692..f6b26ad9 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java @@ -14,6 +14,7 @@ import junit.framework.Assert; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; +import de.dhbwstuttgart.typeinference.unify.model.FunNType; import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.SimpleType; @@ -660,19 +661,81 @@ public class RuleSet implements IRuleSet{ @Override public Optional> reduceFunN(MPair pair) { - // TODO Auto-generated method stub - return null; + if(pair.getPairOp() != PairOperator.SMALLERDOT) + return Optional.empty(); + + Type lhsType = pair.getLhsType(); + Type rhsType = pair.getRhsType(); + + if(!(lhsType instanceof FunNType) || !(rhsType instanceof FunNType)) + return Optional.empty(); + + FunNType funNLhsType = (FunNType) lhsType; + FunNType funNRhsType = (FunNType) rhsType; + + if(funNLhsType.getN() != funNRhsType.getN()) + return Optional.empty(); + + Set result = new HashSet(); + + result.add(new MPair(funNLhsType.getTypeParams().get(0), funNRhsType.getTypeParams().get(0), PairOperator.SMALLERDOT)); + for(int i = 1; i < funNLhsType.getTypeParams().size(); i++) + result.add(new MPair(funNRhsType.getTypeParams().get(i), funNLhsType.getTypeParams().get(i), PairOperator.SMALLERDOT)); + + return Optional.of(result); } @Override public Optional> greaterFunN(MPair pair) { - // TODO Auto-generated method stub - return null; + if(pair.getPairOp() != PairOperator.SMALLERDOT) + return Optional.empty(); + + Type lhsType = pair.getLhsType(); + Type rhsType = pair.getRhsType(); + + if(!(lhsType instanceof FunNType) || !(rhsType instanceof PlaceholderType)) + return Optional.empty(); + + FunNType funNLhsType = (FunNType) lhsType; + + Set result = new HashSet(); + + Type[] freshPlaceholders = new Type[funNLhsType.getTypeParams().size()]; + for(int i = 0; i < freshPlaceholders.length; i++) + freshPlaceholders[i] = PlaceholderType.freshPlaceholder(); + + result.add(new MPair(funNLhsType.getTypeParams().get(0), freshPlaceholders[0], PairOperator.SMALLERDOT)); + for(int i = 1; i < funNLhsType.getTypeParams().size(); i++) + result.add(new MPair(freshPlaceholders[i], funNLhsType.getTypeParams().get(i), PairOperator.SMALLERDOT)); + result.add(new MPair(rhsType, funNLhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT)); + + return Optional.of(result); } @Override public Optional> smallerFunN(MPair pair) { - // TODO Auto-generated method stub - return null; + if(pair.getPairOp() != PairOperator.SMALLERDOT) + return Optional.empty(); + + Type lhsType = pair.getLhsType(); + Type rhsType = pair.getRhsType(); + + if(!(lhsType instanceof PlaceholderType) || !(rhsType instanceof FunNType)) + return Optional.empty(); + + FunNType funNRhsType = (FunNType) rhsType; + + Set result = new HashSet(); + + Type[] freshPlaceholders = new Type[funNRhsType.getTypeParams().size()]; + for(int i = 0; i < freshPlaceholders.length; i++) + freshPlaceholders[i] = PlaceholderType.freshPlaceholder(); + + result.add(new MPair(freshPlaceholders[0], funNRhsType.getTypeParams().get(0), PairOperator.SMALLERDOT)); + for(int i = 1; i < funNRhsType.getTypeParams().size(); i++) + result.add(new MPair(funNRhsType.getTypeParams().get(i), freshPlaceholders[i], PairOperator.SMALLERDOT)); + result.add(new MPair(lhsType, funNRhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT)); + + return Optional.of(result); } } From 1e9d0517f267fcab122dbe1113f74ab77287e839 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Thu, 24 Mar 2016 11:57:17 +0100 Subject: [PATCH 11/57] Umstellung auf MPair beginnen --- src/de/dhbwstuttgart/syntaxtree/Class.java | 6 +- .../dhbwstuttgart/syntaxtree/SourceFile.java | 508 +-- .../syntaxtree/factory/UnifyTypeFactory.java | 16 +- .../factory/Unify_FC_TTO_Builder.java | 4 - .../syntaxtree/type/RefType.java | 37 - .../typeinference/ConstraintsSet.java | 5 +- .../typeinference/KomplexeMenge.java | 6 +- .../typeinference/OderConstraint.java | 11 +- .../typeinference/OderMenge.java | 7 +- .../dhbwstuttgart/typeinference/UndMenge.java | 15 +- .../typeinference/unify/CSet.java | 72 - .../typeinference/unify/CSubstitution.java | 253 -- .../unify/CSubstitutionGenVar.java | 70 - .../typeinference/unify/CSubstitutionSet.java | 111 - .../typeinference/unify/CVectorSet.java | 165 - .../typeinference/unify/FC_TTO.java | 82 - .../GuavaSetOperations.java | 2 +- .../typeinference/unify/MUB.java | 53 - .../{unifynew => unify}/Mapping.java | 2 +- .../MartelliMontanariUnify.java | 2 +- .../typeinference/unify/ParallelUnify.java | 44 - .../{unifynew => unify}/RuleSet.java | 2 +- .../typeinference/unify/Unifier.java | 11 - .../typeinference/unify/Unify.java | 4041 ++--------------- .../unify/model/FiniteClosure.java | 2 +- .../typeinference/unifynew/Unify.java | 480 -- test/unify/RuleSetTest.java | 2 +- test/unify/StandardUnifyTest.java | 2 +- test/unify/UnifyTest.java | 2 +- 29 files changed, 559 insertions(+), 5454 deletions(-) delete mode 100755 src/de/dhbwstuttgart/typeinference/unify/CSet.java delete mode 100755 src/de/dhbwstuttgart/typeinference/unify/CSubstitution.java delete mode 100755 src/de/dhbwstuttgart/typeinference/unify/CSubstitutionGenVar.java delete mode 100755 src/de/dhbwstuttgart/typeinference/unify/CSubstitutionSet.java delete mode 100755 src/de/dhbwstuttgart/typeinference/unify/CVectorSet.java delete mode 100755 src/de/dhbwstuttgart/typeinference/unify/FC_TTO.java rename src/de/dhbwstuttgart/typeinference/{unifynew => unify}/GuavaSetOperations.java (84%) delete mode 100755 src/de/dhbwstuttgart/typeinference/unify/MUB.java rename src/de/dhbwstuttgart/typeinference/{unifynew => unify}/Mapping.java (96%) rename src/de/dhbwstuttgart/typeinference/{unifynew => unify}/MartelliMontanariUnify.java (95%) delete mode 100644 src/de/dhbwstuttgart/typeinference/unify/ParallelUnify.java rename src/de/dhbwstuttgart/typeinference/{unifynew => unify}/RuleSet.java (96%) delete mode 100644 src/de/dhbwstuttgart/typeinference/unify/Unifier.java mode change 100755 => 100644 src/de/dhbwstuttgart/typeinference/unify/Unify.java delete mode 100644 src/de/dhbwstuttgart/typeinference/unifynew/Unify.java diff --git a/src/de/dhbwstuttgart/syntaxtree/Class.java b/src/de/dhbwstuttgart/syntaxtree/Class.java index a044a288..e5894526 100755 --- a/src/de/dhbwstuttgart/syntaxtree/Class.java +++ b/src/de/dhbwstuttgart/syntaxtree/Class.java @@ -47,7 +47,6 @@ import de.dhbwstuttgart.typeinference.exceptions.DebugException; import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; import de.dhbwstuttgart.typeinference.typedeployment.TypeInsertPoint; -import de.dhbwstuttgart.typeinference.unify.FC_TTO; import de.dhbwstuttgart.typeinference.unify.Unify; import org.apache.commons.bcel6.generic.*; @@ -625,7 +624,7 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I */ // ino.end // ino.method.TRProg.23110.definition - public ConstraintsSet typeReconstruction(FC_TTO supportData, TypeAssumptions globalAssumptions) + public ConstraintsSet typeReconstruction(TypeAssumptions globalAssumptions) // ino.end // ino.method.TRProg.23110.body { @@ -637,8 +636,7 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I ////////////////////////////// inferencelog.info("Rufe TRStart()...", Section.TYPEINFERENCE); - typinferenzLog.debug("Erstellte FiniteClosure: "+supportData, Section.TYPEINFERENCE); - ////////////////////////////// + ////////////////////////////// // Ab hier ... // @author A10023 - Andreas Stadelmeier: ////////////////////////////// diff --git a/src/de/dhbwstuttgart/syntaxtree/SourceFile.java b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java index cea600d1..18e43236 100755 --- a/src/de/dhbwstuttgart/syntaxtree/SourceFile.java +++ b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java @@ -9,6 +9,8 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; +import java.util.Set; +import java.util.function.Function; import de.dhbwstuttgart.typeinference.Menge; @@ -23,6 +25,7 @@ import de.dhbwstuttgart.myexception.JVMCodeException; import de.dhbwstuttgart.myexception.SCClassException; import de.dhbwstuttgart.myexception.SCException; import de.dhbwstuttgart.parser.JavaClassName; +import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory; import de.dhbwstuttgart.syntaxtree.misc.DeclId; import de.dhbwstuttgart.syntaxtree.misc.UsedId; import de.dhbwstuttgart.syntaxtree.modifier.Modifiers; @@ -37,6 +40,7 @@ import de.dhbwstuttgart.typeinference.ByteCodeResult; import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.FunNInterface; import de.dhbwstuttgart.typeinference.FunNMethod; +import de.dhbwstuttgart.typeinference.KomplexeMenge; import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; @@ -48,18 +52,14 @@ import de.dhbwstuttgart.typeinference.assumptions.ParameterAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.DebugException; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; -import de.dhbwstuttgart.typeinference.unify.FC_TTO; -import de.dhbwstuttgart.typeinference.unify.Unifier; import de.dhbwstuttgart.typeinference.unify.Unify; +import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; +import de.dhbwstuttgart.typeinference.unify.model.MPair; - -// ino.class.SourceFile.21355.declaration public class SourceFile extends SyntaxTreeNode -// ino.end -// ino.class.SourceFile.21355.body { // ino.attribute.LOAD_BASIC_ASSUMPTIONS_FROM_JRE.21358.decldescription type=javadoc /** @@ -170,17 +170,13 @@ public class SourceFile this.KlassenVektor = classDefinitions; } - // ino.attribute.imports.21382.decldescription type=javadoc /** * HOTI 4.5.06 * Beinhaltet alle Imports des aktuell geparsten Files * in Form einer UsedId */ - // ino.end - // ino.attribute.imports.21382.declaration private ImportDeclarations imports=new ImportDeclarations(); - // ino.end - // ino.attribute.baseTypeTranslationTable.21385.decldescription type=javadoc + /** * Table zum Übersetzen der nicht implementierten Base-Types: * Überall im Compiler wird statt bspw. int Integer verwendet @@ -189,24 +185,13 @@ public class SourceFile * der JRE gelieferten Base-Typen (int,char, etc) und die Objekt- * Typen umwandeln können */ - // ino.end - // ino.attribute.baseTypeTranslationTable.21385.declaration private Hashtable baseTypeTranslationTable; - // ino.end - - - - // ino.method.addElement.21394.defdescription type=javadoc /** * Fuegt ein neues Element (Interface oder Klasse) hinzu. * @param c */ - // ino.end - // ino.method.addElement.21394.definition public void addElement(AClassOrInterface e) - // ino.end - // ino.method.addElement.21394.body { if (e instanceof Class) { KlassenVektor.addElement((Class) e); @@ -214,447 +199,8 @@ public class SourceFile InterfaceVektor.addElement((Interface) e); } } - // ino.end - - // ino.method.codegen.21397.defdescription type=javadoc - /** - * Startet die Bytecodegenerierung fuer alle in der Datei - * enthaltenen Klassen und Interfaces. - * - - // ino.end - // ino.method.codegen.21397.definition - public Menge codegen(ResultSet result) - throws JVMCodeException - // ino.end - // ino.method.codegen.21397.body - { - Menge ret = new Menge(); - codegenlog.info("Anzahl der Interfaces: " - + Integer.toString(InterfaceVektor.size())); - for(int i = 0; i < InterfaceVektor.size(); i++) { - InterfaceVektor.elementAt(i).codegen(result); - } - - codegenlog.info("Anzahl der Klassen: " - + Integer.toString(KlassenVektor.size())); - for(int i = 0; i < KlassenVektor.size(); i++) { - ret.add(KlassenVektor.elementAt(i).codegen(result)); - } - return ret; - } - // ino.end - */ - // ino.method.createPairFromClassAndSuperclass.21400.defdescription type=javadoc - /** - * Erstellt ein Typ-Paar, welches im 1. Durchlauf in die Menge der Finite Closure - * aufgenommen wird Input: Klassenname, Name der Superklasse, ParameterDerKlasse, - * Parameter der Superklasse - * @return - */ - // ino.end - // ino.method.createPairFromClassAndSuperclass.21400.definition - private Pair createPairFromClassAndSuperclass(Class baseClass, Type superclass, Menge classParaOrg, Menge superclassParaOrg, TypeAssumptions ass) - // ino.end - // ino.method.createPairFromClassAndSuperclass.21400.body - { - // Paar erstellen - if(classParaOrg!=null && classParaOrg.size()==0){ - classParaOrg=null; - } - if(superclassParaOrg!=null && superclassParaOrg.size()==0){ - superclassParaOrg=null; - } - /* - Pair P = new Pair( - new RefType( className.toString(), classParaOrg,-1), - new RefType( superclassName.toString(), superclassParaOrg,-1) - ); - */ - Pair P = new Pair(baseClass.getType().TYPE(ass, baseClass), superclass.TYPE(ass, baseClass)); - //PL 04-12-29 freshe Variablen ANFANG - RefType r1 = (RefType)P.getTA1Copy(); - RefType r2 = (RefType)P.getTA2Copy(); - r1 = (RefType) r1.TYPE(ass, baseClass); - r2 = (RefType) r2.TYPE(ass, baseClass); - // #JB# 05.04.2005 - // ########################################################### - Hashtable substHash = new Hashtable(); //fuer jedes Paar komplett neue Variablen - Unify.varSubst(r1, substHash); - Unify.varSubst(r2, substHash); - // ########################################################### - P = new Pair(r1, r2); - //PL 04-12-29 freshe Variablen ENDE - - //HIER AUSKOMMENTIERT, SOLLTE MAN AM ENDE WIEDER DAZU NEHMEN PL 04-12-28 - // gleiches Paar aufnehmen - //vFC.add( new Pair( P.getTA1Copy(), P.getTA1Copy() ) ); - - return(P); - - } - // ino.end - // ino.method.makeFC.21403.defdescription type=javadoc - /** - * Erstellt die Finite Closure - * @return FC_TTO-Object, welches die Finite Closure repräsentiert - */ - public FC_TTO makeFC( TypeAssumptions ass ) - { - - // Menge FC bilden - - Menge vFC = new Menge(); // Menge FC - TypeAssumptions globalAssumptions = this.makeBasicAssumptionsFromJRE(imports, false); - globalAssumptions.add(this.getPublicFieldAssumptions()); - // 1. Menge <= in FC aufnehmen --> Iteration ueber alle Klassen - - Menge ignoreTypes = new Menge<>(); //Enthält die Typen, welche nicht in der FC als Supertypen enthalten sein sollen. - ignoreTypes.add(new RefType("Long",null,-1).TYPE(globalAssumptions, parent)); - ignoreTypes.add(new RefType("Float",null,-1).TYPE(globalAssumptions, parent)); - ignoreTypes.add(new RefType("Double",null,-1).TYPE(globalAssumptions, parent)); - ignoreTypes.add(new RefType("String",null,-1).TYPE(globalAssumptions, parent)); - ignoreTypes.add(new RefType("Integer",null,-1).TYPE(globalAssumptions, parent)); - ignoreTypes.add(new RefType("Object",null,-1).TYPE(globalAssumptions, parent)); - - Menge basicAssumptionsClassMenge = new Menge<>(); //die Klassen aus den BasicAssumptions und den Importierten Klassen - for(ClassAssumption cAss : ass.getClassAssumptions()){ - Type t1 = cAss.getAssumedClass().getType(); - Type t2 = cAss.getAssumedClass().getSuperClass(); - if(t2 != null){ - Pair p = new Pair(t1, t2); - //System.out.println("FCPair: "+p); - if(! t1.equals(t2)){//Um FC_TTO darf kein T <. T stehen. - Type superTypeFromAssumptions = ass.getTypeFor(t2, t2); //In den Assumptions den SuperTyp nachschlagen - if(superTypeFromAssumptions != null && ! ignoreTypes.contains(superTypeFromAssumptions)){//Die Superklasse eines Typs nur anfügen, wenn er auch in den Assumptions vorkommt. - vFC.add(p); - } - basicAssumptionsClassMenge.add(cAss.getAssumedClass());//Klasse ohne die Superklasse anfügen - }else{ - //System.out.println("Wurde nicht aufgenommen"); - } - } - } - - for( int i = 0; i < KlassenVektor.size(); i++ ) - { - Class tempKlasse = KlassenVektor.elementAt(i); - inferencelog.debug("Verarbeite "+tempKlasse.getName(), Section.TYPEINFERENCE); - //TODO: SuperKlasse erstellen, dies sollte am besten beim Konstruktoraufruf von Class geschehen. Diese kann dann mit getSuperClass abgefragt werden. - if( tempKlasse.superclassid != null ) { // Klasse hat Superklasse - Pair P=createPairFromClassAndSuperclass(tempKlasse,tempKlasse.getSuperClass(),tempKlasse.get_ParaList(),tempKlasse.superclassid.get_ParaList(), globalAssumptions); - vFC.add( P ); - } - if(tempKlasse.getSuperInterfaces()!=null){ - Iterator interfaceIterator=tempKlasse.getSuperInterfaces().iterator(); - while(interfaceIterator.hasNext()){ - RefType intf=(RefType) interfaceIterator.next(); - Pair P=createPairFromClassAndSuperclass(tempKlasse,intf,tempKlasse.get_ParaList(),intf.get_ParaList(),globalAssumptions); - vFC.add( P ); - - } - } - } // Schleifenende durch Klassenvektor - for(int i=0; i interfaceIterator=intf.getSuperInterfaces().iterator(); - while(interfaceIterator.hasNext()){ - RefType superintf=(RefType) interfaceIterator.next(); - Pair P=createPairFromClassAndSuperclass(intf,superintf,intf.getParaList(), superintf.get_ParaList(),globalAssumptions); - vFC.add( P ); - - } - } - } - Menge tto = (Menge)vFC.clone(); - - Unify.printMenge( "FC", vFC, 6 ); - /* z.B. - ******************************* - Menge FC = { - (Vektor< A >, Vektor< A >), - (Vektor< A >, AbstractList< A >), - (Matrix< A >, Matrix< A >), - (Matrix< A >, Vektor< Vektor< A > >), - (ExMatrix< A >, ExMatrix< A >), - (ExMatrix< A >, Matrix< A >) } - ******************************* - - ODER - - ******************************* - Menge FC = { - (BB< A >, BB< A >), - (BB< A >, CC< A >), - (AA< A, B >, AA< A, B >), - (AA< A, B >, BB< DD< B, A > >) } - ******************************* - - */ - - // 2. Regel 2 der Huellendefinition "eingeschraenkt" anwenden - // d.h. sinnvolle Substitutionen suchen (nicht alle) - - boolean bPaarHinzu = true; - while( bPaarHinzu ) - { - bPaarHinzu = false; //PL 04-12-29 nur wenn hinzugefuegt auf true setzen - // konkret: rechte Seite von FC nach Typkonstruktoren in der Parameterliste durchsuchen - for( int n = 0; n < vFC.size(); n++ ) - { - // Elemente in FC k�nnen nur Pair's sein --> Cast ohne Abfrage - Pair PTypKonst = vFC.elementAt(n); - - // Parameter des rechten Typausdrucks des betrachteten Paars extrahieren - Menge vPara = ((RefType)(PTypKonst.TA2)).get_ParaList(); - Integer Subst = null; // Substitution - int nSubstStelle = 0; - inferencelog.debug("nSubstStelleStart" + nSubstStelle + " " + n, Section.FINITECLOSURE); - - // Parameter durchlaufen und nach Typkonstruktor suchen - // #JB# 17.05.2005 - // ########################################################### - if(vPara!=null){ - // ########################################################### - for( ; nSubstStelle < vPara.size(); nSubstStelle++ ) - { - inferencelog.debug("nSubstStelle" + nSubstStelle, Section.FINITECLOSURE); - if( vPara.elementAt(nSubstStelle) instanceof RefType && ((RefType)vPara.elementAt(nSubstStelle)).get_ParaList() != null ) - { - // Typkonstruktor gefunden -> wird nun als Substitution verwendet - Subst = 1;//new RefType( (RefType)vPara.elementAt(nSubstStelle) ,-1); - inferencelog.debug( "Ausgangstyp:" + ((RefType)PTypKonst.TA2).getName() , Section.FINITECLOSURE); - inferencelog.debug( "RefType = " + ((RefType)vPara.elementAt(nSubstStelle)).getName() , Section.FINITECLOSURE); - break; // Einschraenkung - nur fuer ein RefType wird eine Substitution gesucht - } - } - // ########################################################### - } - // ########################################################### - if( Subst != null ) - { - // Rechter Typ hat einen Typkonstruktor --> sinvolles neues Paar bilden - // d.h. Rechter Typ auf linker Paarseite suchen - // System.out.println("Subststelle = " + nSubstStelle ); - - for( int t = 0; t < vFC.size(); t++ ) - { - Pair PSuchen = vFC.elementAt(t); - if( ((RefType)(PTypKonst.TA2)).getTypeName().equals( ((RefType)PSuchen.TA1).getTypeName() ) ) - { - inferencelog.debug(" gefundener Typ links: " + ((RefType)(PSuchen.TA1)).getName(), Section.FINITECLOSURE ); - inferencelog.debug(" gefundener Typ rechts: " + ((RefType)(PSuchen.TA2)).getName() , Section.FINITECLOSURE); - // Paar gefunden, das als linken Typ den gleichen Typen enth�lt, der als Parameter einen Typkonstruktor hat - // Substitution - //Pair P = new Pair( PSuchen.getTA1Copy( ), PSuchen.getTA2Copy( ) ); - //linker Typterm bleibt gleich - //rechter Typterm wird aussen auf den Supertyp gesetzt. - //restliches FC erfolgt ueber die Transitivitaet - //siehe im unteren Teil - Pair P = new Pair( PTypKonst.getTA1Copy( ), PSuchen.getTA2Copy( ) ); - // System.out.println(" Subst " + Subst.getName() ); - // System.out.println(" Vor: P = " + P.toString() + P.TA1 ); - // System.out.println(" Vor: PSuchen = " + PSuchen.toString() + PSuchen.TA1 ); - - // Parameter, der substituiert wird, sollte TV sein ??? - //TypePlaceholder TV = null; - // if( ((RefType)P.TA1).isTV( nSubstStelle ) ) - // try - // { - // TV = new TypePlaceholder( ((RefType)P.TA1).getParaN( nSubstStelle ) ); - // } - // catch( Exception E ) - // { - // continue; - // } - // else - // continue; - - //es werden alle Parameter in einem Typeterm, der - //der Argumente hat ersetzt PL 04-12-28 - Hashtable hts = new Hashtable(); - //for(int u = nSubstStelle; u < vPara.size(); u++) { - for(int u = 0; u < vPara.size(); u++) { - try { - // #JB# 05.04.2005 - // ########################################################### - //TV = new TypePlaceholder( ((RefType)PSuchen.TA1).getParaN(u) ); - //System.out.println("TV_Name: " + u + TV.Type2String()); - // ########################################################### - inferencelog.debug("Typterm_Name: " + vPara.elementAt(u), Section.FINITECLOSURE); - inferencelog.debug("Typterm_Name: " + ((Type)vPara.elementAt(u)).Type2String(), Section.FINITECLOSURE); - hts.put(new JavaClassName(((RefType)PSuchen.TA1).getParaN(u)), vPara.elementAt(u)); - } - catch( Exception E ) { - inferencelog.error(E.getMessage(), Section.FINITECLOSURE); - //FIXME Throw Exception or Error instead of exiting! - System.exit(0); - } - - // Subst( P, - // 2, - // TV, - // new RefType( (RefType)vPara.elementAt(u) ), - // false ); // rechte Seite substituieren - //Es genuegt die rechte Seite zu substituieren, da - //die linke Seite ein Typterm ausschlie�lich mit - //Typvariablen ist - } - //Unify.SubstHashtableGeneric(((RefType)P.TA1), hts); //funktioniert nicht - Unify.SubstHashtableGeneric(((RefType)P.TA2), hts); //funktioniert nicht - // System.out.println(" TV!!!= " + TV.getName() ); - //Subst( P, 1, TV, Subst, false ); // linke Seite substituieren - //Subst( P, 2, TV, Subst, false ); // rechte Seite substituieren - // System.out.println(" nach Subst: P = " + P.toString() ); - // System.out.println(" Nach: PSuchen = " + PSuchen.toString() ); - // System.out.println(" Nach: " + P.toString() ); - - // Paar einfuegen, falls noch nicht vorhanden - // System.out.println("Paar alt:" + PSuchen.toString() ); - // System.out.println("Paar neu:" + P.toString() ); - if( !P.isInMenge( vFC ) ) - { - vFC.add( P ); - Unify.printMenge( "FC", vFC, 6 ); - bPaarHinzu = true; - } - //PL 04-12-29 - // else //unnoetig, da am Anfang bereits false gesetzt - // { - // bPaarHinzu = false; - // } - - } - } - } // end if: Substitution gefunden??? - } // end for: Typkonstruktor suchen - - - // Transitivitaet berechnen - for( int u = 0; u < vFC.size(); u++ ) - { - Pair PTemp = vFC.elementAt(u); - - // falls rechtes Paar = RefType - if( PTemp.TA2 instanceof RefType ) - { - RefType R = (RefType)PTemp.TA2; - - // rechte Seite auf linker Seite suchen - for( int e = 0; e < vFC.size(); e++ ) - { - Pair PSuch = vFC.elementAt(e); - // als linke Paarseite theortisch nur RefType's moeglich --> Cast - RefType RSuch = (RefType)PSuch.TA1; - - //if( R.getName().equals(RSuch.getName()) ) - if (R.is_Equiv(RSuch, new Hashtable())) //eingefuegt PL 05-01-07 - { - // Paar einfuegen, falls noch nicht vorhanden - RefType L1 = (RefType)PTemp.getTA1Copy(); - RefType L2 = (RefType)PTemp.getTA2Copy(); - RefType R1 = (RefType)PSuch.getTA1Copy(); - RefType R2 = (RefType)PSuch.getTA2Copy(); - - //zunaechst Variablen disjunkt machen ANFANG - // #JB# 05.04.2005 - // ########################################################### - Hashtable substHash1 = new Hashtable(); - Unify.varSubst(L1, substHash1); - Unify.varSubst(L2, substHash1); - Hashtable substHash2 = new Hashtable(); - Unify.varSubst(R1, substHash2); - Unify.varSubst(R2, substHash2); - // ########################################################### - //zunaechst Variablen disjunkt machen ENDE - - //Variablen so umbennen, dass transitiver Abschluss richtige - //Namen hat ANFANG - - // #JB# 05.04.2005 - // ########################################################### - Hashtable h = new Hashtable(); - L2.Equiv2Equal(R1, h); - Hashtable substHash3 = h; - Unify.varSubst(L1, substHash3); - Unify.varSubst(R2, substHash3); - // ########################################################### - //Variablen so umbennen, dass transitiver Abschluss richitge - //Namen hat ENDE - - //Pair P = new Pair( (RefType)PTemp.TA1, (RefType)PSuch.TA2 ); - Pair P = new Pair(L1, R2); - if( !P.isInMenge( vFC ) ) - { - vFC.add( P ); - bPaarHinzu = true; - } - else - { - bPaarHinzu = false; - } - } - } // end for: linke Seite suchen - } // end if: Element ist RefType - } // end for: Transitivit�ten berechnen - //PL HIER REFLEXIVE HUELLE EINFUEGEN - // 05-01-07 - - } // Ende WHILE - - /* z.B. - ******************************* - Menge nach trans: FC = { - (Vektor< A >, Vektor< A >), - (Vektor< A >, AbstractList< A >), - (Matrix< A >, Matrix< A >), - (Matrix< A >, Vektor< Vektor< A > >), - (ExMatrix< A >, ExMatrix< A >), - (ExMatrix< A >, Matrix< A >), - (Vektor< Vektor< A > >, Vektor< Vektor< A > >), - (Vektor< Vektor< A > >, AbstractList< Vektor< A > >), - (Matrix< A >, AbstractList< Vektor< A > >), - (ExMatrix< A >, Vektor< Vektor< A > >), - (ExMatrix< A >, AbstractList< Vektor< A > >) } - - ODER - - ******************************* - Menge nach trans: FC = { - (BB< A >, BB< A >), - (BB< A >, CC< A >), - (AA< A, B >, AA< A, B >), - (AA< A, B >, BB< DD< B, A > >), - (BB< DD< B, A > >, BB< DD< B, A > >), - (BB< DD< B, A > >, CC< DD< B, A > >), - (AA< A, B >, CC< DD< B, A > >) } - ******************************* - - ******************************* */ - - - // printMenge( "nach trans: FC", vFC, 6 ); - - Menge KlassenVektorunImportierteKlassen = new Menge<>(); - KlassenVektorunImportierteKlassen.addAll(basicAssumptionsClassMenge); - KlassenVektorunImportierteKlassen.addAll(KlassenVektor); - - FC_TTO fctto = new FC_TTO(vFC, tto, KlassenVektorunImportierteKlassen); - return fctto; - } - - public TypeAssumptions getPublicFieldAssumptions(){ - TypeAssumptions publicAssumptions = new TypeAssumptions(null); - //Alle PublicAssumptions der in dieser SourceFile enthaltenen Klassen sammeln: - for(Class klasse : KlassenVektor){ - publicAssumptions.add(klasse.getPublicFieldAssumptions()); - } - return publicAssumptions; - } - ///////////////////////////////////////////////////////////////////////// // TypeReconstructionAlgorithmus ///////////////////////////////////////////////////////////////////////// @@ -691,24 +237,32 @@ public class SourceFile typinferenzLog.debug("Von JRE erstellte Assumptions: "+importAssumptions, Section.TYPEINFERENCE); //FiniteClosure generieren: - FC_TTO finiteClosure = this.makeFC(globalAssumptions); + FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(globalAssumptions); typinferenzLog.debug("FiniteClosure: \n"+finiteClosure, Section.TYPEINFERENCE); ConstraintsSet oderConstraints = new ConstraintsSet(); //Alle Constraints der in dieser SourceFile enthaltenen Klassen sammeln: for(Class klasse : KlassenVektor){ - oderConstraints.add(klasse.typeReconstruction(finiteClosure, globalAssumptions)); + oderConstraints.add(klasse.typeReconstruction(globalAssumptions)); } + /*//////////////// + * Paare in MPairs umwandeln + * (Wird zunächst mal weggelassen. Constraints werden erst beim Unifizieren umgewandelt + *///////////////// + //UnifyTypeFactory.convert(oderConstraints); + + //////////////// //Karthesisches Produkt bilden: //////////////// //Unmögliche ConstraintsSets aussortieren durch Unifizierung - Unifier unifier = (pairs)->{ + Function,Menge>> unifier = (pairs)->{ Menge> retValue = new Menge<>(); - retValue = Unify.unify(pairs, finiteClosure); + Set convertPairs = UnifyTypeFactory.convert(pairs); + Set> unifiedPairs = new Unify().unify(convertPairs, finiteClosure); return retValue;}; //oderConstraints.filterWrongConstraints(unifier); @@ -716,17 +270,17 @@ public class SourceFile typinferenzLog.debug("Übriggebliebene Konstraints:\n"+oderConstraints+"\n", Section.TYPEINFERENCE); //Die Constraints in Pair's umwandeln (Karthesisches Produkt bilden): - Menge> xConstraints = oderConstraints.cartesianProduct(); + Set> xConstraints = oderConstraints.cartesianProduct(); typinferenzLog.debug("Karthesisches Produkt der Constraints: "+xConstraints, Section.TYPEINFERENCE); - finiteClosure.generateFullyNamedTypes(globalAssumptions); + //finiteClosure.generateFullyNamedTypes(globalAssumptions); ////////////////////////////// // Unifizierung der Constraints: ////////////////////////////// boolean unifyFail = true; - for(Menge constraints : xConstraints){ + for(Set constraints : xConstraints){ //Alle durch das Karthesische Produkt entstandenen Möglichkeiten durchgehen: Menge> result = new Menge>(); @@ -741,7 +295,7 @@ public class SourceFile } //Erst die Unifizierung erstellen: - Menge constraintsClone = (Menge)constraints.clone(); + Menge constraintsClone = (Menge)constraints.clone(); //IDEE: Man bildet Zusammenhangskomponenten von Paaren, die gemeinsame Variablen haben // und unifizert nur die Zusammenhangskomponenten in Schritten 1 - 5 @@ -762,17 +316,17 @@ public class SourceFile //Schritt 3: Umwandlung der Indizes in die zugehoerigen Elemente // In streamconstraintsclone sind die Mengen von Paar enthalten die unifiziert werden muessen - Stream> streamconstraintsclone = indexeset.stream().map(x -> x.stream() + Stream> streamconstraintsclone = indexeset.stream().map(x -> x.stream() .map(i -> constraintsClone.elementAt(i)) - .>collect(Menge::new, Menge::add, Menge::addAll)); + .>collect(Menge::new, Menge::add, Menge::addAll)); //Menge> vecconstraintsclone = streamconstraintsclone.collect(Menge::new, Menge::add, Menge::addAll); //System.out.println(); //Schritt 4: Unifikation - Menge>> vecunifyResult = + Set>> vecunifyResult = //streamconstraintsclone.map(x -> Unify.unify(x, finiteClosure)).collect(Menge::new, Menge::add, Menge::addAll); //DEBUG-Variante streamconstraintsclone.map(x -> - { Menge> z = Unify.unify(x, finiteClosure); + { Set> z = new Unify().unify(x, finiteClosure); return z; } ).collect(Menge::new, Menge::add, Menge::addAll); @@ -785,19 +339,19 @@ public class SourceFile //Schritt 5: Bildung des cartesischen Produkts //sollte wieder entfernt werden: Weiterarbeit mit: //[[x_1 -> t_1, x_2 -> t2], [x_1 -> t'_1, x_2 -> t'_2]] x ... x [[x_n -> t_1n], [x_n -> t2n], [x_n -> t3n]] - Menge> cardprodret_start = new Menge<>(); + Set> cardprodret_start = new Menge<>(); cardprodret_start.add(new Menge()); //cart. Produkt mit Linkverschiebung - Menge> unifyResult = vecunifyResult.stream().reduce(cardprodret_start, (x, y) -> { - Menge> cardprodret= new Menge<>(); + Set> unifyResult = vecunifyResult.stream().reduce(cardprodret_start, (x, y) -> { + Set> cardprodret= new Menge<>(); if (y.size() > 0) { //System.out.println(y); //Menge> cardprodretold = x; //cardprodret = new Menge<>(); for(int j = 0; j < x.size(); j++) { for (int k = 0; k < y.size(); k++){ - Menge help = new Menge<>(); + Set help = new Menge<>(); help.addAll(y.elementAt(k)); help.addAll(x.elementAt(j)); cardprodret.add(help); diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 6d2503f8..5e9d1876 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -11,7 +11,11 @@ import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.WildcardType; +import de.dhbwstuttgart.typeinference.KomplexeMenge; import de.dhbwstuttgart.typeinference.Menge; +import de.dhbwstuttgart.typeinference.OderMenge; +import de.dhbwstuttgart.typeinference.Pair; +import de.dhbwstuttgart.typeinference.UndMenge; import de.dhbwstuttgart.typeinference.assumptions.ClassAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; @@ -24,7 +28,7 @@ import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public class UnifyTypeFactory { - + public static FiniteClosure generateFC(TypeAssumptions fromAss){ HashSet pairs = new HashSet<>(); for(ClassAssumption cAss : fromAss.getClassAssumptions()){ @@ -44,7 +48,7 @@ public class UnifyTypeFactory { public static UnifyType convert(Type t){ //Es wurde versucht ein Typ umzuwandeln, welcher noch nicht von der Factory abgedeckt ist - if(t instanceof GenericTypeVar){ + if(t instanceof GenericTypeVar){ //WTF ? return UnifyTypeFactory.convert((GenericTypeVar)t); } System.out.println("Der Typ "+t+" kann nicht umgewandelt werden"); @@ -80,4 +84,12 @@ public class UnifyTypeFactory { public static UnifyType convert(GenericTypeVar t){ return new SimpleType(t.get_Name()); } + + public static UndMenge convert(UndMenge constraints) { + return null; + } + + public static OderMenge convert(OderMenge constraints) { + return null; + } } diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/Unify_FC_TTO_Builder.java b/src/de/dhbwstuttgart/syntaxtree/factory/Unify_FC_TTO_Builder.java index 524e729e..d28992cf 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/Unify_FC_TTO_Builder.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/Unify_FC_TTO_Builder.java @@ -22,10 +22,6 @@ public class Unify_FC_TTO_Builder { fc.add(new Pair(t1, t2)); } - public FC_TTO Get_FC_TTO() { - return new FC_TTO(fc, (Menge) fc.clone(), classes); - } - public void clear() { fc = new Menge(); classes = new Menge(); diff --git a/src/de/dhbwstuttgart/syntaxtree/type/RefType.java b/src/de/dhbwstuttgart/syntaxtree/type/RefType.java index ba03d583..00e808a9 100755 --- a/src/de/dhbwstuttgart/syntaxtree/type/RefType.java +++ b/src/de/dhbwstuttgart/syntaxtree/type/RefType.java @@ -29,8 +29,6 @@ import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResults; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionGenVar; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; @@ -182,41 +180,6 @@ public class RefType extends ObjectType implements IMatchable return name + "<"+para + " >" ; } } - // ino.end - - /** - * Wandelt die Parameter des RefTypes in TPHs um, sofern es sich um Generische Variablen handelt. - * @return - */ - // ino.method.GenericTypeVar2TypePlaceholder.26652.definition - public CSubstitutionSet GenericTypeVar2TypePlaceholder () - // ino.end - // ino.method.GenericTypeVar2TypePlaceholder.26652.body - { - //throw new NotImplementedException(); - ///* - CSubstitutionSet sub = new CSubstitutionSet(); - if(parameter != null) - { - for (int i = 0; i < parameter.size(); i++) - { - if (parameter.elementAt(i) instanceof GenericTypeVar) - { - TypePlaceholder tlv = TypePlaceholder.fresh(null); - sub.addElement(new CSubstitutionGenVar((GenericTypeVar)parameter.elementAt(i), tlv)); - parameter.set(i, tlv); - } - if (parameter.elementAt(i) instanceof RefType) - { - CSubstitutionSet parasub = ((RefType)parameter.elementAt(i)).GenericTypeVar2TypePlaceholder(); - sub.addAll(parasub); //korrigiert PL 07=07=29 - } - } - } - return sub; - //*/ - } - // ino.end /** * Wandelt die Parameter des RefTypes in TPHs um, sofern es sich um Generische Variablen handelt. diff --git a/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java b/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java index 5c8524a8..84475cbf 100755 --- a/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java +++ b/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java @@ -1,6 +1,7 @@ package de.dhbwstuttgart.typeinference; import java.util.Iterator; +import java.util.Set; import java.util.Vector; import de.dhbwstuttgart.logger.Logger; import de.dhbwstuttgart.logger.*; @@ -57,12 +58,12 @@ public class ConstraintsSet extends UndMenge implements Iterable{ - Menge undConstraintsUndPairs = new Menge<>(); + Set undConstraintsUndPairs = new Menge<>(); undConstraintsUndPairs.addAll(pairs); undConstraintsUndPairs.addAll(alleUndConstraints); log.debug("Versuche Pairs auszusondern:\n"+pairs, Section.TYPEINFERENCE); log.debug("Unifiziere:\n"+undConstraintsUndPairs, Section.TYPEINFERENCE); - Menge> unifyResult = unifier.apply(undConstraintsUndPairs); + Set> unifyResult = unifier.apply(undConstraintsUndPairs); return unifyResult; }); } diff --git a/src/de/dhbwstuttgart/typeinference/KomplexeMenge.java b/src/de/dhbwstuttgart/typeinference/KomplexeMenge.java index 25ca29e8..f72d991d 100644 --- a/src/de/dhbwstuttgart/typeinference/KomplexeMenge.java +++ b/src/de/dhbwstuttgart/typeinference/KomplexeMenge.java @@ -1,6 +1,8 @@ package de.dhbwstuttgart.typeinference; +import java.util.Set; + public interface KomplexeMenge{ - Menge> getSet(); - Menge> cartesianProduct(); + Set> getSet(); + Set> cartesianProduct(); } \ No newline at end of file diff --git a/src/de/dhbwstuttgart/typeinference/OderConstraint.java b/src/de/dhbwstuttgart/typeinference/OderConstraint.java index 3896b115..7b88223e 100755 --- a/src/de/dhbwstuttgart/typeinference/OderConstraint.java +++ b/src/de/dhbwstuttgart/typeinference/OderConstraint.java @@ -1,5 +1,6 @@ package de.dhbwstuttgart.typeinference; +import java.util.Set; import java.util.Vector; import de.dhbwstuttgart.logger.Logger; @@ -10,7 +11,7 @@ import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.typeinference.unify.Unifier; public class OderConstraint extends OderMenge{ - private Menge oderConstraintPairs; + private Set oderConstraintPairs; private final static Logger logger = Logger.getLogger(OderConstraint.class.getName()); @@ -70,7 +71,7 @@ public class OderConstraint extends OderMenge{ return ret+"]"; } - public Vector getUndConstraints() { + public Set getUndConstraints() { return this.oderConstraintPairs; /* Vector ret = new Vector(); @@ -91,9 +92,9 @@ public class OderConstraint extends OderMenge{ * @param unifier - Wird für die Unifizierung benutzt */ void filterWrongConstraints(Unifier unifier) { - Menge filteredConstraints = new Menge<>(); + Set filteredConstraints = new Menge<>(); for(UndConstraint cons : this.getUndConstraints()){ - Menge> unifierResult = unifier.apply(cons.getConstraintPairs()); + Set> unifierResult = unifier.apply(cons.getConstraintPairs()); if(!unifierResult.isEmpty()){ filteredConstraints.add(cons); }else{ @@ -111,7 +112,7 @@ public class OderConstraint extends OderMenge{ } @Override - public Menge> getSet() { + public Set> getSet() { return this.oderConstraintPairs; } diff --git a/src/de/dhbwstuttgart/typeinference/OderMenge.java b/src/de/dhbwstuttgart/typeinference/OderMenge.java index 4781d641..842c78a3 100644 --- a/src/de/dhbwstuttgart/typeinference/OderMenge.java +++ b/src/de/dhbwstuttgart/typeinference/OderMenge.java @@ -2,6 +2,7 @@ package de.dhbwstuttgart.typeinference; import java.util.Collection; import java.util.Iterator; +import java.util.Set; import de.dhbwstuttgart.typeinference.Menge; import de.dhbwstuttgart.logger.Logger; @@ -13,11 +14,11 @@ import de.dhbwstuttgart.typeinference.unify.Unifier; public abstract class OderMenge implements KomplexeMenge{ - public abstract Menge> getSet(); + public abstract Set> getSet(); @Override - public Menge> cartesianProduct() { - Menge> ret = new Menge<>(); + public Set> cartesianProduct() { + Set> ret = new Menge<>(); for(KomplexeMenge km : this.getSet()){ ret.addAll(km.cartesianProduct()); } diff --git a/src/de/dhbwstuttgart/typeinference/UndMenge.java b/src/de/dhbwstuttgart/typeinference/UndMenge.java index 6771bf18..146121d7 100644 --- a/src/de/dhbwstuttgart/typeinference/UndMenge.java +++ b/src/de/dhbwstuttgart/typeinference/UndMenge.java @@ -3,24 +3,25 @@ package de.dhbwstuttgart.typeinference; import de.dhbwstuttgart.typeinference.unify.Unify; import java.util.Collection; import java.util.Iterator; +import java.util.Set; //import com.rits.cloning.Cloner; -public abstract class UndMenge implements KomplexeMenge{ +public abstract class UndMenge implements KomplexeMenge{ public abstract Menge> getSet(); @Override - public Menge> cartesianProduct() { - Menge> ret = null; + public Set> cartesianProduct() { + Set> ret = null; //Cloner cloner = new Cloner(); for(KomplexeMenge km : this.getSet()){ if(ret == null){ ret = km.cartesianProduct(); }else{ - Menge> cartesianProduct = new Menge<>(); - for(Menge r : ret)for(Menge m : km.cartesianProduct()){ //Für jedes Element aus dem Karthesischen Produkt: - Menge undElement = new Menge(); + Set> cartesianProduct = new Menge<>(); + for(Set r : ret)for(Set m : km.cartesianProduct()){ //Für jedes Element aus dem Karthesischen Produkt: + Set undElement = new Menge(); undElement.addAll(Unify.deepClone(r)); undElement.addAll(m); cartesianProduct.add(undElement); @@ -28,7 +29,7 @@ public abstract class UndMenge implements KomplexeMenge ret = cartesianProduct; } } - if(ret == null)return new Menge>(); + if(ret == null)return new Menge<>(); return ret; } diff --git a/src/de/dhbwstuttgart/typeinference/unify/CSet.java b/src/de/dhbwstuttgart/typeinference/unify/CSet.java deleted file mode 100755 index 08af741d..00000000 --- a/src/de/dhbwstuttgart/typeinference/unify/CSet.java +++ /dev/null @@ -1,72 +0,0 @@ -// ino.module.CSet.8698.package -package de.dhbwstuttgart.typeinference.unify; -// ino.end - -// ino.module.CSet.8698.import -import java.util.Iterator; -// ino.end - -// ino.class.CSet.27435.description type=javadoc -/** - * - * @author Jrg Buerle - * @version $date - */ -// ino.end -// ino.class.CSet.27435.declaration -public abstract class CSet implements Iterable -// ino.end -// ino.class.CSet.27435.body -{ - // ino.method.addElement.27438.declaration - public abstract void addElement(E element); - // ino.end - // ino.method.removeElement.27441.declaration - public abstract void removeElement(E element); - // ino.end - // ino.method.unite.27444.declaration - public abstract void unite(CSet anotherSet); - // ino.end - // ino.method.subtract.27447.declaration - public abstract void subtract(CSet anotherSet); - // ino.end - // ino.method.shallowCopy.27450.declaration - public abstract CSet shallowCopy(); - // ino.end - // ino.method.deepCopy.27453.declaration - public abstract CSet deepCopy(); - // ino.end - // ino.method.contains.27456.declaration - public abstract boolean contains(E element); - // ino.end - // ino.method.getCardinality.27459.declaration - public abstract int getCardinality(); - // ino.end - // ino.method.getIterator.27462.declaration - public abstract Iterator getIterator(); - // ino.end - // ino.method.equals.27465.declaration - public abstract boolean equals(Object obj); - // ino.end - - // ino.method.toString.27468.definition - public String toString() - // ino.end - // ino.method.toString.27468.body - { - StringBuffer sb = new StringBuffer(); - sb.append("Set {\n"); - Iterator it = this.getIterator(); - while(it.hasNext()){ - sb.append(it.next().toString()); - sb.append(",\n"); - } - if(this.getCardinality()>0){ - sb.delete(sb.length()-2, sb.length()-1); - } - sb.append("}"); - return sb.toString(); - } - // ino.end -} -// ino.end diff --git a/src/de/dhbwstuttgart/typeinference/unify/CSubstitution.java b/src/de/dhbwstuttgart/typeinference/unify/CSubstitution.java deleted file mode 100755 index fc9d6705..00000000 --- a/src/de/dhbwstuttgart/typeinference/unify/CSubstitution.java +++ /dev/null @@ -1,253 +0,0 @@ -// ino.module.CSubstitution.8685.package -package de.dhbwstuttgart.typeinference.unify; -// ino.end - -// ino.module.CSubstitution.8685.import -import java.util.Iterator; -import de.dhbwstuttgart.typeinference.Menge; - -import de.dhbwstuttgart.logger.Logger; -// ino.end - - - - - - - - - -import de.dhbwstuttgart.myexception.CTypeReconstructionException; -import de.dhbwstuttgart.syntaxtree.type.GenericTypeVar; -import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.syntaxtree.type.Type; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.Pair; - -// ino.class.CSubstitution.27003.description type=javadoc -/** - * Implementierung einer Typsubstitution. Bildet eine zu ersetzende - * TypePlaceholder auf einen Substitutions-Typ ab. Instanzen dieser - * Klasse werden in der Regel aus - * Pair-Objekten erzeugt. - * @author J�rg B�uerle - * @version $Date: 2006/07/10 11:27:04 $ - */ -// ino.end -// ino.class.CSubstitution.27003.declaration -public class CSubstitution -// ino.end -// ino.class.CSubstitution.27003.body -{ - // ino.attribute.m_TypeVar.27006.declaration - private TypePlaceholder m_TypeVar = null; - // ino.end - // ino.attribute.m_Type.27009.declaration - protected Type m_Type = null; - // ino.end - // ino.attribute.inferencelog.27012.declaration - protected static Logger inferencelog = Logger.getLogger("inference"); - // ino.end - // ino.method.CSubstitution.27015.definition - public CSubstitution() - // ino.end - // ino.method.CSubstitution.27015.body - { - this(null, null); - } - // ino.end - - // ino.method.CSubstitution.27018.definition - public CSubstitution(TypePlaceholder typeVar, Type type) - // ino.end - // ino.method.CSubstitution.27018.body - { - m_TypeVar = typeVar; - m_Type = type; - } - // ino.end - - // ino.method.CSubstitution.27021.definition - public CSubstitution(Pair unifier) - throws CTypeReconstructionException - // ino.end - // ino.method.CSubstitution.27021.body - { - if(!(unifier.TA1 instanceof TypePlaceholder)){ - throw new CTypeReconstructionException("Unifier enth�lt keinen Typeplaceholder",unifier.TA1); - } - m_TypeVar = (TypePlaceholder)unifier.TA1; - m_Type = unifier.TA2; - } - // ino.end - - - // ino.method.getType.27024.defdescription type=javadoc - /** - * Author: J�rg B�uerle
- * @return Returns the Type. - */ - // ino.end - // ino.method.getType.27024.definition - public Type getType() - // ino.end - // ino.method.getType.27024.body - { - return m_Type; - } - // ino.end - - // ino.method.setType.27027.defdescription type=javadoc - /** - * Author: J�rg B�uerle
- * @param type The Type to set. - */ - // ino.end - // ino.method.setType.27027.definition - public void setType(Type type) - // ino.end - // ino.method.setType.27027.body - { - m_Type = type; - } - // ino.end - - // ino.method.getTypeVar.27030.defdescription type=javadoc - /** - * Author: J�rg B�uerle
- * @return Returns the TypeVar. - */ - // ino.end - // ino.method.getTypeVar.27030.definition - public Type getTypeVar() - // ino.end - // ino.method.getTypeVar.27030.body - { - return this.m_TypeVar; - } - // ino.end - - // ino.method.setTypeVar.27033.defdescription type=javadoc - /** - * Author: J�rg B�uerle
- * @param typeVar The TypeVar to set. - */ - // ino.end - // ino.method.setTypeVar.27033.definition - public void setTypeVar(TypePlaceholder typeVar) - // ino.end - // ino.method.setTypeVar.27033.body - { - m_TypeVar = typeVar; - } - // ino.end - - // ino.method.equals.27036.definition - public boolean equals(Object obj) - // ino.end - // ino.method.equals.27036.body - { - if(obj instanceof CSubstitution){ - CSubstitution sub = (CSubstitution)obj; - boolean ret = true; - ret &= (m_TypeVar.equals(sub.m_TypeVar)); - ret &= (m_Type.equals(sub.m_Type)); - return ret; - } - else{ - return false; - } - } - // ino.end - - // ino.method.toString.27039.definition - public String toString() - // ino.end - // ino.method.toString.27039.body - { - //return m_TypeVar.getName() +" --> "+m_Type.getName(); - return m_TypeVar.toString() +" --> "+m_Type.toString(); - } - // ino.end - - // ino.method.clone.27042.definition - public CSubstitution clone() - // ino.end - // ino.method.clone.27042.body - { - CSubstitution copy = new CSubstitution(m_TypeVar.clone(), m_Type.clone()); - return copy; - } - // ino.end - - - // ino.method.applyUnifier.27048.defdescription type=javadoc - /** - * Wendet den Unifier auf die rechte Seite dieser Substitution an. - *
Author: J�rg B�uerle - * @param unifier - */ - // ino.end - // ino.method.applyUnifier.27048.definition - public void applyUnifier(CSubstitutionSet unifier) - // ino.end - // ino.method.applyUnifier.27048.body - { - Iterator pairIt = unifier.getIterator(); - while(pairIt.hasNext()){ - CSubstitution subst = (CSubstitution)pairIt.next(); - - //korrigiert PL 05-07-31 das erste duerfte doch richtig sein. - //subst.setType(this.applySubstitution(subst.getType(), subst)); - this.setType(this.applySubstitution(this.getType(), subst)); - } - - } - // ino.end - - // ino.method.applySubstitution.27051.defdescription type=javadoc - /** - * Wendet die �bergebene Substitution rekursiv auf den �bergebenen Typ an. - *
Author: J�rg B�uerle - * @param type Der zu untersuchende Typ - * @param unifierSub Die anzuwendende Substitution - * @return Den ermittelnden Typ - */ - // ino.end - // ino.method.applySubstitution.27051.definition - private Type applySubstitution(Type type, CSubstitution unifierSub) - // ino.end - // ino.method.applySubstitution.27051.body - { - if(type instanceof TypePlaceholder){ - if(type.equals(unifierSub.getTypeVar())){ - return unifierSub.getType(); - } - } - else if(type instanceof GenericTypeVar){ - if(type.equals(unifierSub.getTypeVar())){ - return unifierSub.getType(); - } - } - else if(type instanceof RefType){ - Menge paras = ((RefType)type).get_ParaList(); - if(paras != null){ - for(int i=0; iTypePlaceholder auf einen Substitutions-Typ ab. Instanzen dieser - * Klasse werden in der Regel aus - * Pair-Objekten erzeugt. - * @author Martin Pl�micke - * @version $Date: 2006/06/13 10:37:32 $ - */ -// ino.end -// ino.class.CSubstitutionGenVar.27057.declaration -public class CSubstitutionGenVar extends CSubstitution -// ino.end -// ino.class.CSubstitutionGenVar.27057.body -{ - // ino.attribute.m_TypeVar.27061.declaration - private GenericTypeVar m_TypeVar = null; - // ino.end - - // ino.method.CSubstitutionGenVar.27064.definition - public CSubstitutionGenVar() - // ino.end - // ino.method.CSubstitutionGenVar.27064.body - { - this(null, null); - } - // ino.end - - // ino.method.CSubstitutionGenVar.27067.definition - public CSubstitutionGenVar(GenericTypeVar typeVar, Type type) - // ino.end - // ino.method.CSubstitutionGenVar.27067.body - { - m_TypeVar = typeVar; - m_Type = type; - } - // ino.end - - // ino.method.getTypeVar.27070.defdescription type=javadoc - /** - * Author: J�rg B�uerle
- * @return Returns the TypeVar. - */ - // ino.end - // ino.method.getTypeVar.27070.definition - public Type getTypeVar() - // ino.end - // ino.method.getTypeVar.27070.body - { - return this.m_TypeVar; - } - // ino.end - - // ino.method.toString.27073.definition - public String toString() - // ino.end - // ino.method.toString.27073.body - { - return this.m_TypeVar.getName() +" --> "+this.m_Type.getName(); - } - // ino.end -} -// ino.end diff --git a/src/de/dhbwstuttgart/typeinference/unify/CSubstitutionSet.java b/src/de/dhbwstuttgart/typeinference/unify/CSubstitutionSet.java deleted file mode 100755 index 481ca7cf..00000000 --- a/src/de/dhbwstuttgart/typeinference/unify/CSubstitutionSet.java +++ /dev/null @@ -1,111 +0,0 @@ -// ino.module.CSubstitutionSet.8699.package -package de.dhbwstuttgart.typeinference.unify; -// ino.end - -// ino.module.CSubstitutionSet.8699.import -import java.util.Iterator; -import de.dhbwstuttgart.typeinference.Menge; - -import de.dhbwstuttgart.myexception.CTypeReconstructionException; -import de.dhbwstuttgart.syntaxtree.type.Type; -import de.dhbwstuttgart.typeinference.Pair; - -// ino.class.CSubstitutionSet.27471.description type=javadoc -/** - * @author J�rg B�uerle - * @version $Date: 2013/03/27 18:29:34 $ - */ -// ino.end -// ino.class.CSubstitutionSet.27471.declaration -public class CSubstitutionSet extends CVectorSet -// ino.end -// ino.class.CSubstitutionSet.27471.body -{ - // ino.method.CSubstitutionSet.27475.definition - public CSubstitutionSet() - // ino.end - // ino.method.CSubstitutionSet.27475.body - { - super(); - } - // ino.end - - // ino.method.CSubstitutionSet.27478.definition - public CSubstitutionSet(Menge unifiers) - throws CTypeReconstructionException - // ino.end - // ino.method.CSubstitutionSet.27478.body - { - super(); - for(int i=0; i substIter = this.getIterator(); - while(substIter.hasNext()){ - copy.addElement(substIter.next().clone()); - } - return copy; - } - // ino.end - - // ino.method.applyUnifier.27487.defdescription type=javadoc - /** - * Wendet den Unifier auf die rechten Seiten alle Substitutionen an. - *
Author: J�rg B�uerle - * @param unifier - */ - // ino.end - // ino.method.applyUnifier.27487.definition - public void applyUnifier(CSubstitutionSet unifier) - // ino.end - // ino.method.applyUnifier.27487.body - { - Iterator substIt = this.getIterator(); - - while(substIt.hasNext()){ - substIt.next().applyUnifier(unifier); - } - } - // ino.end - - // ino.method.applyThisSubstitutionSet.27490.definition - public Type applyThisSubstitutionSet(Type type) - // ino.end - // ino.method.applyThisSubstitutionSet.27490.body - { - Iterator substIt = this.getIterator(); - Type ty = type; - - while(substIt.hasNext()) { - ty = substIt.next().applyThisSubstitution(ty); - } - return ty; - } - // ino.end - - - public Iterator iterator() { - return this.getIterator(); - } -} -// ino.end diff --git a/src/de/dhbwstuttgart/typeinference/unify/CVectorSet.java b/src/de/dhbwstuttgart/typeinference/unify/CVectorSet.java deleted file mode 100755 index 5fc6146f..00000000 --- a/src/de/dhbwstuttgart/typeinference/unify/CVectorSet.java +++ /dev/null @@ -1,165 +0,0 @@ -// ino.module.CMengeSet.8702.package -package de.dhbwstuttgart.typeinference.unify; -// ino.end - -// ino.module.CMengeSet.8702.import -import java.util.Iterator; -import de.dhbwstuttgart.typeinference.Menge; -// ino.end - -// ino.class.CMengeSet.27519.description type=javadoc -/** - * @author J�rg B�uerle - * @version $Date: 2013/02/07 05:08:51 $ - */ -// ino.end -// ino.class.CMengeSet.27519.declaration -public abstract class CVectorSet extends CSet -// ino.end -// ino.class.CMengeSet.27519.body -{ - // ino.attribute.m_Elements.27523.declaration - private Menge m_Elements = null; - // ino.end - - // ino.method.CMengeSet.27526.definition - public CVectorSet() - // ino.end - // ino.method.CMengeSet.27526.body - { - m_Elements = new Menge(); - } - // ino.end - - // ino.method.addElement.27529.definition - public void addElement(E element) - // ino.end - // ino.method.addElement.27529.body - { - m_Elements.addElement(element); - } - // ino.end - - // ino.method.removeElement.27532.definition - public void removeElement(E element) - // ino.end - // ino.method.removeElement.27532.body - { - m_Elements.addElement(element); - } - // ino.end - - public void addAll( CVectorSet set ) - { - for( int i=0;i getIterator() - // ino.end - // ino.method.getIterator.27535.body - { - return m_Elements.iterator(); - } - // ino.end - - // ino.method.getMenge.27538.definition - public Menge getMenge() - // ino.end - // ino.method.getMenge.27538.body - { - return m_Elements; - } - // ino.end - - // ino.method.setMenge.27541.definition - public void setMenge(Menge elements) - // ino.end - // ino.method.setMenge.27541.body - { - m_Elements = elements; - } - // ino.end - - /** - * Fügt ein CMengeSet an! - * Es handelt sich um eine Vereinigung (es werden keine bereits vorhandenen Elemente übernommen) - * @param anotherSet Das hinzuzufügende CMengeSet (CSet wird ignoriert) - */ - // ino.method.unite.27544.definition - public void unite(CSet anotherSet) - // ino.end - // ino.method.unite.27544.body - { - if(!(anotherSet instanceof CVectorSet)){ - return; - } - CVectorSet MengeSet = (CVectorSet)anotherSet; - - // Elemente der anderen Menge hinzuf�gen: - Iterator it = MengeSet.getIterator(); - while(it.hasNext()){ - E elem = it.next(); - if(!m_Elements.contains(elem)){ - m_Elements.addElement(elem); - } - } - //m_Elements.addAll(MengeSet.m_Elements); - } - // ino.end - - // ino.method.subtract.27547.definition - public void subtract(CSet anotherSet) - // ino.end - // ino.method.subtract.27547.body - { - if(!(anotherSet instanceof CVectorSet)){ - return; - } - CVectorSet MengeSet = (CVectorSet)anotherSet; - - // Elemente der anderen Menge entfernen: - m_Elements.removeAll(MengeSet.m_Elements); - } - // ino.end - - // ino.method.contains.27550.definition - public boolean contains(E element) - // ino.end - // ino.method.contains.27550.body - { - return m_Elements.contains(element); - } - // ino.end - - // ino.method.equals.27553.definition - public boolean equals(Object obj) - // ino.end - // ino.method.equals.27553.body - { - if(obj instanceof CVectorSet){ - CVectorSet tripSet= (CVectorSet)obj; - boolean ret = true; - ret &= (m_Elements.containsAll(tripSet.m_Elements)); - ret &= (tripSet.m_Elements.containsAll(m_Elements)); - return ret; - } - else{ - return false; - } - } - // ino.end - - // ino.method.getCardinality.27556.definition - public int getCardinality() - // ino.end - // ino.method.getCardinality.27556.body - { - return m_Elements.size(); - } - // ino.end -} -// ino.end diff --git a/src/de/dhbwstuttgart/typeinference/unify/FC_TTO.java b/src/de/dhbwstuttgart/typeinference/unify/FC_TTO.java deleted file mode 100755 index f27119a6..00000000 --- a/src/de/dhbwstuttgart/typeinference/unify/FC_TTO.java +++ /dev/null @@ -1,82 +0,0 @@ -// ino.module.FC_TTO.8719.package -package de.dhbwstuttgart.typeinference.unify; -// ino.end - -// ino.module.FC_TTO.8719.import -import de.dhbwstuttgart.typeinference.Menge; - -import de.dhbwstuttgart.syntaxtree.Class; -import de.dhbwstuttgart.typeinference.Pair; -import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; - -// ino.class.FC_TTO.28013.description type=javadoc -/** - * Hilfsklasse f�r den Unifizierungsalgorithmus - * @author Martin Pl�micke - * @version $Date: 2013/05/12 14:00:05 $ - */ -// ino.end -// ino.class.FC_TTO.28013.declaration -public class FC_TTO -// ino.end -// ino.class.FC_TTO.28013.body -{ - - // ino.attribute.FC.28016.declaration - Menge FC; - // ino.end - // ino.attribute.TTO.28019.declaration - Menge TTO; - // ino.end - - Menge CLASSVEC; - - // ino.method.FC_TTO.28022.definition - public FC_TTO(Menge fc, Menge tto, Menge classv) - // ino.end - // ino.method.FC_TTO.28022.body - { - - this.FC = fc; - this.TTO = tto; - this.CLASSVEC = classv; - - } - // ino.end - - // ino.method.getFC.28025.definition - public Menge getFC() - // ino.end - // ino.method.getFC.28025.body - { - return FC; - } - // ino.end - - // ino.method.getTTO.28028.definition - public Menge getTTO() - // ino.end - // ino.method.getTTO.28028.body - { - return TTO; - } - // ino.end - - public Menge getClasses() - { - return CLASSVEC; - } - - @Override - public String toString(){ - return "FC: "+getFC()+"\nTTO: "+getTTO()+"\nCLASSVEC: "+getClasses(); - } - - public void generateFullyNamedTypes(TypeAssumptions ass) { - for(Pair p : this.FC){ - p.TA1 = p.TA1.TYPE(ass, p.TA1.getParent());//ass.getTypeFor(p.TA1, p.TA1.getParent()).getType(); - p.TA2 = p.TA2.TYPE(ass, p.TA2.getParent());//ass.getTypeFor(p.TA2, p.TA2.getParent()).getType(); - } - } -} -// ino.end diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/GuavaSetOperations.java b/src/de/dhbwstuttgart/typeinference/unify/GuavaSetOperations.java similarity index 84% rename from src/de/dhbwstuttgart/typeinference/unifynew/GuavaSetOperations.java rename to src/de/dhbwstuttgart/typeinference/unify/GuavaSetOperations.java index cc4e907c..ba456841 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/GuavaSetOperations.java +++ b/src/de/dhbwstuttgart/typeinference/unify/GuavaSetOperations.java @@ -1,4 +1,4 @@ -package de.dhbwstuttgart.typeinference.unifynew; +package de.dhbwstuttgart.typeinference.unify; import java.util.List; import java.util.Set; diff --git a/src/de/dhbwstuttgart/typeinference/unify/MUB.java b/src/de/dhbwstuttgart/typeinference/unify/MUB.java deleted file mode 100755 index 42e70c64..00000000 --- a/src/de/dhbwstuttgart/typeinference/unify/MUB.java +++ /dev/null @@ -1,53 +0,0 @@ -// ino.module.MUB.8720.package -package de.dhbwstuttgart.typeinference.unify; -// ino.end - -// ino.module.MUB.8720.import -import de.dhbwstuttgart.typeinference.Menge; - -import de.dhbwstuttgart.syntaxtree.type.Type; -import de.dhbwstuttgart.typeinference.Pair; - -// ino.class.MUB.28031.declaration -public class MUB -// ino.end -// ino.class.MUB.28031.body -{ - // ino.attribute.Mub.28034.declaration - Menge Mub; - // ino.end - // ino.attribute.sigma.28037.declaration - Menge sigma; - // ino.end - - // ino.method.MUB.28040.definition - MUB(Menge M, Menge s) - // ino.end - // ino.method.MUB.28040.body - { - Mub = M; - sigma = s; - } - // ino.end - - // ino.method.getUnifier.28043.definition - public Menge getUnifier() - // ino.end - // ino.method.getUnifier.28043.body - { - return sigma; - } - // ino.end - - // ino.method.getMub.28046.definition - public Menge getMub() - // ino.end - // ino.method.getMub.28046.body - { - return Mub; - } - // ino.end - -} -// ino.end - diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Mapping.java b/src/de/dhbwstuttgart/typeinference/unify/Mapping.java similarity index 96% rename from src/de/dhbwstuttgart/typeinference/unifynew/Mapping.java rename to src/de/dhbwstuttgart/typeinference/unify/Mapping.java index e21bb728..603fb0f7 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Mapping.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Mapping.java @@ -1,4 +1,4 @@ -package de.dhbwstuttgart.typeinference.unifynew; +package de.dhbwstuttgart.typeinference.unify; import java.util.HashMap; import java.util.HashSet; diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java b/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java similarity index 95% rename from src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java rename to src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java index 858fd80a..b411e7fe 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java @@ -1,4 +1,4 @@ -package de.dhbwstuttgart.typeinference.unifynew; +package de.dhbwstuttgart.typeinference.unify; import java.util.AbstractMap; import java.util.ArrayList; diff --git a/src/de/dhbwstuttgart/typeinference/unify/ParallelUnify.java b/src/de/dhbwstuttgart/typeinference/unify/ParallelUnify.java deleted file mode 100644 index fffceb53..00000000 --- a/src/de/dhbwstuttgart/typeinference/unify/ParallelUnify.java +++ /dev/null @@ -1,44 +0,0 @@ -package de.dhbwstuttgart.typeinference.unify; - -import de.dhbwstuttgart.typeinference.Menge; -import java.util.stream.Stream; - -import de.dhbwstuttgart.typeinference.ConstraintsSet; -import de.dhbwstuttgart.typeinference.Pair; - -public class ParallelUnify { - - public ParallelUnify(ConstraintsSet constraints){ - //constraints.getConstraints(); - } - - private CartesianProduct parallelCartProd(){ - - return null; - } - - private UnifyResult parallelUnify(Menge pairs, FC_TTO fc){ - UnifyResult ret = new UnifyResult(); - return ret; - } - - public UnifyResult unify(){ - UnifyResult ret = new UnifyResult(); - return ret; - } - -} - -class ParallelConstraintSet extends ConstraintsSet{ - Stream parallelGetConstraints(){ - return null; - } -} - -class UnifyResult{ - -} - -class CartesianProduct{ - -} \ No newline at end of file diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java similarity index 96% rename from src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java rename to src/de/dhbwstuttgart/typeinference/unify/RuleSet.java index fedccd86..51616be3 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -1,4 +1,4 @@ -package de.dhbwstuttgart.typeinference.unifynew; +package de.dhbwstuttgart.typeinference.unify; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/Unifier.java deleted file mode 100644 index 19446236..00000000 --- a/src/de/dhbwstuttgart/typeinference/unify/Unifier.java +++ /dev/null @@ -1,11 +0,0 @@ -package de.dhbwstuttgart.typeinference.unify; - -import de.dhbwstuttgart.typeinference.Menge; - -import de.dhbwstuttgart.typeinference.Pair; - -public interface Unifier { - - public Menge> apply (Menge E); - -} diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unify.java b/src/de/dhbwstuttgart/typeinference/unify/Unify.java old mode 100755 new mode 100644 index 8cd2baa9..cb2cf3c4 --- a/src/de/dhbwstuttgart/typeinference/unify/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unify.java @@ -1,3563 +1,480 @@ -//otth/pluemicke2.1.jav funktioniert nicht xxx anschauen -// ino.module.Unify.8721.package -package de.dhbwstuttgart.typeinference.unify; -import java.util.Collection; -// ino.end -// ino.module.Unify.8721.import -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.function.Function; -import java.util.stream.Stream; - -import de.dhbwstuttgart.logger.Logger; -import de.dhbwstuttgart.logger.Section; -import de.dhbwstuttgart.logger.SectionLogger; -import de.dhbwstuttgart.logger.Timestamp; -import de.dhbwstuttgart.logger.Timewatch; -import de.dhbwstuttgart.core.MyCompiler; -import de.dhbwstuttgart.myexception.CTypeReconstructionException; -import de.dhbwstuttgart.myexception.MatchException; -import de.dhbwstuttgart.myexception.SCException; -import de.dhbwstuttgart.parser.JavaClassName; -import de.dhbwstuttgart.syntaxtree.Class; -import de.dhbwstuttgart.syntaxtree.type.BoundedGenericTypeVar; -import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; -import de.dhbwstuttgart.syntaxtree.type.FreshExtendsWildcardType; -import de.dhbwstuttgart.syntaxtree.type.FreshSuperWildcardType; -import de.dhbwstuttgart.syntaxtree.type.FreshWildcardType; -import de.dhbwstuttgart.syntaxtree.type.GenericTypeVar; -import de.dhbwstuttgart.syntaxtree.type.IMatchable; -import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; -import de.dhbwstuttgart.syntaxtree.type.Type; -import de.dhbwstuttgart.syntaxtree.type.ObjectType; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.syntaxtree.type.WildcardType; -import de.dhbwstuttgart.typeinference.DeepCloneable; -import de.dhbwstuttgart.typeinference.Menge; -import de.dhbwstuttgart.typeinference.Pair; -import de.dhbwstuttgart.typeinference.Pair.PairOperator; - -// ino.end - -// ino.class.Unify.28049.description type=javadoc -/** - * Implementierung des Unifizierungsalgorithmus - * @author Martin Pl�micke, Thomas Ott - * @version $Date: 2013/05/22 22:23:50 $ - */ -// ino.end -// ino.class.Unify.28049.declaration -public class Unify -// ino.end -// ino.class.Unify.28049.body -{ - - // ino.attribute.inferencelog.28052.declaration - protected static SectionLogger inferencelog = Logger.getSectionLogger("inference", Section.UNIFY); - // ino.end - - /** - * Unifiziert ein Pair mit den Elementen ty1 und ty2 -> (ty1 < ty2) - * @param ty1 - * @param ty2 - * @param fc_tto - * @return - */ - // ino.method.unify.28055.definition - public static Menge> unify(Type ty1, Type ty2, FC_TTO fc_tto ) - // ino.end - // ino.method.unify.28055.body - { - Menge pairsToUnify = new Menge(); - Pair retTypePair = new Pair(ty1, ty2); - pairsToUnify.addElement(retTypePair); - return Unify.unify(pairsToUnify, fc_tto); - } - // ino.end - - - /** - * Einstieg in die Unifizierung mit Wildcards - * - * @param ty1 - Typ 1 der Unifizierung - * @param ty2 - Typ 2 der Unifizierung - * @param fc_tto - Hilfsklasse mit FC - * @return Menge> - Ergebnispaare - */ - public static Menge> unifyWC(Type ty1, Type ty2, FC_TTO fc_tto) - { - return unifyWC(new Pair(ty1,ty2),fc_tto); - } - - /** - * Einstieg in die Unifizierung mit Wildcards - * - * @param P - Paar das unifiziert werden soll. - * @param fc_tto - Hilfsklasse mit FC - * @return Menge> - Ergebnispaare - */ - public static Menge> unifyWC (Pair P, FC_TTO fc_tto) - { - Menge tmp = new Menge(); - tmp.add(P); - return unify(tmp,fc_tto); - } - - /** - * Einstieg in die Unifizierung mit Wildcards - * - * @param E - Menge von Paaren die unifiziert werden sollen - * @param fc_tto - Hilfsklasse mit FC - * @return Menge> - Ergebnispaare - * Entweder alle Elemente in solved Form [A =. type, B =. type2, ...] - * oder alle Elemente in der Form [A <. B, C <. D, ..., E in Typ A ...> werden keine ? extends-, ? super-Typen erzeugt - */ - //public static Menge> unifyWC (Menge E, FC_TTO fc_tto) - public static Menge> unify (Menge E, FC_TTO fc_tto) - { - //Schritt 1: Aufrufen der Regeln durch sub_unify. - Menge Eq = sub_unify(E,fc_tto); - /* Schritt 2: Rausfiltern der Typen die entweder beides Typvariablen sind oder nicht. - * Sobald ein Paar auftauch, bei denen kein Typ mehr eine Typvariable ist, kann dieses Paar - * nicht mehr unifiziert werden, deshalb abbruch.*/ - Menge Eq1 = new Menge(); - for(Pair p : Eq) - { - if(p.TA1 instanceof TypePlaceholder && p.TA2 instanceof TypePlaceholder) - { - Eq1.add(p); - } - else if(!(p.TA1 instanceof TypePlaceholder) && !(p.TA2 instanceof TypePlaceholder)) - { - //Diese Paare k�nnen nicht mehr Unifiziert werden. fail. - inferencelog.debug("UNIFY FAIL:" + p.TA1 + " <. " + p.TA2 + " muesste mindestens einen TPH enthalten."); - return new Menge>(); - } - } - //Schritt 3: Differenz bilden, in Eq2 landen alle Paare die nicht in Eq1 sind. - Menge Eq2 = new Menge(); - for(Pair p : Eq) - { - if(!Eq1.contains(p)) - Eq2.add(p); - } - /* Schritt 4, Teil 1: Einsammeln der Sets f�r das Kartesiche Produkt. - * Hier werden die Paare verglichen. Je nach Struktur k�nnen neue Paare erzeugt - * werden, aus denen dann das kartesische Produkt gebildet wird.*/ - Menge>> cartProduktSets = new Menge>>(); - for(Pair p : Eq2) - { - if(p.TA1 instanceof TypePlaceholder) - { - //TPH <. ? super Ty entspricht TPH <. Ty - if (p.TA2 instanceof SuperWildcardType) { - p.TA2 = ((SuperWildcardType)p.TA2).get_SuperType(); - //HIER GIBT ES EIN PROBLEM, WENN get_SuperType ein TPH LIEFERT PL 15-03-12 - //Dann ist THP <. TPH in Eq2 anstatt in Eq1 - //Muesste mit folgendem if gel�st sein. PL 15-03-17 - if (p.TA2 instanceof TypePlaceholder) { - Eq1.addElement(p); - // Eq2.remove(p); - continue; - } - } - - - if(p.OperatorEqual()) - { - //Alle Paare die bereits durch sub_unify die richtige Struktur haben einfach durchleiten. - Menge> setofsetofpairs = new Menge>(); - Menge vTmp = new Menge(); - vTmp.add(p); - setofsetofpairs.add(vTmp); - cartProduktSets.add(setofsetofpairs); - } - else if(p.OperatorSmaller() && (p.TA2 instanceof RefType)) - { - RefType p_TA2 = (RefType)p.TA2; - //1. Menge - //Durch alle Paare p_fc laufen und schauen ob diese von der Struktur zu dem Paar p passen. - Menge fc_refl = copyMengePair(fc_tto.getFC()); - fc_refl.add(new Pair(p_TA2.clone(), p_TA2.clone())); //Reflexivitaet muss beruecksichtigt werden; ergaenzt PL 07-07-28 - //Ist aber in FC nicht enthalten. - Menge> ergMenge1 = new Menge>(); //Ergebnismenge der 1. Menge; - for(Pair p_fc : fc_refl) - { - RefType tmp = ((RefType)p_fc.TA2).clone(); //Unifikation vorgezogen, da isRXSimilarRY nicht ausreicht PL 07-07-29 - CSubstitutionSet gtv2tv = tmp.GenericTypeVar2TypePlaceholder(); - Menge greater1elemente; - if (tmp.get_ParaList() == null) - { - greater1elemente = new Menge(); //Bei Konstanten liefert greater1 [] zurueck - greater1elemente.add(tmp); - } - else - { - greater1elemente = greater1(tmp, fc_tto); - } - Menge> unifyErgs = new Menge>(); - for (Type p_TA2_gr : greater1elemente) //Unify alleine reicht nicht, da p_TA2 Wildcards vorkommen koennen - { //muessen auch alle Typen deren Args Subtypen von p_TA2 sind betrachtet werden. - //Dies wird durch smaller1elemente bzw. smaller1 erledigt PL 07-07-29 - Pair pUnify = new Pair(p_TA2.clone(),p_TA2_gr,PairOperator.Equal); - Menge> unifyErgsElement = unifyWC(pUnify,fc_tto); - if (!unifyErgsElement.isEmpty()) { - unifyErgs.add(unifyErgsElement.firstElement()); - } - } -// Nach dem Unifizieren wird das Ergebnis �berpr�ft, und evtl. durch die FC entstandene TPHs werden gel�scht. - if((p_fc.TA2 instanceof RefType && !unifyErgs.isEmpty()) - || p_fc.TA2.equals(p_TA2)) //Bedingung fuer Reflexifitaet BRAURHT MAN VERMUTLIRH NIRHT PL 07-08-05 - { - //Wenn die Unifizierung erfolgreich war durch jeden Ergebnisvektor der Unifizierung laufen. - for(Menge pVec : unifyErgs) - { -// Das Ergebnis in die linke Seite von p_fc einsetzen, und dort Smaller anwenden. - Hashtable ht = MengePair2SubstHashtableMengePair(pVec); - //PL 07-07-04 smallerArg wird auf die linke Seite von p_FC nach subst angewandt - RefType p_fc_TA1_new = (RefType)p_fc.TA1.clone(); - gtv2tv.applyThisSubstitutionSet(p_fc_TA1_new); //auf der linken Seite - //muessen die GTV durch die gleichen fresh tvs ersetzt werden, wie auf der rechten Seite. PL 07-07-29 - p_fc_TA1_new.GenericTypeVar2TypePlaceholder(); - //die uebrigen GTV muessen durch freshe tvs ersetzt werden. - SubstHashtable((RefType)p_fc_TA1_new,ht); - - //smallerArg ersetz durch folgende Zeilen. Durch Transistivitaet von fc kommen sonst - //doppelte Elemente rein - //Anfang - Menge smallers = new Menge(); - Menge smaller1elemente; - if (p_fc_TA1_new.get_ParaList() == null) - { - smaller1elemente = new Menge(); //Bei Konstanten liefert smaller1 [] zurueck - smaller1elemente.add(p_fc_TA1_new); - } - else - { - smaller1elemente = smaller0(p_fc_TA1_new, fc_tto); //Von Menge 2 kopiert und smaller1 durch smaller0 ersetzt, Luar 07-08-08 - } - - for(ObjectType smele : smaller1elemente) - { - smallers.add(smele); - smallers.add(new ExtendsWildcardType(smele.getOffset(), smele).clone()); //Auskommentiert luar 07-08-08 - //wieder einkommentiert PL 15-03-11 - } - //Ende - -// Ersatz fuer testUnifyErg PL 07-08-05 - //Anfang - for(int vec = 0; vec < pVec.size(); vec++) - { - Pair pTest = pVec.elementAt(vec); - if(!(pTest.TA1 instanceof TypePlaceholder) || !isTVinRefType((TypePlaceholder)pTest.TA1,p_TA2)) - { - pVec.remove(vec); - vec--; - } - } - //ENDE - - Menge> cartProduktErg = new Menge>(); - cartProduktErg.add(pVec); - - //Mit den kleineren Typen neue Paare bilden, linke Seite Klonen. - Menge smallerPairs = new Menge(); - for(Type sT : smallers) - { - smallerPairs.add(new Pair(p.TA1.clone(),sT,PairOperator.Equal)); - } - - //Hier noch das Kartesische Produkt aus den Greater und den Smaller Ergebnissen bilden. - Menge> ergs = new Menge>(); - for(Pair PsmP : smallerPairs) - { - Menge> dolly = copyMengeMengePair(cartProduktErg); - if(dolly.isEmpty()) dolly.add(new Menge()); - for(Menge vecp : dolly) - { - vecp.add(PsmP.clone()); - } - ergs.addAll(dolly); - } - if(!ergs.isEmpty()) - for (Menge ergele : ergs) - if (!ergMenge1.contains(ergele)) //ABFRAGE BRAURHT MAN VERMUTLIRH NIRHT, DA DURRH smaller1 keine doppelten Elemente reinkommen koennen - ergMenge1.add(ergele); - } - } - } - - //aus {ty <. ty'} {? extends ty <. ty'} erzeugen //angefuegt PL 15-03-03 - //DIES IST NICHT RICHTIG GETESTET, ES KOENNTE SEIN, DASS DAS KART. PRODUKT FALSCH GEBILDET WIRD. - //DIES MUEESTE DURCH smallers.add(new ExtendsWildcardType(smele.getOffset(), smele).clone()); weiter ober erledigt sein. - //PL 15-03-11 - //Stream> strextergMenge1 = -// ergMenge1.stream().map(v -> -// v.stream().map(pa -> -// new Pair(pa.getTA1Copy(), new ExtendsWildcardType(pa.getTA2Copy().getOffset(), (ObjectType)pa.getTA2Copy()), pa.GetOperator(), pa.bSubst) -// ).collect(Menge::new, Menge::add, Menge::addAll)); -// -// Menge> extergMenge1 = strextergMenge1.collect(Menge::new, Menge::add, Menge::addAll); -// ergMenge1.addAll(extergMenge1); - cartProduktSets.add(ergMenge1); - } - else if(p.OperatorSmaller() && p.TA2 instanceof GenericTypeVar) - { - //Paar unver�ndert lassen, wenn eine GenericTypeVar ist - Menge> setofsetofpairs = new Menge>(); - Menge vTmp = new Menge(); - vTmp.add(p); - setofsetofpairs.add(vTmp); - cartProduktSets.add(setofsetofpairs); - } - else if(p.OperatorSmallerExtends()) - { - if(p.TA2 instanceof ExtendsWildcardType && ((ExtendsWildcardType)p.TA2).get_ExtendsType() instanceof RefType) - { - RefType p_TA2 = (RefType)((ExtendsWildcardType)p.TA2).get_ExtendsType(); - //2. Menge - //Durch alle Paare p_fc laufen und schauen ob diese von der Struktur zu dem Paar p passen. - Menge fc_refl = copyMengePair(fc_tto.getFC()); - fc_refl.add(new Pair(p_TA2.clone(), p_TA2.clone())); //Reflexivitaet muss beruecksichtigt werden; ergaenzt PL 07-07-28 - //Ist aber in FC nicht enthalten. - Menge> ergMenge2 = new Menge>(); //Ergebnismenge der 2. Menge; ergaenzt PL 07-07-28 - for(Pair p_fc : fc_refl) - { - RefType tmp = ((RefType)p_fc.TA2).clone(); //Unifikation vorgezogen, da isRXSimilarRY nicht ausreicht PL 07-07-29 - CSubstitutionSet gtv2tv = tmp.GenericTypeVar2TypePlaceholder(); - Menge greater1elemente; - if (tmp.get_ParaList() == null) - { - greater1elemente = new Menge(); //Bei Konstanten liefert greater1 [] zurueck - greater1elemente.add(tmp); - } - else - { - greater1elemente = greater1(tmp, fc_tto); - } - Menge> unifyErgs = new Menge>(); - for (Type p_TA2_gr : greater1elemente) //Unify alleine reicht nicht, da p_TA2 Wildcards vorkommen koennen - { //muessen auch alle Typen deren Args Subtypen von p_TA2 sind betrachtet werden. - //Dies wird durch smaller1elemente bzw. smaller1 erledigt PL 07-07-29 - Pair pUnify = new Pair(p_TA2.clone(),p_TA2_gr,PairOperator.Equal); - Menge> unifyErgsElement = unifyWC(pUnify,fc_tto); - if (!unifyErgsElement.isEmpty()) { - unifyErgs.add(unifyErgsElement.firstElement()); - } - } - //Nach dem Unifizieren wird das Ergebnis �berpr�ft, und evtl. durch die FC entstandene TPHs werden gel�scht. - if((p_fc.TA2 instanceof RefType && !unifyErgs.isEmpty()) - || p_fc.TA2.equals(p_TA2)) //Bedingung fuer Reflexifitaet BRAURHT MAN VERMUTLIRH NIRHT PL 07-08-05 - { - //Wenn die Unifizierung erfolgreich war durch jeden Ergebnisvektor der Unifizierung laufen. - for(Menge pVec : unifyErgs) //unifyErgs enthaelt nur einen Unifier STIMMT NIRHT MEHR!!! - { - //Das Ergebnis in die linke Seite von p_fc einsetzen, und dort Smaller anwenden. - Hashtable ht = MengePair2SubstHashtableMengePair(pVec); - //PL 07-07-04 smallerArg wird auf die linke Seite von p_FC nach subst angewandt - RefType p_fc_TA1_new = (RefType)p_fc.TA1.clone(); - gtv2tv.applyThisSubstitutionSet(p_fc_TA1_new); //auf der linken Seite - //muessen die GTV durch die gleichen fresh tvs ersetzt werden, wie auf der rechten Seite. PL 07-07-29 - p_fc_TA1_new.GenericTypeVar2TypePlaceholder(); - //die uebrigen GTV muessen durch freshe tvs ersetzt werden. - SubstHashtable((RefType)p_fc_TA1_new,ht); - - //smallerArg ersetz durch folgende Zeilen. Durch Transistivitaet von fc kommen sonst - //doppelte Elemente rein - //Anfang - Menge smallers = new Menge(); - Menge smaller1elemente; - if (p_fc_TA1_new.get_ParaList() == null) - { - smaller1elemente = new Menge(); //Bei Konstanten liefert smaller1 [] zurueck - smaller1elemente.add(p_fc_TA1_new); - } - else - { - smaller1elemente = smaller1(p_fc_TA1_new, fc_tto); - } - - for(ObjectType smele : smaller1elemente) - { - smallers.add(smele); - smallers.add(new ExtendsWildcardType(smele.getOffset(), smele).clone()); - } - //Ende - - //Ersatz fuer testUnifyErg PL 07-08-05 - //Anfang - for(int vec = 0; vec < pVec.size(); vec++) - { - Pair pTest = pVec.elementAt(vec); - if(!(pTest.TA1 instanceof TypePlaceholder) || !isTVinRefType((TypePlaceholder)pTest.TA1,p_TA2)) - { - pVec.remove(vec); - vec--; - } - } - //ENDE - - Menge> cartProduktErg = new Menge>(); - cartProduktErg.add(pVec); - - //Mit den kleineren Typen neue Paare bilden, linke Seite Klonen. - Menge smallerPairs = new Menge(); - for(Type sT : smallers) - { - smallerPairs.add(new Pair(p.TA1.clone(),sT,PairOperator.Equal)); - } - - //Hier noch das Kartesische Produkt aus den Greater und den Smaller Ergebnissen bilden. - Menge> ergs = new Menge>(); - for(Pair PsmP : smallerPairs) - { - Menge> dolly = copyMengeMengePair(cartProduktErg); - if(dolly.isEmpty()) dolly.add(new Menge()); - for(Menge vecp : dolly) - { - vecp.add(PsmP.clone()); - } - ergs.addAll(dolly); - } - if(!ergs.isEmpty()) - for (Menge ergele : ergs) - if (!ergMenge2.contains(ergele)) //ABFRAGE BRAURHT MAN VERMUTLIRH NIRHT, DA DURRH smaller1 keine doppelten Elemente reinkommen koennen - ergMenge2.add(ergele); - } - } - } - cartProduktSets.add(ergMenge2);// ergaenzt PL 07-07-28 - } - else if(p.TA2 instanceof SuperWildcardType) - { - //3. Menge - //Einfach smallerArg auf die Wildcard aufrufen, mit den Ergebnissen neue Paare bilden. - Menge smErg = smallerArg(p.TA2,fc_tto); - cartProduktSets.add(generateSetOfSetOfPair(p.TA1,smErg)); - } - else - { - //4. Menge - //Den Operator des Paares auf = umbiegen und das Paar in einen Menge verpacken. - Menge> setofsetofpairs = new Menge>(); - Menge vTmp = new Menge(); - p.SetOperator(PairOperator.Equal); - vTmp.add(p); - setofsetofpairs.add(vTmp); - cartProduktSets.add(setofsetofpairs); - } - } - else { - //kein programmierter Fall konnte angewandt werden. PL 15-03-05 - //z.B. TPH <. ? extends Ty - inferencelog.debug("UNIFY FAIL:" + p.TA1 + " <. " + p.TA2 + " Ty wurde kein Fall gefunden"); - return new Menge>(); - } - } - else if (p.TA2 instanceof TypePlaceholder) - { - if(p.OperatorSmaller()) - { - if (p.TA1 instanceof ObjectType) { - //5. Menge - //Greater auf den Typen bilden, und mit den Ergebnissen neue Paare bilden. - Menge grErg = greater((ObjectType)p.TA1,fc_tto); - cartProduktSets.add(generateSetOfSetOfPair(p.TA2,grErg)); - } - else if (p.TA1 instanceof ExtendsWildcardType) { // eingefuegt 15-3-11 PL - Menge grErg1 = greater(((ExtendsWildcardType)p.TA1).getContainedType(),fc_tto); - Menge grErg2 = grErg1.stream().map(ty -> new SuperWildcardType(ty.getOffset(), ty.clone())).collect(Menge::new, Menge::add, Menge::addAll); - Menge grErg = new Menge<>(); - grErg.addAll(grErg1); - grErg.addAll(grErg2); - cartProduktSets.add(generateSetOfSetOfPair(p.TA2,grErg)); - } - else if (p.TA1 instanceof SuperWildcardType) {// eingefuegt 15-3-11 PL - Menge erg = new Menge<> (); - erg.addElement(p.TA1); - cartProduktSets.add(generateSetOfSetOfPair(p.TA2,erg)); - } - } - else if(p.OperatorSmallerExtends()) - { - if(p.TA1 instanceof ExtendsWildcardType) - { - //6. Menge - //GreaterArg auf die Wildcard aufrufen, und mit den Ergebnissen neue Paare bilden. - Menge grErg = greaterArg(p.TA1,fc_tto); - cartProduktSets.add(generateSetOfSetOfPair(p.TA2,grErg)); - } - else if(p.TA1 instanceof SuperWildcardType && ((SuperWildcardType)p.TA1).get_SuperType() instanceof RefType) - { - RefType p_TA1 = (RefType)((SuperWildcardType)p.TA1).get_SuperType(); - //7. Menge - //Durch alle Paare p_fc laufen und schauen ob diese von der Struktur zu dem Paar p passen. - Menge fc_refl = copyMengePair(fc_tto.getFC()); - fc_refl.add(new Pair(p_TA1.clone(), p_TA1.clone())); //Reflexivitaet muss beruecksichtigt werden; ergaenzt PL 07-07-28 - //Ist aber in FC nicht enthalten. - Menge> ergMenge1 = new Menge>(); //Ergebnismenge der 1. Menge; - for(Pair p_fc : fc_refl) - { - RefType tmp = ((RefType)p_fc.TA2).clone(); //Unifikation vorgezogen, da isRXSimilarRY nicht ausreicht PL 07-07-29 - CSubstitutionSet gtv2tv = tmp.GenericTypeVar2TypePlaceholder(); - Menge greater1elemente; - if (tmp.get_ParaList() == null) - { - greater1elemente = new Menge(); //Bei Konstanten liefert greater1 [] zurueck - greater1elemente.add(tmp); - } - else - { - greater1elemente = greater1(tmp, fc_tto); - } - Menge> unifyErgs = new Menge>(); - for (Type p_TA2_gr : greater1elemente) //Unify alleine reicht nicht, da p_TA2 Wildcards vorkommen koennen - { //muessen auch alle Typen deren Args Subtypen von p_TA2 sind betrachtet werden. - //Dies wird durch smaller1elemente bzw. smaller1 erledigt PL 07-07-29 - Pair pUnify = new Pair(p_TA1.clone(),p_TA2_gr,PairOperator.Equal); - Menge> unifyErgsElement = unifyWC(pUnify,fc_tto); - if (!unifyErgsElement.isEmpty()) { - unifyErgs.add(unifyErgsElement.firstElement()); - } - } -// Nach dem Unifizieren wird das Ergebnis �berpr�ft, und evtl. durch die FC entstandene TPHs werden gel�scht. - if((p_fc.TA2 instanceof RefType && !unifyErgs.isEmpty()) - || p_fc.TA2.equals(p_TA1)) //Bedingung fuer Reflexifitaet BRAURHT MAN VERMUTLIRH NIRHT PL 07-08-05 - { - //Wenn die Unifizierung erfolgreich war durch jeden Ergebnisvektor der Unifizierung laufen. - for(Menge pVec : unifyErgs) - { -// Das Ergebnis in die linke Seite von p_fc einsetzen, und dort Smaller anwenden. - Hashtable ht = MengePair2SubstHashtableMengePair(pVec); - //PL 07-07-04 smallerArg wird auf die linke Seite von p_FC nach subst angewandt - RefType p_fc_TA1_new = (RefType)p_fc.TA1.clone(); - gtv2tv.applyThisSubstitutionSet(p_fc_TA1_new); //auf der linken Seite - //muessen die GTV durch die gleichen fresh tvs ersetzt werden, wie auf der rechten Seite. PL 07-07-29 - p_fc_TA1_new.GenericTypeVar2TypePlaceholder(); - //die uebrigen GTV muessen durch freshe tvs ersetzt werden. - SubstHashtable((RefType)p_fc_TA1_new,ht); - - //smallerArg ersetz durch folgende Zeilen. Durch Transistivitaet von fc kommen sonst - //doppelte Elemente rein - //Anfang - Menge smallers = new Menge(); - Menge smaller1elemente; - if (p_fc_TA1_new.get_ParaList() == null) - { - smaller1elemente = new Menge(); //Bei Konstanten liefert smaller1 [] zurueck - smaller1elemente.add(p_fc_TA1_new); - } - else - { - smaller1elemente = smaller0(p_fc_TA1_new, fc_tto); //Von Menge 2 kopiert und smaller1 durch smaller0 ersetzt, Luar 07-08-08 - } - - for(ObjectType smele : smaller1elemente) - { - smallers.add(smele); - //smallers.add(new ExtendsWildcardType(smele.getOffset(), smele).clone()); //Auskommentiert luar 07-08-08 - } - //Ende - -// Ersatz fuer testUnifyErg PL 07-08-05 - //Anfang - for(int vec = 0; vec < pVec.size(); vec++) - { - Pair pTest = pVec.elementAt(vec); - if(!(pTest.TA1 instanceof TypePlaceholder) || !isTVinRefType((TypePlaceholder)pTest.TA1,p_TA1)) - { - pVec.remove(vec); - vec--; - } - } - //ENDE - - Menge> cartProduktErg = new Menge>(); - cartProduktErg.add(pVec); - - //Mit den kleineren Typen neue Paare bilden, linke Seite Klonen. - Menge smallerPairs = new Menge(); - for(ObjectType sT : smallers) - { - smallerPairs.add(new Pair(p.TA2.clone(),new SuperWildcardType(sT.getOffset(),sT),PairOperator.Equal)); - } - - //Hier noch das Kartesische Produkt aus den Greater und den Smaller Ergebnissen bilden. - Menge> ergs = new Menge>(); - for(Pair PsmP : smallerPairs) - { - Menge> dolly = copyMengeMengePair(cartProduktErg); - if(dolly.isEmpty()) dolly.add(new Menge()); - for(Menge vecp : dolly) - { - vecp.add(PsmP.clone()); - } - ergs.addAll(dolly); - } - if(!ergs.isEmpty()) - for (Menge ergele : ergs) - if (!ergMenge1.contains(ergele)) //ABFRAGE BRAURHT MAN VERMUTLIRH NIRHT, DA DURRH smaller1 keine doppelten Elemente reinkommen koennen - ergMenge1.add(ergele); - } - } - } - cartProduktSets.add(ergMenge1); - } - else - { - //8. Menge - //GreaterArg auf die Linke Seite Aufrufen, mit den Ergebnissen neue Paare erzeugen - Menge grErg = greaterArg(p.TA1,fc_tto); - cartProduktSets.add(generateSetOfSetOfPair(p.TA2,grErg)); - } - } - else { - //kein programmierter Fall konnte angewandt werden. PL 15-03-05 - inferencelog.debug("UNIFY FAIL:" + p.TA1 + " <. " + p.TA2 + " Ty wurde kein Fall gefunden"); - return new Menge>(); - } - } - } - //Schritt 4, Teil 2: Kartesisches Produkt bilden. - //TODO: Vor der Bildung des Karthesischen Produkts unm�gliche Kombinationen ausfiltern - //Hier wird aus den in Schritt 4, Teil 1 erzeugten Vektoren das Kartesische Produkt gebilden. - Menge helpvp; - Menge> bigCartProductErg = new Menge>(); - bigCartProductErg.addElement(copyMengePair(Eq1)); - - for (Menge> vecvecpair : cartProduktSets) - { - Menge> bigCartProductErgOld = bigCartProductErg; - bigCartProductErg = new Menge>(); - for(Menge vecpair1 : vecvecpair) - { - for(Menge vecpair2 : bigCartProductErgOld) - { - helpvp = copyMengePair(vecpair2); - helpvp.addAll(copyMengePair(vecpair1)); - bigCartProductErg.addElement(helpvp); - } - } - } - - //Schritt 5: Einsetzen der Subst Regel - //Hier werden die TPHs substituiert, und dann nach ge�nderten und nicht ge�nderten Sets sortiert. - Menge> changedSets = new Menge>(); - Menge> notChangedSets = new Menge>(); - for(Menge vecpair : bigCartProductErg) - { - boolean change = false; //eingefuegt PL 13-05-22 - Pair substPair = null; - do - { - substPair = null; - //Einsammeln der Paare von der Signatur a = Typ - for(Pair p : vecpair) - { - if(p.TA1 instanceof TypePlaceholder && p.OperatorEqual() && !p.bSubst) - { - substPair = p; - p.bSubst = true; - break; - } - } - if(substPair != null) - { - //Einsetzen der Typen in die anderen Paare - //boolean change = false; auskommentiert PL 13-05-22 - for(int i = 0; i< vecpair.size();i++) - { - Pair p = vecpair.elementAt(i); - if(!p.instanzeEquals(substPair)) - { - change |= Subst(p,1,(TypePlaceholder)substPair.TA1,substPair.TA2,true); - change |= Subst(p,2,(TypePlaceholder)substPair.TA1,substPair.TA2,true); - } - } - //Substitution abgeschlossen. Sortieren. - //if(change) auskommentiert PL 13-05-22, da erst nach komplett erfolgter Substitution sortiert wird. - //{ - //changedSets.add(vecpair); - //break; - //} - } - } - while(substPair != null); - - if(change) // NEU PL 13-05-22, da erst nach komplett erfolgter Substitution sortiert wird. - { - changedSets.add(vecpair); - } - else - //if(substPair == null) - { - notChangedSets.add(vecpair); - } - } - - //Eq2Set ist das eigentliche Ergebnis, dass zur�ckgegeben wird. - Menge> Eq2Set = new Menge>(); - - //Schritt 6A: Beginnen mit Schritt 1 bei den ge�nderten. - for(Menge vecpair : changedSets) - { - Menge> unifyErgs = unify(vecpair,fc_tto); - //Die Ergebnissvektoren sind schon im Schritt 7 von dem Rekursiven Aufruf gepr�ft worden. Sie k�nnen direkt eingef�gt werden. - Eq2Set.addAll(unifyErgs); - } - - //Schritt 6B Einf�gen der nicht ge�nderten. - //Schritt 7: Aussortieren der falschen Sets - /* - * Durch die Rekursion in Schritt 6A sind die Ergebnisse, welche in 6A dazukommen auf jeden Fall korrekt. - * Es m�ssen nur die Ergebnisse aus 6B gepr�ft werden. - */ - for(Menge vecpair : notChangedSets) - { - //�berpr�fen ob Menge in SolvedForm ist. - if(hasSolvedForm(vecpair)) //PL 13-05-22 hasSolvedForm angepasst - { - //�berpr�fung auf FreshTypeVars in den Typen - boolean foundFresh = false; - for(Pair p : vecpair) - { - //EINSRHUB ANFANG UM PAARE A schnitt1 (Menge var, Menge> vars, Menge indexe) { - int j = -1; - for (Menge varelems : vars) { - j++; - if (varelems != null) { - if (var.stream().map(x -> varelems.contains(x)).reduce(false, (a,b) -> (a || b)) - && (!indexe.contains(j))) - { - Menge rekvarelements = vars.elementAt(j); - vars.setElementAt(null, j);//Element erledigt muss nicht nochmals bearbeitet werden. - indexe.addElement(j); - indexe = schnitt1(rekvarelements, vars, indexe); - } - } - } - return indexe; - } - - /** - * Bildet Schnittmengen der Mengen von Typeplaceholders - * Rueckgabe ist die Menge der Menge von Indizies die Schnittmengen sind. - * @param vars - * @return - */ - public static Menge> schnitt (Menge> vars) { - Menge> ret = new Menge<>(); - int i = -1; - for (Menge var : vars) { - i++; - if (var != null) {//Element wurde noch bearbeitet - Menge indexe = new Menge<>(); - indexe.add(i); - ret.add(schnitt1(var, vars, indexe)); - } - } - return ret; - } - - - /** - * Diese Methode wird verwendet, um Zuordnungen z.B. TPH a = Integer - * aus der Ergebnismenge zu entfernen, wenn im Typ in den die eingesetzt werden sollen kein TPH a vorhanden ist. - * Beispiel: unifyERgs = [[a = Integer, b = Number ]], test = Menge
- * In diesm fall wird b = Number aus dem Menge entfernt. - * - * Durch das Entfernen entstehen evtl. Identische Mengeen, diese werden auch gel�scht. - * - * @param unifyErgs - Ergebnisse des Unify, die gepr�ft werden sollen. - * @param test - RefType gegen den gepr�ft werden soll. - */ - private static void testUnifyErg(Menge> unifyErgs, RefType test) - { - for(Menge pVec : unifyErgs) - for(int vec = 0; vec < pVec.size(); vec++) - { - Pair pTest = pVec.elementAt(vec); - if(!(pTest.TA1 instanceof TypePlaceholder) || !isTVinRefType((TypePlaceholder)pTest.TA1,test)) - { - pVec.remove(vec); - vec--; - } - } - //Gleiche Mengeen l�schen - for(int i = 0; i < unifyErgs.size(); i++) - { - Menge p1 = unifyErgs.elementAt(i); - for(int j = i + 1; j < unifyErgs.size(); j++) - { - Menge p2 = unifyErgs.elementAt(j); - if(p1.size() == p2.size()) - { - boolean equal = true; - for(Pair p1P : p1) - { - boolean found = false; - for(Pair p2P : p2) - found |= p2P.equals(p1P); - - equal &= found; - } - if(equal) - { - unifyErgs.remove(j); - j--; - } - } - } - } - } - - /** - * Diese Methode generiert einen Menge> wobei immer der �bergebene TA1 vorne steht, und jeder Typ aus otherPairTypes hinten. - * Beispiel: otherPairTypes = [Integer, Number, Menge], TA1 = TPH a. - * return: [[TPH a = Integer],[TPH a = Number],[TPH a = Menge]] - * - * @param TA1 - Der Typ der immer vorne steht - * @param otherPairTypes - Die anderen Typen - * @return - Ein Menge> der alle Paare enth�lt. - */ - private static Menge> generateSetOfSetOfPair(Type TA1, Menge otherPairTypes) - { - Menge> setofsetofpairs = new Menge>(); - for(Type t : otherPairTypes) - { - Menge vTmp = new Menge(); - vTmp.add(new Pair(TA1.clone(),t,PairOperator.Equal)); - setofsetofpairs.add(vTmp); - } - return setofsetofpairs; - } - - // ino.method.unify_Mub.28061.definition - public static MUB unify_Mub(Type ty1, Type ty2, FC_TTO fc_tto) - throws CTypeReconstructionException - // ino.end - // ino.method.unify_Mub.28061.body - { - Menge FC = fc_tto.getFC(); - if (ty1 instanceof TypePlaceholder) { - Menge Mub = new Menge(); - Mub.addElement(ty2); - Menge sigma = new Menge(); - sigma.addElement(new Pair(ty1, ty2)); - return new MUB(Mub, sigma); - } - else if (ty2 instanceof TypePlaceholder) { - Menge Mub = new Menge(); - Mub.addElement(ty1); - Menge sigma = new Menge(); - sigma.addElement(new Pair(ty2, ty1)); - return new MUB(Mub, sigma); - } - else { - Menge ub = new Menge(); //alle oberen Schranken - Menge gr1 = new Menge(); //alle Elemente groesser ty1 - boolean refl_flag1=true; - - //alle groesseren Elemente in FC - for (int i=0; i < FC.size(); i++) { - Pair P; - - // Reflexivitaet, wenn es kein groesseres Element, aber - // kleinere Elemente gibt. - P = isInFC((RefType)(FC.elementAt(i).TA1), (RefType)ty1, FC); - if (P != null) { - gr1.addElement(((RefType)P.TA2).clone()); //Reflexivitaet - refl_flag1 = false; - } - - //echt groessere Elemente aus FC suchen - P = isInFC((RefType)ty1, (RefType)(FC.elementAt(i).TA2), FC); - if (P != null) { - gr1.addElement(((RefType)P.TA2).clone()); - if (refl_flag1) { - gr1.addElement(((RefType)P.TA1).clone()); //Reflexivitaet - } - } - } - - Menge gr2 = new Menge(); - boolean refl_flag2=true; - - //alle groesseren Elemente in FC - for (int i=0; i < FC.size(); i++) { - Pair P; - - // Reflexivitaet, wenn es kein groesseres Element, aber - // kleinere Elemente gibt. - P = isInFC((RefType)(FC.elementAt(i).TA1), (RefType)ty2, FC); - if (P != null) { - gr2.addElement(((RefType)P.TA2).clone()); //Reflexivitaet - } - - P = isInFC((RefType)ty2, (RefType)(FC.elementAt(i).TA2), FC); - if (P != null) { - gr2.addElement(((RefType)P.TA2).clone()); - if (refl_flag2) { - gr2.addElement(((RefType)P.TA1).clone()); //Reflexivitaet - refl_flag1 = false; - } - } - } - if (gr1.size()==0) gr1.addElement((RefType)ty1.clone()); - if (gr2.size()==0) gr2.addElement((RefType)ty2.clone()); - //MIT Usecase_MUBTest4.jav testen und gr1 und gr2 ueberpruefen - - for (int i = 0; i < gr1.size(); i++) { //gemeinsame obere Schranken suchen - for (int j = 0; j < gr2.size(); j++){ - if (gr1.elementAt(i).is_Equiv(gr2.elementAt(j), new Hashtable())) { - ub.addElement(gr1.elementAt(i)); - break; - } - } - } - - //Menge wird geclont, Elemente nicht - //Menge Mub = (Menge)ub.clone(); - - //Elemente die nicht kleinste obere Schranken sind, werden gel�scht - //FUNKTIONIERT NICHT. SIEHE iftest.java PL 08-08-13 - for (int i = 0; i < ub.size(); i++) { - for (int j = 0; j < ub.size(); j++) { - //PL 05-03-22 alle aequivalenten Elemente sollten auch entfernt werden. - if (i != j && - (isInFC(ub.elementAt(j), ub.elementAt(i), FC) != null - || ub.elementAt(j).equals(ub.elementAt(i)))) { - ub.remove(ub.elementAt(i)); - - //durch remove wuerde sonst ein Element - //nicht geprueft - if (j > i) j--; - } - } - } - - //es gibt eine kleinste obere Schranke - if (ub.size() > 0) { - RefType max = ub.elementAt(0); - - //liefert die Sustitution von Genvars in Typeplaceholders, um - //sub dann auf die anderen Elemente von Mub anwenden zu koennen - CSubstitutionSet sub = max.GenericTypeVar2TypePlaceholder(); - //PL 06-03-22 in allen Elementen von Mub muessten die gleichen Typeplaceholders stehen - Menge sigma = unify(ty1, max, fc_tto).elementAt(0); - Menge sigma2 = unify(ty2, max, fc_tto).elementAt(0); - sigma.addAll(sigma2); - Menge> unifiers = unify(sigma, fc_tto); - - //es gibt keinen Unifier - if (unifiers.size()==0) { - throw new CTypeReconstructionException("Es gibt keinen Unifier",null); - } - Iterator MubsIt = ub.iterator(); - while(MubsIt.hasNext()){ - sub.applyThisSubstitutionSet(MubsIt.next()); - } - return new MUB(ub, unifiers.elementAt(0)); - } - //es gibt keine kleinste obere Schranke - else { - throw new CTypeReconstructionException("Es existiert kein MUB",null); - } - - } - } - // ino.end - -// ino.method.match.28064.definition -public static Hashtable match(RefType FCtype, RefType tomatch, Hashtable ht) -throws MatchException -// ino.end -// ino.method.match.28064.body -{ - //PL 05-01-22 - //gibt eine Substitution zur�ck, die den Variablen aus FCtype - //die Typterme aus tomatch zu ordnet. Es wird davon ausgegangen, dass - //FCtype gegen tomatch gematcht werden kann. - if (FCtype.getTypeName().equals(tomatch.getTypeName())) { - inferencelog.debug("match: " + FCtype.getTypeName()); - if (FCtype.get_ParaList() != null) { - for(int i=0; i < FCtype.get_ParaList().size(); i++) { - if (FCtype.get_ParaList().elementAt(i) instanceof GenericTypeVar) { - inferencelog.debug("PUT"); - ht.put(((GenericTypeVar)FCtype.get_ParaList().elementAt(i)).getName(), - tomatch.get_ParaList().elementAt(i)); - } - else if ((FCtype.get_ParaList().elementAt(i) instanceof RefType) && - (tomatch.get_ParaList().elementAt(i) instanceof TypePlaceholder)) { - throw new MatchException("vorne Typterm hinten Typvariable "); - } - else if((FCtype.get_ParaList().elementAt(i) instanceof RefType) && - (tomatch.get_ParaList().elementAt(i) instanceof IMatchable) && - ((IMatchable)tomatch.get_ParaList().elementAt(i)).getMatchType() instanceof RefType) - { - match((RefType)FCtype.get_ParaList().elementAt(i), (RefType)((IMatchable)tomatch.get_ParaList().elementAt(i)).getMatchType(), ht); - } - } - } - return ht; - } - else { - throw new MatchException("different Name 1. " + FCtype.getTypeName()+ " 2. " + tomatch.getTypeName()); - } - } -// ino.end - - /* Einstieg in die Unifizierung mit den 4 Regeln. */ - public static Menge sub_unify(Menge E, FC_TTO fc_tto) - { - return sub_unify(E,fc_tto,true); - } - - // ino.method.sub_unify.28067.definition - public static Menge sub_unify( Menge E, FC_TTO fc_tto, boolean useSubst ) - // ino.end - // ino.method.sub_unify.28067.body - { - //PL 05-01-21 umbenannt in sub_unify - //Luar boolean useSubst hinzugef�gt, um bei bedarf zu Steuern ob Subst Regel angewendet wird oder nicht. - // otth: Unifikation - Versuch 1 :-) - - //Menge FC = fc_tto.getFC(); - Menge TTO = fc_tto.getTTO(); - Menge H = new Menge(); // Hilfsmenge - boolean bRegel = true; // gibt an, ob eine Regel gepasst hat - - int n = 0; - - while( bRegel ) - { - n++; - - // zum Debuggen - printMenge( "E", E, 6 ); - bRegel = false; - for( int i = 0; i < E.size(); i++ ) - { - Pair P = E.elementAt(i); - inferencelog.debug(""); - inferencelog.debug(""); - inferencelog.debug("Ausgewaehltes Paar = " + P.toString() + ""); - inferencelog.debug( "--------------------------------------------------"); - - // Bei allen Erase erfolgt keine Kopie nach H, dadurch wird das Pair gel�scht. - //ERASE3 - if( P.isEqual() && P.OperatorEqual() ) - { - inferencelog.debug(" ================================"); - inferencelog.debug(" ERASE3"); - inferencelog.debug(" ================================"); - bRegel = true; - continue; - } - // ERASE1 luar 15-04-07 - if(P.OperatorSmaller()) - { - if (P.TA1 instanceof ObjectType) { - Menge greaters = greater((ObjectType)P.TA1,fc_tto); - if (greaters.contains(P.TA2)) - { - inferencelog.debug(" ================================"); - inferencelog.debug(" ERASE1 ObjectType"); - inferencelog.debug(" ================================"); - bRegel = true; - continue; - } - } - else if (P.TA1 instanceof ExtendsWildcardType) { - ObjectType pta1 = ((ExtendsWildcardType)P.TA1).getContainedType(); - Menge greaters = greater((ObjectType)pta1,fc_tto); - if (greaters.contains(P.TA2)) - { - inferencelog.debug(" ================================"); - inferencelog.debug(" ERASE1 ExtendsWildcardType"); - inferencelog.debug(" ================================"); - bRegel = true; - continue; - } - } - } - else if (P.TA1 instanceof SuperWildcardType) { - if( P.isEqual()) { - inferencelog.debug(" ================================"); - inferencelog.debug(" ERASE1 SuperWildcardType"); - inferencelog.debug(" ================================"); - bRegel = true; - continue; - } - } - //ERASE2 luar 15-04-07 - if(P.OperatorSmallerExtends()) - { - Menge greaterArgs = greaterArg(P.TA1,fc_tto); - if(greaterArgs.contains(P.TA2)) - { - inferencelog.debug(" ================================"); - inferencelog.debug(" ERASE2"); - inferencelog.debug(" ================================"); - bRegel = true; - continue; - } - } - - //ReduceUp luar 10-04-2007 - if(P.TA1 instanceof RefType && P.TA2 instanceof SuperWildcardType && P.OperatorSmaller()) - { - inferencelog.debug(" REDUCEUP"); - SuperWildcardType TA2 = ((SuperWildcardType)P.TA2); - - H.add(new Pair(P.TA1,TA2.get_SuperType())); - bRegel = true; - continue; - } - //ReduceLow luar 10-04-2007 - if(P.TA1 instanceof ExtendsWildcardType && P.TA2 instanceof RefType && P.OperatorSmaller()) - { - inferencelog.debug(" REDUCELOW"); - ExtendsWildcardType TA1 = ((ExtendsWildcardType)P.TA1); - - H.add(new Pair(TA1.get_ExtendsType(),P.TA2)); - bRegel = true; - continue; - } - //ReduceUpLow luar 10-04-2007 - if(P.TA1 instanceof ExtendsWildcardType && P.TA2 instanceof SuperWildcardType && P.OperatorSmaller()) - { - inferencelog.debug(" REDUCEUPLOW"); - ExtendsWildcardType TA1 = ((ExtendsWildcardType)P.TA1); - SuperWildcardType TA2 = ((SuperWildcardType)P.TA2); - - H.add(new Pair(TA1.get_ExtendsType(),TA2.get_SuperType())); - bRegel = true; - continue; - } - - //ReduceExt luar 19-04-2007 - if((P.TA1 instanceof RefType - || (P.TA1 instanceof ExtendsWildcardType && ((ExtendsWildcardType)P.TA1).get_ExtendsType() instanceof RefType)) - && P.TA2 instanceof ExtendsWildcardType && P.OperatorSmallerExtends()) - { - inferencelog.debug(" REDUCEEXT"); - ExtendsWildcardType ExT = (ExtendsWildcardType)P.TA2; - RefType TA1; - if(P.TA1 instanceof RefType) - TA1 = (RefType)P.TA1; - else - TA1 = (RefType)((ExtendsWildcardType)P.TA1).get_ExtendsType(); - - if(ExT.get_ExtendsType() instanceof RefType) - { - RefType TA2 = (RefType)ExT.get_ExtendsType(); - if(isRealSubClass(TA1.getTypeName(),TA2.getTypeName(),fc_tto) || TA1.getTypeName().equals(TA2.getTypeName())) - { - if(TA1.get_ParaList() != null && TA2.get_ParaList() != null) - { - if(TA1.get_ParaList().size() == TA2.get_ParaList().size()) - { - try - { - reduceExt(H,TA1,TA2,TTO); - bRegel = true; - continue; - } - catch( SCException Ex ) - { - inferencelog.debug("---- Unifikation nicht m�glich: Permutation fehlgeschlagen!"); - break; - } - } - else - { - inferencelog.info("---- Unifikation nicht m�glich: Anzahl der Parameter verschieden!"); - break; - } - } - } - } - - inferencelog.debug(" ADAPTEXT"); - if(ExT.get_ExtendsType() instanceof RefType) - { - RefType TA2 = (RefType)ExT.get_ExtendsType(); - Pair PFC = isInFClinks( TA1, TA2, fc_tto.getFC() ); - if(PFC != null) - { - adaptExt(H,PFC,TA1,TA2,fc_tto); - bRegel = true; - continue; - } - } - } - - //ReduceSup luar 19-04-2007 - if((P.TA1 instanceof RefType - || (P.TA1 instanceof SuperWildcardType && ((SuperWildcardType)P.TA1).get_SuperType() instanceof RefType)) - && P.TA2 instanceof SuperWildcardType && P.OperatorSmallerExtends()) - { - inferencelog.debug(" REDUCESUP"); - SuperWildcardType SuT = (SuperWildcardType)P.TA2; - RefType TA1; - if(P.TA1 instanceof RefType) - TA1 = (RefType)P.TA1; - else - TA1 = (RefType)((SuperWildcardType)P.TA1).get_SuperType(); - - if(SuT.get_SuperType() instanceof RefType) - { - RefType TA2 = (RefType)SuT.get_SuperType(); - if(isRealSubClass(TA2.getTypeName(),TA1.getTypeName(),fc_tto) || TA1.getTypeName().equals(TA2.getTypeName())) - { - if(TA1.get_ParaList() != null && TA2.get_ParaList() != null) - { - if(TA1.get_ParaList().size() == TA2.get_ParaList().size()) - { - try - { - reduceSup(H,TA1,TA2,TTO); - bRegel = true; - continue; - } - catch( SCException Ex ) - { - inferencelog.debug("---- Unifikation nicht m�glich: Permutation fehlgeschlagen!"); - break; - } - } - else - { - inferencelog.info("---- Unifikation nicht m�glich: Anzahl der Parameter verschieden!"); - break; - } - } - } - } - - inferencelog.debug(" ADAPTSUP"); - if(SuT.get_SuperType() instanceof RefType) - { - RefType TA2 = (RefType)SuT.get_SuperType(); - Pair PFC = isInFClinks( TA2, TA1, fc_tto.getFC() ); - if(PFC != null) - { - adaptSup(H,PFC,TA2,TA1,fc_tto); - bRegel = true; - continue; - } - } - } - //REDUCE2 - //PL 15-01-20: HIER MUESSEN NOCH ALLE FAELLE MIT EXTENDS UND SUPER GEMISCHT ERGAENZT WERDEN - //BEACHTEN: WAS PASSIERT WENN HINTER ? extends/super EINE TYPVAR/KEIN REFTYPE STEHT - //erledigt 15-02-03 - if(P.OperatorEqual()) - { - if((P.TA1 instanceof ExtendsWildcardType && P.TA2 instanceof ExtendsWildcardType) || //PL 15-03-31 eingefuegt - (P.TA1 instanceof SuperWildcardType && P.TA2 instanceof SuperWildcardType)) - { - H.add(new Pair(((WildcardType)P.TA1).GetWildcardType(), ((WildcardType)P.TA2).GetWildcardType(), PairOperator.Equal)); - bRegel = true; - continue; - } - ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //PL 15-03-05: Ich halte dies fuer falsch - ////PL 15-02-08 bisher mit keinem Beispiel getestet - //if(P.TA1 instanceof WildcardType && ((WildcardType)P.TA1).GetWildcardType() instanceof TypePlaceholder - //&& (P.TA2 instanceof GenericTypeVar || P.TA2 instanceof RefType)) - //{ - //H.add(new Pair(((WildcardType)P.TA1).GetWildcardType(),P.TA2, PairOperator.Equal)); - //bRegel = true; - //continue; - //} - - //PL 15-02-08 bisher mit keinem Beispiel getestet - //if((P.TA1 instanceof GenericTypeVar || P.TA1 instanceof RefType) - //&& (P.TA2 instanceof WildcardType && ((WildcardType)P.TA2).GetWildcardType() instanceof TypePlaceholder)) - //{ - //H.add(new Pair(P.TA1, ((WildcardType)P.TA2).GetWildcardType(), PairOperator.Equal)); - //bRegel = true; - //continue; - //} - ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - //wenn noetig extends-wildcards entfernen PL 15-02-03 - //korrekt da P.OperatorEqual() - - ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //PL 15-03-05: Ich halte dies fuer falsch - //if(P.TA1 instanceof WildcardType) - //{ - //P.TA1 = ((WildcardType)P.TA1).GetWildcardType(); - //} - //if(P.TA2 instanceof WildcardType) { - //P.TA2 = ((WildcardType)P.TA2).GetWildcardType(); - //} - ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - - RefType TA1 = null; - RefType TA2 = null; - //Hier werden die RefTypes gef�llt. - if(P.TA1 instanceof RefType && P.TA2 instanceof RefType) - { - TA1 = (RefType)P.TA1; - TA2 = (RefType)P.TA2; - } - - if(TA1 != null && TA2 != null && TA1.getTypeName().equals(TA2.getTypeName())) - { - inferencelog.debug(" REDUCE2"); - // REDUCE - if(TA1.get_ParaList() != null && TA2.get_ParaList() != null && TA1.get_ParaList().size() == TA2.get_ParaList().size()) - { - try - { - // REDUCE-Regel anwendbar - reduce2(H,TA1,TA2,TTO); - bRegel = true; - continue; - } - catch( SCException Ex ) - { - inferencelog.error("---- Unifikation nicht m�glich: Permutation fehlgeschlagen!"); - break; - } - } - } - } // end if: Reduce2 - inferencelog.debug("NACH REDUCE2"); - - // REDUCE1, REDUCEEQ, ADAPT - //HIER MUSS BEI PAARBILDUNG NOCH bEqual AUF true GESETZT WERDEN - //CONTRAVARIANZ-PROBLEM OO-PROGRAMMIERUNG erlegigt PL 05-01-22 - //BEISPIEL pl1.1.1.2.java - if (P.TA1 instanceof RefType && P.TA2 instanceof RefType) - { - inferencelog.debug(" REDUCE1"); - RefType TA1 = ((RefType)P.TA1); - RefType TA2 = ((RefType)P.TA2); - - // REDUCE1 - if((isRealSubClass(TA1.getTypeName(), TA2.getTypeName(), fc_tto) || TA1.getTypeName().equals(TA2.getTypeName())) - && P.OperatorSmaller()) - { - // REDUCE - if(TA1.get_ParaList() != null && TA2.get_ParaList() != null && TA1.get_ParaList().size() == TA2.get_ParaList().size()) - { - try - { - reduce1(H,TA1,TA2,TTO); - bRegel = true; - continue; - } - catch( SCException Ex ) - { - inferencelog.debug("---- Unifikation nicht m�glich: Permutation fehlgeschlagen!"); - break; - } - } - } // end if: Reduce1 - inferencelog.debug("NACH REDUCE1"); - // REDUCEEQ - if(TA1.getTypeName().equals(TA2.getTypeName()) && P.OperatorSmallerExtends()) - { - inferencelog.debug("REDUCEEQ"); - if(TA1.get_ParaList() != null && TA2.get_ParaList() != null && TA1.get_ParaList().size() == TA2.get_ParaList().size()) - { - try - { - reduceEq(H,TA1,TA2,TTO); - bRegel = true; - continue; - } - catch( SCException Ex ) - { - inferencelog.error("---- Unifikation nicht m�glich: Permutation fehlgeschlagen!"); - break; - } - } - } // end if: Reduce2 - inferencelog.debug("NACH REDUCEEQ"); - // ADAPT - if (P.OperatorSmaller()) - { - Pair PFC = isInFClinks( TA1, TA2, fc_tto.getFC() ); - inferencelog.debug(" ADAPTStart"); - if( PFC != null ) - { - inferencelog.debug("isInFCrechtsUnify" + PFC.toString()); - adapt(H,PFC,TA1,TA2,fc_tto); - bRegel = true; - continue; - - } // end if: Ende Adapt bzw. isInFC - } // end if P.OperatorSmaller() - } // end if: RefType - - - // Swap - if( (P.TA1 instanceof RefType || P.TA1 instanceof GenericTypeVar || P.TA1 instanceof WildcardType) && P.TA2 instanceof TypePlaceholder && P.OperatorEqual()) - //PL 06-05-16 GenericTypeVar eingefuegt - { - H.addElement( new Pair( P.TA2, P.TA1, PairOperator.Equal ) ); - inferencelog.debug(" ================================"); - inferencelog.debug(" SWAP"); - inferencelog.debug(" ================================"); - bRegel = true; - continue; - } - - if (P.OperatorSmallerExtends()) //PL 15-02-17 alle eingefuegt - { - if(P.TA1 instanceof ExtendsWildcardType && P.TA2 instanceof ExtendsWildcardType) - { - - inferencelog.debug(" Extends noch zu pr�fen - if( P.TA1 instanceof TypePlaceholder && P.OperatorEqual() && useSubst) //&& P.TA2 instanceof RefType ) - //PL 05-02-09 P.TA@ duerfen auch TypePlaceholder sein - /* BEISPIEL: - ******************************* - Menge E = { - (A, %F%), - (A, %F%), - (C, %G%) } - ******************************* - */ - { - inferencelog.debug(" SUBSTITUTE: in "); - // Ersetzungen im Rest von E - inferencelog.debug(" Subst?"); - boolean bTempSubst = P.bSubst; - for( int q = i+1; q < E.size(); q++ ) - { - if( !P.bSubst ) - //GIBT ES PROBLEME: WIRD DAS P.bSubst ZURUECKGESETZT????? - { - inferencelog.debug(" ================================"); - inferencelog.debug(" SUBSTITUTE: in " + E.elementAt(q).toString() + " alle " + P.TA1.getName() + " durch " + P.TA2.getName()); - inferencelog.debug(" ================================"); - bRegel = true; - bTempSubst = true; - - //PL 05-02-09 Typecast vor P.TA2 entfernt, da auch TypePlaceholder - //eingesetzt werden duerfen - Subst( E.elementAt(q), 1, (TypePlaceholder)P.TA1, P.TA2, true ); - Subst( E.elementAt(q), 2, (TypePlaceholder)P.TA1, P.TA2, true ); - } - } - // Ersetzungen in H - for( int q = 0; q < H.size(); q++ ) - { - if( !P.bSubst ) - { - inferencelog.debug(" ================================"); - inferencelog.debug(" SUBSTITUTE: in " + H.elementAt(q).toString() + " alle " + P.TA1.getName() + " durch " + P.TA2.getName()); - inferencelog.debug(" ================================"); - bRegel = true; - bTempSubst = true; - //P.bSubst = true; geloescht PL 06-04-29 darf hire nicht sein, sonst - //wird P nur auf ein Paar in E bzw. H angewandt. - - // Ursprungspaar nicht ersetzen - //PL 05-02-09 Typecast vor P.TA2 entfernt, da auch TypePlaceholder - //eingesetzt werden duerfen - Subst( H.elementAt(q), 1, (TypePlaceholder)P.TA1, P.TA2, true ); - Subst( H.elementAt(q), 2, (TypePlaceholder)P.TA1, P.TA2, true ); - } - } - - P.bSubst = bTempSubst; - - // falls wirklich was gemacht wurde - H.addElement( E.elementAt(i) ); - continue; - } - - // keine Regel --> Element nach H kopieren! - H.addElement( E.elementAt(i) ); - inferencelog.debug("\n--> keine Regel anwendbar --> umkopieren !!!!!!!!!!!!!!!!!!!!!"); - } - - // Hilfsvektor nach E kopieren - // MyCompiler.printDebugInfo("---- Vektoren kopieren", 6); - // MyCompiler.printDebugInfo("---- E = " + E, 6); - // MyCompiler.printDebugInfo("---- H = " + H, 6); - E.removeAllElements(); - Menge vTemp = E; - E = H; - H = vTemp; - } - return E; - } - // ino.end - - /** - * Implementiert die reduce1 Regel des sub_unify - */ - private static void reduce1(Menge H, RefType TA1, RefType TA2, Menge TTO) throws SCException - { - inferencelog.debug(" ================================"); - inferencelog.debug(" REDUCE1"); - inferencelog.debug(" ================================"); - - Menge L1 = TA1.get_ParaList(); - Menge L2 = TA2.get_ParaList(); - - inferencelog.debug("---- Parameteranzahl gleich"); - inferencelog.debug("---- Reduce !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! (" + L1.size() + ") neue(s) Paar(e)"); - - inferencelog.debug("---- PAARBILDUNG "); - for( int k = 0; k < L1.size(); k++ ) - { - Pair P2 = new Pair(L1.elementAt( pi(k, TA1.getTypeName(), TA2.getTypeName(), TTO )),L2.elementAt(k), PairOperator.SmallerExtends ); - inferencelog.debug("---- Paar1: (" + (L1.elementAt( pi(k, TA1.getTypeName(), TA2.getTypeName(), TTO ) )).getName() + ", " + (L2.elementAt(k)).getName() + P2.OperatorEqual() + ")"); - H.addElement(P2); - } - } - - /** - * Implementiert die reduceExt Regel des sub_unify - */ - private static void reduceExt(Menge H, RefType TA1, RefType TA2, Menge TTO) throws SCException - { - inferencelog.debug(" ================================"); - inferencelog.debug(" REDUCEEXT"); - inferencelog.debug(" ================================"); - - Menge L1 = TA1.get_ParaList(); - Menge L2 = TA2.get_ParaList(); - - inferencelog.debug("---- Parameteranzahl gleich"); - inferencelog.debug("---- ReduceExt !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! (" + L1.size() + ") neue(s) Paar(e)"); - - inferencelog.debug("---- PAARBILDUNG "); - for( int k = 0; k < L1.size(); k++ ) - { - Pair P2 = new Pair( L1.elementAt( pi(k, TA1.getTypeName(), TA2.getTypeName(), TTO )), L2.elementAt(k), PairOperator.SmallerExtends ); - inferencelog.debug("---- Paar1: (" + (L1.elementAt( pi(k, TA1.getTypeName(), TA2.getTypeName(), TTO ) )).getName() + ", " + (L2.elementAt(k)).getName() + P2.OperatorEqual() + ")"); - H.addElement(P2); - - } - } - - /** - * Implementiert die reduceSup Regel des sub_unify - */ - private static void reduceSup(Menge H, RefType TA1, RefType TA2, Menge TTO) throws SCException - { - inferencelog.debug(" ================================"); - inferencelog.debug(" REDUCEEXT"); - inferencelog.debug(" ================================"); - - Menge L1 = TA1.get_ParaList(); - Menge L2 = TA2.get_ParaList(); - - inferencelog.debug("---- Parameteranzahl gleich"); - inferencelog.debug("---- ReduceExt !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! (" + L1.size() + ") neue(s) Paar(e)"); - - inferencelog.debug("---- PAARBILDUNG "); - for( int k = 0; k < L1.size(); k++ ) - { - Pair P2 = new Pair(L2.elementAt(k), L1.elementAt( pi(k, TA2.getTypeName(), TA1.getTypeName(), TTO )), PairOperator.SmallerExtends ); - inferencelog.debug("---- Paar1: (" + (L1.elementAt( pi(k, TA2.getTypeName(), TA1.getTypeName(), TTO ) )).getName() + ", " + (L2.elementAt(k)).getName() + P2.OperatorEqual() + ")"); - H.addElement(P2); - } - } - - /** - * Implementiert die reduceEq Regel des sub_unify - * Da in reduce2 unn�tigerweise pi verwendet wird (siehe Kommentar in reduce2), kann reduceEq einfach an reduce2 deligieren. - */ - private static void reduceEq(Menge H, RefType TA1, RefType TA2, Menge TTO) throws SCException - { - reduce2(H,TA1,TA2,TTO); - } - - /** - * Implementiert die reduce2 Regel des sub_unify - */ - private static void reduce2(Menge H, RefType TA1, RefType TA2, Menge TTO) throws SCException - { - inferencelog.debug(" ================================"); - inferencelog.debug(" REDUCE2"); - inferencelog.debug(" ================================"); - - Menge L1 = TA1.get_ParaList(); - Menge L2 = TA2.get_ParaList(); - - inferencelog.debug("---- Parameteranzahl gleich"); - inferencelog.debug("---- Reduce !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! (" + L1.size() + ") neue(s) Paar(e)"); - - // hier mu� die PERMUTATION erfolgen - inferencelog.debug("---- PAARBILDUNG "); - for( int k = 0; k < L1.size(); k++ ) - { - // pi eig. bei reduce2 �berfl�ssig, schadet aber hoff. auch nicht :-) - //luar 19-04-2007 durch das pi kann reduce2 auch als reduceEq verwendet werden. Wenn das pi durch k ersetzt wird, muss reduceEq entsprechend ausprogrammiert werden. - Pair P2 = new Pair( L1.elementAt( pi(k, TA1.getTypeName(), TA2.getTypeName(), TTO ) ), L2.elementAt(k), PairOperator.Equal ); - inferencelog.debug("---- Paar1: (" + (L1.elementAt( pi(k, TA1.getTypeName(), TA2.getTypeName(), TTO ) )).getName() + ", " + (L2.elementAt(k)).getName() + P2.OperatorEqual() + ")"); - H.addElement(P2); - } - } - - /** - * Implementiert die adapt Regel des sub_unify - */ - private static void adapt(Menge H, Pair PFC, RefType TA1, RefType TA2,FC_TTO fc_tto) - { - Hashtable ht = new Hashtable(); - RefType TA1neu = (RefType)Pair.copyType((RefType)PFC.TA2); - inferencelog.debug("TA1neu " + TA1neu.Type2String()); - try - { - match ((RefType)(PFC.TA1), TA1, ht); - ht = CaptureConversionHashtable(ht,fc_tto); - SubstHashtable(TA1neu, ht); - inferencelog.debug("TA1neu " + TA1neu.Type2String()); - } - catch (MatchException e) - { - inferencelog.debug("match im adapt nicht geklappt"); - return; - } - H.addElement(new Pair(TA1neu, TA2, PairOperator.Smaller)); - // Paar P ist Element von FC (von der Struktur her) - inferencelog.debug(" ================================"); - inferencelog.debug(" ADAPT"); - inferencelog.debug(" ================================"); - } - - /** - * Implementiert die adaptExt Regel des sub_unify - */ - private static void adaptExt(Menge H, Pair PFC, RefType TA1, RefType TA2, FC_TTO fc_tto) - { - Hashtable ht = new Hashtable(); - RefType TA1neu = (RefType)Pair.copyType((RefType)PFC.TA2); - inferencelog.debug("TA1neu " + TA1neu.Type2String()); - try - { - match ((RefType)(PFC.TA1), TA1, ht); - ht = CaptureConversionHashtable(ht,fc_tto); - SubstHashtable(TA1neu, ht); - inferencelog.debug("TA1neu " + TA1neu.Type2String()); - } - catch (MatchException e) - { - inferencelog.debug("match im adapt nicht geklappt"); - return; - } - H.addElement(new Pair(TA1neu, new ExtendsWildcardType(TA2.getOffset(),TA2), PairOperator.SmallerExtends)); - // Paar P ist Element von FC (von der Struktur her) - inferencelog.debug(" ================================"); - inferencelog.debug(" ADAPTEXT"); - inferencelog.debug(" ================================"); - } - - /** - * Implementiert die adaptSup Regel des sub_unify - */ - private static void adaptSup(Menge H, Pair PFC, RefType TA1, RefType TA2, FC_TTO fc_tto) - { - Hashtable ht = new Hashtable(); - RefType TA1neu = (RefType)Pair.copyType((RefType)PFC.TA2); - inferencelog.debug("TA1neu " + TA1neu.Type2String()); - try - { - match ((RefType)(PFC.TA1), TA1, ht); - ht = CaptureConversionHashtable(ht,fc_tto); - SubstHashtable(TA1neu, ht); - inferencelog.debug("TA1neu " + TA1neu.Type2String()); - } - catch (MatchException e) - { - inferencelog.debug("match im adapt nicht geklappt"); - return; - } - H.addElement(new Pair(TA1neu, new ExtendsWildcardType(TA2.getOffset(),TA2), PairOperator.SmallerExtends)); - // Paar P ist Element von FC (von der Struktur her) - inferencelog.debug(" ================================"); - inferencelog.debug(" ADAPTSUP"); - inferencelog.debug(" ================================"); - } - - /* luar 03-05-2007 - * Diese Methode ersetzt alle Typen in der Hashtable durch deren CaptureConversion - */ - private static Hashtable CaptureConversionHashtable(Hashtable ht, FC_TTO fc_tto) - { - Hashtable retHT = new Hashtable(); - for(JavaClassName s : ht.keySet()) - { - Type t = ht.get(s); - Type ccT = CaptureConversion(t,fc_tto); - if(ccT != null) - retHT.put(s,ccT); - else - retHT.put(s,t); - } - return retHT; - } - - private static Pair isInFClinks( RefType RT1, RefType RT2, Menge FC) - { - for(Pair p : FC) - { - if(p.TA1 instanceof RefType && p.TA2 instanceof RefType) - { - RefType TA1 = (RefType)p.TA1; - RefType TA2 = (RefType)p.TA2; - if(TA1.getTypeName().equals(RT1.getTypeName()) && TA2.getTypeName().equals(RT2.getTypeName())) - { - Pair dolly = p.clone(); - //((RefType)dolly.TA1).GenericTypeVar2TypePlaceholder(); - MyCompiler.makeGenericTypeVars2TypePlaceHolders(dolly.TA2); - return dolly; - } - } - } - - return null; - } - - - - // ino.method.isRXSimilarRY.28073.defdescription type=line - // PL 06-03-16 - // TypePlaceholder durch GenericTypeVar ersetzt. Das duerfte eigentlich keine - // Fehler ergeben. - // ino.end - // ino.method.isRXSimilarRY.28073.definition - public static boolean isRXSimilarRY( RefType RFC, RefType RY, boolean allowTPH ) - // ino.end - // ino.method.isRXSimilarRY.28073.body - { - // otth: prueft (rekursiv) ob RFC gleiche Sturktur hat wie RY - // RFC: falls Typvariable als Parameterlistenelement vorkommt --> Entsprechung in RY ist egal - - // Namen von RFC und RY muessen gleich sein - if( RFC.getTypeName().equals( RY.getTypeName() ) ) - { - if( RFC.get_ParaList() == null && RY.get_ParaList() == null ) - { - // beide Typen haben keine Parameter --> nur Typnamen muessen uebereinstimmen - return true; - } - - if( RFC.get_ParaList() != null && RY.get_ParaList() != null ) - { - // beide Typen haben Parameter --> Parameterliste durchlaufen - Menge px = RFC.get_ParaList(); - Menge py = RY.get_ParaList(); - if( px.size() == py.size() ) - { - for( int i = 0; i < px.size(); i++ ) - { - if(px.elementAt(i) instanceof GenericTypeVar || (px.elementAt(i) instanceof TypePlaceholder && allowTPH)) { - // Element von RFC ist Typvariable --> Entsprechung von RY kann alles sein - continue; - } - - if( px.elementAt(i) instanceof RefType && py.elementAt(i) instanceof RefType ) - { - RefType RTempX = (RefType)px.elementAt(i); - RefType RTempY = (RefType)py.elementAt(i); - - if( RTempX.get_ParaList() == null && RTempY.get_ParaList() == null ) - { - continue; - } - - // zwei RefTypes --> weiter, rekursiv pruefen - if( isRXSimilarRY( RTempX, RTempY,allowTPH ) ) - { - continue; - } - } - - return false; - } - return true; - } - } - } - - return false; - } - // ino.end - - // ino.method.SubstHashtable2MengePair.28076.definition - public static Menge SubstHashtable2MengePair (Hashtable ht) - // ino.end - // ino.method.SubstHashtable2MengePair.28076.body - { - //PL 05-01-23 wandelt eine Hashtable von Substitutionen - //PL 05-02-12 true BEI KONSTRUKTOR Pair EINGEFUEGT - //in ein Menge von Paaren um. - - Menge ret = new Menge(); - for(Enumeration e=ht.keys();e.hasMoreElements();) { - String k = e.nextElement().toString(); - // #JB# 11.04.2005 - // ########################################################### - ret.addElement(new Pair(TypePlaceholder.backdoorCreate(k), (Type)ht.get(k), PairOperator.Equal)); - //ret.addElement(new Pair(new TypePlaceholder(k), (Type)ht.get(k), true)); - // ########################################################### - } - return ret; - } - // ino.end - - // ino.method.MengePair2SubstHashtableMengePair.28079.definition - public static Hashtable MengePair2SubstHashtableMengePair (Menge v) - // ino.end - // ino.method.MengePair2SubstHashtableMengePair.28079.body - { - //PL 05-01-23 wandelt einen Menge von Paaren (a, ty) von Substitutionen - //in eine Hashtable um. - - Hashtable ret = new Hashtable(); - for(Enumeration e=v.elements();e.hasMoreElements();) { - Pair p = e.nextElement(); - ret.put(p.TA1.getName(), p.TA2); - } - return ret; - } - // ino.end - - // ino.method.copyMengePair.28082.definition - public static Menge copyMengePair (Menge vp) - // ino.end - // ino.method.copyMengePair.28082.body - { - //PL 05-01-23 kopiert einen Menge von Typ-Paaren - - Menge ret = new Menge(); - for (int i=0; i < vp.size(); i++) { - ret.addElement(vp.elementAt(i).copyPair()); - } - return ret; - } - // ino.end - - // ino.method.copyMengeMengePair.28085.definition - public static Menge> copyMengeMengePair (Menge> vp) - // ino.end - // ino.method.copyMengeMengePair.28085.body - { - //PL 05-02-08 kopiert einen Menge von Mengeen von Typ-Paaren - - Menge> ret = new Menge>(); - for (int i=0; i < vp.size(); i++) { - ret.addElement(copyMengePair(vp.elementAt(i))); - } - return ret; - } - // ino.end - - - - // ino.method.instanceSmaller.28088.definition - public static Menge> instanceSmaller(Pair P, FC_TTO fc_tto ) - // ino.end - // ino.method.instanceSmaller.28088.body - { - //PL 05-01-23 bekommt als Eingabe ein Paar (a, ty') und bestimmt - //die Menge der Menge aller Substitutionen a \leq^* \sigma(ty), wobei - //\sigma = unify(ty', \ol{ty}') (ty, \ol{ty}') \in FC - - Menge FC = fc_tto.getFC(); - Menge> ret = new Menge>(); - Menge element; - - RefType ty = (RefType)P.TA2; - //Menge der \sigma(\theta) bestimmen, die in FC als linke Seite - //vorkommt - Hashtable testht = new Hashtable(); - for (int i=0; i < FC.size(); i++) { - // try { - Hashtable ht = new Hashtable(); - //HIER MOEGLICHERWEISE sub_unify MIT true IN DEN PAAREN AUFRUFEN - //BEI INSTANZIERTEN TYPEN WEREDN KEINE SUBTYPEN GEBILDET - //VERGLEICHE pl1.1.1.3.jav - //match(ty, (RefType)(((Pair)FC.elementAt(i)).TA2), ht); - Menge subunifypair = new Menge (); - RefType ob = ((RefType)(FC.elementAt(i).TA2)).clone();// !!!oder Pair.copyType!!! - CSubstitutionSet sub = ob.GenericTypeVar2TypePlaceholder(); - sub.applyThisSubstitutionSet(ob); - subunifypair.addElement(new Pair(Pair.copyType(ty), ob, PairOperator.Equal)); - //06-04-27 PL HIER MUSS VERMUTLIRH NORH AUF DAS TA2 ein fresh angewandt werden. - //MEHRFACHES UNIFIZIEREN, WENN EIN TYP UND EINE INSTANZ DAVON AUCH IN FC - //LIEGT - //erlegigt 06-04-28 - Menge res = sub_unify(subunifypair, fc_tto); - if (hasSolvedForm(res)) { //PL 13-05-22: hasSolvedForm geaendert, es nicht gekl�rt, ob es funktioniert. - inferencelog.debug("HasSolvedForm: "); - printMenge("RES_SMALLER", res, 6); - ht = MengePair2SubstHashtableMengePair(res); - //RefType tynew = (RefType)Pair.copyType(ty); - RefType tynew = (RefType)Pair.copyType((RefType)(FC.elementAt(i).TA1)); - sub.applyThisSubstitutionSet(tynew); - //HIER MUESSEN IM SUBTYPE tynew NEU HINZUGEKOMMENE GENTYPEVARS NOCH DURCH TypePlaceholders VARS ERSETZT WERDEN - //pl 06-04-29 - SubstHashtable(tynew, ht); - //falls Typvariablen bei Vererbung hinzugekommen sind. - CSubstitutionSet sub1 = tynew.GenericTypeVar2TypePlaceholder(); - sub1.applyThisSubstitutionSet(tynew); - element = SubstHashtable2MengePair(ht); - printMenge("ELEMENT", element, 6); - //Menge smaller = new Menge (); - //smaller.addElement(tynew); - Menge smaller; - - //DIESER AUFRUF IS MOEGLICHERWEISE UNNOETIG, DA ALLE - //KLEINEREN ELEMENTE BEREITS DURCH ANDERE ELEMENTE AUS - //FC BESTIMMT WURDEN BZW. WERDEN. - smaller = allSmaller(tynew, FC); - - //wegen Reflexivitaet hinzufuegen, wenn tynew und ty aequivalent - //dann wird ganz am Ende hinzugefuet - smaller.addElement(tynew); - - for (int j = 0; j < smaller.size(); j++) { - Menge newelement = copyMengePair(element); - if (smaller.size() >= 1) { - RefType testreftype = testht.put(smaller.elementAt(j).Type2Key(), smaller.elementAt(j)); - if (testreftype == null) - { - newelement.addElement(new Pair(P.TA1, smaller.elementAt(j), PairOperator.Equal)); - printMenge("NEWELEMENT", newelement, 6); - ret.addElement(newelement); - } - } - } - // } - // catch (matchException e) { - // System.out.println("matchException " + e.getMessage() + " " + ((RefType)(((Pair)FC.elementAt(i)).TA2)).Type2String()); - // //smaller = new Menge(); - // //element = new Menge(); - // } - } - } - Menge equalElement = new Menge(); - equalElement.addElement(new Pair(P.TA1, P.TA2, PairOperator.Equal)); - ret.addElement(equalElement); - printMengeUnifier("RES_SMALLERend", ret, 6); - return ret; - } - // ino.end - - // ino.method.allSmaller.28091.definition - public static Menge allSmaller(RefType ty, Menge FC) - // ino.end - // ino.method.allSmaller.28091.body - { - //PL 05-01-22 bestimmt alle Typen die kleiner sind als ty - - Menge ret = new Menge(); - - inferencelog.debug("New allSmaller " + ty.Type2String()); - - //doppelte untere Typen von Paaren eleminieren - Hashtable hht = new Hashtable(); - - for (int i=0; i < FC.size(); i++) { - if (hht.put(((RefType)(FC.elementAt(i).TA1)).getName(), (RefType)(FC.elementAt(i).TA1)) != null) { } - else { - inferencelog.debug("Getestet1: " + (new Pair((RefType)(FC.elementAt(i).TA1), ty)).toString()); - RefType ty1 = (RefType)Pair.copyType(ty); - Pair P = isInFC((RefType)(FC.elementAt(i).TA1), ty1, FC); - // RefType FCrselem = (RefType)(((Pair)FC.elementAt(i)).TA2); - - // //bestimmt alle Element, die ohne instance kleiner als ty ist - // P = (Pair)FC.elementAt(i); //angenommenes Ergebnis, wird ggfs. geloescht - // if (FCrselem.getTypeName().equals(ty.getTypeName())) { - // if (FCrselem.get_ParaList() != null && ty.get_ParaList() != null) { - // if (FCrselem.get_ParaList().size() == ty.get_ParaList().size()) { - // for (int j = 0; j < FCrselem.get_ParaList().size(); j++) { - // if (!(FCrselem.get_ParaList().elementAt(j) instanceof TypePlaceholder) - // || !(ty.get_ParaList().elementAt(j) instanceof TypePlaceholder)) { - // P = null; - // break; - // } - // } - // } - // } - // } - // else P = null; - inferencelog.debug("Getestet2: " + P); - //HIER IN isInFC SCHEINT EIN FEHLER ZU SEIN. - - if (P != null) { - //System.out.println("ISIN"); - RefType smaller = (RefType)Pair.copyType(P.TA1); - Hashtable ht = new Hashtable(); - try { - match((RefType)P.TA2, ty, ht); - //Problem koennte sein, dass ein TypePlaceholder mehrere Typterme - //zugeordnet werden. - SubstHashtable(smaller, ht); - ret.addElement(smaller); - } - catch (MatchException e) { } - } - } - } - return ret; - } - // ino.end - // ino.method.allGreater.28094.definition - public static Menge allGreater (RefType ty, Menge FC) - // ino.end - // ino.method.allGreater.28094.body - { - - Menge ret = new Menge(); - - - Hashtable testht = new Hashtable(); - for (int i=0; i < FC.size(); i++) { - //System.out.println("Getestet1: " + (new Pair((RefType)(((Pair)FC.elementAt(i)).TA1), ty)).toString()); - Pair P; - P = isInFC(ty, (RefType)(FC.elementAt(i).TA2), FC); - if (P != null) { - //Testen, ob das mit der Hashtable funktioniert. - Pair testreftype = testht.put(P, P); - if (testreftype == null) { - inferencelog.debug("ISIN" + ty.Type2String() + P.toString()+" "+(FC.elementAt(i)).toString()); - RefType greater = (RefType)Pair.copyType(P.TA2); - Hashtable ht = new Hashtable(); - try { - //Hier muessen GTV durch TLV ersetzt werden. - //vgl. searchAndHandleMethod in MethodCall.java - match((RefType)P.TA1, ty, ht); - //Problem koennte sein, dass ein TypePlaceholder mehrere Typterme - //zugeordnet werden. - SubstHashtableGeneric(greater, ht); - ret.addElement(greater); - } - catch (MatchException e) { - inferencelog.error("Kein Match im allGreater"); - } - } - } - } - return ret; - } - // ino.end - - // ino.method.isInFC.28097.definition - public static Pair isInFC( RefType R1, RefType R2, Menge FC ) - // ino.end - // ino.method.isInFC.28097.body - { - // otth: Funktion, die prueft, ob Paar( R1, R2 ) in FC liegt, - // bzw. deren rechten Seiten, ohne die TypePlaceholder-Variablen zu beachten - // z.B. Menge w�re hier gleich wie Menge - - // z.B. FC = { ( AA <=* CC< DD > ) ,...} - // R1 = AA - // R2 = CC< DD< Char, a> > - - // FC durchlaufen - RefType RFC = null; // temporaer, fuer Element von FC - for( int i = 0; i < FC.size(); i++ ) - { - Pair P = FC.elementAt(i); - - // R1 bzw. linke Seite testen - if( P.TA1 instanceof RefType && P.TA2 instanceof RefType ) - { - RFC = (RefType)P.TA1; - //System.out.println("SIMILAR1"); - if( isRXSimilarRY( RFC, R1, false ) ) - { - //System.out.println("SIMILAR2"); - // linke Seiten gleich --> rechte Seiten testen - RFC = (RefType)P.TA2; - if( isRXSimilarRY( RFC, R2, false ) ) - { - // rechte Seiten gleich - inferencelog.debug("Folgendes Paar ist Element von FC: " + P.toString() + (new Pair(R1, R2)).toString()); - return P; - } - } - } - - // Paare sind nicht gleich --> FC weiter durchlaufen - - } // end for: FC durchlaufen - - // kein passendes Paar in FC gefunden - return null; - - } // end Funktino: isInFC - // ino.end - - // ino.method.isInFCrechtsUnify.28100.definition - public static Pair isInFCrechtsUnify( RefType RT1, RefType RT2, FC_TTO fc_tto ) - // ino.end - // ino.method.isInFCrechtsUnify.28100.body - { - // otth: Funktion, die prueft, ob Paar( R1, \sigma(R2) ) in FC liegt, - // bzw. deren rechten Seiten, ohne die TypePlaceholders zu beachten - // z.B. Menge w�re hier gleich wie Menge - - // z.B. FC = { ( AA <=* CC< DD > ) ,...} - // R1 = AA - // R2 = CC< DD< Char, a> > - - // FC durchlaufen - Menge FC = fc_tto.getFC(); - RefType RFC = null; // temporaer, fuer Element von FC - for( int i = 0; i < FC.size(); i++ ) - { - RefType R1 = (RefType)Pair.copyType(RT1); - RefType R2 = (RefType)Pair.copyType(RT2); - Pair P = FC.elementAt(i); - inferencelog.debug("getestestes Paar" + P.toString()); - - // R1 bzw. linke Seite testen - if( P.TA1 instanceof RefType && P.TA2 instanceof RefType ) - { - RFC = (RefType)P.TA1; - inferencelog.debug("VOR SIMILAR1" + RFC.Type2String() + " " + R1.Type2String()); - if( isRXSimilarRY( RFC, R1, false ) ) - { - inferencelog.debug("SIMILAR1"); - // linke Seiten gleich --> rechte Seiten testen - RFC = (RefType)P.TA2; - Menge R2vec = new Menge (); - inferencelog.debug("New_Pair" + (new Pair(RFC, R2, PairOperator.Smaller)).toString()); - - //STIMMT DAS copyType??? - RefType RFC_new = RFC.clone(); - RFC_new.GenericTypeVar2TypePlaceholder(); - R2vec.addElement(new Pair(RFC_new, R2.clone(), PairOperator.Smaller)); - - printMenge("R2vec", R2vec, 6); - Menge vp = sub_unify(R2vec, fc_tto); - - printMenge("VP", vp, 6); - if ( hasSolvedForm(vp) ) //PL 13-05-22: hasSolvedForm geaendert, es nicht gekl�rt, ob es funktioniert. - //if( isRXSimilarRY( RFC, R2 ) ) - { - inferencelog.debug("SIMILAR2"); - // rechte Seiten gleich - inferencelog.debug("Folgendes Paar ist Element von FC: " + P.toString()); - return P; - } - } - } - - // Paare sind nicht gleich --> FC weiter durchlaufen - - } // end for: FC durchlaufen - - // kein passendes Paar in FC gefunden - return null; - - } // end Funktino: isInFC - // ino.end - - // ino.method.isTVinRefType.28103.definition - public static boolean isTVinRefType( TypePlaceholder TV, RefType RT ) - // ino.end - // ino.method.isTVinRefType.28103.body - { - // otth: Prueft ob TV in RefType vorkommt, falls ja --> true - - // Name der Typvariablen - JavaClassName strTV = TV.getName(); - - // Parameterliste extrahieren - if( RT.get_ParaList() == null ) - // keine Parameterliste - return false; - else - { - // Parameterliste vorhanden --> durchiterieren - Menge P = RT.get_ParaList(); - for( int i = 0; i < P.size(); i++ ) - { - Type T = (Type)P.elementAt( i ); - if (T instanceof ExtendsWildcardType) T = ((ExtendsWildcardType)T).get_ExtendsType(); - - if( T instanceof TypePlaceholder ) - { - // T ist eine Typvariable --> gleiche Namen??? - if( strTV.equals(T.getName()) ) - return true; - } - - if( T instanceof RefType ) - { - // T ist wieder ein RefType --> rekursiver Aufruf - if( isTVinRefType( TV, (RefType)T ) ) - return true; - } - - } - - return false; - } - } - // ino.end - - // ino.method.Subst.28106.defdescription type=line - // void Subst( Pair P, int nTypnrInPair, TypePlaceholder a, RefType o, boolean - // bMitVorbedingung ) PL 05-02-10 fuer o sind auch TypePlaceholder moeglich - // ino.end - // ino.method.Subst.28106.definition - public static boolean Subst( Pair P, int nTypnrInPair, TypePlaceholder a, Type o, boolean bMitVorbedingung ) - // ino.end - // ino.method.Subst.28106.body - { - // otth: Hilfsfunktion zur Unifikation - // otth: Ersetzen der Typvariablen a durch den RefType o - // otth: in dem nTypnrInPair. Type des Paares P - // otth: Pair uebergeben, da Zeiger nur by Value kopiert wird, s. TV - // otth: bMitVorbedingung: Darf die Typvariable a auf der rechten Seite auch vorkommen oder nicht? - - inferencelog.debug("SUBST: "); - inferencelog.debug("Pair: " + P.toString()); - inferencelog.debug("Nummer: " + nTypnrInPair); - inferencelog.debug("TV: " + a.getName()); - inferencelog.debug("Bedingung: " + bMitVorbedingung); - - // richtiger Typ aus Pair raussuchen - Type T = null; - if( nTypnrInPair == 1 ) - T = (Type)P.TA1; - else - T = (Type)P.TA2; - - // Vorbedingung: in o darf a nicht vorkommen!!! - if (o instanceof RefType) {//PL 05-02-09 eingefuegt siehe Methodenkopf - if( bMitVorbedingung && isTVinRefType( a, (RefType)o ) ) - { - inferencelog.debug(" Subst nicht m�glich, da TV " + a.getName() + " in RefType " + o.getName()); - return false; - } - } - - // Reftypes substituieren - if( T instanceof RefType && ((RefType)T).get_ParaList() != null ) - { - // Parameterliste durchgehen - Menge vTemp = ((RefType)T).get_ParaList(); - Boolean ret = true; //EINGEFUEGT PL 14-01-16: Return darf erst am Ende zur�ckgegeben werden und nicht in den ifs - //sonst werden nicht alle Elemente der Forschleife durchlaufen - for( int i = 0; i < vTemp.size(); i++ ) - { - Type Temp = (Type)vTemp.elementAt(i); - - // u.U. umwandeln in TypePlaceholders, auskommentiert, da umgestellt auf RefType und TypePlaceholder - // if( Temp instanceof RefType && ((RefType)Temp).get_ParaList() == null ) - // Temp = new TypePlaceholder( ((RefType)Temp).getName() ); - - if( Temp instanceof TypePlaceholder ) - { - - if( Temp.getName().equals(a.getName()) ) - { - // Typvariable ersetzen - Menge vParaListTemp = ((RefType)T).get_ParaList(); - vParaListTemp.set( i, o ); // i. Element ersetzen - ret &= true; //GEAENDERT PL 14-01-17 - } - } - if( (Temp instanceof RefType ) || (Temp instanceof ExtendsWildcardType ) || (Temp instanceof SuperWildcardType ) ) - //PL 2015-01-20 eingefuegt: || (Temp instanceof ExtendsWildcardType ) || (Temp instanceof SuperWildcardType ) - { - Pair PTemp = new Pair( Temp, null); - inferencelog.debug(" TV!!!" + PTemp.toString() ); - ret &= Subst( PTemp, 1, a, o, bMitVorbedingung ); //GEAENDERT PL 14-01-17 - } - } - return ret; //EINGEFUEGT PL 14-01-16 - } - - // TV substituieren - if( T instanceof TypePlaceholder ) - { - if( T.getName().equals( a.getName() ) ) - { - // TV ersetzen - if( nTypnrInPair == 1 ) - P.TA1 = o; - else - P.TA2 = o; - - return true; - } - } - //Wildcard erg�nzt PL 14-12-05 - if ( T instanceof ExtendsWildcardType ) - { - Type Temp = ((ExtendsWildcardType) T).get_ExtendsType(); - if( Temp instanceof TypePlaceholder ) - { - - if( Temp.getName().equals(a.getName()) ) - { - // Typvariable ersetzen - ((ExtendsWildcardType) T).SetWildcardType(o); - return true; - } - } - } - //Wildcard erg�nzt PL 14-12-05 - if ( T instanceof SuperWildcardType ) - { - Type Temp = ((SuperWildcardType) T).get_SuperType(); - if( Temp instanceof TypePlaceholder ) - { - - if( Temp.getName().equals(a.getName()) ) - { - // Typvariable ersetzen - ((SuperWildcardType) T).SetWildcardType(o); - return true; - } - } - } - return false; - } - // ino.end - - // ino.method.SubstHashtableGeneric.28109.defdescription type=line - // SubstHashtableGeneric ersetzt in typterm alle GenericType Variablen aus ht - // durch den zugeordneten Typ. - // ht enthaelt Elemente der (String, Type) - // ino.end - // ino.method.SubstHashtableGeneric.28109.definition - public static void SubstHashtableGeneric(RefType typterm, Hashtable ht) - // ino.end - // ino.method.SubstHashtableGeneric.28109.body - { - Menge para = typterm.get_ParaList(); - if (para != null) { - for (int i=0; i < para.size(); i++) { - if (para.elementAt(i) instanceof GenericTypeVar) { - if (ht.get(((GenericTypeVar)para.elementAt(i)).getName()) != null) { - para.set(i, ht.get(((GenericTypeVar)para.elementAt(i)).getName())); - } - } - else { - if (para.elementAt(i) instanceof RefType) - SubstHashtableGeneric(((RefType)para.elementAt(i)), ht); - } - } - } - } - // ino.end - - // ino.method.SubstHashtable.28112.defdescription type=line - // SubstHashtable ersetzt in typterm alle TypePlaceholder-Variablen aus ht durch - // den zugeordneten Typ. - // ht enthaelt Elemente der (String, Type) - // ino.end - // ino.method.SubstHashtable.28112.definition - public static void SubstHashtable(RefType typterm, Hashtable ht) - // ino.end - // ino.method.SubstHashtable.28112.body - { - Menge para = typterm.get_ParaList(); - if (para != null) { - for (int i=0; i < para.size(); i++) { - if (para.elementAt(i) instanceof TypePlaceholder) { - if (ht.get(((TypePlaceholder)para.elementAt(i)).getName()) != null) { - para.set(i, ht.get(((TypePlaceholder)para.elementAt(i)).getName())); - } - } - else { - if (para.elementAt(i) instanceof RefType) - SubstHashtable(((RefType)para.elementAt(i)), ht); - } - } - } - } - // ino.end - - - // ino.method.isRealSubClass.28115.definition - public static boolean isRealSubClass( String Basis, String Mutter, FC_TTO fc_tto ) - // ino.end - // ino.method.isRealSubClass.28115.body - { - - - // otth: Funktion pr�ft, ob Klasse 'Basis' von Klasse 'Mutter' direkt oder indirekt abgeleitet ist - - // Basisklasse suchen - Menge tto = fc_tto.getTTO(); - for( int i = 0; i < tto.size(); i++ ) - { - //Class tempKlasse = (Class)KlassenVektor.elementAt(i); - Pair tempPair = (Pair)tto.elementAt(i); - //if( Basis.equals( tempKlasse.get_classname() ) ) - if( Basis.equals( ((RefType)tempPair.TA1).getTypeName() ) ) - { - //if( tempKlasse.get_Superclass_Name() != null ) - { - // Zusatzbedingung: otth - falls Typkonstruktoren in Superklassen auftreten --> ungueltig ?? - //Menge s = ((UsedId)tempKlasse.superclassid).vParaOrg; - Menge s = ((RefType)tempPair.TA2).get_ParaList(); - - // HOTI: Bugfixing: Wenn die ParaList leer ist, wird schlich ein neuer Vektor angelegt,der leer ist - - if(s==null){ - s=new Menge(); - } - - /* - * Hier wird �berpr�ft ob in der Paraliste ein anderes Element als ein GTV drinne ist. - * Sollte ein anderes Element gefunden werden ist Reduce nicht m�glich. - * Beispiel: Matrix <. Menge> ist nur durch adapt m�glich. - */ - for(Type t : s) - { - if(!(t instanceof GenericTypeVar)) - return false; - } - - /*for( int l = 0; l < s.size(); l++ ) - { - if( s.elementAt(l) instanceof RefType ) - { - if( ((RefType)s.elementAt(l)).get_ParaList() != null ) - { - inferencelog.debug("Superklasse enthaelt Typkonstruktoren!"); - return false; - } - } - }*/ - - //if( tempKlasse.get_Superclass_Name().equals( Mutter ) ) - if( ((RefType)tempPair.TA2).getTypeName().equals( Mutter ) ) - return true; // Basis ist von Mutter abgeleitet - else - { - //return isRealSubClass( tempKlasse.get_Superclass_Name(), Mutter, fc_tto ); - return isRealSubClass( ((RefType)tempPair.TA2).getTypeName(), Mutter, fc_tto ); - } - } - //else - //{ - // return false; - //} - } - } - return false; - } - // ino.end - -// ino.method.pi.28118.defdescription type=block -/* - public static void test( ) - { - for( int i = 0; i < KlassenVektor.size(); i++ ) - { - Class tempKlasse = (Class)KlassenVektor.elementAt(i); - System.out.println( "Klasse: " + tempKlasse.get_classname() ); - System.out.println( "P. K.: " + tempKlasse.get_ParaList() ); - if( tempKlasse.get_Superclass_Name() != null ) - { - Menge s = ((UsedId)tempKlasse.superclassid).vParaOrg; - System.out.println( "S. Klasse: " + -tempKlasse.get_Superclass_Name() ); System.out.println( "P. S.: -" + tempKlasse.get_ParaList() ); - } - } - } -*/ -// ino.end - - /* Alte pi-Methode: -<<<<<<< HEAD - // ino.method.pi.28118.definition - public static int pi( int n, String C, String D, Menge tto ) - throws SCException - // ino.end - // ino.method.pi.28118.body - { - // otth: Permutation, benoetigt fuer Unifikation - // C, D: Namen von Klassen - // z.B. class C --- class D - // pi(1) = 2 - - // MyCompiler.printDebugInfo("---------------- Permutation: n = " + String.valueOf(n) + " - C = " + C + " - D = " + D, 6); - - // Klassen suchen - //Class KlasseC = null; - //Class KlasseD = null; - //Class tempKlasse = null; - // for( int i = 0; i < KlassenVektor.size(); i++ ) - // { - // // MyCompiler.printDebugInfo("---------------- Permutation: i = " + String.valueOf(i) + " - Classname = " + ((Class)KlassenVektor.elementAt(i)).get_classname(), 6); - - // if( KlasseC != null && KlasseD != null ) - // break; - - // tempKlasse = (Class)KlassenVektor.elementAt(i); - // if( C.equals( tempKlasse.get_classname() ) ) - // { - // KlasseC = tempKlasse; - // // MyCompiler.printDebugInfo("---------------- Permutation: C-Klasse gefunden!", 6); - // } - - // if( D.equals( tempKlasse.get_classname() ) ) - // { - // KlasseD = tempKlasse; - // // MyCompiler.printDebugInfo("---------------- Permutation: D-Klasse gefunden!", 6); - // } - // } - - if (C.equals(D)) return n; //Reduktion mit gleichen Typkonstruktoren - - else { - RefType KlasseC = null; - RefType KlasseD = null; - //RefType tempKlasse = null; - - for( int i = 0; i < tto.size(); i++ ) { - - KlasseC = (RefType)((Pair)tto.elementAt(i)).TA1; - KlasseD = (RefType)((Pair)tto.elementAt(i)).TA2; - - if (KlasseC.getTypeName().equals(C) && KlasseD.getTypeName().equals(D)) { - break; - } - else { - KlasseC = null; - KlasseD = null; - } - - } - - SCException F = new SCException(); - if( KlasseC == null && KlasseD == null ) - throw F; // Fehler - - // Vektorlisten extrahieren - Menge vC = KlasseC.get_ParaList(); - Menge vD = KlasseD.get_ParaList(); - - if( vC == null || vD == null ) - throw F; - - if( n >= vD.size() ) - throw F; - - // Permuationswert f�r 'n' berechnen - Type TV = (Type)vD.elementAt(n); - - int nPos = -1; - - // MyCompiler.printDebugInfo("---------------- Permutation: vC.size() = " + String.valueOf( vC.size() ), 6); - - for( int i = 0; i < vC.size(); i++ ) - { - // MyCompiler.printDebugInfo("---------------- Permutation: TV = " + ((Type)vC.elementAt(i)).getName_(), 6); - if( ((Type)vC.elementAt(i)).getName().equals( TV.getName() ) ) - { - nPos = i; - break; - } - } - - if (nPos == -1) - throw F; - - // MyCompiler.printDebugInfo("---------------- Permutation: = " + String.valueOf( nPos ), 6); - - return nPos; - } - } -======= -*/ - // ino.method.pi.28118.definition - public static int pi(int n, String C, String D, Menge tto) - throws SCException { - - if (C.equals(D)) - return n; // Reduktion mit gleichen Typkonstruktoren - - RefType KlasseC = null; - RefType KlasseD = null; - - for (int i = 0; i < tto.size(); i++) { - - KlasseC = (RefType) ((Pair) tto.elementAt(i)).TA1; - KlasseD = (RefType) ((Pair) tto.elementAt(i)).TA2; - - if (KlasseC.getTypeName().equals(C) - && KlasseD.getTypeName().equals(D)) - break; - else { - KlasseC = null; - KlasseD = null; - } - } - - SCException F = new SCException(); - if (KlasseC == null && KlasseD == null) - throw F; // Fehler - - // Vektorlisten extrahieren - Menge vC = KlasseC.get_ParaList(); - Menge vD = KlasseD.get_ParaList(); - - if (vC == null || vD == null) - throw F; - - if (n >= vD.size()) - throw F; - - // Permuationswert f�r 'n' berechnen - Type TV = (Type) vD.elementAt(n); - int nPos = -1; - for (int i = 0; i < vC.size(); i++) - if (((Type) vC.elementAt(i)).getName().equals(TV.getName())) { - nPos = i; - break; - } - - return nPos; - - } +package de.dhbwstuttgart.typeinference.unify; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import de.dhbwstuttgart.typeinference.Menge; +import de.dhbwstuttgart.typeinference.Pair; +import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; +import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; +import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; +import de.dhbwstuttgart.typeinference.unify.interfaces.ISetOperations; +import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; +import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; +import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; +import de.dhbwstuttgart.typeinference.unify.model.SuperType; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; +import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.TypeParams; +import de.dhbwstuttgart.typeinference.unify.model.Unifier; + + +/** + * Implementation of the type unification algorithm + * @author Florian Steurer + */ +public class Unify { + + public Set> unify(Set eq, IFiniteClosure fc) { + /* + * Step 1: Repeated application of reduce, adapt, erase, swap + */ + + Set eq0 = applyTypeUnificationRules(eq, fc); + + /* + * Step 2 and 3: Create a subset eq1s of pairs where both sides are TPH and eq2s of the other pairs + */ + + Set eq1s = new HashSet<>(); + Set eq2s = new HashSet<>(); + splitEq(eq0, eq1s, eq2s); + + /* + * Step 4: Create possible typings + * + * "Manche Autoren identifizieren die Paare (a, (b,c)) und ((a,b),c) + * mit dem geordneten Tripel (a,b,c), wodurch das kartesische Produkt auch assoziativ wird." - Wikipedia + */ + + // There are up to 10 toplevel set. 8 of 10 are the result of the + // cartesian product of the sets created by pattern matching. + List>> topLevelSets = new ArrayList<>(); + + if(eq1s.size() != 0) { + Set> wrap = new HashSet<>(); + wrap.add(eq1s); + topLevelSets.add(wrap); // Add Eq1' + } + + // Add the set of [a =. Theta | (a=. Theta) in Eq2'] + Set bufferSet = eq2s.stream() + .filter(x -> x.getPairOp() == PairOperator.EQUALSDOT && x.getLhsType() instanceof PlaceholderType) + .collect(Collectors.toSet()); + + if(bufferSet.size() != 0) { + Set> wrap = new HashSet<>(); + wrap.add(bufferSet); + topLevelSets.add(wrap); + } + + // Sets that originate from pair pattern matching + // Sets of the "second level" + Set>> secondLevelSets = calculatePairSets(eq2s, fc); + + /* Up to here, no cartesian products are calculated. + * filters for pairs and sets can be applied here */ + + ISetOperations setOps = new GuavaSetOperations(); + + // Sub cartesian products of the second level (pattern matched) sets + for(Set> secondLevelSet : secondLevelSets) { + List> secondLevelSetList = new ArrayList<>(secondLevelSet); + topLevelSets.add(setOps.cartesianProduct(secondLevelSetList) + .stream().map(x -> new HashSet<>(x)) + .collect(Collectors.toCollection(HashSet::new))); + } + + // Cartesian product over all (up to 10) top level sets + Set>> eqPrimeSet = setOps.cartesianProduct(topLevelSets) + .stream().map(x -> new HashSet<>(x)) + .collect(Collectors.toCollection(HashSet::new)); + //System.out.println(result); + + /* + * Step 5: Substitution + */ + + /* + * TODO hier das ergebnis schonh flach machen? (wird im unify old (glaub ich) so gemacht) + */ + Set> eqPrimeSetFlat = new HashSet<>(); + for(Set> setToFlatten : eqPrimeSet) { + Set buffer = new HashSet<>(); + setToFlatten.stream().forEach(x -> buffer.addAll(x)); + eqPrimeSetFlat.add(buffer); + } + + IRuleSet rules = new RuleSet(fc); + Set> changed = new HashSet<>(); + Set> eqPrimePrimeSet = new HashSet<>(); + + for(Set eqPrime : eqPrimeSetFlat) { + Optional> eqPrimePrime = rules.subst(eqPrime); + + if(eqPrimePrime.isPresent()) + changed.add(eqPrimePrime.get()); + else + eqPrimePrimeSet.add(eqPrime); + } + + /* + * Step 6 a) Restart for pairs where subst was applied + * b) Build the union over everything + */ + + for(Set eqss : changed) { + eqPrimePrimeSet.addAll(this.unify(eqss, fc)); + } + + /* + * Step 7: Filter result for solved pairs + */ + return eqPrimePrimeSet; + + } + + protected Set applyTypeUnificationRules(Set eq, IFiniteClosure fc) { + + /* + * Rule Application Strategy: + * + * 1. Swap all pairs and erase all erasable pairs + * 2. Apply all possible rules to a single pair, then move it to the result set. + * Iterating over pairs first, then iterating over rules prevents the application + * of rules to a "finished" pair over and over. + * 2.1 Apply all rules repeatedly except for erase rules. If + * the application of a rule creates new pairs, check immediately + * against the erase rules. + */ + + + LinkedHashSet targetSet = new LinkedHashSet(); + LinkedList eqQueue = new LinkedList<>(); + IRuleSet rules = new RuleSet(fc); + + /* + * Swap all pairs and erase all erasable pairs + */ + eq.forEach(x -> swapAddOrErase(x, rules, eqQueue)); + + /* + * Apply rules until the queue is empty + */ + while(!eqQueue.isEmpty()) { + MPair pair = eqQueue.pollFirst(); + + // ReduceUp, ReduceLow, ReduceUpLow + Optional opt = rules.reduceUpLow(pair); + opt = opt.isPresent() ? opt : rules.reduceLow(pair); + opt = opt.isPresent() ? opt : rules.reduceUp(pair); + + // One of the rules has been applied + if(opt.isPresent()) { + swapAddOrErase(opt.get(), rules, eqQueue); + continue; + } + + // Reduce1, Reduce2, ReduceExt, ReduceSup, ReduceEq + Optional> optSet = rules.reduce1(pair); + optSet = optSet.isPresent() ? optSet : rules.reduce2(pair); + optSet = optSet.isPresent() ? optSet : rules.reduceExt(pair); + optSet = optSet.isPresent() ? optSet : rules.reduceSup(pair); + optSet = optSet.isPresent() ? optSet : rules.reduceEq(pair); + + // One of the rules has been applied + if(optSet.isPresent()) { + optSet.get().forEach(x -> swapAddOrErase(x, rules, eqQueue)); + continue; + } + + // Adapt, AdaptExt, AdaptSup + opt = rules.adapt(pair); + opt = opt.isPresent() ? opt : rules.adaptExt(pair); + opt = opt.isPresent() ? opt : rules.adaptSup(pair); + + // One of the rules has been applied + if(opt.isPresent()) { + swapAddOrErase(opt.get(), rules, eqQueue); + continue; + } + + // None of the rules has been applied + targetSet.add(pair); + } + + return targetSet; + } + + protected void swapAddOrErase(MPair pair, IRuleSet rules, Collection collection) { + Optional opt = rules.swap(pair); + MPair pair2 = opt.isPresent() ? opt.get() : pair; + + if(rules.erase1(pair2) || rules.erase3(pair2) || rules.erase2(pair2)) + return; + + collection.add(pair2); + } + + protected void splitEq(Set eq, Set eq1s, Set eq2s) { + for(MPair pair : eq) + if(pair.getLhsType() instanceof PlaceholderType && pair.getRhsType() instanceof PlaceholderType) + eq1s.add(pair); + else + eq2s.add(pair); + } + + + protected Set>> calculatePairSets(Set eq2s, IFiniteClosure fc) { + List>> result = new ArrayList<>(); + + // Init all 8 cases + for(int i = 0; i < 8; i++) + result.add(new HashSet<>()); + + for(MPair pair : eq2s) { + + PairOperator pairOp = pair.getPairOp(); + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + + // Case 1: (a <. Theta') + if(pairOp == PairOperator.SMALLERDOT && lhsType instanceof PlaceholderType) + result.get(0).add(unifyCase1((PlaceholderType) pair.getLhsType(), pair.getRhsType(), fc)); + + // Case 2: (a <.? ? ext Theta') + else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof ExtendsType) + result.get(1).add(unifyCase2((PlaceholderType) pair.getLhsType(), (ExtendsType) pair.getRhsType(), fc)); + + // Case 3: (a <.? ? sup Theta') + else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof SuperType) + result.get(2).add(unifyCase3((PlaceholderType) lhsType, (SuperType) rhsType, fc)); + + // Case 4: (a <.? Theta') + else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType) + result.get(3).add(unifyCase4((PlaceholderType) lhsType, rhsType, fc)); + + // Case 5: (Theta <. a) + else if(pairOp == PairOperator.SMALLERDOT && rhsType instanceof PlaceholderType) + result.get(4).add(unifyCase5(lhsType, (PlaceholderType) rhsType, fc)); + + // Case 6: (? ext Theta <.? a) + else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof ExtendsType && rhsType instanceof PlaceholderType) + result.get(5).add(unifyCase6((ExtendsType) lhsType, (PlaceholderType) rhsType, fc)); + + // Case 7: (? sup Theta <.? a) + else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof SuperType && rhsType instanceof PlaceholderType) + result.get(6).add(unifyCase7((SuperType) lhsType, (PlaceholderType) rhsType, fc)); + + // Case 8: (Theta <.? a) + else if(pairOp == PairOperator.SMALLERDOTWC && rhsType instanceof PlaceholderType) + result.get(7).add(unifyCase8(lhsType, (PlaceholderType) rhsType, fc)); + } + + return result.stream().filter(x -> x.size() > 0).collect(Collectors.toCollection(HashSet::new)); + } + + protected Set unifyCase1(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { + Set result = new HashSet<>(); + IUnify unify = new MartelliMontanariUnify(); + + Set cs = fc.getAllTypesByName(thetaPrime.getName()); + + for(UnifyType c : cs) { + + // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? + Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + thetaQs.add(c); // reflexive + + Set thetaQPrimes = new HashSet<>(); + TypeParams cParams = c.getTypeParams(); + if(cParams.size() == 0) + thetaQPrimes.add(c); + else { + ArrayList> candidateParams = new ArrayList<>(); + for(UnifyType param : cParams) + candidateParams.add(fc.grArg(param)); + + for(TypeParams tp : permuteParams(candidateParams)) + thetaQPrimes.add(c.setTypeParams(tp)); + } + + for(UnifyType tqp : thetaQPrimes) { + Optional opt = unify.unify(tqp, thetaPrime); + if (!opt.isPresent()) + continue; + + Unifier unifier = opt.get(); + Set> substitutions = unifier.getSubstitutions(); + for (Entry sigma : substitutions) + result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + for (UnifyType tq : thetaQs) { + Set smaller = fc.smaller(unifier.apply(tq)); + smaller.stream().map(x -> new MPair(a, x, PairOperator.EQUALSDOT)) + .forEach(x -> result.add(x)); + } + + } + } + + return result; + } + + protected Set unifyCase2(PlaceholderType a, ExtendsType extThetaPrime, IFiniteClosure fc) { + Set result = new HashSet<>(); + IUnify unify = new MartelliMontanariUnify(); + + UnifyType thetaPrime = extThetaPrime.getExtendedType(); + Set cs = fc.getAllTypesByName(thetaPrime.getName()); + + for(UnifyType c : cs) { + + // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? + Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + thetaQs.add(c); // reflexive + + Set thetaQPrimes = new HashSet<>(); + TypeParams cParams = c.getTypeParams(); + if(cParams.size() == 0) + thetaQPrimes.add(c); + else { + ArrayList> candidateParams = new ArrayList<>(); + for(UnifyType param : cParams) + candidateParams.add(fc.grArg(param)); + + for(TypeParams tp : permuteParams(candidateParams)) + thetaQPrimes.add(c.setTypeParams(tp)); + } + + for(UnifyType tqp : thetaQPrimes) { + Optional opt = unify.unify(tqp, thetaPrime); + if (!opt.isPresent()) + continue; + + Unifier unifier = opt.get(); + Set> substitutions = unifier.getSubstitutions(); + for (Entry sigma : substitutions) + result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + for (UnifyType tq : thetaQs) { + ExtendsType extTq = new ExtendsType(tq); + Set smaller = fc.smaller(unifier.apply(extTq)); + smaller.stream().map(x -> new MPair(a, x, PairOperator.EQUALSDOT)) + .forEach(x -> result.add(x)); + } + } + } + + return result; + } - // ino.end - // ino.method.printMengeUnifier.28121.definition - public static void printMengeUnifier(String strMenge, Menge> Uni, int nDebug ) - // ino.end - // ino.method.printMengeUnifier.28121.body - { - //PL 05-01-21 - //Ruft f�r eine Menge von Unifikatoren die Methode - //printMenge auf - for (int i = 0; i < Uni.size(); i++) { - inferencelog.debug((i+1) + ". Unifier"); - printMenge(strMenge, Uni.elementAt(i), nDebug); - if( hasSolvedForm( Uni.elementAt(i) ) ) { //PL 13-05-22: hasSolvedForm geaendert, es nicht gekl�rt, ob es funktioniert. - inferencelog.debug((i+1) + ". Unifier ist in 'Solved form'!\n"); - } - else { - inferencelog.debug((i+1) + ". Unifier ist nicht in 'Solved Form'\n"); - } - - } - } - // ino.end - - // ino.method.printMenge.28124.definition - public static void printMenge( String strMenge, Menge E, int nDebug ) - // ino.end - // ino.method.printMenge.28124.body - { - // otth - zum Debuggen: Menge ausgeben *********************** - String strTemp = ""; - if( E.size() == 0 ) - { - inferencelog.debug("*******************************"); - inferencelog.debug("Menge " + strMenge + " ist leer!"); - inferencelog.debug("*******************************"); - return; - } - - for( int tt = 0; tt < E.size(); tt++ ) { - //luar 13-03-07 If Else Block gel�scht, da sinnlos. - if( tt > 0 ) - strTemp = strTemp + ",\n" + E.elementAt(tt).toString(); - else - strTemp = E.elementAt(tt).toString(); - strTemp = strTemp + (E.elementAt(tt).GetOperator()); - } - inferencelog.debug("*******************************"); - inferencelog.debug("Menge " + strMenge + " = {" + strTemp + " }"); - inferencelog.debug("*******************************"); - } - // ino.end - - // ino.method.hasSolvedForm.28127.definition - public static boolean hasSolvedForm( Menge E ) - // ino.end - // ino.method.hasSolvedForm.28127.body - { - // otth: prueft, ob Menge E in 'Solved form' - - // TV im Vektor speichern - Menge vTV = new Menge(); - for(Pair P : E) - { - // linke Seite == TypePlaceholder - if( !(P.TA1 instanceof TypePlaceholder) ) - { - return false; - } - else - { - vTV.add( (TypePlaceholder)P.TA1 ); //wird benoetigt um spaeter zu pruefen, - //ob tlv auf der rechten Seite steht - } - } - - for(Pair P : E) - { - //for( int u = 0; u < vTV.size(); u++ )// geloescht PL 13-05-22 - { - if (P.TA2 instanceof RefType) - { //eingefuegt PL 05-01-30 s.o. - //if( isTVinRefType(vTV.elementAt(u), (RefType)P.TA2 ) ) - if (isTVinRefType((TypePlaceholder)P.TA1, (RefType)P.TA2 )) - return false; - } - } - } - return true; - } - // ino.end - - // ino.method.varSubst.28130.defdescription type=line - // varSubst ersetzt all TypePlaceholders eines Typterms. - // Wenn eine Variable zum ersten Mal auftritt, wird eine freshe generiert - // und diese in ht gespeichert. - // Wenn eine Variable auftaucht, die bereits schon einmal ersetzt wurde, wird - // sie durch die selbe Variable ersetzt. - // ino.end - // ino.method.varSubst.28130.definition - public static void varSubst(RefType typterm, Hashtable ht) - // ino.end - // ino.method.varSubst.28130.body - { - Menge para = typterm.get_ParaList(); - if (para != null) { - for (int i=0; i < para.size(); i++) { - if (para.elementAt(i) instanceof TypePlaceholder) { - if (ht.get(((TypePlaceholder)para.elementAt(i)).getName()) != null) { - para.set(i, ht.get(((TypePlaceholder)para.elementAt(i)).getName())); - } - else { - // #JB# 11.04.2005 - // ########################################################### - ht.put(((TypePlaceholder)para.elementAt(i)).getName(), TypePlaceholder.backdoorFresh()); - //ht.put(((TypePlaceholder)para.elementAt(i)).getName(), TypePlaceholder.fresh()); - // ########################################################### - para.set(i, ht.get(((TypePlaceholder)para.elementAt(i)).getName())); - - } - } - else { - if (para.elementAt(i) instanceof RefType) - varSubst(((RefType)para.elementAt(i)), ht); - } - } - } - } - // ino.end - - - /** - * Implementiert die CaptureConversion. Wendet diese auf jeden Typ im Menge TVec an. - * R�ckgabe ist ein ErgebnisMenge - */ - private static Menge CaptureConversion(Menge TVec, FC_TTO fc_tto) - { - Menge retVec = new Menge(); - for(ObjectType t : TVec) - { - ObjectType ccT = (ObjectType)CaptureConversion(t,fc_tto); - //CaptureConversion kann nur ObjectTypes zur�ckliefern, laesst sich aber nicht zurziehen. - if(ccT != null) - retVec.add(ccT); - } - return retVec; - } - - /** - * Erzeugt die CaptureConversion von einem Typ. - * - * @param T - �bergebener Typ, von welchem die CaptureConversion gemacht werden soll. - * @param fc_tto - Hilfsklasse. - * @return - CC(T) - */ - private static Type CaptureConversion(Type T, FC_TTO fc_tto) - { - if(T instanceof RefType) - { - //Klasse aus Klassenvektor holen. - Class cl = null; - for(Class c : fc_tto.getClasses()) - { - if(c.getSimpleName().equals(T.getName())) - { - cl = c; - break; - } - } - if(cl == null) //Keine Klasse gefunden? - return null; - - Menge ccTypes = new Menge(); - RefType refT = (RefType)T.clone(); - boolean ccDone = false; - if(refT.get_ParaList() != null) - { - Menge paras = refT.get_ParaList(); - //Durch jeden Typ in der Paralist des RefTypes laufen. - for(int i = 0; i in Typ A ...> werden keine ? extends-, ? super-Typen erzeugt - */ - private static Menge greater(ObjectType T, FC_TTO fc_tto) - //an die Aenderungen im Skript anpassen 07-11-03 - { - Menge retVec = new Menge(); - Menge greater0Erg = greater0(T,fc_tto); - for(ObjectType t : greater0Erg) - { - if(!DelFreshWildcardTypeVar(t)) - retVec.add(t); - } - return retVec; - } - - /** - * greater0 Schritt von greater. - */ - private static Menge greater0(ObjectType T, FC_TTO fc_tto) - { - Menge retVec = new Menge(); - - //greater1 Erzeugen - Menge greater1Erg = greater1(T,fc_tto); - - //Reflexivit�t, deshalb T hinzuf�gen. - if(!greater1Erg.contains(T)) - greater1Erg.add(T); - - //Falls in greater1Erg Typen doppelt vorhanden sind werden diese nicht in retVec �bernommen. - for(ObjectType t : greater1Erg) - if(!retVec.contains(t)) - retVec.add(t); - - //Ergebnis von greater1 an greater2 durchreichen, ERgebnisse in retVec einf�gen - Menge greater2Erg = greater2(greater1Erg,fc_tto); - for(ObjectType t : greater2Erg) - if(!retVec.contains(t)) - retVec.add(t); - - //Ergebnis von greater2 an greater3 durchreichen, ERgebnisse in retVec einf�gen - Menge greater3Erg = greater3(greater2Erg,fc_tto); - for(ObjectType t : greater3Erg) - if(!retVec.contains(t)) - retVec.add(t); - - return retVec; - } - - /** - * greater1 Schritt von greater. - * F�r den Argumenttype FunN<...> in Typ A ...> werden keine ? extends-, ? super-Typen erzeugt - */ - private static Menge greater1(ObjectType T, FC_TTO fc_tto) - { - Menge retVec = new Menge(); - if(T instanceof RefType) - { - RefType refT = (RefType)T; - if(refT.get_ParaList() != null && refT.get_ParaList().size() > 0) - { - Menge> types = new Menge>(); - Menge paras = refT.get_ParaList(); - //Greater Arg von jedem Parameter einsammeln. - for(int i = 0; i> kart = cartProductType(types); - //Mit den neuen Parameterlisten neue Typen erzeugen. - for(Menge t : kart) - { - RefType dolly = refT.clone(); - dolly.set_ParaList(t); - retVec.add(dolly); - } - } - } - else if(T instanceof BoundedGenericTypeVar) //PL 15-02-03 angefuegt da BGTV Kleiner als alle seine Bounds ist - { - BoundedGenericTypeVar bgtv = (BoundedGenericTypeVar)T; - Menge types = bgtv.getBounds(); - retVec = types.stream().map(ty -> greater(ty, fc_tto)).reduce(new Menge(), (a,b) -> { a.addAll(b); return a;}); - } - return retVec; - } - - /** - * �berladung der Funktion cartProductType, damit der Programmierer beim ersten Aufruf nicht den 2. Parameter - * welcher f�r die rekursion erforderlich ist mit �bergeben muss. - */ - private static Menge> cartProductType (Menge> vec) - { - return cartProductType(vec,0); - } - - /** - * Erzeugt das Kartesische Product von mehreren Mengeen von Typen. - * F�r den Startaufruf ist der index = 0. Danach ruft sich cartProductType rekursiv auf. - */ - private static Menge> cartProductType (Menge> vec, int index) - { - Menge> retVec = new Menge>(); - if(vec.isEmpty()) return retVec; - - Menge myTypes = vec.get(index); - - if(index < (vec.size()-1)) - { - Menge> nextTypes = cartProductType(vec,index+1); - for(Type t : myTypes) - { - for(Menge tt : nextTypes) - { - Menge actual = copyMengeType(tt); - actual.insertElementAt(t.clone(),0); - retVec.add(actual); - } - } - } - else - { - for(Type t : myTypes) - { - Menge tVec = new Menge(); - tVec.insertElementAt(t.clone(),0); - retVec.add(tVec); - } - } - return retVec; - } - - /** - * �berladung der Funktion cartProductPair, damit der Programmierer beim ersten Aufruf nicht den 2. Parameter - * welcher f�r die rekursion erforderlich ist mit �bergeben muss. - */ - private static Menge> cartProductPair (Menge> vec) - { - return cartProductPair(vec,0); - } - - /** - * Erzeugt das Kartesische Product von mehreren Mengeen von Paaren. - * F�r den Startaufruf ist der index = 0. Danach ruft sich cartProductPair rekursiv auf. - */ - private static Menge> cartProductPair (Menge> vec, int index) - { - Menge> retVec = new Menge>(); - if(vec.isEmpty()) return retVec; - - Menge myPairs = vec.get(index); - - if(index < (vec.size()-1)) - { - Menge> nextPairs = cartProductPair(vec,index+1); - for(Pair p : myPairs) - { - for(Menge pp : nextPairs) - { - Menge actual = copyMengePair(pp); - actual.insertElementAt(p.clone(),0); - retVec.add(actual); - } - } - } - else - { - for(Pair p : myPairs) - { - Menge tVec = new Menge(); - tVec.insertElementAt(p.clone(),0); - retVec.add(tVec); - } - } - return retVec; - } - /** - * Kopiert einen Menge. Es ist eine Deep Copy, da die Elemente auch kopiert werden. - */ - private static Menge copyMengeType(Menge vec) - { - Menge retVec = new Menge(); - for(Type t : vec) - retVec.add(t.clone()); - - return retVec; - } - - /** - * Kopiert einen Menge. Es ist eine Deep Copy, da die Elemente auch kopiert werden. - * noetig wegen Type-Erasure - */ - private static Menge copyMengeObjectType(Menge vec) - { - Menge retVec = new Menge(); - for(ObjectType t : vec) - retVec.add(t.clone()); - - return retVec; - } - - /** - * greaterArg Schritt von greater - * F�r den Argumenttype FunN<...> werden keine ? extends-, ? super-Typen erzeugt - */ - private static Menge greaterArg(Type T, FC_TTO fc_tto) - { - Menge retVec = new Menge(); - if(T instanceof ExtendsWildcardType) - { - //Bei einer ExtendsWildcard Rekursiv greater0 aufrufen und neue ExtendsWildcars erzeugen - ExtendsWildcardType exT = (ExtendsWildcardType)T; - Menge greaterTypes = greater0(exT.get_ExtendsType(),fc_tto); - for(ObjectType t : greaterTypes) - retVec.add(new ExtendsWildcardType(t.getOffset(),t.clone())); - } - else if(T instanceof SuperWildcardType) - { - //Bei einer SuperWildcard Rekursiv smaller0 aufrufen und neue SuperWildcards erzeugen. - SuperWildcardType suT = (SuperWildcardType)T; - Menge smallerTypes = smaller0(suT.get_SuperType(),fc_tto); - for(ObjectType t : smallerTypes) - retVec.add(new SuperWildcardType(t.getOffset(),t.clone())); - } - - /* PL 15-03-10 - * Kann meiner Ansicht nach nicht vorkommen - - else if(T instanceof FreshExtendsWildcardType) - { - //Bei einer FreshExtendsWildcard greaterArg aufrufen, auf Bounds achten. - retVec.add(T); - retVec.add(new ExtendsWildcardType(T.getOffset(),T.clone())); - - FreshExtendsWildcardType fexT = (FreshExtendsWildcardType)T; - ExtendsWildcardType extT = new ExtendsWildcardType(fexT.get_ExtendsBound().getOffset(), fexT.get_ExtendsBound().clone()); - - //Menge tmp = greaterArg(fexT.get_ExtendsBound(),fc_tto); //hier stimmt es nicht PL 07-07-21 - Menge tmp = greaterArg(extT,fc_tto); - //for(int i = 0; i(); - */ - - //Diese Abfrage sorgt f�r grArg(a) = {a} //Luar 07-07-31 - else if(T instanceof TypePlaceholder) - retVec.add(T); - //Diese Abfrage verhindert, dass bei FunN Wildcard-Typen generiert werden //PL 13-05-22 - else if((T instanceof RefType) && (T.getName().equals("FunN"))) - retVec.add(T); - else //RefType oder GTV - { - //Bei allen anderen Typen greater0 und smaller0 aufrufen. - retVec.add((ObjectType)T); - Menge greaterTypes = greater0((ObjectType)T,fc_tto); - Menge smallerTypes = smaller0((ObjectType)T,fc_tto); - for(ObjectType t : greaterTypes) - retVec.add(new ExtendsWildcardType(t.getOffset(),t.clone())); - - for(ObjectType t : smallerTypes) - retVec.add(new SuperWildcardType(t.getOffset(),t.clone())); - } - return retVec; - } - - /** - * greater2 Schritt von greater - */ - private static Menge greater2(Menge greater1Erg, FC_TTO fc_tto) - { - Menge retVec = new Menge(); - /* - * luar 02-05-07: Beschreibung der Funktion: - * F�r Jeden Typ aus greater1 durch die FC laufen, und auf der Linken seite einen Match versuchen. - * Wenn das Funktioniert, dann ist der Typ auf der rechten Seite auch greater. - * */ - Hashtable ht = new Hashtable(); - for(Type t : greater1Erg) - { - for(Pair p : fc_tto.getFC()) - { - ht.clear(); - if(p.TA2 instanceof RefType && p.TA1 instanceof RefType && t instanceof RefType) - { - try - { - match((RefType)p.TA1,(RefType)t,ht); - ht = CaptureConversionHashtable(ht,fc_tto); - for(Type tt : ht.values()) - { - if(tt instanceof WildcardType) - throw new MatchException("Wildcards not allowed"); - } - - //Macht hat funktioniert. In Linker Seite Typen substituieren - RefType TA2neu = ((RefType)p.TA2).clone(); - SubstHashtableGeneric(TA2neu,ht); - - //TA2neu ist greater als T. Einf�gen in retVec - if(!retVec.contains(TA2neu)) - retVec.add(TA2neu); - } - catch(MatchException ex) - {} - } - } - } - return retVec; - } - - /** - * greater3 Schritt von greater - */ - private static Menge greater3(Menge greater2Erg, FC_TTO fc_tto) - { - Menge retVec = new Menge(); - for(ObjectType t : greater2Erg) - { - Menge greater1Erg = greater1(t,fc_tto); - for(ObjectType tt : greater1Erg) - if(!retVec.contains(tt)) - retVec.add(tt); - } - return retVec; - } - - //Von hier an Smaller implementierung luar 28-03-07 - /** - * Der Komplette Ablauf von smaller und was die einzelnen Teilschritte machen kann anhand von Aktivit�tsdiagrammen - * im Inovator Projekt, oder in der Studienarbeit Arne L�dtke, 2007 nachgelesen werden. - */ - - /** - * Erzeugt alle Typen die smaller sind als T. Gibt diese zur�ck. - */ - private static Menge smaller(ObjectType T, FC_TTO fc_tto) - //an die Aenderungen im Skript anpassen 07-11-03 - { - Menge retVec = new Menge(); - Menge smaller0Erg = smaller0(T,fc_tto); - for(ObjectType t : smaller0Erg) - { - if(!DelFreshWildcardTypeVar(t)) - retVec.add(t); - } - return retVec; - } - - /** - * smaller0 Schritt von smaller - */ - private static Menge smaller0(ObjectType T, FC_TTO fc_tto) - { - Menge retVec = new Menge(); - - Menge smaller1Erg = smaller1(T,fc_tto); - - - Menge smaller2Erg = smaller2(smaller1Erg,fc_tto); - - //Unite von smaller 1 und 2 bilden, um dies an smaller 3 weiterzugeben. - Menge smaller12Erg = copyMengeObjectType(smaller1Erg); - for(ObjectType t : smaller2Erg) - if(!smaller12Erg.contains(t)) - smaller12Erg.add(t); - - if(!smaller12Erg.contains(T)) - smaller12Erg.add(T); - - //Ergebnise in retVec einf�gen. Doppelte werden gel�scht. - for(ObjectType t : smaller12Erg) - if(!retVec.contains(t)) - retVec.add(t); - - //Ergebnis von smaller1 und smaller2 an smaller3 weitergeben, Ergebnisse einf�gen. - Menge smaller3Erg = smaller3(smaller12Erg,fc_tto); - for(ObjectType t : smaller3Erg) - if(!retVec.contains(t)) - retVec.add(t); - - //Ergebnisse von smaller3 an smaller4 weitergeben, Ergebnisse einf�gen. - Menge smaller4Erg = smaller4(smaller3Erg); - for(ObjectType t : smaller4Erg) - if(!retVec.contains(t)) - retVec.add(t); - - return retVec; - } - - /** - * smaller1 Schritt von smaller - */ - private static Menge smaller1(Type T, FC_TTO fc_tto) - { - Menge retVec = new Menge(); - if(T instanceof RefType) - { - RefType refT = (RefType)T; - if(refT.get_ParaList() != null && refT.get_ParaList().size() > 0) - { - Menge> types = new Menge>(); - Menge paras = refT.get_ParaList(); - //Smaller Arg von jedem Parameter einsammeln. - for(int i = 0; i> kart = cartProductType(types); - //Mit den neuen Parameterlisten neue Typen klonen, Parameterlisten zuweisen - for(Menge t : kart) - { - RefType dolly = refT.clone(); - dolly.set_ParaList(t); - retVec.add(dolly); - } - } - } - return retVec; - } - - /** - * smallerArg Schritt von smaller - */ - private static Menge smallerArg(Type T, FC_TTO fc_tto) - { - Menge retVec = new Menge(); - if(T instanceof ExtendsWildcardType) - { - //F�r eine ExtendsWildcard rekursiv smaller0 aufrufen, und neue Wildcards erzeugen. - ExtendsWildcardType exT = (ExtendsWildcardType)T; - Menge smallerTypes = smaller0(exT.get_ExtendsType(),fc_tto); - for(ObjectType t : smallerTypes) - { - retVec.add(new ExtendsWildcardType(t.getOffset(),t.clone())); - retVec.add(t.clone()); - } - } - else if(T instanceof SuperWildcardType) - { - //F�r eine SuperWildcard rekursiv greater0 aufrufen, unr neue Wildcards erzeugen. - SuperWildcardType suT = (SuperWildcardType)T; - Menge greaterTypes = greater0(suT.get_SuperType(),fc_tto); - for(ObjectType t : greaterTypes) - { - retVec.add(new SuperWildcardType(-1,t.clone())); - retVec.add(t.clone()); - } - } - else if(T instanceof FreshExtendsWildcardType) - return new Menge(); //HIER NOCH T EINFUEGEN 07-11-03 PL - - else if(T instanceof FreshSuperWildcardType) - {//HIER AUCH NUR T EINFUEGEN 07-11-03 PL - FreshSuperWildcardType fsuT = (FreshSuperWildcardType)T; - return smallerArg(fsuT.get_SuperBound(),fc_tto); - } - else - retVec.add(T); - - return retVec; - } - - /** - * smaller2 Schritt von smaller - */ - private static Menge smaller2(Menge smaller1Erg, FC_TTO fc_tto) - { - return CaptureConversion(smaller1Erg,fc_tto); - } - - /** - * smaller3 Schritt von smaller - */ - private static Menge smaller3(Menge smaller12Erg, FC_TTO fc_tto) - { - Menge retVec = new Menge(); - /* - * luar 02-05-07: Beschreibung der Funktion: - * F�r Jeden Typ aus Smaller12 durch die FC laufen, und auf der Rechten seite einen Match versuchen. - * Wenn das Funktioniert, dann ist der Typ auf der linken Seite auch smaller. - * */ - Hashtable ht = new Hashtable(); - for(Type t : smaller12Erg) - { - for(Pair p : fc_tto.getFC()) - { - ht.clear(); - if(p.TA2 instanceof RefType && p.TA1 instanceof RefType && t instanceof RefType) - { - try - { - match((RefType)p.TA2,(RefType)t,ht); - for(Type tt : ht.values()) - { - if(tt instanceof WildcardType) - throw new MatchException("Wildcards not allowed"); - } - - //Macht hat funktioniert. In Linker Seite Typen substituieren - RefType TA1neu = ((RefType)p.TA1).clone(); - SubstHashtableGeneric(TA1neu,ht); - //TA1neu ist smaller als T. Einf�gen in retVec - if(!retVec.contains(TA1neu)) - retVec.add(TA1neu); - } - catch(MatchException ex) - {} - } - } - } - return retVec; - } - - /** - * smaller4 Schritt von smaller - */ - private static Menge smaller4(Menge smallerErg) - { - /* smaller4 ist die inverse CaptureConversion. - * Alle Typen in smallerErg werden durchlaufen, und evtl. gefundene - * FreshWildcardTypes werden durch die entsprechenden Wildcards ersetzt. - * */ - Menge retVec = new Menge(); - for(ObjectType t : smallerErg) - { - if(t instanceof RefType) - { - RefType refT = (RefType)t.clone(); - if(refT.get_ParaList() != null) - { - Menge paras = refT.get_ParaList(); - for(int i = 0; i Menge deepClone(Menge m){ - Timewatch watch = Timewatch.getTimewatch(); - Timestamp timer = watch.start("Unify - deepClone"); - Menge ret = m.stream().map((Function)(x -> x.deepClone())).>collect(Menge::new, Menge::add, Menge::addAll); - timer.stop(); - return ret; - } - - -} -// ino.end + protected Set unifyCase3(PlaceholderType a, SuperType subThetaPrime, IFiniteClosure fc) { + Set result = new HashSet<>(); + for(UnifyType theta : fc.smArg(subThetaPrime)) + result.add(new MPair(a, theta, PairOperator.EQUALSDOT)); + return result; + } + + protected Set unifyCase4(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { + Set result = new HashSet<>(); + result.add(new MPair(a, thetaPrime, PairOperator.EQUALSDOT)); + return result; + } + + protected Set unifyCase5(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { + Set result = new HashSet<>(); + for(UnifyType thetaS : fc.greater(theta)) + result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + return result; + } + + protected Set unifyCase6(ExtendsType extTheta, PlaceholderType a, IFiniteClosure fc) { + Set result = new HashSet<>(); + for(UnifyType thetaS : fc.grArg(extTheta)) + result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + return result; + } + + protected Set unifyCase7(SuperType supTheta, PlaceholderType a, IFiniteClosure fc) { + Set result = new HashSet<>(); + IUnify unify = new MartelliMontanariUnify(); + + UnifyType theta = supTheta.getSuperedType(); + Set cs = fc.getAllTypesByName(theta.getName()); + + for(UnifyType c : cs) { + + // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? + Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + thetaQs.add(c); // reflexive + + Set thetaQPrimes = new HashSet<>(); + TypeParams cParams = c.getTypeParams(); + if(cParams.size() == 0) + thetaQPrimes.add(c); + else { + ArrayList> candidateParams = new ArrayList<>(); + for(UnifyType param : cParams) + candidateParams.add(fc.grArg(param)); + + for(TypeParams tp : permuteParams(candidateParams)) + thetaQPrimes.add(c.setTypeParams(tp)); + } + + for(UnifyType tqp : thetaQPrimes) { + Optional opt = unify.unify(tqp, theta); + if (!opt.isPresent()) + continue; + + Unifier unifier = opt.get(); + Set> substitutions = unifier.getSubstitutions(); + for (Entry sigma : substitutions) + result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + for (UnifyType tq : thetaQs) { + Set smaller = fc.smaller(unifier.apply(tq)); + smaller.stream().map(x -> new MPair(a, new SuperType(x), PairOperator.EQUALSDOT)) + .forEach(x -> result.add(x)); + } + + } + } + + return result; + } + + protected Set unifyCase8(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { + Set result = new HashSet<>(); + for(UnifyType thetaS : fc.grArg(theta)) + result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + return result; + } + + protected Set permuteParams(ArrayList> candidates) { + Set result = new HashSet<>(); + permuteParams(candidates, 0, result, new UnifyType[candidates.size()]); + return result; + } + + private void permuteParams(ArrayList> candidates, int idx, Set result, UnifyType[] current) { + if(candidates.size() == idx) { + result.add(new TypeParams(Arrays.copyOf(current, current.length))); + return; + } + + Set localCandidates = candidates.get(idx); + + for(UnifyType t : localCandidates) { + current[idx] = t; + permuteParams(candidates, idx+1, result, current); + } + } +} diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 757e53d1..3fb48ac9 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -8,10 +8,10 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import de.dhbwstuttgart.typeinference.unify.MartelliMontanariUnify; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; -import de.dhbwstuttgart.typeinference.unifynew.MartelliMontanariUnify; public class FiniteClosure implements IFiniteClosure { diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java deleted file mode 100644 index 1023c852..00000000 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java +++ /dev/null @@ -1,480 +0,0 @@ -package de.dhbwstuttgart.typeinference.unifynew; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import de.dhbwstuttgart.typeinference.Menge; -import de.dhbwstuttgart.typeinference.Pair; -import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; -import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; -import de.dhbwstuttgart.typeinference.unify.interfaces.ISetOperations; -import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; -import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; -import de.dhbwstuttgart.typeinference.unify.model.MPair; -import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; -import de.dhbwstuttgart.typeinference.unify.model.SuperType; -import de.dhbwstuttgart.typeinference.unify.model.UnifyType; -import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; -import de.dhbwstuttgart.typeinference.unify.model.TypeParams; -import de.dhbwstuttgart.typeinference.unify.model.Unifier; - - -/** - * Implementation of the type unification algorithm - * @author Florian Steurer - */ -public class Unify { - - public Set> unify(Set eq, IFiniteClosure fc) { - /* - * Step 1: Repeated application of reduce, adapt, erase, swap - */ - - Set eq0 = applyTypeUnificationRules(eq, fc); - - /* - * Step 2 and 3: Create a subset eq1s of pairs where both sides are TPH and eq2s of the other pairs - */ - - Set eq1s = new HashSet<>(); - Set eq2s = new HashSet<>(); - splitEq(eq0, eq1s, eq2s); - - /* - * Step 4: Create possible typings - * - * "Manche Autoren identifizieren die Paare (a, (b,c)) und ((a,b),c) - * mit dem geordneten Tripel (a,b,c), wodurch das kartesische Produkt auch assoziativ wird." - Wikipedia - */ - - // There are up to 10 toplevel set. 8 of 10 are the result of the - // cartesian product of the sets created by pattern matching. - List>> topLevelSets = new ArrayList<>(); - - if(eq1s.size() != 0) { - Set> wrap = new HashSet<>(); - wrap.add(eq1s); - topLevelSets.add(wrap); // Add Eq1' - } - - // Add the set of [a =. Theta | (a=. Theta) in Eq2'] - Set bufferSet = eq2s.stream() - .filter(x -> x.getPairOp() == PairOperator.EQUALSDOT && x.getLhsType() instanceof PlaceholderType) - .collect(Collectors.toSet()); - - if(bufferSet.size() != 0) { - Set> wrap = new HashSet<>(); - wrap.add(bufferSet); - topLevelSets.add(wrap); - } - - // Sets that originate from pair pattern matching - // Sets of the "second level" - Set>> secondLevelSets = calculatePairSets(eq2s, fc); - - /* Up to here, no cartesian products are calculated. - * filters for pairs and sets can be applied here */ - - ISetOperations setOps = new GuavaSetOperations(); - - // Sub cartesian products of the second level (pattern matched) sets - for(Set> secondLevelSet : secondLevelSets) { - List> secondLevelSetList = new ArrayList<>(secondLevelSet); - topLevelSets.add(setOps.cartesianProduct(secondLevelSetList) - .stream().map(x -> new HashSet<>(x)) - .collect(Collectors.toCollection(HashSet::new))); - } - - // Cartesian product over all (up to 10) top level sets - Set>> eqPrimeSet = setOps.cartesianProduct(topLevelSets) - .stream().map(x -> new HashSet<>(x)) - .collect(Collectors.toCollection(HashSet::new)); - //System.out.println(result); - - /* - * Step 5: Substitution - */ - - /* - * TODO hier das ergebnis schonh flach machen? (wird im unify old (glaub ich) so gemacht) - */ - Set> eqPrimeSetFlat = new HashSet<>(); - for(Set> setToFlatten : eqPrimeSet) { - Set buffer = new HashSet<>(); - setToFlatten.stream().forEach(x -> buffer.addAll(x)); - eqPrimeSetFlat.add(buffer); - } - - IRuleSet rules = new RuleSet(fc); - Set> changed = new HashSet<>(); - Set> eqPrimePrimeSet = new HashSet<>(); - - for(Set eqPrime : eqPrimeSetFlat) { - Optional> eqPrimePrime = rules.subst(eqPrime); - - if(eqPrimePrime.isPresent()) - changed.add(eqPrimePrime.get()); - else - eqPrimePrimeSet.add(eqPrime); - } - - /* - * Step 6 a) Restart for pairs where subst was applied - * b) Build the union over everything - */ - - for(Set eqss : changed) { - eqPrimePrimeSet.addAll(this.unify(eqss, fc)); - } - - /* - * Step 7: Filter result for solved pairs - */ - return eqPrimePrimeSet; - - } - - protected Set applyTypeUnificationRules(Set eq, IFiniteClosure fc) { - - /* - * Rule Application Strategy: - * - * 1. Swap all pairs and erase all erasable pairs - * 2. Apply all possible rules to a single pair, then move it to the result set. - * Iterating over pairs first, then iterating over rules prevents the application - * of rules to a "finished" pair over and over. - * 2.1 Apply all rules repeatedly except for erase rules. If - * the application of a rule creates new pairs, check immediately - * against the erase rules. - */ - - - LinkedHashSet targetSet = new LinkedHashSet(); - LinkedList eqQueue = new LinkedList<>(); - IRuleSet rules = new RuleSet(fc); - - /* - * Swap all pairs and erase all erasable pairs - */ - eq.forEach(x -> swapAddOrErase(x, rules, eqQueue)); - - /* - * Apply rules until the queue is empty - */ - while(!eqQueue.isEmpty()) { - MPair pair = eqQueue.pollFirst(); - - // ReduceUp, ReduceLow, ReduceUpLow - Optional opt = rules.reduceUpLow(pair); - opt = opt.isPresent() ? opt : rules.reduceLow(pair); - opt = opt.isPresent() ? opt : rules.reduceUp(pair); - - // One of the rules has been applied - if(opt.isPresent()) { - swapAddOrErase(opt.get(), rules, eqQueue); - continue; - } - - // Reduce1, Reduce2, ReduceExt, ReduceSup, ReduceEq - Optional> optSet = rules.reduce1(pair); - optSet = optSet.isPresent() ? optSet : rules.reduce2(pair); - optSet = optSet.isPresent() ? optSet : rules.reduceExt(pair); - optSet = optSet.isPresent() ? optSet : rules.reduceSup(pair); - optSet = optSet.isPresent() ? optSet : rules.reduceEq(pair); - - // One of the rules has been applied - if(optSet.isPresent()) { - optSet.get().forEach(x -> swapAddOrErase(x, rules, eqQueue)); - continue; - } - - // Adapt, AdaptExt, AdaptSup - opt = rules.adapt(pair); - opt = opt.isPresent() ? opt : rules.adaptExt(pair); - opt = opt.isPresent() ? opt : rules.adaptSup(pair); - - // One of the rules has been applied - if(opt.isPresent()) { - swapAddOrErase(opt.get(), rules, eqQueue); - continue; - } - - // None of the rules has been applied - targetSet.add(pair); - } - - return targetSet; - } - - protected void swapAddOrErase(MPair pair, IRuleSet rules, Collection collection) { - Optional opt = rules.swap(pair); - MPair pair2 = opt.isPresent() ? opt.get() : pair; - - if(rules.erase1(pair2) || rules.erase3(pair2) || rules.erase2(pair2)) - return; - - collection.add(pair2); - } - - protected void splitEq(Set eq, Set eq1s, Set eq2s) { - for(MPair pair : eq) - if(pair.getLhsType() instanceof PlaceholderType && pair.getRhsType() instanceof PlaceholderType) - eq1s.add(pair); - else - eq2s.add(pair); - } - - - protected Set>> calculatePairSets(Set eq2s, IFiniteClosure fc) { - List>> result = new ArrayList<>(); - - // Init all 8 cases - for(int i = 0; i < 8; i++) - result.add(new HashSet<>()); - - for(MPair pair : eq2s) { - - PairOperator pairOp = pair.getPairOp(); - UnifyType lhsType = pair.getLhsType(); - UnifyType rhsType = pair.getRhsType(); - - // Case 1: (a <. Theta') - if(pairOp == PairOperator.SMALLERDOT && lhsType instanceof PlaceholderType) - result.get(0).add(unifyCase1((PlaceholderType) pair.getLhsType(), pair.getRhsType(), fc)); - - // Case 2: (a <.? ? ext Theta') - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof ExtendsType) - result.get(1).add(unifyCase2((PlaceholderType) pair.getLhsType(), (ExtendsType) pair.getRhsType(), fc)); - - // Case 3: (a <.? ? sup Theta') - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof SuperType) - result.get(2).add(unifyCase3((PlaceholderType) lhsType, (SuperType) rhsType, fc)); - - // Case 4: (a <.? Theta') - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType) - result.get(3).add(unifyCase4((PlaceholderType) lhsType, rhsType, fc)); - - // Case 5: (Theta <. a) - else if(pairOp == PairOperator.SMALLERDOT && rhsType instanceof PlaceholderType) - result.get(4).add(unifyCase5(lhsType, (PlaceholderType) rhsType, fc)); - - // Case 6: (? ext Theta <.? a) - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof ExtendsType && rhsType instanceof PlaceholderType) - result.get(5).add(unifyCase6((ExtendsType) lhsType, (PlaceholderType) rhsType, fc)); - - // Case 7: (? sup Theta <.? a) - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof SuperType && rhsType instanceof PlaceholderType) - result.get(6).add(unifyCase7((SuperType) lhsType, (PlaceholderType) rhsType, fc)); - - // Case 8: (Theta <.? a) - else if(pairOp == PairOperator.SMALLERDOTWC && rhsType instanceof PlaceholderType) - result.get(7).add(unifyCase8(lhsType, (PlaceholderType) rhsType, fc)); - } - - return result.stream().filter(x -> x.size() > 0).collect(Collectors.toCollection(HashSet::new)); - } - - protected Set unifyCase1(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { - Set result = new HashSet<>(); - IUnify unify = new MartelliMontanariUnify(); - - Set cs = fc.getAllTypesByName(thetaPrime.getName()); - - for(UnifyType c : cs) { - - // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); - thetaQs.add(c); // reflexive - - Set thetaQPrimes = new HashSet<>(); - TypeParams cParams = c.getTypeParams(); - if(cParams.size() == 0) - thetaQPrimes.add(c); - else { - ArrayList> candidateParams = new ArrayList<>(); - for(UnifyType param : cParams) - candidateParams.add(fc.grArg(param)); - - for(TypeParams tp : permuteParams(candidateParams)) - thetaQPrimes.add(c.setTypeParams(tp)); - } - - for(UnifyType tqp : thetaQPrimes) { - Optional opt = unify.unify(tqp, thetaPrime); - if (!opt.isPresent()) - continue; - - Unifier unifier = opt.get(); - Set> substitutions = unifier.getSubstitutions(); - for (Entry sigma : substitutions) - result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); - for (UnifyType tq : thetaQs) { - Set smaller = fc.smaller(unifier.apply(tq)); - smaller.stream().map(x -> new MPair(a, x, PairOperator.EQUALSDOT)) - .forEach(x -> result.add(x)); - } - - } - } - - return result; - } - - protected Set unifyCase2(PlaceholderType a, ExtendsType extThetaPrime, IFiniteClosure fc) { - Set result = new HashSet<>(); - IUnify unify = new MartelliMontanariUnify(); - - UnifyType thetaPrime = extThetaPrime.getExtendedType(); - Set cs = fc.getAllTypesByName(thetaPrime.getName()); - - for(UnifyType c : cs) { - - // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); - thetaQs.add(c); // reflexive - - Set thetaQPrimes = new HashSet<>(); - TypeParams cParams = c.getTypeParams(); - if(cParams.size() == 0) - thetaQPrimes.add(c); - else { - ArrayList> candidateParams = new ArrayList<>(); - for(UnifyType param : cParams) - candidateParams.add(fc.grArg(param)); - - for(TypeParams tp : permuteParams(candidateParams)) - thetaQPrimes.add(c.setTypeParams(tp)); - } - - for(UnifyType tqp : thetaQPrimes) { - Optional opt = unify.unify(tqp, thetaPrime); - if (!opt.isPresent()) - continue; - - Unifier unifier = opt.get(); - Set> substitutions = unifier.getSubstitutions(); - for (Entry sigma : substitutions) - result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); - for (UnifyType tq : thetaQs) { - ExtendsType extTq = new ExtendsType(tq); - Set smaller = fc.smaller(unifier.apply(extTq)); - smaller.stream().map(x -> new MPair(a, x, PairOperator.EQUALSDOT)) - .forEach(x -> result.add(x)); - } - } - } - - return result; - } - - protected Set unifyCase3(PlaceholderType a, SuperType subThetaPrime, IFiniteClosure fc) { - Set result = new HashSet<>(); - for(UnifyType theta : fc.smArg(subThetaPrime)) - result.add(new MPair(a, theta, PairOperator.EQUALSDOT)); - return result; - } - - protected Set unifyCase4(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { - Set result = new HashSet<>(); - result.add(new MPair(a, thetaPrime, PairOperator.EQUALSDOT)); - return result; - } - - protected Set unifyCase5(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { - Set result = new HashSet<>(); - for(UnifyType thetaS : fc.greater(theta)) - result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); - return result; - } - - protected Set unifyCase6(ExtendsType extTheta, PlaceholderType a, IFiniteClosure fc) { - Set result = new HashSet<>(); - for(UnifyType thetaS : fc.grArg(extTheta)) - result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); - return result; - } - - protected Set unifyCase7(SuperType supTheta, PlaceholderType a, IFiniteClosure fc) { - Set result = new HashSet<>(); - IUnify unify = new MartelliMontanariUnify(); - - UnifyType theta = supTheta.getSuperedType(); - Set cs = fc.getAllTypesByName(theta.getName()); - - for(UnifyType c : cs) { - - // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); - thetaQs.add(c); // reflexive - - Set thetaQPrimes = new HashSet<>(); - TypeParams cParams = c.getTypeParams(); - if(cParams.size() == 0) - thetaQPrimes.add(c); - else { - ArrayList> candidateParams = new ArrayList<>(); - for(UnifyType param : cParams) - candidateParams.add(fc.grArg(param)); - - for(TypeParams tp : permuteParams(candidateParams)) - thetaQPrimes.add(c.setTypeParams(tp)); - } - - for(UnifyType tqp : thetaQPrimes) { - Optional opt = unify.unify(tqp, theta); - if (!opt.isPresent()) - continue; - - Unifier unifier = opt.get(); - Set> substitutions = unifier.getSubstitutions(); - for (Entry sigma : substitutions) - result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); - for (UnifyType tq : thetaQs) { - Set smaller = fc.smaller(unifier.apply(tq)); - smaller.stream().map(x -> new MPair(a, new SuperType(x), PairOperator.EQUALSDOT)) - .forEach(x -> result.add(x)); - } - - } - } - - return result; - } - - protected Set unifyCase8(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { - Set result = new HashSet<>(); - for(UnifyType thetaS : fc.grArg(theta)) - result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); - return result; - } - - protected Set permuteParams(ArrayList> candidates) { - Set result = new HashSet<>(); - permuteParams(candidates, 0, result, new UnifyType[candidates.size()]); - return result; - } - - private void permuteParams(ArrayList> candidates, int idx, Set result, UnifyType[] current) { - if(candidates.size() == idx) { - result.add(new TypeParams(Arrays.copyOf(current, current.length))); - return; - } - - Set localCandidates = candidates.get(idx); - - for(UnifyType t : localCandidates) { - current[idx] = t; - permuteParams(candidates, idx+1, result, current); - } - } -} diff --git a/test/unify/RuleSetTest.java b/test/unify/RuleSetTest.java index 1fe1359d..f38d9f2c 100644 --- a/test/unify/RuleSetTest.java +++ b/test/unify/RuleSetTest.java @@ -8,13 +8,13 @@ import junit.framework.Assert; import org.junit.Test; +import de.dhbwstuttgart.typeinference.unify.RuleSet; import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.SimpleType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; -import de.dhbwstuttgart.typeinference.unifynew.RuleSet; public class RuleSetTest { diff --git a/test/unify/StandardUnifyTest.java b/test/unify/StandardUnifyTest.java index e75bf38c..ac6e5c0c 100644 --- a/test/unify/StandardUnifyTest.java +++ b/test/unify/StandardUnifyTest.java @@ -7,11 +7,11 @@ import junit.framework.Assert; import org.junit.Test; +import de.dhbwstuttgart.typeinference.unify.MartelliMontanariUnify; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; -import de.dhbwstuttgart.typeinference.unifynew.MartelliMontanariUnify; public class StandardUnifyTest { diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index e9bed425..8a6f2f32 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -6,12 +6,12 @@ import java.util.Set; import org.junit.Test; +import de.dhbwstuttgart.typeinference.unify.Unify; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.TypeParams; -import de.dhbwstuttgart.typeinference.unifynew.Unify; public class UnifyTest extends Unify { From ad2804fab918c907957f54715a738c39cbe2b201 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Thu, 24 Mar 2016 11:57:31 +0100 Subject: [PATCH 12/57] Umstellung auf MPair beginnen --- src/de/dhbwstuttgart/typeinference/unify/Unifier.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 src/de/dhbwstuttgart/typeinference/unify/Unifier.java diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/Unifier.java new file mode 100644 index 00000000..acc14281 --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/unify/Unifier.java @@ -0,0 +1,11 @@ +package de.dhbwstuttgart.typeinference.unify; + +import java.util.Set; + +import de.dhbwstuttgart.typeinference.Pair; + +public interface Unifier { + + public Set> apply (Set E); + +} From bbfd8699e885fbfd7408d79cc744b58fc2cf43ca Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Sat, 26 Mar 2016 00:03:26 +0100 Subject: [PATCH 13/57] smaller / smArg / grArg / TODO: greater --- .../unify/model/FiniteClosure.java | 103 ++++-------------- .../typeinference/unify/model/Unifier.java | 6 +- .../unifynew/MartelliMontanariUnify.java | 6 +- 3 files changed, 31 insertions(+), 84 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 27827dbe..a1b56472 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -24,11 +24,13 @@ public class FiniteClosure implements IFiniteClosure { } public FiniteClosure(Set pairs) { - inheritanceGraph = new HashMap>(); // Build the transitive closure of the inheritance tree for(MPair pair : pairs) { + if(!pair.getLhsType().getTypeParams().arePlaceholders()) + throw new IllegalArgumentException("The finite closure only has pairs of the form D <= C<...>"); + if(pair.getPairOp() != PairOperator.SMALLER) continue; @@ -66,14 +68,15 @@ public class FiniteClosure implements IFiniteClosure { */ @Override public Set smaller(Type type) { - // - if(T < T') then T <=* T' - Set result = inheritanceGraph.containsKey(type) ? inheritanceGraph.get(type).getContentOfDescendants() : new HashSet<>(); + Set result = new HashSet<>(); result.add(type); + // - if(T < T') then T <=* T' // if T1 <=* T2 then sigma1(T1) <=* sigma1(T2) // where foreach type var a in T2: // sigma1(T1) <=* sigma2(T2) - /*if(strInheritanceGraph.containsKey(type.getName())) { + //If a type of the same name is in the fc AND the type "type" is parameterized (some substitution sigma1 was applied) + if(strInheritanceGraph.containsKey(type.getName())) { IUnify unify = new MartelliMontanariUnify(); HashSet> candidateNodes = strInheritanceGraph.get(type.getName()); for(Node candidateNode : candidateNodes) { @@ -81,67 +84,27 @@ public class FiniteClosure implements IFiniteClosure { Optional sigma2 = unify.unify(theta2, type); if(!sigma2.isPresent()) continue; - for(Type sigma1theta1 : candidateNode.getContentOfDescendants()) { - Type theta1 = sigma2.get().apply(sigma1theta1); + Set theta1s = inheritanceGraph.containsKey(type) ? inheritanceGraph.get(type).getContentOfDescendants() : smaller(theta2); + for(Type theta1 : theta1s) { + // Because only the most general type is calculated, sigma1 = sigma2 + Type sigma1Theta1 = sigma2.get().apply(theta1); + + ArrayList> paramCandidates = new ArrayList<>(); + for(Type param : sigma1Theta1.getTypeParams()) + paramCandidates.add(smArg(param)); + + Set permResult = new HashSet<>(); + permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); + + for(TypeParams newParams : permResult) + result.add(sigma1Theta1.setTypeParams(newParams)); } } - }*/ - - if(type.getTypeParams().size() == 0) - return result; - - ArrayList> paramCandidates = new ArrayList<>(); - for(Type param : type.getTypeParams()) { - if(param instanceof ExtendsType || param instanceof SuperType) { - Set pc = param.smArg(this); - paramCandidates.add(pc); - } else { - HashSet pc = new HashSet<>(); - pc.add(param); - paramCandidates.add(pc); - } } - Set permResult = new HashSet<>(); - permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); - - for(TypeParams newParams : permResult) - result.add(type.setTypeParams(newParams)); - return result; } - /** - * @param t1 - * @param t2 - * @return - */ - protected Optional match(Type t1, Type t2) { - if(!t1.getName().equals(t2.getName())) - return Optional.empty(); - - TypeParams t1Params = t1.getTypeParams(); - TypeParams t2Params = t2.getTypeParams(); - - if(t1Params.size() != t2Params.size()) - return Optional.empty(); - - Unifier result = new Unifier(); - for(int i = 0; i < t1Params.size(); i++) { - Type t1i = t1Params.get(i); - Type t2i = t2Params.get(i); - - boolean equal = t1i.equals(t2i); - if(!equal && !(t2i instanceof PlaceholderType)) - return Optional.empty(); - - if(!equal && t2i instanceof PlaceholderType) - result.Add((PlaceholderType) t2i, t1i); - } - - return Optional.of(result); - } - /** * Returns all types of the finite closure that are supertypes of the argument. * @return The set of supertypes of the argument. @@ -182,9 +145,6 @@ public class FiniteClosure implements IFiniteClosure { @Override public Set grArg(SimpleType type) { - if(!inheritanceGraph.containsKey(type)) - return new HashSet(); - Set result = new HashSet(); result.add(type); @@ -201,9 +161,6 @@ public class FiniteClosure implements IFiniteClosure { @Override public Set grArg(ExtendsType type) { - if(!inheritanceGraph.containsKey(type.getExtendedType())) - return new HashSet(); - Set result = new HashSet(); result.add(type); @@ -216,9 +173,6 @@ public class FiniteClosure implements IFiniteClosure { @Override public Set grArg(SuperType type) { - if(!inheritanceGraph.containsKey(type.getSuperedType())) - return new HashSet(); - Set result = new HashSet(); result.add(type); @@ -245,13 +199,10 @@ public class FiniteClosure implements IFiniteClosure { @Override public Set smArg(SimpleType type) { - if(!inheritanceGraph.containsKey(type)) - return new HashSet(); - Set result = new HashSet(); result.add(type); - smaller(type).forEach(x -> result.add(new ExtendsType(x))); + // smaller(type).forEach(x -> result.add(new ExtendsType(x))); TODO inkorrekt? daher erstmal raus return result; } @@ -263,9 +214,6 @@ public class FiniteClosure implements IFiniteClosure { @Override public Set smArg(ExtendsType type) { - if(!inheritanceGraph.containsKey(type.getExtendedType())) - return new HashSet(); - Set result = new HashSet(); result.add(type); @@ -283,9 +231,6 @@ public class FiniteClosure implements IFiniteClosure { @Override public Set smArg(SuperType type) { - if(!inheritanceGraph.containsKey(type.getSuperedType())) - return new HashSet(); - Set result = new HashSet(); result.add(type); @@ -304,8 +249,8 @@ public class FiniteClosure implements IFiniteClosure { public Set smArg(PlaceholderType type) { HashSet result = new HashSet<>(); result.add(type); - result.add(new SuperType(type)); - result.add(new ExtendsType(type)); + //result.add(new SuperType(type)); TODO inkorrekt, daher erstmal raus + //result.add(new ExtendsType(type)); return result; } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java index add681e5..6c2eaa0f 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java @@ -8,8 +8,6 @@ import java.util.function.Function; public class Unifier implements Function /*, Set*/ { // TODO set implementieren private HashMap substitutions = new HashMap<>(); - public static Unifier IDENTITY = new Unifier(); - public Unifier(PlaceholderType source, Type target) { substitutions.put(source, target); } @@ -21,6 +19,10 @@ public class Unifier implements Function /*, Set*/ { // TODO } + public static Unifier Identity() { + return new Unifier(); + } + public void Add(PlaceholderType source, Type target) { Unifier tempU = new Unifier(source, target); for(PlaceholderType pt : substitutions.keySet()) diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java b/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java index d15fefdd..6ae0acf6 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java @@ -26,7 +26,7 @@ public class MartelliMontanariUnify implements IUnify { @Override public Optional unify(Set terms) { if(terms.size() < 2) - return Optional.of(Unifier.IDENTITY); + return Optional.of(Unifier.Identity()); ArrayList termsQ = new ArrayList(); Iterator iter = terms.iterator(); @@ -37,7 +37,7 @@ public class MartelliMontanariUnify implements IUnify { prev = next; } - Unifier mgu = Unifier.IDENTITY; + Unifier mgu = Unifier.Identity(); int idx = 0; while(idx < termsQ.size()) { @@ -101,7 +101,7 @@ public class MartelliMontanariUnify implements IUnify { TypeParams rhsTypeParams = rhs.getTypeParams(); TypeParams lhsTypeParams = lhs.getTypeParams(); - if(!rhs.getName().equals(lhs.getName()) || rhsTypeParams.size() != lhsTypeParams.size()) + if(rhsTypeParams.size() != lhsTypeParams.size() || (!rhs.getName().equals(lhs.getName()) && rhsTypeParams.size() != 0)) return null; // conflict if(rhsTypeParams.size() == 0 || lhsTypeParams.size() == 0) From 5e184968470c813e0d804a5be6d8ccbedd87a5aa Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Sat, 26 Mar 2016 12:59:38 +0100 Subject: [PATCH 14/57] smaller and test cases --- .../unify/model/FiniteClosure.java | 60 ++--- test/unify/FiniteClosureTest.java | 227 +++++++++++++++--- 2 files changed, 224 insertions(+), 63 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index a1b56472..427122bf 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -19,10 +19,6 @@ public class FiniteClosure implements IFiniteClosure { private HashMap> inheritanceGraph; private HashMap>> strInheritanceGraph; - public FiniteClosure() { - - } - public FiniteClosure(Set pairs) { inheritanceGraph = new HashMap>(); @@ -76,32 +72,42 @@ public class FiniteClosure implements IFiniteClosure { // where foreach type var a in T2: // sigma1(T1) <=* sigma2(T2) //If a type of the same name is in the fc AND the type "type" is parameterized (some substitution sigma1 was applied) - if(strInheritanceGraph.containsKey(type.getName())) { - IUnify unify = new MartelliMontanariUnify(); - HashSet> candidateNodes = strInheritanceGraph.get(type.getName()); - for(Node candidateNode : candidateNodes) { - Type theta2 = candidateNode.getContent(); - Optional sigma2 = unify.unify(theta2, type); - if(!sigma2.isPresent()) - continue; - Set theta1s = inheritanceGraph.containsKey(type) ? inheritanceGraph.get(type).getContentOfDescendants() : smaller(theta2); - for(Type theta1 : theta1s) { - // Because only the most general type is calculated, sigma1 = sigma2 - Type sigma1Theta1 = sigma2.get().apply(theta1); + + IUnify unify = new MartelliMontanariUnify(); + HashSet candidates = new HashSet<>(); + if (strInheritanceGraph.containsKey(type.getName())) + strInheritanceGraph.get(type.getName()).forEach(x -> candidates.add(x.getContent())); + else + candidates.add(type); + + for (Type theta2 : candidates) { + Optional sigma2 = unify.unify(theta2, type); + if (!sigma2.isPresent()) + continue; + Set theta1s = new HashSet<>(); + if(inheritanceGraph.containsKey(type)) + theta1s = inheritanceGraph.get(type).getContentOfDescendants(); + else if(theta2.equals(type)) + theta1s.add(type); + else + theta1s = smaller(theta2); + for (Type theta1 : theta1s) { + // Because only the most general type is calculated, sigma1 = + // sigma2 + Type sigma1Theta1 = sigma2.get().apply(theta1); - ArrayList> paramCandidates = new ArrayList<>(); - for(Type param : sigma1Theta1.getTypeParams()) - paramCandidates.add(smArg(param)); - - Set permResult = new HashSet<>(); - permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); - - for(TypeParams newParams : permResult) - result.add(sigma1Theta1.setTypeParams(newParams)); - } + ArrayList> paramCandidates = new ArrayList<>(); + for (Type param : sigma1Theta1.getTypeParams()) + paramCandidates.add(smArg(param)); + + Set permResult = new HashSet<>(); + permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); + + for (TypeParams newParams : permResult) + result.add(sigma1Theta1.setTypeParams(newParams)); } } - + return result; } diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index 073b4a94..c35bfe66 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -1,49 +1,218 @@ package unify; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + import org.junit.Assert; import org.junit.Test; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -import de.dhbwstuttgart.typeinference.unify.model.MPair; -import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; -import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.Type; import de.dhbwstuttgart.typeinference.unifynew.TypeFactory; -public class FiniteClosureTest extends FiniteClosure { +public class FiniteClosureTest { @Test - public void testMatch() { + public void testSmaller() { TypeFactory tf = new TypeFactory(); - Type a = tf.getPlaceholderType("a"); - Type b = tf.getPlaceholderType("b"); - Type c = tf.getPlaceholderType("c"); + Type integer = tf.getSimpleType("Integer"); + Type number = tf.getSimpleType("Number"); - Type A = tf.getSimpleType("A"); - Type B = tf.getSimpleType("B"); - Type C1 = tf.getSimpleType("C", a, b, c); - Type C2 = tf.getSimpleType("C", a, A, b); - Type C3 = tf.getSimpleType("C", A, B, A); - Type D1 = tf.getSimpleType("D", C1, a, b, c); - Type D2 = tf.getSimpleType("D", C3, A, B, A); + FiniteClosureBuilder fcb = new FiniteClosureBuilder(); + fcb.add(integer, number); + fcb.add(tf.getSimpleType("MyMap", "T"), tf.getSimpleType("HashMap", tf.getSimpleType("Integer"))); + fcb.add(tf.getSimpleType("HashMap", "T"), tf.getSimpleType("Collection")); + IFiniteClosure fc = fcb.getCollectionExample(); + + /* + * Test Case 1: + * + * smaller(Set) = { HashSet, Set, LinkedHashSet } + */ - System.out.println(match(C2, C1)); - System.out.println(match(C3, C1)); - System.out.println(match(D2, D1)); - Assert.assertFalse(match(C3, C2).isPresent()); - Assert.assertFalse(match(C1, C2).isPresent()); + Type setInt = tf.getSimpleType("Set", integer); + Type hashSetInt = tf.getSimpleType("HashSet", integer); + Type treeSetInt = tf.getSimpleType("TreeSet", integer); + Type linkedHashSetInt = tf.getSimpleType("LinkedHashSet", integer); + + Set expectedResult = new HashSet<>(Arrays.stream(new Type[] { + setInt, hashSetInt, linkedHashSetInt, treeSetInt, + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setInt)); + + /* + * Test Case 2: + * + * smaller(Set) = + * { HashSet, Set, TreeSet, LinkedHashSet, + * HashSet, Set, TreeSet, LinkedHashSet } + */ + + Type extInt = tf.getExtendsType(integer); + Type hashSetExtInt = tf.getSimpleType("HashSet", extInt); + Type treeSetExtInt = tf.getSimpleType("TreeSet", extInt); + Type linkedHashSetExtInt = tf.getSimpleType("LinkedHashSet", extInt); + Type setExtInt = tf.getSimpleType("Set", extInt); + + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + setInt, hashSetInt, linkedHashSetInt, treeSetInt, + hashSetExtInt, treeSetExtInt, linkedHashSetExtInt, setExtInt, + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setExtInt)); + + /* + * Test Case 3: + * + * smaller(Set) = + * { HashSet, Set, TreeSet, LinkedHashSet, + * HashSet, Set, TreeSet, LinkedHashSet, + * HashSet, Set, TreeSet, LinkedHashSet + * HashSet } + */ + + Type hashSetNum = tf.getSimpleType("HashSet", number); + Type treeSetNum = tf.getSimpleType("TreeSet", number); + Type linkedHashSetNum = tf.getSimpleType("LinkedHashSet", number); + Type setNum = tf.getSimpleType("Set", number); + + Type extNum = tf.getExtendsType(number); + Type hashSetExtNum = tf.getSimpleType("HashSet", extNum); + Type treeSetExtNum = tf.getSimpleType("TreeSet", extNum); + Type linkedHashSetExtNum = tf.getSimpleType("LinkedHashSet", extNum); + Type setExtNum = tf.getSimpleType("Set", extNum); + + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + setInt, hashSetInt, linkedHashSetInt, treeSetInt, + setNum, hashSetNum, linkedHashSetNum, treeSetNum, + setExtInt, hashSetExtInt, linkedHashSetExtInt, treeSetExtInt, + setExtNum, hashSetExtNum, linkedHashSetExtNum, treeSetExtNum + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setExtNum)); + + /* + * Test Case 4: + * TODO ist das ergebnis korrekt oder müssen die ? ext Ts raus weil der allgemeienste Typ T ausreicht? + * smaller(Set) = + * { HashSet, Set, TreeSet, LinkedHashSet, + * HashSet, Set, TreeSet, LinkedHashSet } + */ + + Type t = tf.getPlaceholderType("T"); + Type setT = tf.getSimpleType("Set", t); + Type hashSetT = tf.getSimpleType("HashSet", t); + Type treeSetT = tf.getSimpleType("TreeSet", t); + Type linkedHashSetT = tf.getSimpleType("LinkedHashSet", t); + Type hashSetExtT = tf.getSimpleType("HashSet", t); + Type treeSetExtT = tf.getSimpleType("TreeSet", t); + Type linkedHashSetExtT = tf.getSimpleType("LinkedHashSet", t); + Type setExtT = tf.getSimpleType("Set", t); + + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + setT, hashSetT, treeSetT, linkedHashSetT, + setExtT, hashSetExtT, treeSetExtT, linkedHashSetExtT + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setT)); + + /* + * Test Case 5 + * + * smaller(Set = + * { Set, HashSet, TreeSet, LinkedHashSet, + * Set, HashSet, TreeSet, LinkedHashSet, + * Set, HashSet, TreeSet, LinkedHashSet } + */ + + Type superNum = tf.getSuperType(number); + Type superInt = tf.getSuperType(integer); + + Type setSupInt = tf.getSimpleType("Set", superInt); + Type hashSetSupInt = tf.getSimpleType("HashSet", superInt); + Type linkedHashSetSupInt = tf.getSimpleType("LinkedHashSet", superInt); + Type treeSetSupInt = tf.getSimpleType("TreeSet", superInt); + Type setSupNum = tf.getSimpleType("Set", superNum); + Type hashSetSupNum = tf.getSimpleType("HashSet", superNum); + Type linkedHashSetSupNum = tf.getSimpleType("LinkedHashSet", superNum); + Type treeSetSupNum = tf.getSimpleType("TreeSet", superNum); + + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + setSupInt, hashSetSupInt, linkedHashSetSupInt, treeSetSupInt, + setSupNum, hashSetSupNum, linkedHashSetSupNum, treeSetSupNum, + setInt, hashSetInt, linkedHashSetInt, treeSetInt, + setNum, hashSetNum, linkedHashSetNum, treeSetNum + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setSupInt)); + + /* + * Test Case 6: + * + * smaller(Set, Set, TreeSet, LinkedHashSet, + * HashSet, Set, TreeSet, LinkedHashSet } + * + */ + + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + setT, hashSetT, treeSetT, linkedHashSetT, + setExtT, hashSetExtT, treeSetExtT, linkedHashSetExtT + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setExtT)); + + /* + * Test Case 7: + * smaller(Set) = + * { HashSet, Set, TreeSet, LinkedHashSet, + * HashSet, Set, TreeSet, LinkedHashSet } + */ + + Type notInFc = tf.getSimpleType("notInFC"); + Type setNotInFc = tf.getSimpleType("Set", notInFc); + Type hashSetNotInFc = tf.getSimpleType("HashSet", notInFc); + Type treeSetNotInFc = tf.getSimpleType("TreeSet", notInFc); + Type linkedHashSetNotInFc = tf.getSimpleType("LinkedHashSet", notInFc); + Type hashSetExtNotInFc = tf.getSimpleType("HashSet", notInFc); + Type treeSetExtNotInFc = tf.getSimpleType("TreeSet", notInFc); + Type linkedHashSetExtNotInFc = tf.getSimpleType("LinkedHashSet", notInFc); + Type setExtNotInFc = tf.getSimpleType("Set", notInFc); + + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + setNotInFc, hashSetNotInFc, treeSetNotInFc, linkedHashSetNotInFc, + setExtNotInFc, hashSetExtNotInFc, treeSetExtNotInFc, linkedHashSetExtNotInFc + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setNotInFc)); + + /* + * Test Case 8: + * + */ } @Test public void testGreater() { - IFiniteClosure fc = new FiniteClosureBuilder().getCollectionExample(); TypeFactory tf = new TypeFactory(); - + FiniteClosureBuilder fcb = new FiniteClosureBuilder(); + fcb.add(tf.getSimpleType("Integer"), tf.getSimpleType("Number")); + fcb.add(tf.getSimpleType("MyMap", "T"), tf.getSimpleType("HashMap", tf.getSimpleType("Integer"))); + fcb.add(tf.getSimpleType("HashMap", "T"), tf.getSimpleType("Collection")); + IFiniteClosure fc = fcb.getCollectionExample(); + System.out.println("\n\n----- Greater Test -----"); System.out.println("Greater(LinkedList) = " + fc.greater(tf.getSimpleType("LinkedList", "T"))); System.out.println("Greater(TreeSet) = " + fc.greater(tf.getSimpleType("TreeSet", "T"))); System.out.println("Greater(Collection) = " + fc.greater(tf.getSimpleType("Collection"))); + System.out.println(fc.greater(tf.getSimpleType("Deque", tf.getSimpleType("Integer")))); + System.out.println(fc.greater(tf.getSimpleType("Deque", tf.getSimpleType("Number")))); + System.out.println(fc.greater(tf.getSimpleType("Deque", tf.getExtendsType(tf.getSimpleType("Integer"))))); + System.out.println(fc.greater(tf.getSimpleType("Deque", tf.getSuperType(tf.getSimpleType("Integer"))))); } @Test @@ -57,20 +226,6 @@ public class FiniteClosureTest extends FiniteClosure { System.out.println("GrArg(? super List) = " + fc.grArg(tf.getSuperType(tf.getSimpleType("List", "T")))); } - @Test - public void testSmaller() { - FiniteClosureBuilder fcb = new FiniteClosureBuilder(); - TypeFactory tf = new TypeFactory(); - - fcb.add(tf.getSimpleType("Integer"), tf.getSimpleType("Number")); - IFiniteClosure fc = fcb.getCollectionExample(); - - System.out.println("\n\n----- Smaller Test -----"); - System.out.println("Smaller(List) = " + fc.smaller(tf.getSimpleType("List", tf.getExtendsType(tf.getSimpleType("Number"))))); - System.out.println("Smaller(List) = " + fc.smaller(tf.getSimpleType("List", "T"))); - System.out.println("Smaller(TreeSet) = " + fc.smaller(tf.getSimpleType("TreeSet", "T"))); - System.out.println("Smaller(Collection) = " + fc.smaller(tf.getSimpleType("Collection"))); - } @Test public void testSmArg() { From 257edfc0b3c19bf43f71952d5066abf572445101 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Sat, 26 Mar 2016 14:09:45 +0100 Subject: [PATCH 15/57] fc smaller test --- test/unify/FiniteClosureBuilder.java | 18 +++++ test/unify/FiniteClosureTest.java | 107 +++++++++++++++++++++++++++ 2 files changed, 125 insertions(+) diff --git a/test/unify/FiniteClosureBuilder.java b/test/unify/FiniteClosureBuilder.java index d5b3b32b..5a639b38 100644 --- a/test/unify/FiniteClosureBuilder.java +++ b/test/unify/FiniteClosureBuilder.java @@ -29,6 +29,8 @@ public class FiniteClosureBuilder { public IFiniteClosure getCollectionExample() { TypeFactory tf = new TypeFactory(); + /* Collection */ + Type collection = tf.getSimpleType("Collection"); Type set = tf.getSimpleType("Set", "T"); Type sortedSet = tf.getSimpleType("Set", "T"); @@ -58,6 +60,22 @@ public class FiniteClosureBuilder { add(arrayList, list); add(stack, vector); + /* Map */ + Type map = tf.getSimpleType("Map", "K", "V"); + Type sortedMap = tf.getSimpleType("SortedMap", "K", "V"); + Type navigableMap = tf.getSimpleType("NavigableMap", "K", "V"); + Type treeMap = tf.getSimpleType("TreeMap", "K", "V"); + Type hashMap = tf.getSimpleType("HashMap", "K", "V"); + Type hashtable = tf.getSimpleType("Hashtable", "K", "V"); + Type linkedHashMap = tf.getSimpleType("LinkedHashSet", "K", "V"); + + add(sortedMap, map); + add(hashMap, map); + add(hashtable, map); + add(navigableMap, sortedMap); + add(treeMap, navigableMap); + add(linkedHashMap, hashMap); + IFiniteClosure fc = getFiniteClosure(); clear(); return fc; diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index c35bfe66..d3766e74 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -168,6 +168,7 @@ public class FiniteClosureTest { /* * Test Case 7: + * * smaller(Set) = * { HashSet, Set, TreeSet, LinkedHashSet, * HashSet, Set, TreeSet, LinkedHashSet } @@ -193,6 +194,112 @@ public class FiniteClosureTest { /* * Test Case 8: * + * smaller(Set) = + * { Set, HashSet, LinkedHashSet, TreeSet, + * Set, HashSet, LinkedHashSet, TreeSet } + */ + + Type superNotInFc = tf.getSuperType(notInFc); + Type setSuperNotInFc = tf.getSimpleType("Set", superNotInFc); + Type hashSetSuperNotInFc = tf.getSimpleType("HashSet", superNotInFc); + Type treeSetSuperNotInFc = tf.getSimpleType("TreeSet", superNotInFc); + Type linkedHashSetSuperNotInFc = tf.getSimpleType("LinkedHashSet", superNotInFc); + + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + setNotInFc, hashSetNotInFc, treeSetNotInFc, linkedHashSetNotInFc, + setSuperNotInFc, hashSetSuperNotInFc, treeSetSuperNotInFc, linkedHashSetSuperNotInFc + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setSuperNotInFc)); + + /* + * Test Case 8: + * + * smaller(NotInFc) = + * { NotInFc, NotInFc, NotInFc, NotInFc } + */ + + Type notInFcExtNumber = tf.getSimpleType("NotInFc", extNum); + Type notInFcInteger = tf.getSimpleType("NotInFc", integer); + Type notInFcNumber = tf.getSimpleType("NotInFc", number); + Type notInFcExtInt = tf.getSimpleType("NotInFc", extInt); + + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + notInFcExtNumber, notInFcInteger, notInFcNumber, notInFcExtInt + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(notInFcExtNumber)); + + /* + * Test Case 9: + * + * smaller(NotInFc = + * { NotInFc, NotInFc } + */ + + Type alsoNotInFc = tf.getSimpleType("AlsoNotInFc"); + Type notInFcAlsoNotInFc = tf.getSimpleType("NotInFc", alsoNotInFc); + Type notInFcSupAlsoNotInFc = tf.getSimpleType("NotInFc", tf.getSuperType(alsoNotInFc)); + + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + notInFcAlsoNotInFc, notInFcSupAlsoNotInFc + }).collect(Collectors.toSet())); + + Set actual = fc.smaller(notInFcSupAlsoNotInFc); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 10: + * + * smaller(HashMap) = + * { HashMap, HashMap, HashMap, HashMap + * HashMap, HashMap, HashMap, HashMap, + * HashMap, HashMap, HashMap + * HashMap, HashMap, HashMap, HashMap } + */ + + /* + * Test Case 11: + * + * smaller(SortedMap) = { SortedMap, NavigableMap, TreeMap } + */ + + /* + * Test Case 12: + * + * MyMap> <* HashMap + * + * smaller(HashMap) = { HashMap>, MyMap> } + */ + + /* + * Test Case 13: + * + * MyMap> <* HashMap + * + * smaller(HashMap) = + * { HashMap, List>, + * HashMap>, + * MyMap> } + */ + + /* + * Test Case 14 + * + * MyMap> <* HashMap + * + * smaller(HashMap) = + */ + + /* + * Test Case 13: + * + * MyMap> <* HashMap +// * TODO sinnvoll ausformulieren + * smaller(HashMap) = + * { HashMap, List>, + * HashMap>, + * MyMap> } */ } From 26cc9b85efa4a2d7f8bec46874ce9b11fef76563 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 28 Mar 2016 01:01:46 +0200 Subject: [PATCH 16/57] smalller und neue testcases --- .../unify/interfaces/IFiniteClosure.java | 2 +- .../unify/model/FiniteClosure.java | 145 +++++++++++------- .../unifynew/MartelliMontanariUnify.java | 8 +- .../typeinference/unifynew/RuleSet.java | 14 +- test/unify/FiniteClosureBuilder.java | 9 +- test/unify/FiniteClosureTest.java | 88 +++++++++-- 6 files changed, 185 insertions(+), 81 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java index 0bba681f..00c12f65 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java @@ -53,6 +53,6 @@ public interface IFiniteClosure { public Set grArg(FunNType type); public Set smArg(FunNType type); - public Optional getGenericType(String typeName); + public Optional findGenericParent(String typeName); public Set getAllTypesByName(String typeName); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 427122bf..4a331353 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -18,15 +18,17 @@ public class FiniteClosure implements IFiniteClosure { private HashMap> inheritanceGraph; private HashMap>> strInheritanceGraph; + private Set pairs; + private Set basicTypes; + //TODO im konstruktor mitgeben um typenabzuhandeln die keine extends beziehung haben. (Damit die FC diese Typen auch kennt) + //(ALternative: immer die extends zu object beziehung einfügen) public FiniteClosure(Set pairs) { + this.pairs = new HashSet<>(pairs); inheritanceGraph = new HashMap>(); // Build the transitive closure of the inheritance tree for(MPair pair : pairs) { - if(!pair.getLhsType().getTypeParams().arePlaceholders()) - throw new IllegalArgumentException("The finite closure only has pairs of the form D <= C<...>"); - if(pair.getPairOp() != PairOperator.SMALLER) continue; @@ -64,51 +66,68 @@ public class FiniteClosure implements IFiniteClosure { */ @Override public Set smaller(Type type) { - Set result = new HashSet<>(); - result.add(type); - - // - if(T < T') then T <=* T' - // if T1 <=* T2 then sigma1(T1) <=* sigma1(T2) - // where foreach type var a in T2: - // sigma1(T1) <=* sigma2(T2) - //If a type of the same name is in the fc AND the type "type" is parameterized (some substitution sigma1 was applied) - + if(inheritanceGraph.containsKey(type)) { + Set result = new HashSet<>(); + result.add(type); + result.addAll(inheritanceGraph.get(type).getContentOfDescendants()); + return result; + } + IUnify unify = new MartelliMontanariUnify(); - HashSet candidates = new HashSet<>(); - if (strInheritanceGraph.containsKey(type.getName())) - strInheritanceGraph.get(type.getName()).forEach(x -> candidates.add(x.getContent())); - else - candidates.add(type); + Set result1 = new HashSet<>(); - for (Type theta2 : candidates) { - Optional sigma2 = unify.unify(theta2, type); - if (!sigma2.isPresent()) - continue; - Set theta1s = new HashSet<>(); - if(inheritanceGraph.containsKey(type)) - theta1s = inheritanceGraph.get(type).getContentOfDescendants(); - else if(theta2.equals(type)) - theta1s.add(type); - else - theta1s = smaller(theta2); - for (Type theta1 : theta1s) { - // Because only the most general type is calculated, sigma1 = - // sigma2 - Type sigma1Theta1 = sigma2.get().apply(theta1); - - ArrayList> paramCandidates = new ArrayList<>(); - for (Type param : sigma1Theta1.getTypeParams()) - paramCandidates.add(smArg(param)); - - Set permResult = new HashSet<>(); - permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); - - for (TypeParams newParams : permResult) - result.add(sigma1Theta1.setTypeParams(newParams)); + // if T = T' then T <=* T' + result1.add(type); + + {ArrayList> paramCandidates = new ArrayList<>(); + for (Type param : type.getTypeParams()) + paramCandidates.add(smArg(param)); + + Set permResult = new HashSet<>(); + permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); + + for (TypeParams newParams : permResult) + result1.add(type.setTypeParams(newParams));} + + Set result2 = new HashSet<>(); + if (strInheritanceGraph.containsKey(type.getName())) { + HashSet candidates = new HashSet<>(); + strInheritanceGraph.get(type.getName()).forEach(x -> candidates.add(x.getContent())); + + for(Type typePrime : result1) { + for (Type theta2 : candidates) { + Optional sigma2 = unify.unify(typePrime, theta2); + if (!sigma2.isPresent()) + continue; + if(type.equals(theta2)) + continue; + Set theta1s = smaller(theta2); + for (Type theta1 : theta1s) { + // Because only the most general type is calculated, sigma1 = sigma2 + Type sigma1Theta1 = sigma2.get().apply(theta1); + result2.add(sigma1Theta1); + } + } } } - - return result; + else + result2 = result1; + + Set result3 = new HashSet<>(); + for(Type t : result2) { + ArrayList> paramCandidates = new ArrayList<>(); + for (Type param : t.getTypeParams()) + paramCandidates.add(smArg(param)); + + Set permResult = new HashSet<>(); + permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); + + for (TypeParams newParams : permResult) + result3.add(t.setTypeParams(newParams)); + + } + + return result3; } /** @@ -260,19 +279,37 @@ public class FiniteClosure implements IFiniteClosure { return result; } + + public boolean isGenericType(Type t) { + if(t.getTypeParams().size() == 0) + return true; + + if(!strInheritanceGraph.containsKey(t.getName())) + return false; + + for(MPair pair : pairs) + if(pair.getLhsType().equals(t)) + return true; + + return false; + } + @Override - public Optional getGenericType(String typeName) { - if(!strInheritanceGraph.containsKey(typeName)) - return Optional.empty(); - - HashSet> candidates = strInheritanceGraph.get(typeName); - - for(Node node : candidates) { - Type candidate = node.getContent(); - if(candidate.getTypeParams().arePlaceholders()) - return Optional.of(candidate); + public Optional findGenericParent(String type) { + Type genericType = null; + for(MPair pair : pairs) { + Type lhs = pair.getLhsType(); + if(lhs.getName().equals(type)) { + genericType = lhs; + break; + } } + if(genericType == null) + return Optional.empty(); + + // TODO reduce reglen überarbeiten, es kann mehrere Typen D geben die eine bedingung + // erfüllen, diese methode ausimplementieren return Optional.empty(); } diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java b/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java index 6ae0acf6..e3ae2322 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java @@ -101,8 +101,12 @@ public class MartelliMontanariUnify implements IUnify { TypeParams rhsTypeParams = rhs.getTypeParams(); TypeParams lhsTypeParams = lhs.getTypeParams(); - if(rhsTypeParams.size() != lhsTypeParams.size() || (!rhs.getName().equals(lhs.getName()) && rhsTypeParams.size() != 0)) - return null; // conflict + if(!(rhs instanceof PlaceholderType) && !(lhs instanceof PlaceholderType)) { + if(!rhs.getName().equals(lhs.getName())) + return null; // conflict + if(rhsTypeParams.size() != lhsTypeParams.size()) + return null; // conflict; + } if(rhsTypeParams.size() == 0 || lhsTypeParams.size() == 0) return Optional.empty(); diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java index f6b26ad9..bae13582 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java @@ -328,7 +328,7 @@ public class RuleSet implements IRuleSet{ if(typeD.getName().equals(typeDs.getName())) return Optional.empty(); - Optional opt = finiteClosure.getGenericType(typeD.getName()); + Optional opt = finiteClosure.findGenericParent(typeD.getName()); if(!opt.isPresent()) return Optional.empty(); @@ -373,9 +373,9 @@ public class RuleSet implements IRuleSet{ Type typeDgen; if(typeD instanceof SimpleType) - typeDgen = finiteClosure.getGenericType(typeD.getName()).orElse(null); + typeDgen = finiteClosure.findGenericParent(typeD.getName()).orElse(null); else { - Optional opt = finiteClosure.getGenericType(((ExtendsType) typeD).getExtendedType().getName()); + Optional opt = finiteClosure.findGenericParent(((ExtendsType) typeD).getExtendedType().getName()); typeDgen = opt.isPresent() ? new ExtendsType(opt.get()) : null; } @@ -418,7 +418,7 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); - Optional opt = finiteClosure.getGenericType(((SuperType) typeSupD).getSuperedType().getName()); + Optional opt = finiteClosure.findGenericParent(((SuperType) typeSupD).getSuperedType().getName()); if(!opt.isPresent()) return Optional.empty(); @@ -462,13 +462,13 @@ public class RuleSet implements IRuleSet{ private int[] pi(Type C, Type D) { Type cFromFc = null; if(C instanceof SimpleType) - cFromFc = finiteClosure.getGenericType(C.getName()).orElse(null); + cFromFc = finiteClosure.findGenericParent(C.getName()).orElse(null); else if(C instanceof ExtendsType) { - Optional opt = finiteClosure.getGenericType(((ExtendsType) C).getExtendedType().getName()); + Optional opt = finiteClosure.findGenericParent(((ExtendsType) C).getExtendedType().getName()); if(opt.isPresent()) cFromFc = new ExtendsType(opt.get()); } else if(C instanceof SuperType) { - Optional opt = finiteClosure.getGenericType(((SuperType) C).getSuperedType().getName()); + Optional opt = finiteClosure.findGenericParent(((SuperType) C).getSuperedType().getName()); if(opt.isPresent()) cFromFc = new SuperType(opt.get()); } diff --git a/test/unify/FiniteClosureBuilder.java b/test/unify/FiniteClosureBuilder.java index 5a639b38..f4ea2133 100644 --- a/test/unify/FiniteClosureBuilder.java +++ b/test/unify/FiniteClosureBuilder.java @@ -33,7 +33,8 @@ public class FiniteClosureBuilder { Type collection = tf.getSimpleType("Collection"); Type set = tf.getSimpleType("Set", "T"); - Type sortedSet = tf.getSimpleType("Set", "T"); + //Type sortedSet = tf.getSimpleType("SortedSet", "T"); Sorted set bei den Unit-Tests vergessen + // nachträgliches einfügen zu aufwendig Type TreeSet = tf.getSimpleType("TreeSet", "T"); Type hashSet = tf.getSimpleType("HashSet", "T"); Type linkedHashSet = tf.getSimpleType("LinkedHashSet", "T"); @@ -46,8 +47,8 @@ public class FiniteClosureBuilder { Type arrayList = tf.getSimpleType("ArrayList", "T"); add(set, collection); - add(sortedSet, set); - add(TreeSet, sortedSet); + //add(sortedSet, set); + add(TreeSet, set); add(hashSet, set); add(linkedHashSet, set); @@ -67,7 +68,7 @@ public class FiniteClosureBuilder { Type treeMap = tf.getSimpleType("TreeMap", "K", "V"); Type hashMap = tf.getSimpleType("HashMap", "K", "V"); Type hashtable = tf.getSimpleType("Hashtable", "K", "V"); - Type linkedHashMap = tf.getSimpleType("LinkedHashSet", "K", "V"); + Type linkedHashMap = tf.getSimpleType("LinkedHashMap", "K", "V"); add(sortedMap, map); add(hashMap, map); diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index d3766e74..a8a72273 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -251,37 +251,91 @@ public class FiniteClosureTest { /* * Test Case 10: * - * smaller(HashMap) = - * { HashMap, HashMap, HashMap, HashMap - * HashMap, HashMap, HashMap, HashMap, - * HashMap, HashMap, HashMap - * HashMap, HashMap, HashMap, HashMap } + * smaller(TreeMap) = + * { TreeMap, TreeMap, TreeMap, TreeMap + * TreeMap, TreeMap, TreeMap, TreeMap, + * TreeMap, TreeMap, TreeMap + * TreeMap, TreeMap, TreeMap, TreeMap } */ + Type treeMapExtNumSupInt = tf.getSimpleType("TreeMap", extNum, superInt); + + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + treeMapExtNumSupInt, tf.getSimpleType("TreeMap", extNum, superNum), tf.getSimpleType("TreeMap", extNum, integer), tf.getSimpleType("TreeMap", extNum, number), + tf.getSimpleType("TreeMap", number, superInt), tf.getSimpleType("TreeMap", number, superNum), tf.getSimpleType("TreeMap", number, integer), tf.getSimpleType("TreeMap", number, number), + tf.getSimpleType("TreeMap", integer, superInt), tf.getSimpleType("TreeMap", integer, superNum), tf.getSimpleType("TreeMap", integer, integer), tf.getSimpleType("TreeMap", integer, number), + tf.getSimpleType("TreeMap", extInt, superInt), tf.getSimpleType("TreeMap", extInt, superNum), tf.getSimpleType("TreeMap", extInt, integer), tf.getSimpleType("TreeMap", extInt, number) + }).collect(Collectors.toSet())); + + actual = fc.smaller(treeMapExtNumSupInt); + Assert.assertEquals(expectedResult, actual); + /* * Test Case 11: * * smaller(SortedMap) = { SortedMap, NavigableMap, TreeMap } */ + Type sortedMapNumberT = tf.getSimpleType("SortedMap", number, t); + Type navigableMapNumberT = tf.getSimpleType("NavigableMap", number, t); + Type treeMapNumberT = tf.getSimpleType("TreeMap", number, t); + + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + sortedMapNumberT, navigableMapNumberT, treeMapNumberT + }).collect(Collectors.toSet())); + + actual = fc.smaller(sortedMapNumberT); + Assert.assertEquals(expectedResult, actual); + /* * Test Case 12: * - * MyMap> <* HashMap + * MyMap <* TreeMap> * - * smaller(HashMap) = { HashMap>, MyMap> } + * smaller(TreeMap) = { TreeMap>, MyMap } */ + fcb = new FiniteClosureBuilder(); + Type k = tf.getPlaceholderType("K"); + Type myMap = tf.getSimpleType("MyMap", k); + fcb.add(myMap, tf.getSimpleType("TreeMap", k, tf.getSimpleType("List", k))); + fcb.add(integer, number); + fc = fcb.getCollectionExample(); + + Type treeMapNumberListNumber = tf.getSimpleType("TreeMap", number, tf.getSimpleType("List", number)); + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + treeMapNumberListNumber, + tf.getSimpleType("MyMap", number) + }).collect(Collectors.toSet())); + + actual = fc.smaller(treeMapNumberListNumber); + Assert.assertEquals(expectedResult, actual); + /* * Test Case 13: * - * MyMap> <* HashMap + * MyMap <* TreeMap> * - * smaller(HashMap) = - * { HashMap, List>, - * HashMap>, - * MyMap> } + * smaller(TreeMap) = + * { TreeMap, List>, + * TreeMap>, + * TreeMap>, + * TreeMap>, + * MyMap } */ + + Type listInteger = tf.getSimpleType("List", integer); + Type treeMapExtNumberListInteger = tf.getSimpleType("TreeMap", extNum, listInteger); + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + treeMapExtNumberListInteger, + tf.getSimpleType("TreeMap", extInt, listInteger), + tf.getSimpleType("TreeMap", number, listInteger), + tf.getSimpleType("TreeMap", integer, listInteger), + tf.getSimpleType("MyMap", integer) + }).collect(Collectors.toSet())); + + actual = fc.smaller(treeMapExtNumberListInteger); + Assert.assertEquals(expectedResult, actual); /* * Test Case 14 @@ -292,7 +346,7 @@ public class FiniteClosureTest { */ /* - * Test Case 13: + * Test Case 15: * * MyMap> <* HashMap // * TODO sinnvoll ausformulieren @@ -350,4 +404,12 @@ public class FiniteClosureTest { // TODO } + + private void printDiff(Set expected, Set actual) { + System.out.println("Diff:"); + System.out.println("In expected but not in actual:"); + Set expected1 = new HashSet<>(expected); + expected1.removeAll(actual); + System.out.println(expected1); + } } From de607cfd53c332a00e13dc88f81f8254161795bb Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 28 Mar 2016 01:19:57 +0200 Subject: [PATCH 17/57] noch ein smaller test --- test/unify/FiniteClosureTest.java | 37 ++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index a8a72273..7c422bda 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -340,17 +340,44 @@ public class FiniteClosureTest { /* * Test Case 14 * - * MyMap> <* HashMap + * MyMap <* TreeMap> * - * smaller(HashMap) = + * smaller(TreeMap) = + * { TreeMap, List>, + * TreeMap>, + * TreeMap>, + * TreeMap>, + * MyMap + * MyMap + * MyMap + * MyMap */ + Type listExtNum = tf.getSimpleType("List", extNum); + Type treeMapExtNumListExtNum = tf.getSimpleType("TreeMap", extNum, listExtNum); + Type myMapInt = tf.getSimpleType("MyMap", integer); + Type myMapNumber = tf.getSimpleType("MyMap", number); + Type myMapExtInt = tf.getSimpleType("MyMap", extInt); + Type myMapExtNum = tf.getSimpleType("MyMap", extNum); + + actual = fc.smaller(treeMapExtNumListExtNum); + + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + tf.getSimpleType("TreeMap", extNum, listExtNum), + tf.getSimpleType("TreeMap", extInt, listExtNum), + tf.getSimpleType("TreeMap", number, listExtNum), + tf.getSimpleType("TreeMap", integer, listExtNum), + myMapInt, myMapNumber, myMapExtInt, myMapExtNum + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, actual); + /* * Test Case 15: * - * MyMap> <* HashMap -// * TODO sinnvoll ausformulieren - * smaller(HashMap) = + * MyMap <* HashMap> + * + * smaller(SortedSet) = * { HashMap, List>, * HashMap>, * MyMap> } From 67e1c5c7367c3db24c268a255ffe6f68d2352b3c Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 28 Mar 2016 01:26:53 +0200 Subject: [PATCH 18/57] 15ter testcase --- test/unify/FiniteClosureTest.java | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index 7c422bda..d1f99d60 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -377,11 +377,20 @@ public class FiniteClosureTest { * * MyMap <* HashMap> * - * smaller(SortedSet) = - * { HashMap, List>, - * HashMap>, - * MyMap> } + * smaller(NavigableSet>) = + * { NavigableSet>, + * NavigableSet> + * NavigableSet> + * NavigableSet> + * TreeSet>, + * TreeSet> + * TreeSet> + * TreeSet> } */ + + Type navSet = tf.getSimpleType("NavigableSet", extInt, tf.getExtendsType(tf.getSimpleType("ArrayList", extInt))); + + Assert.assertEquals(8, fc.smaller(navSet).size()); } @Test From ac3ce7d2147973ae5db41e3b8420c238dd5e0c4f Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 28 Mar 2016 11:40:21 +0200 Subject: [PATCH 19/57] smaller --- .../unify/model/FiniteClosure.java | 9 +++++-- test/unify/FiniteClosureTest.java | 24 +++++++++---------- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 4a331353..1c45680b 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -122,8 +122,13 @@ public class FiniteClosure implements IFiniteClosure { Set permResult = new HashSet<>(); permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); - for (TypeParams newParams : permResult) - result3.add(t.setTypeParams(newParams)); + for (TypeParams newParams : permResult) { + Type tPrime = t.setTypeParams(newParams); + if(tPrime.equals(t)) + result3.add(t); + else + result3.addAll(smaller(tPrime)); + } } diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index d1f99d60..33ba1d0a 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -375,22 +375,22 @@ public class FiniteClosureTest { /* * Test Case 15: * - * MyMap <* HashMap> + * MyMap <* TreeMap> * - * smaller(NavigableSet>) = - * { NavigableSet>, - * NavigableSet> - * NavigableSet> - * NavigableSet> - * TreeSet>, - * TreeSet> - * TreeSet> - * TreeSet> } + * smaller(NavigableSet>) = + * { Permutationen der List, + * Permutationen der List in TreeSets, + * MyMap und MyMap + * } */ - Type navSet = tf.getSimpleType("NavigableSet", extInt, tf.getExtendsType(tf.getSimpleType("ArrayList", extInt))); + Type navSet = tf.getSimpleType("NavigableMap", extInt, tf.getExtendsType(tf.getSimpleType("List", extInt))); - Assert.assertEquals(8, fc.smaller(navSet).size()); + actual = fc.smaller(navSet); + + Assert.assertEquals(82, actual.size()); + Assert.assertTrue(actual.contains(myMapExtInt)); + Assert.assertTrue(actual.contains(myMapInt)); } @Test From 332dd57de3fe79dfb4fde48ceed17f4ed4632f0a Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 28 Mar 2016 15:00:34 +0200 Subject: [PATCH 20/57] greater und testy --- .../unify/model/FiniteClosure.java | 83 ++++-- test/unify/FiniteClosureTest.java | 241 +++++++++++++++++- 2 files changed, 291 insertions(+), 33 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 1c45680b..4bbcde0b 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -140,32 +140,71 @@ public class FiniteClosure implements IFiniteClosure { * @return The set of supertypes of the argument. */ @Override - public Set greater(Type type) { - Set result = inheritanceGraph.containsKey(type) ? inheritanceGraph.get(type).getContentOfPredecessors() : new HashSet<>(); - result.add(type); - - if(type.getTypeParams().size() == 0) - return result; + public Set greater(Type type) { + IUnify unify = new MartelliMontanariUnify(); + Set result1 = new HashSet<>(); - ArrayList> paramCandidates = new ArrayList<>(); - for(Type param : type.getTypeParams()) { - if(param instanceof ExtendsType || param instanceof SuperType) { - Set pc = param.grArg(this); - paramCandidates.add(pc); - } else { - HashSet pc = new HashSet<>(); - pc.add(param); - paramCandidates.add(pc); + if(inheritanceGraph.containsKey(type)) + result1.addAll(inheritanceGraph.get(type).getContentOfPredecessors()); + + // if T = T' then T <=* T' + result1.add(type); + + {ArrayList> paramCandidates = new ArrayList<>(); + for (Type param : type.getTypeParams()) + paramCandidates.add(grArg(param)); + + Set permResult = new HashSet<>(); + permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); + + for (TypeParams newParams : permResult) + result1.add(type.setTypeParams(newParams));} + + Set result2 = new HashSet<>(); + if (strInheritanceGraph.containsKey(type.getName()) && !inheritanceGraph.containsKey(type)) { + HashSet candidates = new HashSet<>(); + strInheritanceGraph.get(type.getName()).forEach(x -> candidates.add(x.getContent())); + + for(Type typePrime : result1) { + for (Type theta2 : candidates) { + Optional sigma2 = unify.unify(typePrime, theta2); + if (!sigma2.isPresent()) + continue; + if(type.equals(theta2)) + continue; + Set theta1s = greater(theta2); + for (Type theta1 : theta1s) { + // Because only the most general type is calculated, sigma1 = sigma2 + Type sigma1Theta1 = sigma2.get().apply(theta1); + result2.add(sigma1Theta1); + } + } } } - Set permResult = new HashSet<>(); - permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); + result2.addAll(result1); - for(TypeParams newParams : permResult) - result.add(type.setTypeParams(newParams)); + Set result3 = new HashSet<>(); + for(Type t : result2) { + ArrayList> paramCandidates = new ArrayList<>(); + for (Type param : t.getTypeParams()) + paramCandidates.add(grArg(param)); + + Set permResult = new HashSet<>(); + permuteParams(paramCandidates, 0, permResult, new Type[paramCandidates.size()]); + + for (TypeParams newParams : permResult) { + Type tPrime = t.setTypeParams(newParams); + if(tPrime.equals(t)) + result3.add(t); + else + result3.addAll(greater(tPrime)); + } + + } + + return result3; - return result; } @Override @@ -217,8 +256,8 @@ public class FiniteClosure implements IFiniteClosure { public Set grArg(PlaceholderType type) { HashSet result = new HashSet<>(); result.add(type); - result.add(new SuperType(type)); - result.add(new ExtendsType(type)); + //result.add(new SuperType(type)); + //result.add(new ExtendsType(type)); return result; } diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index 33ba1d0a..7322e857 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -2,6 +2,7 @@ package unify; import java.util.Arrays; import java.util.HashSet; +import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -397,19 +398,237 @@ public class FiniteClosureTest { public void testGreater() { TypeFactory tf = new TypeFactory(); FiniteClosureBuilder fcb = new FiniteClosureBuilder(); - fcb.add(tf.getSimpleType("Integer"), tf.getSimpleType("Number")); - fcb.add(tf.getSimpleType("MyMap", "T"), tf.getSimpleType("HashMap", tf.getSimpleType("Integer"))); - fcb.add(tf.getSimpleType("HashMap", "T"), tf.getSimpleType("Collection")); + Type k = tf.getPlaceholderType("K"); + Type integer = tf.getSimpleType("Integer"); + Type number = tf.getSimpleType("Number"); + Type myMap = tf.getSimpleType("MyMap", k); + Type myIntMap = tf.getSimpleType("MyIntMap"); + Type collection = tf.getSimpleType("Collection"); + Type sortedSet =tf.getSimpleType("SortedSet", "T"); + Type extInt = tf.getExtendsType(integer); + Type extNum = tf.getExtendsType(number); + Type supInt = tf.getSuperType(integer); + Type supNum = tf.getSuperType(number); + fcb.add(myMap, tf.getSimpleType("Map", k, tf.getSimpleType("List", k))); + fcb.add(myIntMap, tf.getSimpleType("MyMap", integer)); + fcb.add(sortedSet, tf.getSimpleType("Set", "T")); // sortedSet < Set missing in collection example + fcb.add(integer, number); IFiniteClosure fc = fcb.getCollectionExample(); - System.out.println("\n\n----- Greater Test -----"); - System.out.println("Greater(LinkedList) = " + fc.greater(tf.getSimpleType("LinkedList", "T"))); - System.out.println("Greater(TreeSet) = " + fc.greater(tf.getSimpleType("TreeSet", "T"))); - System.out.println("Greater(Collection) = " + fc.greater(tf.getSimpleType("Collection"))); - System.out.println(fc.greater(tf.getSimpleType("Deque", tf.getSimpleType("Integer")))); - System.out.println(fc.greater(tf.getSimpleType("Deque", tf.getSimpleType("Number")))); - System.out.println(fc.greater(tf.getSimpleType("Deque", tf.getExtendsType(tf.getSimpleType("Integer"))))); - System.out.println(fc.greater(tf.getSimpleType("Deque", tf.getSuperType(tf.getSimpleType("Integer"))))); + /* + * Test Case 1: + * + * greater(SortedSet) = + * { SortedSet, Set, Collection + * SortedSet, SortedSet, SortedSet, + * Set, Set, Set } + */ + + Type sortedSetInteger = tf.getSimpleType("SortedSet", integer); + Set expectedResult = new HashSet<>(Arrays.stream(new Type[] { + sortedSetInteger, tf.getSimpleType("Set", integer), collection, + tf.getSimpleType("SortedSet", extInt), tf.getSimpleType("SortedSet", supInt), + tf.getSimpleType("SortedSet", extNum), tf.getSimpleType("Set", extInt), + tf.getSimpleType("Set", supInt), tf.getSimpleType("Set", extNum) + }).collect(Collectors.toSet())); + + Set actual = fc.greater(sortedSetInteger); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 2: + * + * greater(SortedSet) = + * { SortedSet, SortedSet, + * Set, Set, Collection } + */ + + Type sortedSetExtInt = tf.getSimpleType("SortedSet", extInt); + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + sortedSetExtInt, tf.getSimpleType("SortedSet", extNum), collection, + tf.getSimpleType("Set", extInt), tf.getSimpleType("Set", extNum) + }).collect(Collectors.toSet())); + + actual = fc.greater(sortedSetExtInt); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 3: + * + * TODO hier extends und super? (siehe test case 4 bei smaller) + * greater(SortedSet) = + * { SortedSet, SortedSet, SortedSet, + * Set, Set, Set, Collection } + */ + + /* + * Test Case 4: + * + * greater(SortedSet) = + * { SortedSet, SortedSet + * Set, Set, Collection } + */ + + Type sortedSetSupNum = tf.getSimpleType("SortedSet", supNum); + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + sortedSetSupNum, tf.getSimpleType("SortedSet", supInt), collection, + tf.getSimpleType("Set", supNum), tf.getSimpleType("Set", supInt) + }).collect(Collectors.toSet())); + + actual = fc.greater(sortedSetSupNum); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 5: + * + * TODO nicht unifizierbar bei T wenn Set deklariert wurde. Können die beiden T's verschieden sein? + * greater(SortedSet) = + * { SortedSet, Set, Collection } + */ + + Type extT = tf.getExtendsType(tf.getPlaceholderType("T1")); + Type sortedSetExtT = tf.getSimpleType("SortedSet", extT); + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + sortedSetExtT, tf.getSimpleType("Set", extT), collection, + }).collect(Collectors.toSet())); + + actual = fc.greater(sortedSetExtT); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 6: + * + * greater(SortedSet) = + * { SortedSet, SortedSet, SortedSet, + * Set, Set, Set, Collection } + */ + + Type notInFc = tf.getSimpleType("NotInFc"); + Type extNotInFc = tf.getExtendsType(notInFc); + Type supNotInFc = tf.getSuperType(notInFc); + Type sortedSetNotInFc= tf.getSimpleType("SortedSet", notInFc); + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + sortedSetNotInFc, tf.getSimpleType("SortedSet", extNotInFc), tf.getSimpleType("SortedSet", supNotInFc), + tf.getSimpleType("Set", notInFc), tf.getSimpleType("Set", extNotInFc), tf.getSimpleType("Set", supNotInFc), + collection + }).collect(Collectors.toSet())); + + actual = fc.greater(sortedSetNotInFc); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 7: + * + * greater(SortedSet, Set, Collection } + */ + + Type sortedSetSupNotInFc= tf.getSimpleType("SortedSet", supNotInFc); + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + sortedSetSupNotInFc, tf.getSimpleType("Set", supNotInFc), collection + }).collect(Collectors.toSet())); + + actual = fc.greater(sortedSetSupNotInFc); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 8: + * + * greater(NotInFc) = + * { NotInFc, NotInFc, NotInFC, + * NotInFc } + */ + + Type notInFcInteger = tf.getSimpleType("NotInFc", integer); + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + notInFcInteger, tf.getSimpleType("NotInFc", supInt), + tf.getSimpleType("NotInFc", extInt), tf.getSimpleType("NotInFc", extNum) + }).collect(Collectors.toSet())); + + actual = fc.greater(notInFcInteger); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 9: + * greater(NotInFc) = + * { NotInFc, NotInFc } + */ + + Type notInFcAlsoNotInFc = tf.getSimpleType("NotInFc", tf.getSimpleType("AlsoNotInFc")); + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + notInFcAlsoNotInFc, tf.getSimpleType("NotInFc", tf.getExtendsType(tf.getSimpleType("AlsoNotInFc"))), + tf.getSimpleType("NotInFc", tf.getSuperType(tf.getSimpleType("AlsoNotInFc"))) + }).collect(Collectors.toSet())); + + actual = fc.greater(notInFcAlsoNotInFc); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 10: + * greater(Map) = + * { Map, Map, + * Map, Map, + * Map, Map, + * Map, Map } + */ + + Type mapExtIntInt = tf.getSimpleType("Map", extInt, integer); + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + mapExtIntInt, tf.getSimpleType("Map", extInt, extInt), + tf.getSimpleType("Map", extInt, supInt), tf.getSimpleType("Map", extInt, extNum), + tf.getSimpleType("Map", extNum, integer), tf.getSimpleType("Map", extNum, extInt), + tf.getSimpleType("Map", extNum, supInt), tf.getSimpleType("Map", extNum, extNum) + }).collect(Collectors.toSet())); + + actual = fc.greater(mapExtIntInt); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 11: + * + * MyIntMap < MyMap + * MyMap < Map> + * + * greater(MyIntMap) = + * { MyMap, MyMap, MyMap, MyMap, + * Map, Map, List, + * Map, List, Map, MyIntMap } + */ + + Type listInteger = tf.getSimpleType("List", integer); + expectedResult = new HashSet<>(Arrays.stream(new Type[] { + myIntMap, tf.getSimpleType("MyMap", integer), tf.getSimpleType("MyMap", extInt), + tf.getSimpleType("MyMap", extNum), tf.getSimpleType("MyMap", supInt), + tf.getSimpleType("Map", integer, listInteger), tf.getSimpleType("Map", extInt, listInteger), + tf.getSimpleType("MyMap", extNum, listInteger), tf.getSimpleType("MyMap", supInt, listInteger) + }).collect(Collectors.toSet())); + + actual = fc.greater(myIntMap); + //Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 12: + * + * MyIntMap < MyMap + * MyMap < Map> + * + * TODO + * D d = null; + * A> a = null; + * a = d; ist nicht möglich! + * + * greater(MyMap) = + * { MyMap, MyMap, + * Map>, + * Map, List> } + */ + + /* + * Test Case 13: + * + * greater(SortedMap, ? super List>) = + * + */ } @Test From 639ac8430ce2accca03597aa8c70492ae8e09fb2 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 28 Mar 2016 20:56:24 +0200 Subject: [PATCH 21/57] adapted adaptRules --- .../unify/interfaces/IFiniteClosure.java | 4 +- .../unify/model/FiniteClosure.java | 43 +++++---- .../typeinference/unifynew/RuleSet.java | 88 ++++++++----------- 3 files changed, 59 insertions(+), 76 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java index 00c12f65..d2c6f0f4 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java @@ -53,6 +53,8 @@ public interface IFiniteClosure { public Set grArg(FunNType type); public Set smArg(FunNType type); - public Optional findGenericParent(String typeName); + public Optional getLeftHandedType(Type t); + public Set getAncestors(Type t); + public Set getAllTypesByName(String typeName); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 4bbcde0b..9e1b8808 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -271,8 +272,6 @@ public class FiniteClosure implements IFiniteClosure { Set result = new HashSet(); result.add(type); - // smaller(type).forEach(x -> result.add(new ExtendsType(x))); TODO inkorrekt? daher erstmal raus - return result; } @@ -318,8 +317,6 @@ public class FiniteClosure implements IFiniteClosure { public Set smArg(PlaceholderType type) { HashSet result = new HashSet<>(); result.add(type); - //result.add(new SuperType(type)); TODO inkorrekt, daher erstmal raus - //result.add(new ExtendsType(type)); return result; } @@ -337,25 +334,6 @@ public class FiniteClosure implements IFiniteClosure { return false; } - - @Override - public Optional findGenericParent(String type) { - Type genericType = null; - for(MPair pair : pairs) { - Type lhs = pair.getLhsType(); - if(lhs.getName().equals(type)) { - genericType = lhs; - break; - } - } - - if(genericType == null) - return Optional.empty(); - - // TODO reduce reglen überarbeiten, es kann mehrere Typen D geben die eine bedingung - // erfüllen, diese methode ausimplementieren - return Optional.empty(); - } @Override public Set getAllTypesByName(String typeName) { @@ -364,6 +342,25 @@ public class FiniteClosure implements IFiniteClosure { return strInheritanceGraph.get(typeName).stream().map(x -> x.getContent()).collect(Collectors.toCollection(HashSet::new)); } + @Override + public Optional getLeftHandedType(Type t) { + if(!strInheritanceGraph.containsKey(t.getName())) + return Optional.empty(); + + for(MPair pair : pairs) + if(pair.getLhsType().getName().equals(t.getName())) + return Optional.of(pair.getLhsType()); + + return Optional.empty(); + } + + @Override + public Set getAncestors(Type t) { + if(!inheritanceGraph.containsKey(t)) + return new HashSet<>(); + return inheritanceGraph.get(t).getContentOfPredecessors(); + } + protected void permuteParams(ArrayList> candidates, int idx, Set result, Type[] current) { if(candidates.size() == idx) { result.add(new TypeParams(Arrays.copyOf(current, current.length))); diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java index bae13582..672c104d 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java @@ -85,26 +85,26 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); - Type lhsType = pair.getLhsType(); + Type x = pair.getLhsType(); - if(!(lhsType instanceof SimpleType) && !(lhsType instanceof ExtendsType)) + if(!(x instanceof SimpleType) && !(x instanceof ExtendsType)) return Optional.empty(); - Type rhsType = pair.getRhsType(); + Type extY = pair.getRhsType(); - if(!(rhsType instanceof ExtendsType)) + if(!(extY instanceof ExtendsType)) return Optional.empty(); - if(lhsType.getTypeParams().empty() || rhsType.getTypeParams().size() != lhsType.getTypeParams().size()) + if(x.getTypeParams().empty() || extY.getTypeParams().size() != x.getTypeParams().size()) return Optional.empty(); - int[] pi = pi(lhsType, rhsType); + int[] pi = pi(x, extY); if(pi.length == 0) return Optional.empty(); - TypeParams rhsTypeParams = rhsType.getTypeParams(); - TypeParams lhsTypeParams = lhsType.getTypeParams(); + TypeParams rhsTypeParams = extY.getTypeParams(); + TypeParams lhsTypeParams = x.getTypeParams(); Set result = new HashSet<>(); for(int rhsIdx = 0; rhsIdx < rhsTypeParams.size(); rhsIdx++) @@ -160,7 +160,7 @@ public class RuleSet implements IRuleSet{ if(!rhsType.getName().equals(lhsType.getName())) return Optional.empty(); - if(rhsType instanceof PlaceholderType || rhsType.getTypeParams().empty()) + if(rhsType instanceof PlaceholderType || lhsType instanceof PlaceholderType || rhsType.getTypeParams().empty()) return Optional.empty(); if(rhsType.getTypeParams().size() != lhsType.getTypeParams().size()) @@ -328,16 +328,16 @@ public class RuleSet implements IRuleSet{ if(typeD.getName().equals(typeDs.getName())) return Optional.empty(); - Optional opt = finiteClosure.findGenericParent(typeD.getName()); + Optional opt = finiteClosure.getLeftHandedType(typeD); if(!opt.isPresent()) return Optional.empty(); // The generic Version of Type D (D) Type typeDgen = opt.get(); - + // Actually greater+ because the types are ensured to have different names - Set greater = finiteClosure.greater(typeDgen); + Set greater = finiteClosure.getAncestors(typeDgen); opt = greater.stream().filter(x -> x.getName().equals(typeDs.getName())).findAny(); if(!opt.isPresent()) @@ -350,7 +350,7 @@ public class RuleSet implements IRuleSet{ Unifier unif = new Unifier((PlaceholderType) typeDgenParams.get(0), typeDParams.get(0)); for(int i = 1; i < typeDParams.size(); i++) - unif.andThen(new Unifier((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i))); + unif.Add((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i)); return Optional.of(new MPair(unif.apply(newLhs), typeDs, PairOperator.SMALLERDOT)); } @@ -373,9 +373,9 @@ public class RuleSet implements IRuleSet{ Type typeDgen; if(typeD instanceof SimpleType) - typeDgen = finiteClosure.findGenericParent(typeD.getName()).orElse(null); + typeDgen = finiteClosure.getLeftHandedType(typeD).orElse(null); else { - Optional opt = finiteClosure.findGenericParent(((ExtendsType) typeD).getExtendedType().getName()); + Optional opt = finiteClosure.getLeftHandedType(((ExtendsType) typeD).getExtendedType()); typeDgen = opt.isPresent() ? new ExtendsType(opt.get()) : null; } @@ -396,7 +396,7 @@ public class RuleSet implements IRuleSet{ Unifier unif = new Unifier((PlaceholderType) typeDgenParams.get(0), typeDParams.get(0)); for(int i = 1; i < typeDParams.size(); i++) - unif.andThen(new Unifier((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i))); + unif.Add((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i)); return Optional.of(new MPair(unif.apply(newLhs), typeExtDs, PairOperator.SMALLERDOTWC)); } @@ -418,7 +418,7 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); - Optional opt = finiteClosure.findGenericParent(((SuperType) typeSupD).getSuperedType().getName()); + Optional opt = finiteClosure.getLeftHandedType(((SuperType) typeSupD).getSuperedType()); if(!opt.isPresent()) return Optional.empty(); @@ -448,7 +448,7 @@ public class RuleSet implements IRuleSet{ Unifier unif = new Unifier((PlaceholderType) typeSupDsgenParams.get(0), typeDParams.get(0)); for(int i = 1; i < typeDParams.size(); i++) - unif.andThen(new Unifier((PlaceholderType) typeSupDsgenParams.get(i), typeDParams.get(i))); + unif.Add((PlaceholderType) typeSupDsgenParams.get(i), typeDParams.get(i)); return Optional.of(new MPair(unif.apply(newLhs), newRhs, PairOperator.SMALLERDOTWC)); } @@ -460,43 +460,27 @@ public class RuleSet implements IRuleSet{ * @return An array containing the values of pi for every type argument of C or an empty array if the search failed. */ private int[] pi(Type C, Type D) { - Type cFromFc = null; - if(C instanceof SimpleType) - cFromFc = finiteClosure.findGenericParent(C.getName()).orElse(null); - else if(C instanceof ExtendsType) { - Optional opt = finiteClosure.findGenericParent(((ExtendsType) C).getExtendedType().getName()); - if(opt.isPresent()) cFromFc = new ExtendsType(opt.get()); - } - else if(C instanceof SuperType) { - Optional opt = finiteClosure.findGenericParent(((SuperType) C).getSuperedType().getName()); - if(opt.isPresent()) cFromFc = new SuperType(opt.get()); - } + String simpleTypeDName = D.getName(); + if(D instanceof ExtendsType) + simpleTypeDName = ((ExtendsType) D).getExtendedType().getName(); + else if(D instanceof SuperType) + simpleTypeDName = ((SuperType) D).getSuperedType().getName(); - if(cFromFc == null) + String simpleTypeCName = C.getName(); + if(C instanceof ExtendsType) + simpleTypeCName = ((ExtendsType) C).getExtendedType().getName(); + if(C instanceof SuperType) + simpleTypeCName = ((SuperType) C).getSuperedType().getName(); + + Optional typesFromFc = Optional.empty(); //TODO reduce regeln + //finiteClosure.findCandD(simpleTypeCName, simpleTypeDName); + + if(typesFromFc == null) return new int[0]; - Optional opt = Optional.empty(); - if(D instanceof ExtendsType) { - SimpleType dSType = (SimpleType) ((ExtendsType) D).getExtendedType(); - opt = finiteClosure.grArg(cFromFc).stream() - .filter(x -> x instanceof ExtendsType) - .filter(x -> ((ExtendsType) x).getExtendedType().getName().equals(dSType.getName())).findAny(); - } - else if(D instanceof SuperType) { - SimpleType dSType = (SimpleType) ((SuperType) D).getSuperedType(); - opt = finiteClosure.grArg(cFromFc).stream() - .filter(x -> x instanceof SuperType) - .filter(x -> ((SuperType) x).getSuperedType().getName().equals(dSType.getName())).findAny(); - } - else if (D instanceof SimpleType) - opt = finiteClosure.greater(cFromFc).stream() - .filter(x -> x.getName().equals(D.getName())).findAny(); - - if(!opt.isPresent()) - return new int[0]; - - Type dFromFc = opt.get(); - + Type cFromFc = typesFromFc.get()[0]; + Type dFromFc = typesFromFc.get()[1]; + Assert.assertEquals(cFromFc.getTypeParams().size(), dFromFc.getTypeParams().size()); Assert.assertTrue(dFromFc.getTypeParams().size() > 0); From fa337c554612f297acfc5979c822971fdb1a828c Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Tue, 29 Mar 2016 13:23:05 +0200 Subject: [PATCH 22/57] Umstellung auf MPair beginnen --- .settings/org.eclipse.core.resources.prefs | 2 + .../dhbwstuttgart/syntaxtree/SourceFile.java | 44 ++++++++----------- .../syntaxtree/factory/UnifyTypeFactory.java | 38 ++++++++++++++-- .../typeinference/ConstraintsSet.java | 4 ++ .../typeinference/EinzelElement.java | 4 ++ .../typeinference/UndConstraint.java | 4 ++ .../typeinference/unify/Unifier.java | 4 +- 7 files changed, 69 insertions(+), 31 deletions(-) diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs index 5c6e1080..9305e36f 100755 --- a/.settings/org.eclipse.core.resources.prefs +++ b/.settings/org.eclipse.core.resources.prefs @@ -3,4 +3,6 @@ encoding//src/de/dhbwstuttgart/core/MyCompiler.java=UTF-8 encoding//src/de/dhbwstuttgart/syntaxtree/statement/LambdaExpression.java=UTF-8 encoding//src/de/dhbwstuttgart/typeinference/SingleConstraint.java=UTF-8 encoding//src/de/dhbwstuttgart/typeinference/UndConstraint.java=UTF-8 +encoding//src/de/dhbwstuttgart/typeinference/UnifySingleConstraint.java=UTF-8 +encoding//src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java=UTF-8 encoding/=UTF-8 diff --git a/src/de/dhbwstuttgart/syntaxtree/SourceFile.java b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java index 18e43236..301b73f1 100755 --- a/src/de/dhbwstuttgart/syntaxtree/SourceFile.java +++ b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java @@ -46,6 +46,7 @@ import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResults; import de.dhbwstuttgart.typeinference.UndConstraint; +import de.dhbwstuttgart.typeinference.UnifyConstraintsSet; import de.dhbwstuttgart.typeinference.assumptions.ClassAssumption; import de.dhbwstuttgart.typeinference.assumptions.MethodAssumption; import de.dhbwstuttgart.typeinference.assumptions.ParameterAssumption; @@ -255,22 +256,27 @@ public class SourceFile //////////////// - //Karthesisches Produkt bilden: + //Typen in UnifyTypen umwandeln: //////////////// + UnifyConstraintsSet unifyConstraints = UnifyTypeFactory.convert(oderConstraints); //Unmögliche ConstraintsSets aussortieren durch Unifizierung - Function,Menge>> unifier = (pairs)->{ - Menge> retValue = new Menge<>(); - Set convertPairs = UnifyTypeFactory.convert(pairs); - Set> unifiedPairs = new Unify().unify(convertPairs, finiteClosure); + Function,Menge>> unifier = (pairs)->{ + Menge> retValue = new Menge<>(); + Set> unifiedPairs = new Unify().unify(pairs, finiteClosure); return retValue;}; //oderConstraints.filterWrongConstraints(unifier); //oderConstraints.unifyUndConstraints(unifier); //rausgeworfen für Tests (08.12.2015) - + typinferenzLog.debug("Übriggebliebene Konstraints:\n"+oderConstraints+"\n", Section.TYPEINFERENCE); - //Die Constraints in Pair's umwandeln (Karthesisches Produkt bilden): - Set> xConstraints = oderConstraints.cartesianProduct(); + + //////////////// + //Karthesisches Produkt bilden: + //////////////// + Set> xConstraints = unifyConstraints.cartesianProduct(); + + typinferenzLog.debug("Karthesisches Produkt der Constraints: "+xConstraints, Section.TYPEINFERENCE); @@ -280,28 +286,15 @@ public class SourceFile // Unifizierung der Constraints: ////////////////////////////// boolean unifyFail = true; - for(Set constraints : xConstraints){ + for(Set constraints : xConstraints){ //Alle durch das Karthesische Produkt entstandenen Möglichkeiten durchgehen: Menge> result = new Menge>(); - //Alle FunN-Typen werden per clone-methode in RefTypes verwandelt. (Die clone Methode in FunN darf nicht überschrieben werden. - for(Pair p : constraints){ - if(p.TA1 instanceof FunN){ - p.TA1 = p.TA1.clone(); - } - if(p.TA2 instanceof FunN){ - p.TA2 = p.TA2.clone(); - } - } - - //Erst die Unifizierung erstellen: - Menge constraintsClone = (Menge)constraints.clone(); - //IDEE: Man bildet Zusammenhangskomponenten von Paaren, die gemeinsame Variablen haben // und unifizert nur die Zusammenhangskomponenten in Schritten 1 - 5 - + /* //Schritt 1: Alle Variablen in den Paaren von Elementen einsammeln - Menge> constraintsclonevars = constraintsClone.stream().map(p -> {Menge TPHs = new Menge<>(); + Menge> constraintsclonevars = constraints.stream().map(p -> {Menge TPHs = new Menge<>(); TPHs.addAll(p.TA1.getInvolvedTypePlaceholder()); TPHs.addAll(p.TA2.getInvolvedTypePlaceholder()); return TPHs;} @@ -362,7 +355,8 @@ public class SourceFile return new Menge<>(); //kein unifiziertes Ergebnis, damit wird das Geseamtergebnis [] return cardprodret; }); - + */ + Set> unifyResult = new Unify().unify(constraints, finiteClosure); //Dann den Ergebnissen anfügen typinferenzLog.debug("\nErgebnis der Unifizierung:\n"+unifyResult, Section.TYPEINFERENCE); result.addAll(unifyResult); diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 5e9d1876..9a53305b 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -11,11 +11,18 @@ import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.WildcardType; +import de.dhbwstuttgart.typeinference.ConstraintsSet; +import de.dhbwstuttgart.typeinference.EinzelElement; import de.dhbwstuttgart.typeinference.KomplexeMenge; import de.dhbwstuttgart.typeinference.Menge; +import de.dhbwstuttgart.typeinference.OderConstraint; import de.dhbwstuttgart.typeinference.OderMenge; import de.dhbwstuttgart.typeinference.Pair; +import de.dhbwstuttgart.typeinference.UndConstraint; import de.dhbwstuttgart.typeinference.UndMenge; +import de.dhbwstuttgart.typeinference.UnifyConstraintsSet; +import de.dhbwstuttgart.typeinference.UnifyOderConstraint; +import de.dhbwstuttgart.typeinference.UnifyUndConstraint; import de.dhbwstuttgart.typeinference.assumptions.ClassAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; @@ -85,11 +92,34 @@ public class UnifyTypeFactory { return new SimpleType(t.get_Name()); } - public static UndMenge convert(UndMenge constraints) { - return null; + public static UnifyConstraintsSet convert(ConstraintsSet constraints) { + UnifyConstraintsSet ret = new UnifyConstraintsSet(); + for(OderConstraint oC : constraints.getOderConstraints()){ + ret.add(UnifyTypeFactory.convert(oC)); + } + return ret; + } + + private static UnifyOderConstraint convert(OderConstraint set) { + UnifyOderConstraint ret = new UnifyOderConstraint(); + for(UndConstraint oC : set.getUndConstraints()){ + ret.addConstraint(UnifyTypeFactory.convert(oC)); + } + return ret; } - public static OderMenge convert(OderMenge constraints) { - return null; + private static UnifyUndConstraint convert(UndConstraint set) { + UnifyUndConstraint ret = new UnifyUndConstraint(); + for(EinzelElement oC : set.getPairs()){ + ret.add(UnifyTypeFactory.convert(oC)); + } + return ret; + } + + private static MPair convert(EinzelElement p) { + if(!p.getItem().OperatorSmaller())throw new NotImplementedException(); + MPair ret = smaller(UnifyTypeFactory.convert(p.getItem().TA1) + , UnifyTypeFactory.convert(p.getItem().TA2)); + return ret; } } diff --git a/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java b/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java index 84475cbf..5728f1dc 100755 --- a/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java +++ b/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java @@ -90,6 +90,10 @@ public class ConstraintsSet extends UndMenge implements Iterable> getSet() { + return this.getOderConstraints(); + } + + public Menge getOderConstraints() { return this.constraintsSet; } } diff --git a/src/de/dhbwstuttgart/typeinference/EinzelElement.java b/src/de/dhbwstuttgart/typeinference/EinzelElement.java index 58f4970d..17f3b302 100644 --- a/src/de/dhbwstuttgart/typeinference/EinzelElement.java +++ b/src/de/dhbwstuttgart/typeinference/EinzelElement.java @@ -30,4 +30,8 @@ public class EinzelElement implements KomplexeMenge{ return item.toString(); } + public A getItem(){ + return item; + } + } \ No newline at end of file diff --git a/src/de/dhbwstuttgart/typeinference/UndConstraint.java b/src/de/dhbwstuttgart/typeinference/UndConstraint.java index a30e4127..741667f3 100755 --- a/src/de/dhbwstuttgart/typeinference/UndConstraint.java +++ b/src/de/dhbwstuttgart/typeinference/UndConstraint.java @@ -1,6 +1,7 @@ package de.dhbwstuttgart.typeinference; import java.util.Collection; +import java.util.Set; import java.util.Vector; import de.dhbwstuttgart.syntaxtree.type.Type; @@ -41,6 +42,9 @@ public class UndConstraint extends UndMenge { return ret; } + public Set> getPairs(){ + return set; + } /* public UndConstraint(ConstraintType p1, ConstraintType p2) { diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/Unifier.java index acc14281..b348b28c 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unifier.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unifier.java @@ -2,10 +2,10 @@ package de.dhbwstuttgart.typeinference.unify; import java.util.Set; -import de.dhbwstuttgart.typeinference.Pair; +import de.dhbwstuttgart.typeinference.unify.model.MPair; public interface Unifier { - public Set> apply (Set E); + public Set> apply (Set E); } From 43a8c9e647aca543fde404c8f2cff5448351034e Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Tue, 29 Mar 2016 13:23:15 +0200 Subject: [PATCH 23/57] Umstellung auf MPair beginnen --- .../typeinference/UnifyConstraintsSet.java | 96 +++++++++++++++ .../typeinference/UnifyOderConstraint.java | 112 ++++++++++++++++++ .../typeinference/UnifySingleConstraint.java | 50 ++++++++ .../typeinference/UnifyUndConstraint.java | 44 +++++++ 4 files changed, 302 insertions(+) create mode 100644 src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java create mode 100644 src/de/dhbwstuttgart/typeinference/UnifyOderConstraint.java create mode 100644 src/de/dhbwstuttgart/typeinference/UnifySingleConstraint.java create mode 100644 src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java diff --git a/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java b/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java new file mode 100644 index 00000000..16aa7b8d --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java @@ -0,0 +1,96 @@ +package de.dhbwstuttgart.typeinference; + +import java.util.Iterator; +import java.util.Set; +import java.util.Vector; +import de.dhbwstuttgart.logger.Logger; +import de.dhbwstuttgart.logger.*; +import de.dhbwstuttgart.typeinference.unify.Unifier; +import de.dhbwstuttgart.typeinference.unify.model.MPair; + +public class UnifyConstraintsSet extends UndMenge implements Iterable{ + private static final Logger log = Logger.getLogger(UnifyConstraintsSet.class.getName()); + private Menge constraintsSet; + + public UnifyConstraintsSet(){ + constraintsSet = new Menge(); + } + + public void add(UnifyConstraintsSet CSet){ + for(UnifyOderConstraint element : CSet) + add(element); + } + public void add(UnifyOderConstraint constraint){ + constraintsSet.add(constraint); + } + + @Override + public String toString(){ + String ret =""; + for(UnifyOderConstraint constraint : this){ + ret += constraint.toString()+"\n"; + } + return ret; + } + + public Iterator iterator() { + return constraintsSet.iterator(); + } + + public void filterWrongConstraints(Unifier unify) { + /* + * Das ConstraintsSet enthält nur OderConstraints, welche UND-Verknüpft sind. + * Hier werden Constraints in den OderConstraints kontrolliert: + */ + for(UnifyOderConstraint constraint : this){ + constraint.filterWrongConstraints(unify); + } + } + + /** + * Nimmt alle UndConstraints und filtert mithilfe dieser die falschen Constraints aus den OderConstraints + * @param unifier + */ + public void unifyUndConstraints(Unifier unifier) { + Vector uCons = this.filterUndConstraints(); + Vector alleUndConstraints = new Vector<>(); + for(UnifyUndConstraint undConstraint : uCons){ + alleUndConstraints.addAll(undConstraint.getConstraintPairs()); + } + this.filterWrongConstraints( + (pairs)->{ + Set undConstraintsUndPairs = new Menge<>(); + undConstraintsUndPairs.addAll(pairs); + undConstraintsUndPairs.addAll(alleUndConstraints); + log.debug("Versuche Pairs auszusondern:\n"+pairs, Section.TYPEINFERENCE); + log.debug("Unifiziere:\n"+undConstraintsUndPairs, Section.TYPEINFERENCE); + Set> unifyResult = unifier.apply(undConstraintsUndPairs); + return unifyResult; + }); + } + + /** + * Aus dem ConstraintsSet [ u1, u2, ... (OderConstraint), ... uN ] werden alle + * UndConstraints, welche sich nicht innerhalb eines OderConstraints befinden, herausgefiltert + * @return [u1, ... , uN] + */ + private Vector filterUndConstraints() { + Vector ret = new Vector<>(); + for(UnifyOderConstraint con : constraintsSet){ + UnifyUndConstraint filtered = con.filterUndConstraints(); + if(filtered != null)ret.add(filtered); + } + return ret; + } + + public void add(UnifyUndConstraint singleConstraint) { + UnifyOderConstraint toAdd = new UnifyOderConstraint(); + toAdd.addConstraint(singleConstraint); + constraintsSet.add(toAdd); + } + + @Override + public Menge> getSet() { + return this.constraintsSet; + } +} diff --git a/src/de/dhbwstuttgart/typeinference/UnifyOderConstraint.java b/src/de/dhbwstuttgart/typeinference/UnifyOderConstraint.java new file mode 100644 index 00000000..2d3c9375 --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/UnifyOderConstraint.java @@ -0,0 +1,112 @@ +package de.dhbwstuttgart.typeinference; + +import java.util.Set; +import java.util.Vector; + +import de.dhbwstuttgart.logger.Logger; +import de.dhbwstuttgart.logger.Section; +import de.dhbwstuttgart.syntaxtree.type.RefType; +import de.dhbwstuttgart.syntaxtree.type.Type; +import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; +import de.dhbwstuttgart.typeinference.unify.Unifier; +import de.dhbwstuttgart.typeinference.unify.model.MPair; + +public class UnifyOderConstraint extends OderMenge{ + private Set oderConstraintPairs; + + private final static Logger logger = Logger.getLogger(UnifyOderConstraint.class.getName()); + + /** + * Erstellt ein neues Oder Constraint und f�gt bereits ein Constraint hinzu. + * @param p1 + * @param p2 + + public OderConstraint(Pair p1, Pair p2){ + if(p1 == null || p2 == null)throw new NullPointerException(); + Pair constraintPair = new Pair(p1,p2); + oderConstraintPairs = new Menge(); + this.addConstraint(constraintPair); + } + */ + + public UnifyOderConstraint(){ + oderConstraintPairs = new Menge(); + } + + + /** + * Liefert alle in diesem OderConstraint enthaltene Constraints. Dabei gehen die Verkn�pfungen (Oder/Und) verloren. + * @return + */ + public Menge getConstraintPairs(){ + Menge ret = new Menge(); + for(UnifyUndConstraint oC : this.oderConstraintPairs){ + ret.addAll(oC.getConstraintPairs()); + } + return ret; + } + + /** + * Falls die Type des toAdd-Pairs nicht vom Typ RefType bzw. TypePlaceholder sind, so werden sie in einen RefType umgewandelt. + * @param toAdd + */ + public void addConstraint(MPair toAdd){ + oderConstraintPairs.add(new UnifySingleConstraint(toAdd)); + } + + @Override + public String toString(){ + String ret = "["; + for(UnifyUndConstraint p : this.getUndConstraints()){ + ret += p.toString()+ "| "; + } + return ret+"]"; + } + + public Set getUndConstraints() { + return this.oderConstraintPairs; + /* + Vector ret = new Vector(); + for(Pair p : this.getConstraintPairs()){ + ret.add(new UndConstraint(p.TA1,p.TA2)); + } + return ret; + */ + } + + public void addConstraint(UnifyUndConstraint constraint) { + oderConstraintPairs.add(constraint); + } + + /** + * Filtert die Constraints in diesem ODER-Verknüpften Constraint aus, + * welche keinen Sinn ergeben, also beim unifizieren scheitern. + * @param unifier - Wird für die Unifizierung benutzt + */ + void filterWrongConstraints(Unifier unifier) { + Set filteredConstraints = new Menge<>(); + for(UnifyUndConstraint cons : this.getUndConstraints()){ + Set> unifierResult = unifier.apply(cons.getConstraintPairs()); + if(!unifierResult.isEmpty()){ + filteredConstraints.add(cons); + }else{ + logger.debug("Ausgesondertes Constraint: "+cons, Section.TYPEINFERENCE); + } + } + this.oderConstraintPairs = filteredConstraints; + } + + UnifyUndConstraint filterUndConstraints() { + if(this.oderConstraintPairs.size()==1){ + return this.oderConstraintPairs.iterator().next(); + } + return null; + } + + @Override + public Set> getSet() { + return this.oderConstraintPairs; + } + + +} diff --git a/src/de/dhbwstuttgart/typeinference/UnifySingleConstraint.java b/src/de/dhbwstuttgart/typeinference/UnifySingleConstraint.java new file mode 100644 index 00000000..66cc2bbc --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/UnifySingleConstraint.java @@ -0,0 +1,50 @@ +package de.dhbwstuttgart.typeinference; + +import java.util.Vector; + +import de.dhbwstuttgart.syntaxtree.type.GenericTypeVar; +import de.dhbwstuttgart.syntaxtree.type.RefType; +import de.dhbwstuttgart.syntaxtree.type.Type; +import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; +import de.dhbwstuttgart.typeinference.exceptions.DebugException; +import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; +import de.dhbwstuttgart.typeinference.unify.model.MPair; + + +public class UnifySingleConstraint extends UnifyUndConstraint{ + + private MPair constraintPair; //entspricht θ condition θ' + + @Override + public Menge> getSet() { + Menge> ret = new Menge<>(); + ret.add(new EinzelElement<>(constraintPair)); + return ret; + } + + public UnifySingleConstraint(MPair toAdd) { + this.addConstraint(toAdd); + } + + public MPair getPair(){ + return constraintPair; + } + + @Override //Methode überschreiben, damit immer nur ein Vector mit nur einem Element zurückgeliefert wird. + public Menge getConstraintPairs(){ + Menge ret = new Menge<>(); + ret.add(constraintPair); + return ret; + } + + public void addConstraint(MPair toAdd){ + if(constraintPair != null)throw new DebugException("Ein Constraint darf nur aus einem ConstraintPair bestehen. Das hinzufügen von "+ toAdd + " ist nicht möglich."); + + constraintPair = toAdd; + } + + @Override + public String toString(){ + return constraintPair.toString(); + } +} diff --git a/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java b/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java new file mode 100644 index 00000000..b20cd6e6 --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java @@ -0,0 +1,44 @@ +package de.dhbwstuttgart.typeinference; + +import java.util.Collection; +import java.util.Set; +import java.util.Vector; + +import de.dhbwstuttgart.syntaxtree.type.Type; +import de.dhbwstuttgart.typeinference.exceptions.DebugException; +import de.dhbwstuttgart.typeinference.unify.Unifier; +import de.dhbwstuttgart.typeinference.unify.model.MPair; + +/** + * Stellt ein Constraint dar, welches aus mehreren Constraint-Paaren besteht. Diese gelten alle stets gleichzeitig / sind per "Und" miteinander verknüpft. + * @author janulrich + * + */ +public class UnifyUndConstraint extends UndMenge { + + Menge> set = new Menge<>(); + + @Override + public Menge> getSet() { + return set; + } + + public Set getConstraintPairs() { + Set> ret = this.cartesianProduct(); + if(ret.size() != 1){ + //UndConstraints enthalten nur SingleConstraints, wodurch das Karthesische Produkt nur aus einem Element bestehen kann. + throw new DebugException("Fehler in ConstraintPairs-Bildung"); + } + return ret.iterator().next(); + } + + @Override + public String toString() { + String ret = this.getConstraintPairs().toString(); + return ret; + } + + public void add(MPair pair){ + set.add(new EinzelElement<>(pair)); + } +} From 23142adc70ccf9bf9ed502750acccd33a475f055 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Tue, 29 Mar 2016 17:52:38 +0200 Subject: [PATCH 24/57] reduce rules --- .../typeinference/unifynew/RuleSet.java | 140 ++++++++++-------- 1 file changed, 81 insertions(+), 59 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java index 672c104d..aa966e5b 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java @@ -11,6 +11,7 @@ import java.util.Set; import java.util.stream.Collectors; import junit.framework.Assert; +import de.dhbwstuttgart.typeinference.unify.FC_TTO; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; @@ -86,8 +87,13 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); Type x = pair.getLhsType(); + Type sTypeX; - if(!(x instanceof SimpleType) && !(x instanceof ExtendsType)) + if(x instanceof SimpleType) + sTypeX = x; + else if(x instanceof ExtendsType) + sTypeX = ((ExtendsType) x).getExtendedType(); + else return Optional.empty(); Type extY = pair.getRhsType(); @@ -98,17 +104,31 @@ public class RuleSet implements IRuleSet{ if(x.getTypeParams().empty() || extY.getTypeParams().size() != x.getTypeParams().size()) return Optional.empty(); - int[] pi = pi(x, extY); + Type xFromFc = finiteClosure.getLeftHandedType(sTypeX).orElse(null); + + if(xFromFc == null || !xFromFc.getTypeParams().arePlaceholders()) + return Optional.empty(); + + if(x instanceof ExtendsType) + xFromFc = new ExtendsType(xFromFc); + + Type extYFromFc = finiteClosure.grArg(xFromFc).stream().filter(t -> t.getName().equals(extY.getName())).filter(t -> t.getTypeParams().arePlaceholders()).findAny().orElse(null); + + if(extYFromFc == null || extYFromFc.getTypeParams() != xFromFc.getTypeParams()) + return Optional.empty(); + + TypeParams extYParams = extY.getTypeParams(); + TypeParams xParams = x.getTypeParams(); + + int[] pi = pi(xParams, extYParams); if(pi.length == 0) return Optional.empty(); - TypeParams rhsTypeParams = extY.getTypeParams(); - TypeParams lhsTypeParams = x.getTypeParams(); Set result = new HashSet<>(); - for(int rhsIdx = 0; rhsIdx < rhsTypeParams.size(); rhsIdx++) - result.add(new MPair(lhsTypeParams.get(pi[rhsIdx]), rhsTypeParams.get(rhsIdx), PairOperator.SMALLERDOTWC)); + for(int rhsIdx = 0; rhsIdx < extYParams.size(); rhsIdx++) + result.add(new MPair(xParams.get(pi[rhsIdx]), extYParams.get(rhsIdx), PairOperator.SMALLERDOTWC)); return Optional.of(result); } @@ -118,30 +138,48 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); - Type lhsType = pair.getLhsType(); + Type x = pair.getLhsType(); + Type sTypeX; - if(!(lhsType instanceof SimpleType) && !(lhsType instanceof SuperType)) + if(x instanceof SimpleType) + sTypeX = x; + else if(x instanceof SuperType) + sTypeX = ((SuperType) x).getSuperedType(); + else return Optional.empty(); - Type rhsType = pair.getRhsType(); + Type supY = pair.getRhsType(); - if(!(rhsType instanceof SuperType)) + if(!(supY instanceof SuperType)) return Optional.empty(); - if(lhsType.getTypeParams().empty() || rhsType.getTypeParams().size() != lhsType.getTypeParams().size()) + if(x.getTypeParams().empty() || supY.getTypeParams().size() != x.getTypeParams().size()) return Optional.empty(); - int[] pi = pi(lhsType, rhsType); + Type xFromFc = finiteClosure.getLeftHandedType(sTypeX).orElse(null); + + if(xFromFc == null || !xFromFc.getTypeParams().arePlaceholders()) + return Optional.empty(); + + if(x instanceof SuperType) + xFromFc = new SuperType(xFromFc); + + Type supYFromFc = finiteClosure.grArg(xFromFc).stream().filter(t -> t.getName().equals(supY.getName())).filter(t -> t.getTypeParams().arePlaceholders()).findAny().orElse(null); + + if(supYFromFc == null || supYFromFc.getTypeParams() != xFromFc.getTypeParams()) + return Optional.empty(); + + TypeParams supYParams = supY.getTypeParams(); + TypeParams xParams = x.getTypeParams(); + Set result = new HashSet<>(); + + int[] pi = pi(xParams, supYParams); if(pi.length == 0) return Optional.empty(); - TypeParams rhsTypeParams = rhsType.getTypeParams(); - TypeParams lhsTypeParams = lhsType.getTypeParams(); - Set result = new HashSet<>(); - - for(int rhsIdx = 0; rhsIdx < rhsTypeParams.size(); rhsIdx++) - result.add(new MPair(lhsTypeParams.get(pi[rhsIdx]), rhsTypeParams.get(rhsIdx), PairOperator.SMALLERDOTWC)); + for(int rhsIdx = 0; rhsIdx < supYParams.size(); rhsIdx++) + result.add(new MPair(supYParams.get(rhsIdx), xParams.get(pi[rhsIdx]), PairOperator.SMALLERDOTWC)); return Optional.of(result); } @@ -166,7 +204,7 @@ public class RuleSet implements IRuleSet{ if(rhsType.getTypeParams().size() != lhsType.getTypeParams().size()) return Optional.empty(); - // TODO Permutation? + // Keine Permutation wie im Paper nötig Set result = new HashSet<>(); TypeParams lhsTypeParams = lhsType.getTypeParams(); TypeParams rhsTypeParams = rhsType.getTypeParams(); @@ -182,27 +220,37 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); - Type lhsType = pair.getLhsType(); - if(!(lhsType instanceof SimpleType)) + Type c = pair.getLhsType(); + if(!(c instanceof SimpleType)) return Optional.empty(); - Type rhsType = pair.getRhsType(); - if(!(rhsType instanceof SimpleType)) + Type d = pair.getRhsType(); + if(!(d instanceof SimpleType)) return Optional.empty(); - SimpleType lhsSType = (SimpleType) lhsType; - SimpleType rhsSType = (SimpleType) rhsType; + SimpleType lhsSType = (SimpleType) c; + SimpleType rhsSType = (SimpleType) d; if(lhsSType.getTypeParams().empty() || lhsSType.getTypeParams().size() != rhsSType.getTypeParams().size()) return Optional.empty(); - int[] pi = pi(lhsSType, rhsSType); + Type cFromFc = finiteClosure.getLeftHandedType(c).orElse(null); + + if(cFromFc == null || !cFromFc.getTypeParams().arePlaceholders()) + return Optional.empty(); + + Type dFromFc = finiteClosure.getAncestors(cFromFc).stream().filter(x -> x.getName().equals(d.getName())).findAny().orElse(null); + + if(dFromFc == null || !dFromFc.getTypeParams().arePlaceholders() || dFromFc.getTypeParams().size() != cFromFc.getTypeParams().size()) + return Optional.empty(); + + int[] pi = pi(cFromFc.getTypeParams(), dFromFc.getTypeParams()); if(pi.length == 0) return Optional.empty(); - TypeParams rhsTypeParams = rhsType.getTypeParams(); - TypeParams lhsTypeParams = lhsType.getTypeParams(); + TypeParams rhsTypeParams = d.getTypeParams(); + TypeParams lhsTypeParams = c.getTypeParams(); Set result = new HashSet<>(); for(int rhsIdx = 0; rhsIdx < rhsTypeParams.size(); rhsIdx++) @@ -459,34 +507,9 @@ public class RuleSet implements IRuleSet{ * @param D The other type * @return An array containing the values of pi for every type argument of C or an empty array if the search failed. */ - private int[] pi(Type C, Type D) { - String simpleTypeDName = D.getName(); - if(D instanceof ExtendsType) - simpleTypeDName = ((ExtendsType) D).getExtendedType().getName(); - else if(D instanceof SuperType) - simpleTypeDName = ((SuperType) D).getSuperedType().getName(); - - String simpleTypeCName = C.getName(); - if(C instanceof ExtendsType) - simpleTypeCName = ((ExtendsType) C).getExtendedType().getName(); - if(C instanceof SuperType) - simpleTypeCName = ((SuperType) C).getSuperedType().getName(); - - Optional typesFromFc = Optional.empty(); //TODO reduce regeln - //finiteClosure.findCandD(simpleTypeCName, simpleTypeDName); - - if(typesFromFc == null) - return new int[0]; - - Type cFromFc = typesFromFc.get()[0]; - Type dFromFc = typesFromFc.get()[1]; - - Assert.assertEquals(cFromFc.getTypeParams().size(), dFromFc.getTypeParams().size()); - Assert.assertTrue(dFromFc.getTypeParams().size() > 0); - - TypeParams cArgs = cFromFc.getTypeParams(); - TypeParams dArgs = dFromFc.getTypeParams(); - + private int[] pi(TypeParams cArgs, TypeParams dArgs) { + Assert.assertEquals(cArgs.size(), dArgs.size()); + int[] permutation = new int[dArgs.size()]; boolean succ = true; @@ -500,9 +523,8 @@ public class RuleSet implements IRuleSet{ break; } } - - if(succ) return permutation; - return new int[0]; + + return succ ? permutation : new int[0]; } @Override From 50304109782e46e8d7826096dd6f1a68c7d9c9e8 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Tue, 29 Mar 2016 19:07:54 +0200 Subject: [PATCH 25/57] finitclosure tests angepasst --- test/unify/FiniteClosureTest.java | 37 ++++++++++++++++--------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index 7322e857..6512243c 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -98,10 +98,8 @@ public class FiniteClosureTest { /* * Test Case 4: - * TODO ist das ergebnis korrekt oder müssen die ? ext Ts raus weil der allgemeienste Typ T ausreicht? * smaller(Set) = - * { HashSet, Set, TreeSet, LinkedHashSet, - * HashSet, Set, TreeSet, LinkedHashSet } + * { HashSet, Set, TreeSet, LinkedHashSet } */ Type t = tf.getPlaceholderType("T"); @@ -109,14 +107,9 @@ public class FiniteClosureTest { Type hashSetT = tf.getSimpleType("HashSet", t); Type treeSetT = tf.getSimpleType("TreeSet", t); Type linkedHashSetT = tf.getSimpleType("LinkedHashSet", t); - Type hashSetExtT = tf.getSimpleType("HashSet", t); - Type treeSetExtT = tf.getSimpleType("TreeSet", t); - Type linkedHashSetExtT = tf.getSimpleType("LinkedHashSet", t); - Type setExtT = tf.getSimpleType("Set", t); expectedResult = new HashSet<>(Arrays.stream(new Type[] { - setT, hashSetT, treeSetT, linkedHashSetT, - setExtT, hashSetExtT, treeSetExtT, linkedHashSetExtT + setT, hashSetT, treeSetT, linkedHashSetT }).collect(Collectors.toSet())); Assert.assertEquals(expectedResult, fc.smaller(setT)); @@ -153,19 +146,28 @@ public class FiniteClosureTest { /* * Test Case 6: - * - * smaller(Set, Set, TreeSet, LinkedHashSet, - * HashSet, Set, TreeSet, LinkedHashSet } + * TODO probleme wenn Set weil T auch in der Klassendeklaration class Set verwendet wird. + * smaller(Set, Set, TreeSet, LinkedHashSet, + * HashSet, Set, TreeSet, LinkedHashSet } * */ - + Type t1 = tf.getPlaceholderType("T1"); + Type extT1 = tf.getExtendsType(t1); + Type setExtT1 = tf.getSimpleType("Set", extT1); + Type hashSetExtT1 = tf.getSimpleType("HashSet", extT1); + Type treeSetExtT1 = tf.getSimpleType("TreeSet", extT1); + Type linkedHashSetExtT1 = tf.getSimpleType("LinkedHashSet", extT1); + Type setT1 = tf.getSimpleType("Set", t1); + Type hashSetT1 = tf.getSimpleType("HashSet", t1); + Type treeSetT1 = tf.getSimpleType("TreeSet", t1); + Type linkedHashSetT1 = tf.getSimpleType("LinkedHashSet", t1); expectedResult = new HashSet<>(Arrays.stream(new Type[] { - setT, hashSetT, treeSetT, linkedHashSetT, - setExtT, hashSetExtT, treeSetExtT, linkedHashSetExtT + setT1, hashSetT1, treeSetT1, linkedHashSetT1, + setExtT1, hashSetExtT1, treeSetExtT1, linkedHashSetExtT1 }).collect(Collectors.toSet())); - Assert.assertEquals(expectedResult, fc.smaller(setExtT)); + Assert.assertEquals(expectedResult, fc.smaller(setExtT1)); /* * Test Case 7: @@ -656,7 +658,6 @@ public class FiniteClosureTest { @Test public void testGetGenericType() { - // TODO } From 304a5693a6b5606459a6a985042672c82d8ff05e Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Wed, 30 Mar 2016 16:25:26 +0200 Subject: [PATCH 26/57] wc regeln angepasst, triviale tests fertig --- .../unify/interfaces/IFiniteClosure.java | 2 +- .../unify/model/FiniteClosure.java | 17 +- .../typeinference/unifynew/RuleSet.java | 8 +- .../typeinference/unifynew/Unify.java | 10 +- test/unify/UnifyTest.java | 252 ++++++++++++++++-- 5 files changed, 253 insertions(+), 36 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java index d2c6f0f4..87693e4d 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java @@ -55,6 +55,6 @@ public interface IFiniteClosure { public Optional getLeftHandedType(Type t); public Set getAncestors(Type t); - + public Set getChildren(Type t); public Set getAllTypesByName(String typeName); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 9e1b8808..a36b93d2 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -94,7 +94,7 @@ public class FiniteClosure implements IFiniteClosure { if (strInheritanceGraph.containsKey(type.getName())) { HashSet candidates = new HashSet<>(); strInheritanceGraph.get(type.getName()).forEach(x -> candidates.add(x.getContent())); - + for(Type typePrime : result1) { for (Type theta2 : candidates) { Optional sigma2 = unify.unify(typePrime, theta2); @@ -135,7 +135,7 @@ public class FiniteClosure implements IFiniteClosure { return result3; } - + /** * Returns all types of the finite closure that are supertypes of the argument. * @return The set of supertypes of the argument. @@ -358,7 +358,18 @@ public class FiniteClosure implements IFiniteClosure { public Set getAncestors(Type t) { if(!inheritanceGraph.containsKey(t)) return new HashSet<>(); - return inheritanceGraph.get(t).getContentOfPredecessors(); + Set result = inheritanceGraph.get(t).getContentOfPredecessors(); + result.add(t); + return result; + } + + @Override + public Set getChildren(Type t) { + if(!inheritanceGraph.containsKey(t)) + return new HashSet<>(); + Set result = inheritanceGraph.get(t).getContentOfDescendants(); + result.add(t); + return result; } protected void permuteParams(ArrayList> candidates, int idx, Set result, Type[] current) { diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java index aa966e5b..fde25609 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java @@ -587,7 +587,7 @@ public class RuleSet implements IRuleSet{ Type lhsType = pair.getLhsType(); Type rhsType = pair.getRhsType(); - if((lhsType instanceof ExtendsType) || !(rhsType instanceof ExtendsType)) + if(!(lhsType instanceof SimpleType) || !(rhsType instanceof ExtendsType)) return Optional.empty(); return Optional.of(new MPair(lhsType, ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT)); @@ -613,10 +613,10 @@ public class RuleSet implements IRuleSet{ Type lhsType = pair.getLhsType(); Type rhsType = pair.getRhsType(); - if((lhsType instanceof SuperType) || !(rhsType instanceof SuperType)) + if(!(lhsType instanceof SimpleType) || !(rhsType instanceof SuperType)) return Optional.empty(); - return Optional.of(new MPair(((SuperType) rhsType).getSuperedType(), lhsType, PairOperator.SMALLERDOT)); + return Optional.of(new MPair(((SuperType) rhsType).getSuperedType(), lhsType, PairOperator.SMALLERDOTWC)); } @Override @@ -651,7 +651,7 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); Type rhsType = pair.getRhsType(); - if((rhsType instanceof SuperType) || (rhsType instanceof ExtendsType)) + if(!(rhsType instanceof SimpleType)) return Optional.empty(); Type lhsType = pair.getLhsType(); diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java index 6e6fe376..26a74729 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java @@ -138,9 +138,9 @@ public class Unify { } /* - * Step 7: Filter result for solved pairs + * Step 7: Filter empty sets; */ - return eqPrimePrimeSet; + return eqPrimePrimeSet.stream().filter(x -> !x.isEmpty()).collect(Collectors.toCollection(HashSet::new)); } @@ -300,7 +300,7 @@ public class Unify { for(Type c : cs) { // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + Set thetaQs = fc.getChildren(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); thetaQs.add(c); // reflexive Set thetaQPrimes = new HashSet<>(); @@ -347,7 +347,7 @@ public class Unify { for(Type c : cs) { // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + Set thetaQs = fc.getChildren(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); thetaQs.add(c); // reflexive Set thetaQPrimes = new HashSet<>(); @@ -422,7 +422,7 @@ public class Unify { for(Type c : cs) { // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + Set thetaQs = fc.getChildren(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); thetaQs.add(c); // reflexive Set thetaQPrimes = new HashSet<>(); diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index ae219dd2..2d2faad8 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -1,8 +1,11 @@ package unify; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashSet; import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; import org.junit.Test; @@ -13,39 +16,237 @@ import de.dhbwstuttgart.typeinference.unify.model.Type; import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unifynew.TypeFactory; import de.dhbwstuttgart.typeinference.unifynew.Unify; +import junit.framework.Assert; public class UnifyTest extends Unify { + /** + * Testing the unification for cases with (n)one pair and without generics. + */ @Test - public void unifyTest() { + public void unifyTestTrivial() { + /* + * INIT + */ + TypeFactory tf = new TypeFactory(); FiniteClosureBuilder fcb = new FiniteClosureBuilder(); - Set eq = new HashSet(); - - //fcb.add(tf.getSimpleType("Number"), tf.getSimpleType("Object")); - fcb.add(tf.getSimpleType("Integer"), tf.getSimpleType("Number")); - fcb.add(tf.getSimpleType("Double"), tf.getSimpleType("Number")); - fcb.add(tf.getSimpleType("MyList"), tf.getSimpleType("List", tf.getSimpleType("Integer"))); - //fcb.add(tf.getSimpleType("List", "T")); + + Type number = tf.getSimpleType("Number"); + Type object = tf.getSimpleType("Object"); + Type integer = tf.getSimpleType("Integer"); + Type doubl = tf.getSimpleType("Double"); + fcb.add(number, object); + fcb.add(integer, number); + fcb.add(doubl, number); + IFiniteClosure fc = fcb.getCollectionExample(); - // Vector <. Vector - // Vector - // A <. Integer - // Number <. A - // Double <. B - // B <. Object - eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Integer")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); - eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Number")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Integer")), tf.getSimpleType("Vector", "C"), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getPlaceholderType("A"), tf.getSimpleType("List", "A"), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getSimpleType("Number"), tf.getPlaceholderType("A"), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getPlaceholderType("A"), tf.getPlaceholderType("C"), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getSimpleType("Double"), tf.getPlaceholderType("B"), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getPlaceholderType("B"), tf.getSimpleType("Object"), PairOperator.EQUALSDOT)); + /* + * Test 1: + * + * unify({ }) = { } + */ - System.out.println(this.unify(eq, fc)); + Set eq = new HashSet(); + Set> expected = new HashSet<>(); + Set> actual = unify(eq, fc); + Assert.assertEquals(actual, expected); + + /* + * Test 2: + * + * (a <. Number) + */ + + Type tphA = tf.getPlaceholderType("a"); + eq = new HashSet<>(); + eq.add(new MPair(tphA, number, PairOperator.SMALLERDOT)); + + expected = new HashSet<>(); + addAsSet(expected, new MPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, integer, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, doubl, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + /* + * Test 3: + * + * (Integer <. a) + */ + + eq = new HashSet<>(); + eq.add(new MPair(integer, tphA, PairOperator.SMALLERDOT)); + + expected = new HashSet<>(); + addAsSet(expected, new MPair(tphA, integer, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, object, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + + /* + * Test 4: + * + * (a <.? Number) + */ + + eq = new HashSet<>(); + eq.add(new MPair(tphA, number, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new MPair(tphA, number, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + /* + * Test 5: + * + * (a <.? ? super Integer) + */ + + Type supInteger = tf.getSuperType(integer); + Type supNumber = tf.getSuperType(number); + Type supObject = tf.getSuperType(object); + eq = new HashSet<>(); + eq.add(new MPair(tphA, supInteger, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new MPair(tphA, integer, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, object, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, supInteger, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, supNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, supObject, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + /* + * Test 6: + * + * (Number <.? a) + * + */ + + eq = new HashSet<>(); + Type extNumber = tf.getExtendsType(number); + Type extObject = tf.getExtendsType(object); + Type supDouble = tf.getSuperType(doubl); + eq.add(new MPair(number, tphA, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new MPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, extNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, extObject, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, supInteger, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, supDouble, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, supNumber, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + /* + * Test 7: + * + * (? extends Number <.? a) + */ + + eq = new HashSet<>(); + eq.add(new MPair(extNumber, tphA, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new MPair(tphA, extNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, extObject, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + + /* + * Test 8: + * + * (Integer <. Number) + */ + + eq = new HashSet<>(); + eq.add(new MPair(integer, number, PairOperator.SMALLERDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + /* + * Test 9: + * + * (Integer <.? Number) + */ + + eq = new HashSet<>(); + eq.add(new MPair(integer, number, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + /* + * Test 10: + * + * (a <. b) + */ + + Type tphB = tf.getPlaceholderType("b"); + eq = new HashSet<>(); + eq.add(new MPair(tphA, tphB, PairOperator.SMALLERDOT)); + + expected = new HashSet<>(); + addAsSet(expected, new MPair(tphA, tphB, PairOperator.SMALLERDOT)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + /* + * Test 11: + * + * (a <.? b) + */ + + eq = new HashSet<>(); + eq.add(new MPair(tphA, tphB, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new MPair(tphA, tphB, PairOperator.SMALLERDOTWC)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + } + + @Test + public void unifyTestSimple() { + + } + + @Test + public void unifyTestComplex() { } @@ -83,7 +284,12 @@ public class UnifyTest extends Unify { Set result = permuteParams(candidates); + System.out.println(result); } + + private void addAsSet(Set> addTo, MPair... mPairs) { + addTo.add(new HashSet<>(Arrays.stream(mPairs).collect(Collectors.toSet()))); + } } From d89d06797e17a7a95f007fe24e9b6133b3b13179 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Thu, 31 Mar 2016 22:09:46 +0200 Subject: [PATCH 27/57] isInSolvedForm(), Unit-Tests, removed PairOp.Equals --- .../typeinference/unify/model/MPair.java | 3 - .../typeinference/unifynew/Mapping.java | 23 +- .../unifynew/MartelliMontanariUnify.java | 2 +- .../typeinference/unifynew/RuleSet.java | 11 +- .../typeinference/unifynew/Unify.java | 30 +- test/unify/UnifyOldTest.java | 585 ++++++++++-------- test/unify/UnifyTest.java | 95 ++- 7 files changed, 443 insertions(+), 306 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/MPair.java b/src/de/dhbwstuttgart/typeinference/unify/model/MPair.java index 6b740c46..60a3ff0d 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/MPair.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/MPair.java @@ -6,7 +6,6 @@ public class MPair { SMALLER, SMALLERDOT, SMALLERDOTWC, - EQUALS, EQUALSDOT; @Override @@ -18,8 +17,6 @@ public class MPair { return "<."; case SMALLERDOTWC: return "<.?"; - case EQUALS: - return "="; default: return "=."; } diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Mapping.java b/src/de/dhbwstuttgart/typeinference/unifynew/Mapping.java index c8996dc8..9a80f75d 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Mapping.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/Mapping.java @@ -56,32 +56,27 @@ public class Mapping { return result.size() == pairs.size() ? Optional.of(result) : Optional.empty(); } - private de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator mapOp(de.dhbwstuttgart.typeinference.Pair.PairOperator op) { - /* - * TODO - * Warum hat der PairOp nur drei Werte? Wie wird SMALLERDOTWC etc im anderen Pair geregelt? - */ - + private de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator mapOp(de.dhbwstuttgart.typeinference.Pair.PairOperator op) { switch(op) { case Equal: - return de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator.EQUALS; + return de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator.EQUALSDOT; case Smaller: - return de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator.SMALLER; - case SmallerExtends: return de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator.SMALLERDOT; - default: - return de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator.EQUALS; + case SmallerExtends: + return de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator.SMALLERDOTWC; + default: + return de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator.EQUALSDOT; } } private de.dhbwstuttgart.typeinference.Pair.PairOperator unmapOp(de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator op) { switch(op) { - case EQUALS: - return de.dhbwstuttgart.typeinference.Pair.PairOperator.Equal; case SMALLER: return de.dhbwstuttgart.typeinference.Pair.PairOperator.Smaller; case SMALLERDOT: - return de.dhbwstuttgart.typeinference.Pair.PairOperator.SmallerExtends; + return de.dhbwstuttgart.typeinference.Pair.PairOperator.Smaller; + case SMALLERDOTWC: + return de.dhbwstuttgart.typeinference.Pair.PairOperator.SmallerExtends; default: return de.dhbwstuttgart.typeinference.Pair.PairOperator.Equal; } diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java b/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java index e3ae2322..f6bc2ca5 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java @@ -33,7 +33,7 @@ public class MartelliMontanariUnify implements IUnify { Type prev = iter.next(); while(iter.hasNext()) { Type next = iter.next(); - termsQ.add(new MPair(prev, next, PairOperator.EQUALS)); + termsQ.add(new MPair(prev, next, PairOperator.EQUALSDOT)); prev = next; } diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java index fde25609..d3f89104 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java @@ -542,12 +542,12 @@ public class RuleSet implements IRuleSet{ typeMap.put(t2, typeMap.get(t2)+1); } - ArrayList result = new ArrayList(pairs); - + Queue result1 = new LinkedList(pairs); + ArrayList result = new ArrayList(); boolean applied = false; - for(int i = 0; i < result.size(); i++) { - MPair pair = result.get(i); + while(!result1.isEmpty()) { + MPair pair = result1.poll(); PlaceholderType lhsType = null; Type rhsType; @@ -560,8 +560,11 @@ public class RuleSet implements IRuleSet{ && !rhsType.getTypeParams().occurs(lhsType)) { Unifier uni = new Unifier(lhsType, rhsType); result = result.stream().map(uni::apply).collect(Collectors.toCollection(ArrayList::new)); + result1 = result1.stream().map(uni::apply).collect(Collectors.toCollection(LinkedList::new)); applied = true; } + + result.add(pair); } return applied ? Optional.of(new HashSet<>(result)) : Optional.empty(); diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java index 26a74729..5d2040c3 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java @@ -12,9 +12,6 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; -import de.dhbwstuttgart.typeinference.Menge; -import de.dhbwstuttgart.typeinference.Pair; -import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; import de.dhbwstuttgart.typeinference.unify.interfaces.ISetOperations; @@ -68,7 +65,7 @@ public class Unify { } // Add the set of [a =. Theta | (a=. Theta) in Eq2'] - Set bufferSet = eq2s.stream() + Set bufferSet = eq2s.stream() .filter(x -> x.getPairOp() == PairOperator.EQUALSDOT && x.getLhsType() instanceof PlaceholderType) .collect(Collectors.toSet()); @@ -133,17 +130,31 @@ public class Unify { * b) Build the union over everything */ - for(Set eqss : changed) { + for(Set eqss : changed) eqPrimePrimeSet.addAll(this.unify(eqss, fc)); - } - + /* * Step 7: Filter empty sets; */ - return eqPrimePrimeSet.stream().filter(x -> !x.isEmpty()).collect(Collectors.toCollection(HashSet::new)); + return eqPrimePrimeSet.stream().filter(x -> isSolvedForm(x)).collect(Collectors.toCollection(HashSet::new)); } + protected boolean isSolvedForm(Set eqPrimePrime) { + for(MPair pair : eqPrimePrime) { + Type lhsType = pair.getLhsType(); + Type rhsType = pair.getRhsType(); + + if(!(lhsType instanceof PlaceholderType)) + return false; + + if(pair.getPairOp() != PairOperator.EQUALSDOT && !(rhsType instanceof PlaceholderType)) + return false; + } + + return true; + } + protected Set applyTypeUnificationRules(Set eq, IFiniteClosure fc) { /* @@ -288,7 +299,8 @@ public class Unify { result.get(7).add(unifyCase8(lhsType, (PlaceholderType) rhsType, fc)); } - return result.stream().filter(x -> x.size() > 0).collect(Collectors.toCollection(HashSet::new)); + return result.stream().map(x -> x.stream().filter(y -> y.size() > 0).collect(Collectors.toCollection(HashSet::new))) + .filter(x -> x.size() > 0).collect(Collectors.toCollection(HashSet::new)); } protected Set unifyCase1(PlaceholderType a, Type thetaPrime, IFiniteClosure fc) { diff --git a/test/unify/UnifyOldTest.java b/test/unify/UnifyOldTest.java index 85f5ffd5..b93ba610 100644 --- a/test/unify/UnifyOldTest.java +++ b/test/unify/UnifyOldTest.java @@ -7,7 +7,9 @@ import org.junit.Test; import de.dhbwstuttgart.syntaxtree.factory.UnifyPairMengenBuilder; import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory; import de.dhbwstuttgart.syntaxtree.factory.Unify_FC_TTO_Builder; +import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; import de.dhbwstuttgart.syntaxtree.type.RefType; +import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.typeinference.Menge; import de.dhbwstuttgart.typeinference.Pair; @@ -17,287 +19,322 @@ import de.dhbwstuttgart.typeinference.unify.Unify; public class UnifyOldTest { @Test - public void unifyTestSimpleTypes() { + public void unifyTest1() { // Init Factories and Builders UnifyTypeFactory typeFactory = new UnifyTypeFactory(); Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); - /* - * Test a <. Boolean - */ - - // Init Types - RefType boolT = typeFactory.GetSimpleType("java.lang.Boolean"); - TypePlaceholder aTph = typeFactory.GetTypePlaceholder("a"); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(aTph, boolT, PairOperator.Equal); - resultBuilder.addPair(aTph, typeFactory.GetExtendsType(boolT), - PairOperator.Equal); - Menge> expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(aTph, boolT); - Menge> actualResult = Unify.unify( - assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test b <. a, a <. Boolean - */ - - // Init Types - boolT = typeFactory.GetSimpleType("java.lang.Boolean"); - aTph = typeFactory.GetTypePlaceholder("a"); - TypePlaceholder bTph = typeFactory.GetTypePlaceholder("b"); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(aTph, boolT, PairOperator.Equal); - resultBuilder.addPair(aTph, typeFactory.GetExtendsType(boolT), - PairOperator.Equal); - resultBuilder.addPair(bTph, boolT, PairOperator.Equal); - resultBuilder.addPair(bTph, typeFactory.GetExtendsType(boolT), - PairOperator.Equal); - expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(bTph, aTph); - assumptionBuilder.addPair(aTph, boolT); - actualResult = Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - // NOTE: Elemente im actualResult sind nicht unique - // Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test b <. a, a <. b - */ - - aTph = typeFactory.GetTypePlaceholder("a"); - bTph = typeFactory.GetTypePlaceholder("b"); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(bTph, aTph); - resultBuilder.addPair(aTph, bTph); - - Menge buffer = resultBuilder.getPairMenge(); - expectedResult = new Menge>(); - expectedResult.add(buffer); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(bTph, aTph); - assumptionBuilder.addPair(aTph, bTph); - actualResult = Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test Integer <. a, a <. Boolean - */ - - RefType intT = typeFactory.GetSimpleType("java.lang.Integer"); - boolT = typeFactory.GetSimpleType("java.lang.Boolean"); - aTph = typeFactory.GetTypePlaceholder("a"); - bTph = typeFactory.GetTypePlaceholder("b"); - - // Expected Result - resultBuilder.clear(); - expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(intT, aTph); - assumptionBuilder.addPair(aTph, boolT); - actualResult = Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); + TypePlaceholder a = typeFactory.GetTypePlaceholder("a"); + ExtendsWildcardType extA = typeFactory.GetExtendsType(a); + TypePlaceholder b = typeFactory.GetTypePlaceholder("b"); + ExtendsWildcardType extB = typeFactory.GetExtendsType(b); + RefType integer = typeFactory.GetSimpleType("Integer"); + SuperWildcardType supInt = typeFactory.GetSuperType(integer); + RefType listsupint = typeFactory.GetSimpleType("List", supInt); + RefType number = typeFactory.GetSimpleType("Number"); + RefType object = typeFactory.GetSimpleType("XObjectX"); + ExtendsWildcardType extNum = typeFactory.GetExtendsType(number); + RefType intlist = typeFactory.GetSimpleType("List", integer); + RefType alist = typeFactory.GetSimpleType("List", a); + RefType extBlist = typeFactory.GetSimpleType("List", extB); + RefType blist = typeFactory.GetSimpleType("List", b); + RefType extNumlist = typeFactory.GetSimpleType("List", extNum); + fcBuilder.AddInheritance(number, object); + fcBuilder.AddInheritance(integer, number); + + + assumptionBuilder.addPair(alist, extBlist, PairOperator.Smaller); + assumptionBuilder.addPair(blist, extNumlist, PairOperator.Smaller); + + System.out.println(Unify.unify(assumptionBuilder.getPairMenge(), + fcBuilder.Get_FC_TTO())); } - - @Test - public void unifyTestGenerics() { - - // Init Factories and Builders - UnifyTypeFactory typeFactory = new UnifyTypeFactory(); - Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); - UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); - UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); - - /* - * Test a <. MyClass - */ - - TypePlaceholder aTph = typeFactory.GetTypePlaceholder("a"); - RefType myType = typeFactory.GetSimpleType("MyClass", - typeFactory.GetTypePlaceholder("T"), - typeFactory.GetTypePlaceholder("F")); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(aTph, myType, PairOperator.Equal); - resultBuilder.addPair(aTph, typeFactory.GetExtendsType(myType)); - Menge> expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(aTph, myType); - Menge> actualResult = Unify.unify( - assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test List> <. List - */ - - TypePlaceholder tTph = typeFactory.GetTypePlaceholder("T"); - RefType list = typeFactory.GetSimpleType("List", tTph); - RefType listlist = typeFactory.GetSimpleType("List", list); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(typeFactory.GetExtendsType(list), tTph, - PairOperator.Equal); - expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(listlist, list); - actualResult = Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO()); - - System.out.println(expectedResult); - System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test List <. List> - */ - } - - @Test - public void unifyTestInheritance() { - - // Init Factories and Builders - UnifyTypeFactory typeFactory = new UnifyTypeFactory(); - Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); - UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); - UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); - - // Init Types - RefType tBool = typeFactory.GetSimpleType("java.lang.Boolean"); - RefType tString = typeFactory.GetSimpleType("java.lang.String"); - RefType tInt = typeFactory.GetSimpleType("java.lang.Integer"); - TypePlaceholder tphA = typeFactory.GetTypePlaceholder("a"); - - // Build inheritance hierachy - // Bool <. String <. Int - fcBuilder.AddInheritance(tBool, tString); - fcBuilder.AddInheritance(tString, tInt); - - // Build Assumptions - assumptionBuilder.addPair(tphA, tString); - - // Build expected result - resultBuilder.addPair(tphA, tBool, PairOperator.Equal); - resultBuilder.addPair(tphA, typeFactory.GetExtendsType(tBool), - PairOperator.Equal); - resultBuilder.addPair(tphA, tString, PairOperator.Equal); - resultBuilder.addPair(tphA, typeFactory.GetExtendsType(tString), - PairOperator.Equal); - - // Assert - Menge> actualResult = Unify.unify( - assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); - - // System.out.println(actualResult); - // System.out.println("-------------------"); - // System.out.println(resultBuilder.getNestedPairMenge()); - - Assert.assertTrue(mengeEquals(resultBuilder.getNestedPairMenge(), - actualResult)); - } - - @Test - public void unifyTestWildcards() { - - } - - private static boolean mengeEquals(Menge> m1, - Menge> m2) { - if (m1.size() != m2.size()) - return false; - - return containsAll(m1, m2) && containsAll(m2, m1); - } - - private static boolean containsAll(Menge> m1, - Menge> m2) { - for (Menge elem : m2) - if (!contains(m1, elem)) - return false; - return true; - } - - private static boolean contains(Menge> m1, Menge m2) { - for (Menge elem : m1) - if (mengePairEquals(elem, m2)) - return true; - return false; - } - - private static boolean mengePairEquals(Menge m1, Menge m2) { - if (m1.size() != m2.size()) - return false; - - return containsAllPair(m1, m2) && containsAllPair(m2, m1); - } - - private static boolean containsAllPair(Menge m1, Menge m2) { - for (Pair elem : m1) - if (contains(m2, elem)) - return true; - return false; - } - - private static boolean contains(Menge m, Pair p) { - for (Pair elem : m) - if (pairEquals(elem, p)) - return true; - return false; - - } - - private static boolean pairEquals(Pair p1, Pair p2) { - return (p1.TA1.equals(p2.TA1) && p1.TA2.equals(p2.TA2)) - || (p1.TA1.equals(p2.TA2) && p1.TA2.equals(p2.TA1)); - } +// +// @Test +// public void unifyTestSimpleTypes() { +// // Init Factories and Builders +// UnifyTypeFactory typeFactory = new UnifyTypeFactory(); +// Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); +// UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); +// UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); +// +// /* +// * Test a <. Boolean +// */ +// +// // Init Types +// RefType boolT = typeFactory.GetSimpleType("java.lang.Boolean"); +// TypePlaceholder aTph = typeFactory.GetTypePlaceholder("a"); +// +// // Expected Result +// resultBuilder.clear(); +// resultBuilder.addPair(aTph, boolT, PairOperator.Equal); +// resultBuilder.addPair(aTph, typeFactory.GetExtendsType(boolT), +// PairOperator.Equal); +// Menge> expectedResult = resultBuilder.getNestedPairMenge(); +// +// // Actual Result +// assumptionBuilder.clear(); +// assumptionBuilder.addPair(aTph, boolT); +// Menge> actualResult = Unify.unify( +// assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); +// +// // System.out.println(expectedResult); +// // System.out.println(actualResult); +// +// Assert.assertTrue(mengeEquals(expectedResult, actualResult)); +// +// /* +// * Test b <. a, a <. Boolean +// */ +// +// // Init Types +// boolT = typeFactory.GetSimpleType("java.lang.Boolean"); +// aTph = typeFactory.GetTypePlaceholder("a"); +// TypePlaceholder bTph = typeFactory.GetTypePlaceholder("b"); +// +// // Expected Result +// resultBuilder.clear(); +// resultBuilder.addPair(aTph, boolT, PairOperator.Equal); +// resultBuilder.addPair(aTph, typeFactory.GetExtendsType(boolT), +// PairOperator.Equal); +// resultBuilder.addPair(bTph, boolT, PairOperator.Equal); +// resultBuilder.addPair(bTph, typeFactory.GetExtendsType(boolT), +// PairOperator.Equal); +// expectedResult = resultBuilder.getNestedPairMenge(); +// +// // Actual Result +// assumptionBuilder.clear(); +// assumptionBuilder.addPair(bTph, aTph); +// assumptionBuilder.addPair(aTph, boolT); +// actualResult = Unify.unify(assumptionBuilder.getPairMenge(), +// fcBuilder.Get_FC_TTO()); +// +// // System.out.println(expectedResult); +// // System.out.println(actualResult); +// +// // NOTE: Elemente im actualResult sind nicht unique +// // Assert.assertTrue(mengeEquals(expectedResult, actualResult)); +// +// /* +// * Test b <. a, a <. b +// */ +// +// aTph = typeFactory.GetTypePlaceholder("a"); +// bTph = typeFactory.GetTypePlaceholder("b"); +// +// // Expected Result +// resultBuilder.clear(); +// resultBuilder.addPair(bTph, aTph); +// resultBuilder.addPair(aTph, bTph); +// +// Menge buffer = resultBuilder.getPairMenge(); +// expectedResult = new Menge>(); +// expectedResult.add(buffer); +// +// // Actual Result +// assumptionBuilder.clear(); +// assumptionBuilder.addPair(bTph, aTph); +// assumptionBuilder.addPair(aTph, bTph); +// actualResult = Unify.unify(assumptionBuilder.getPairMenge(), +// fcBuilder.Get_FC_TTO()); +// +// // System.out.println(expectedResult); +// // System.out.println(actualResult); +// +// Assert.assertTrue(mengeEquals(expectedResult, actualResult)); +// +// /* +// * Test Integer <. a, a <. Boolean +// */ +// +// RefType intT = typeFactory.GetSimpleType("java.lang.Integer"); +// boolT = typeFactory.GetSimpleType("java.lang.Boolean"); +// aTph = typeFactory.GetTypePlaceholder("a"); +// bTph = typeFactory.GetTypePlaceholder("b"); +// +// // Expected Result +// resultBuilder.clear(); +// expectedResult = resultBuilder.getNestedPairMenge(); +// +// // Actual Result +// assumptionBuilder.clear(); +// assumptionBuilder.addPair(intT, aTph); +// assumptionBuilder.addPair(aTph, boolT); +// actualResult = Unify.unify(assumptionBuilder.getPairMenge(), +// fcBuilder.Get_FC_TTO()); +// +// // System.out.println(expectedResult); +// // System.out.println(actualResult); +// +// Assert.assertTrue(mengeEquals(expectedResult, actualResult)); +// +// } +// +// @Test +// public void unifyTestGenerics() { +// +// // Init Factories and Builders +// UnifyTypeFactory typeFactory = new UnifyTypeFactory(); +// Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); +// UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); +// UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); +// +// /* +// * Test a <. MyClass +// */ +// +// TypePlaceholder aTph = typeFactory.GetTypePlaceholder("a"); +// RefType myType = typeFactory.GetSimpleType("MyClass", +// typeFactory.GetTypePlaceholder("T"), +// typeFactory.GetTypePlaceholder("F")); +// +// // Expected Result +// resultBuilder.clear(); +// resultBuilder.addPair(aTph, myType, PairOperator.Equal); +// resultBuilder.addPair(aTph, typeFactory.GetExtendsType(myType)); +// Menge> expectedResult = resultBuilder.getNestedPairMenge(); +// +// // Actual Result +// assumptionBuilder.clear(); +// assumptionBuilder.addPair(aTph, myType); +// Menge> actualResult = Unify.unify( +// assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); +// +// // System.out.println(expectedResult); +// // System.out.println(actualResult); +// +// Assert.assertTrue(mengeEquals(expectedResult, actualResult)); +// +// /* +// * Test List> <. List +// */ +// +// TypePlaceholder tTph = typeFactory.GetTypePlaceholder("T"); +// RefType list = typeFactory.GetSimpleType("List", tTph); +// RefType listlist = typeFactory.GetSimpleType("List", list); +// +// // Expected Result +// resultBuilder.clear(); +// resultBuilder.addPair(typeFactory.GetExtendsType(list), tTph, +// PairOperator.Equal); +// expectedResult = resultBuilder.getNestedPairMenge(); +// +// // Actual Result +// assumptionBuilder.clear(); +// assumptionBuilder.addPair(listlist, list); +// actualResult = Unify.unify(assumptionBuilder.getPairMenge(), +// fcBuilder.Get_FC_TTO()); +// +// System.out.println(expectedResult); +// System.out.println(actualResult); +// +// Assert.assertTrue(mengeEquals(expectedResult, actualResult)); +// +// /* +// * Test List <. List> +// */ +// } +// +// @Test +// public void unifyTestInheritance() { +// +// // Init Factories and Builders +// UnifyTypeFactory typeFactory = new UnifyTypeFactory(); +// Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); +// UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); +// UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); +// +// // Init Types +// RefType tBool = typeFactory.GetSimpleType("java.lang.Boolean"); +// RefType tString = typeFactory.GetSimpleType("java.lang.String"); +// RefType tInt = typeFactory.GetSimpleType("java.lang.Integer"); +// TypePlaceholder tphA = typeFactory.GetTypePlaceholder("a"); +// +// // Build inheritance hierachy +// // Bool <. String <. Int +// fcBuilder.AddInheritance(tBool, tString); +// fcBuilder.AddInheritance(tString, tInt); +// +// // Build Assumptions +// assumptionBuilder.addPair(tphA, tString); +// +// // Build expected result +// resultBuilder.addPair(tphA, tBool, PairOperator.Equal); +// resultBuilder.addPair(tphA, typeFactory.GetExtendsType(tBool), +// PairOperator.Equal); +// resultBuilder.addPair(tphA, tString, PairOperator.Equal); +// resultBuilder.addPair(tphA, typeFactory.GetExtendsType(tString), +// PairOperator.Equal); +// +// // Assert +// Menge> actualResult = Unify.unify( +// assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); +// +// // System.out.println(actualResult); +// // System.out.println("-------------------"); +// // System.out.println(resultBuilder.getNestedPairMenge()); +// +// Assert.assertTrue(mengeEquals(resultBuilder.getNestedPairMenge(), +// actualResult)); +// } +// +// @Test +// public void unifyTestWildcards() { +// +// } +// +// private static boolean mengeEquals(Menge> m1, +// Menge> m2) { +// if (m1.size() != m2.size()) +// return false; +// +// return containsAll(m1, m2) && containsAll(m2, m1); +// } +// +// private static boolean containsAll(Menge> m1, +// Menge> m2) { +// for (Menge elem : m2) +// if (!contains(m1, elem)) +// return false; +// return true; +// } +// +// private static boolean contains(Menge> m1, Menge m2) { +// for (Menge elem : m1) +// if (mengePairEquals(elem, m2)) +// return true; +// return false; +// } +// +// private static boolean mengePairEquals(Menge m1, Menge m2) { +// if (m1.size() != m2.size()) +// return false; +// +// return containsAllPair(m1, m2) && containsAllPair(m2, m1); +// } +// +// private static boolean containsAllPair(Menge m1, Menge m2) { +// for (Pair elem : m1) +// if (contains(m2, elem)) +// return true; +// return false; +// } +// +// private static boolean contains(Menge m, Pair p) { +// for (Pair elem : m) +// if (pairEquals(elem, p)) +// return true; +// return false; +// +// } +// +// private static boolean pairEquals(Pair p1, Pair p2) { +// return (p1.TA1.equals(p2.TA1) && p1.TA2.equals(p2.TA2)) +// || (p1.TA1.equals(p2.TA2) && p1.TA2.equals(p2.TA1)); +// } } diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 2d2faad8..3c5792a3 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -4,7 +4,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import java.util.TreeSet; import java.util.stream.Collectors; import org.junit.Test; @@ -242,6 +241,100 @@ public class UnifyTest extends Unify { @Test public void unifyTestSimple() { + /* + * INIT + */ + TypeFactory tf = new TypeFactory(); + FiniteClosureBuilder fcb = new FiniteClosureBuilder(); + + Type number = tf.getSimpleType("Number"); + Type object = tf.getSimpleType("Object"); + Type integer = tf.getSimpleType("Integer"); + Type doubl = tf.getSimpleType("Double"); + + fcb.add(number, object); + fcb.add(integer, number); + fcb.add(doubl, number); + + IFiniteClosure fc = fcb.getCollectionExample(); + + /* + * Test 1: + * + * (Vector <. Vector) + * (List <. List) + */ + + Type tphA = tf.getPlaceholderType("a"); + Type tphB = tf.getPlaceholderType("b"); + Type extB = tf.getExtendsType(tphB); + Type extNum = tf.getExtendsType(number); + + Set eq = new HashSet(); + eq.add(new MPair(tf.getSimpleType("Vector", tphA), tf.getSimpleType("Vector", extB), PairOperator.SMALLERDOT)); + eq.add(new MPair(tf.getSimpleType("List", tphB), tf.getSimpleType("List", extNum), PairOperator.SMALLERDOT)); + + Set> expected = new HashSet<>(); + Set> actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(actual, expected); + + /* + * Test 2: + * + * Vector <. List + * + */ + + Type extA = tf.getExtendsType(tphA); + + eq = new HashSet(); + eq.add(new MPair(tf.getSimpleType("Vector", extA), tf.getSimpleType("Vector", extNum), PairOperator.SMALLERDOT)); + + expected = new HashSet<>(); + actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(actual, expected); + + /* + * Test 3: + * + * Vector <. List + * + */ + + eq = new HashSet(); + eq.add(new MPair(tf.getSimpleType("Vector", extNum), tf.getSimpleType("Vector", extA), PairOperator.SMALLERDOT)); + + expected = new HashSet<>(); + actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(actual, expected); + + /* + * Test 4: + * + * LinkedList <. Deque <. Queue <. Collection + * + * Vector <. List + * List <. AbstractList + * ? extends Number <.? b + */ + + eq = new HashSet(); + eq.add(new MPair(tf.getSimpleType("LinkedList", number), tf.getSimpleType("Deque", tphA), PairOperator.SMALLERDOT)); + eq.add(new MPair(tf.getSimpleType("Deque", tphA), tf.getSimpleType("Queue", tphB), PairOperator.SMALLERDOT)); + eq.add(new MPair(extNum, tphB, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(actual, expected); + } From 4cdcde8fefe8f841c9a26462e6777129599175ec Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Fri, 1 Apr 2016 16:12:30 +0200 Subject: [PATCH 28/57] Neuen Unify Algorithmus eingebaut --- .settings/org.eclipse.core.resources.prefs | 1 - .../dhbwstuttgart/syntaxtree/Constructor.java | 1 - .../syntaxtree/FieldDeclaration.java | 6 +- src/de/dhbwstuttgart/syntaxtree/Method.java | 4 +- .../syntaxtree/NullSyntaxTreeNode.java | 26 +++ .../syntaxtree/factory/ASTFactory.java | 2 +- .../factory/UnifyPairMengenBuilder.java | 2 +- .../syntaxtree/factory/UnifyTypeFactory.java | 32 +++- .../factory/Unify_FC_TTO_Builder.java | 1 - .../syntaxtree/operator/AddOp.java | 1 - .../syntaxtree/operator/AndOp.java | 1 - .../syntaxtree/operator/LogOp.java | 1 - .../syntaxtree/operator/Operator.java | 22 --- .../syntaxtree/statement/Assign.java | 5 +- .../syntaxtree/statement/Binary.java | 1 - .../syntaxtree/statement/Block.java | 5 +- .../syntaxtree/statement/ForStmt.java | 1 - .../syntaxtree/statement/IfStmt.java | 7 +- .../statement/LambdaExpression.java | 3 +- .../syntaxtree/statement/LocalOrFieldVar.java | 1 - .../syntaxtree/statement/LocalVarDecl.java | 3 +- .../syntaxtree/statement/NewClass.java | 1 - .../syntaxtree/statement/Return.java | 3 +- .../syntaxtree/statement/WhileStmt.java | 4 +- .../type/BoundedGenericTypeVar.java | 1 - .../syntaxtree/type/ExtendsWildcardType.java | 6 + .../syntaxtree/type/GenericTypeVar.java | 1 - .../syntaxtree/type/SuperWildcardType.java | 7 +- .../syntaxtree/type/TypePlaceholder.java | 14 +- .../syntaxtree/type/WildcardType.java | 6 +- .../typeinference/ConstraintsSet.java | 11 ++ .../typeinference/SingleConstraint.java | 71 -------- .../typeinference/TypeinferenceResultSet.java | 1 - .../typeinference/UnifyUndConstraint.java | 1 + .../typeinference/unify/Mapping.java | 35 +--- .../typeinference/unify/RuleSet.java | 2 +- .../typeinference/unify/Unify.java | 2 +- .../unify/model/ExtendsType.java | 1 + .../typeinference/unify/model/SuperType.java | 1 + test/unify/UnifyTypeFactoryTest.java | 152 ++++++++++++++++++ 40 files changed, 269 insertions(+), 177 deletions(-) create mode 100644 src/de/dhbwstuttgart/syntaxtree/NullSyntaxTreeNode.java delete mode 100755 src/de/dhbwstuttgart/typeinference/SingleConstraint.java create mode 100644 test/unify/UnifyTypeFactoryTest.java diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs index 9305e36f..1f0adda8 100755 --- a/.settings/org.eclipse.core.resources.prefs +++ b/.settings/org.eclipse.core.resources.prefs @@ -1,7 +1,6 @@ eclipse.preferences.version=1 encoding//src/de/dhbwstuttgart/core/MyCompiler.java=UTF-8 encoding//src/de/dhbwstuttgart/syntaxtree/statement/LambdaExpression.java=UTF-8 -encoding//src/de/dhbwstuttgart/typeinference/SingleConstraint.java=UTF-8 encoding//src/de/dhbwstuttgart/typeinference/UndConstraint.java=UTF-8 encoding//src/de/dhbwstuttgart/typeinference/UnifySingleConstraint.java=UTF-8 encoding//src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java=UTF-8 diff --git a/src/de/dhbwstuttgart/syntaxtree/Constructor.java b/src/de/dhbwstuttgart/syntaxtree/Constructor.java index 9859a734..73cfb0f8 100644 --- a/src/de/dhbwstuttgart/syntaxtree/Constructor.java +++ b/src/de/dhbwstuttgart/syntaxtree/Constructor.java @@ -28,7 +28,6 @@ import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.ConstructorAssumption; import de.dhbwstuttgart.typeinference.assumptions.MethodAssumption; diff --git a/src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java b/src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java index 7cc3c54b..d4814cb9 100644 --- a/src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java +++ b/src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java @@ -21,8 +21,8 @@ import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.OderConstraint; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; +import de.dhbwstuttgart.typeinference.UndConstraint; import de.dhbwstuttgart.typeinference.assumptions.FieldAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; @@ -148,13 +148,13 @@ public class FieldDeclaration extends Field{ } */ - SingleConstraint c1 = new SingleConstraint(thisType, thisType); + UndConstraint c1 = ConstraintsSet.createSingleConstraint(thisType, thisType); ret.add(c1); //Damit die TypVariable des Felds in den Constraints auftaucht if(this.wert!=null){ //Falls bei der Deklaration ein Wert zugewiesen wird, verhält sich das Constraintserzeugen wie bei dem Assign-Statement: ret.add(this.wert.TYPEExpr(localAssumptions)); - ret.add(new SingleConstraint(this.wert.getType().TYPE(localAssumptions,this), thisType)); + ret.add(ConstraintsSet.createSingleConstraint(this.wert.getType().TYPE(localAssumptions,this), thisType)); } return ret; } diff --git a/src/de/dhbwstuttgart/syntaxtree/Method.java b/src/de/dhbwstuttgart/syntaxtree/Method.java index ebed1381..662ac477 100755 --- a/src/de/dhbwstuttgart/syntaxtree/Method.java +++ b/src/de/dhbwstuttgart/syntaxtree/Method.java @@ -46,9 +46,9 @@ import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeInsertable; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; +import de.dhbwstuttgart.typeinference.UndConstraint; import de.dhbwstuttgart.typeinference.assumptions.MethodAssumption; import de.dhbwstuttgart.typeinference.assumptions.ParameterAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; @@ -499,7 +499,7 @@ public class Method extends Field implements IItemWithOffset, TypeInsertable ret.add(this.block.TYPEStmt(localAss)); // eine Verknüpfung mit der Type Assumption aus dem Assumption Set // und dem ermittelten Typ der Methode: - ret.add(new SingleConstraint(this.block.getType().TYPE(localAss, this), this.returntype.TYPE(localAss, this))); + ret.add(ConstraintsSet.createSingleConstraint(this.block.getType().TYPE(localAss, this), this.returntype.TYPE(localAss, this))); return ret; } diff --git a/src/de/dhbwstuttgart/syntaxtree/NullSyntaxTreeNode.java b/src/de/dhbwstuttgart/syntaxtree/NullSyntaxTreeNode.java new file mode 100644 index 00000000..5952cd17 --- /dev/null +++ b/src/de/dhbwstuttgart/syntaxtree/NullSyntaxTreeNode.java @@ -0,0 +1,26 @@ +package de.dhbwstuttgart.syntaxtree; + +import de.dhbwstuttgart.typeinference.Menge; + +/** + * Dieser SyntaxTreeNode kann anstelle von null in einem Syntaxbaum eingesetzt werden. + * Vorsicht: Als Offset wird dann immer 0 zurück gegeben. + */ +public class NullSyntaxTreeNode extends SyntaxTreeNode { + + @Override + public int getOffset() { + return 0; + } + + @Override + public int getVariableLength() { + return 0; + } + + @Override + public Menge getChildren() { + return new Menge<>(); + } + +} diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java b/src/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java index 12c1a654..c02ed64f 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java @@ -55,7 +55,7 @@ public class ASTFactory { return new Constructor(method, superClass); } - public static Class createClass(String className, Type type, Modifiers modifiers, Menge supertypeGenPara, SourceFile parent) { + public static Class createClass(String className, RefType type, Modifiers modifiers, Menge supertypeGenPara, SourceFile parent) { // TODO bytecode createClass //String name, RefType superClass, Modifiers modifiers, Menge supertypeGenPara Class generatedClass = new Class(className, type, modifiers, supertypeGenPara); diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyPairMengenBuilder.java b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyPairMengenBuilder.java index 95fd0897..8caf73cc 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyPairMengenBuilder.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyPairMengenBuilder.java @@ -3,7 +3,7 @@ package de.dhbwstuttgart.syntaxtree.factory; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.typeinference.Menge; import de.dhbwstuttgart.typeinference.Pair; -import de.dhbwstuttgart.typeinference.Pair.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; public class UnifyPairMengenBuilder { diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 51a895b4..193c8589 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -4,6 +4,7 @@ import java.util.HashSet; import java.util.logging.Logger; import de.dhbwstuttgart.myexception.NotImplementedException; +import de.dhbwstuttgart.syntaxtree.NullSyntaxTreeNode; import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; import de.dhbwstuttgart.syntaxtree.type.GenericTypeVar; import de.dhbwstuttgart.syntaxtree.type.ObjectType; @@ -36,8 +37,11 @@ import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; + public class UnifyTypeFactory { + private final static NullSyntaxTreeNode NULL_NODE = new NullSyntaxTreeNode(); + public static FiniteClosure generateFC(TypeAssumptions fromAss){ HashSet pairs = new HashSet<>(); for(ClassAssumption cAss : fromAss.getClassAssumptions()){ @@ -63,6 +67,10 @@ public class UnifyTypeFactory { return UnifyTypeFactory.convert((RefType)t); }else if(t instanceof TypePlaceholder){ return UnifyTypeFactory.convert((TypePlaceholder)t); + }else if(t instanceof ExtendsWildcardType){ + return UnifyTypeFactory.convert((ExtendsWildcardType)t); + }else if(t instanceof SuperWildcardType){ + return UnifyTypeFactory.convert((SuperWildcardType)t); } throw new NotImplementedException("Der Typ "+t+" kann nicht umgewandelt werden"); } @@ -105,7 +113,7 @@ public class UnifyTypeFactory { return ret; } - private static UnifyOderConstraint convert(OderConstraint set) { + public static UnifyOderConstraint convert(OderConstraint set) { UnifyOderConstraint ret = new UnifyOderConstraint(); for(UndConstraint oC : set.getUndConstraints()){ ret.addConstraint(UnifyTypeFactory.convert(oC)); @@ -113,7 +121,7 @@ public class UnifyTypeFactory { return ret; } - private static UnifyUndConstraint convert(UndConstraint set) { + public static UnifyUndConstraint convert(UndConstraint set) { UnifyUndConstraint ret = new UnifyUndConstraint(); for(EinzelElement oC : set.getPairs()){ ret.add(UnifyTypeFactory.convert(oC)); @@ -121,10 +129,14 @@ public class UnifyTypeFactory { return ret; } - private static MPair convert(EinzelElement p) { - if(!p.getItem().OperatorSmaller())throw new NotImplementedException(); - MPair ret = smaller(UnifyTypeFactory.convert(p.getItem().TA1) - , UnifyTypeFactory.convert(p.getItem().TA2)); + public static MPair convert(EinzelElement p) { + return convert(p.getItem()); + } + + public static MPair convert(Pair p) { + if(!p.OperatorSmaller())throw new NotImplementedException(); + MPair ret = smaller(UnifyTypeFactory.convert(p.TA1) + , UnifyTypeFactory.convert(p.TA2)); return ret; } @@ -139,12 +151,12 @@ public class UnifyTypeFactory { } public static Type convert(SuperType t) { - RefType innerType = new RefType(t.getSuperedType().getName(),null,0); + RefType innerType = new RefType(t.getSuperedType().getName(),NULL_NODE,0); return new SuperWildcardType(innerType); } public static Type convert(ExtendsType t) { - RefType innerType = new RefType(t.getExtendedType().getName(),null,0); + RefType innerType = new RefType(t.getExtendedType().getName(),NULL_NODE,0); return new ExtendsWildcardType(innerType); } @@ -153,6 +165,10 @@ public class UnifyTypeFactory { } public static Type convert(UnifyType t) { + if(t instanceof SimpleType)return convert((SimpleType) t); + if(t instanceof SuperType)return convert((SuperType) t); + if(t instanceof ExtendsType)return convert((ExtendsType) t); + if(t instanceof PlaceholderType)return convert((PlaceholderType) t); throw new NotImplementedException("Der Typ "+t+" kann nicht umgewandelt werden"); } } diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/Unify_FC_TTO_Builder.java b/src/de/dhbwstuttgart/syntaxtree/factory/Unify_FC_TTO_Builder.java index d28992cf..5f10ea6b 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/Unify_FC_TTO_Builder.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/Unify_FC_TTO_Builder.java @@ -2,7 +2,6 @@ package de.dhbwstuttgart.syntaxtree.factory; import de.dhbwstuttgart.typeinference.Menge; import de.dhbwstuttgart.typeinference.Pair; -import de.dhbwstuttgart.typeinference.unify.FC_TTO; import de.dhbwstuttgart.syntaxtree.Class; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.Type; diff --git a/src/de/dhbwstuttgart/syntaxtree/operator/AddOp.java b/src/de/dhbwstuttgart/syntaxtree/operator/AddOp.java index c9e95ee3..b1b4e4b6 100755 --- a/src/de/dhbwstuttgart/syntaxtree/operator/AddOp.java +++ b/src/de/dhbwstuttgart/syntaxtree/operator/AddOp.java @@ -15,7 +15,6 @@ import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.Pair; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.DebugException; import de.dhbwstuttgart.typeinference.unify.Unify; diff --git a/src/de/dhbwstuttgart/syntaxtree/operator/AndOp.java b/src/de/dhbwstuttgart/syntaxtree/operator/AndOp.java index fdb01d2c..09323e48 100755 --- a/src/de/dhbwstuttgart/syntaxtree/operator/AndOp.java +++ b/src/de/dhbwstuttgart/syntaxtree/operator/AndOp.java @@ -7,7 +7,6 @@ import de.dhbwstuttgart.syntaxtree.SyntaxTreeNode; import de.dhbwstuttgart.syntaxtree.statement.Expr; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.typeinference.ConstraintsSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; // ino.class.AndOp.24101.declaration diff --git a/src/de/dhbwstuttgart/syntaxtree/operator/LogOp.java b/src/de/dhbwstuttgart/syntaxtree/operator/LogOp.java index afea3229..40c4d0c3 100755 --- a/src/de/dhbwstuttgart/syntaxtree/operator/LogOp.java +++ b/src/de/dhbwstuttgart/syntaxtree/operator/LogOp.java @@ -18,7 +18,6 @@ import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.Pair; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.DebugException; import de.dhbwstuttgart.typeinference.unify.Unify; diff --git a/src/de/dhbwstuttgart/syntaxtree/operator/Operator.java b/src/de/dhbwstuttgart/syntaxtree/operator/Operator.java index 8639bb8f..f4534b45 100755 --- a/src/de/dhbwstuttgart/syntaxtree/operator/Operator.java +++ b/src/de/dhbwstuttgart/syntaxtree/operator/Operator.java @@ -19,54 +19,32 @@ import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.OderConstraint; import de.dhbwstuttgart.typeinference.Pair; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.UndConstraint; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; import de.dhbwstuttgart.typeinference.unify.Unify; - -// ino.class.Operator.24257.declaration public abstract class Operator extends SyntaxTreeNode -// ino.end -// ino.class.Operator.24257.body { - // ino.attribute.offset.24261.declaration private int offset; - // ino.end - // ino.attribute.variableLength.24264.declaration private int variableLength; - // ino.end - - // ino.method.Operator.24267.definition public Operator(int offset,int variableLength) - // ino.end - // ino.method.Operator.24267.body { this.offset=offset; this.variableLength=variableLength; } - // ino.end - // ino.method.getOffset.24270.definition public int getOffset() - // ino.end - // ino.method.getOffset.24270.body { return offset; } - // ino.end - // ino.method.getVariableLength.24273.definition public int getVariableLength() - // ino.end - // ino.method.getVariableLength.24273.body { return variableLength; } - // ino.end /** diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/Assign.java b/src/de/dhbwstuttgart/syntaxtree/statement/Assign.java index 9e1ade7c..2154d35e 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/Assign.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/Assign.java @@ -33,7 +33,6 @@ import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.unify.Unify; @@ -107,8 +106,8 @@ public class Assign extends Expr ret.add(expr2.TYPEExpr(assumptions)); //this.setTypeVariable( TypePlaceholder.fresh(this)); this.setType(TypePlaceholder.fresh(this)); - ret.add(new SingleConstraint(expr2.getType().TYPE(assumptions, this), expr1.getType().TYPE(assumptions, this))); //expr2.type <. expr1.type - ret.add(new SingleConstraint(expr1.getType().TYPE(assumptions, this), this.getType().TYPE(assumptions, this))); + ret.add(ConstraintsSet.createSingleConstraint(expr2.getType().TYPE(assumptions, this), expr1.getType().TYPE(assumptions, this))); //expr2.type <. expr1.type + ret.add(ConstraintsSet.createSingleConstraint(expr1.getType().TYPE(assumptions, this), this.getType().TYPE(assumptions, this))); return ret; } diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/Binary.java b/src/de/dhbwstuttgart/syntaxtree/statement/Binary.java index d8f836ed..44fc3cc8 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/Binary.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/Binary.java @@ -38,7 +38,6 @@ import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.OderConstraint; import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.UndConstraint; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/Block.java b/src/de/dhbwstuttgart/syntaxtree/statement/Block.java index bba4069a..9931abb4 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/Block.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/Block.java @@ -32,7 +32,6 @@ import de.dhbwstuttgart.syntaxtree.type.Void; import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; @@ -187,8 +186,8 @@ public class Block extends Statement } else { TypePlaceholder tph = TypePlaceholder.fresh(this); - ret.add(new SingleConstraint(this.getType().TYPE(assumptions, this), tph)); - ret.add(new SingleConstraint(stmt.getType().TYPE(assumptions, this), tph)); + ret.add(ConstraintsSet.createSingleConstraint(this.getType().TYPE(assumptions, this), tph)); + ret.add(ConstraintsSet.createSingleConstraint(stmt.getType().TYPE(assumptions, this), tph)); this.setType(tph); } } diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/ForStmt.java b/src/de/dhbwstuttgart/syntaxtree/statement/ForStmt.java index eeff85ba..7168da1b 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/ForStmt.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/ForStmt.java @@ -33,7 +33,6 @@ import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/IfStmt.java b/src/de/dhbwstuttgart/syntaxtree/statement/IfStmt.java index 51e535b6..23131b42 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/IfStmt.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/IfStmt.java @@ -44,7 +44,6 @@ import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; @@ -141,10 +140,10 @@ public class IfStmt extends Statement ret.add(this.then_block.TYPEStmt(assumptions)); if(else_block!=null){ ret.add(this.else_block.TYPEStmt(assumptions)); - if(!(else_block.getType() instanceof Void))ret.add(new SingleConstraint(else_block.getType().TYPE(assumptions, this),this.getType().TYPE(assumptions, this))); + if(!(else_block.getType() instanceof Void))ret.add(ConstraintsSet.createSingleConstraint(else_block.getType().TYPE(assumptions, this),this.getType().TYPE(assumptions, this))); } - ret.add(new SingleConstraint(expr.getType().TYPE(assumptions, this),new RefType("Boolean",this,0).TYPE(assumptions, this))); //(expressionDesIfStmt)<.boolean - if(!(then_block.getType() instanceof Void))ret.add(new SingleConstraint(then_block.getType().TYPE(assumptions, this),this.getType().TYPE(assumptions, this))); + ret.add(ConstraintsSet.createSingleConstraint(expr.getType().TYPE(assumptions, this),new RefType("Boolean",this,0).TYPE(assumptions, this))); //(expressionDesIfStmt)<.boolean + if(!(then_block.getType() instanceof Void))ret.add(ConstraintsSet.createSingleConstraint(then_block.getType().TYPE(assumptions, this),this.getType().TYPE(assumptions, this))); if(then_block.getType() instanceof Void && (else_block == null || else_block.getType() instanceof Void))this.setType(new Void(this,this.getOffset())); return ret; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/LambdaExpression.java b/src/de/dhbwstuttgart/syntaxtree/statement/LambdaExpression.java index 5643f26e..4acaa018 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/LambdaExpression.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/LambdaExpression.java @@ -41,7 +41,6 @@ import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.OderConstraint; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.Typeable; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.ParameterAssumption; @@ -198,7 +197,7 @@ public class LambdaExpression extends Expr{ }else{ this.lambdaType = new FunN(retType, modifiedParamTypes); } - ret.add(new SingleConstraint(lambdaType.TYPE(assumptions, this),this.getType().TYPE(assumptions, this))); + ret.add(ConstraintsSet.createSingleConstraint(lambdaType.TYPE(assumptions, this),this.getType().TYPE(assumptions, this))); return ret; } diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/LocalOrFieldVar.java b/src/de/dhbwstuttgart/syntaxtree/statement/LocalOrFieldVar.java index 2c6debd6..9c3c23e4 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/LocalOrFieldVar.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/LocalOrFieldVar.java @@ -28,7 +28,6 @@ import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.FieldAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/LocalVarDecl.java b/src/de/dhbwstuttgart/syntaxtree/statement/LocalVarDecl.java index 544e9fe2..ccda7e96 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/LocalVarDecl.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/LocalVarDecl.java @@ -27,7 +27,6 @@ import de.dhbwstuttgart.syntaxtree.type.Void; import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeInsertable; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.LocalVarAssumption; @@ -371,7 +370,7 @@ public class LocalVarDecl extends Statement implements TypeInsertable } assumptions.addAssumption(new LocalVarAssumption(this, this.getType())); //Bevor der Typ auf Void gesetzt wird. //if(this.getType() == null)throw new DebugException("Parser Post Processing nicht aufgerufen"); - ret.add(new SingleConstraint(this.getType().TYPE(assumptions, this), this.getType().TYPE(assumptions, this))); + ret.add(ConstraintsSet.createSingleConstraint(this.getType().TYPE(assumptions, this), this.getType().TYPE(assumptions, this))); //assumptions.remove(null); // falls Variable mit diesem Namen bereits vorhanden. this.setReturnType(new Void(this,0)); //Return typ einer Variablendeklaration ist Void return ret; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/NewClass.java b/src/de/dhbwstuttgart/syntaxtree/statement/NewClass.java index 5b9e35e4..b0542207 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/NewClass.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/NewClass.java @@ -34,7 +34,6 @@ import de.dhbwstuttgart.syntaxtree.type.Void; import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.UndConstraint; import de.dhbwstuttgart.typeinference.assumptions.ConstructorAssumption; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/Return.java b/src/de/dhbwstuttgart/syntaxtree/statement/Return.java index 73bb9f89..dce35395 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/Return.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/Return.java @@ -24,7 +24,6 @@ import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; @@ -95,7 +94,7 @@ public class Return extends Statement ret.add(this.retexpr.TYPEExpr(assumptions)); //this.setTypeVariable(TypePlaceholder.fresh("Return Type")); this.setType(TypePlaceholder.fresh(this)); - ret.add(new SingleConstraint(retexpr.getType().TYPE(assumptions, this), this.getType().TYPE(assumptions, this))); + ret.add(ConstraintsSet.createSingleConstraint(retexpr.getType().TYPE(assumptions, this), this.getType().TYPE(assumptions, this))); return ret; } diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/WhileStmt.java b/src/de/dhbwstuttgart/syntaxtree/statement/WhileStmt.java index d96ed086..35a18dc7 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/WhileStmt.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/WhileStmt.java @@ -28,8 +28,8 @@ import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; +import de.dhbwstuttgart.typeinference.UndConstraint; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; import de.dhbwstuttgart.typeinference.unify.Unify; @@ -112,7 +112,7 @@ public class WhileStmt extends Statement public ConstraintsSet TYPEStmt(TypeAssumptions assumptions) { ConstraintsSet ret = new ConstraintsSet(); ret.add(expr.TYPEExpr(assumptions)); - SingleConstraint exprMustBeBool = new SingleConstraint(expr.getType().TYPE(assumptions, this), new RefType("Boolean",this, 0).TYPE(assumptions, this)); // while(expr){}; expr <. boolean + UndConstraint exprMustBeBool = ConstraintsSet.createSingleConstraint(expr.getType().TYPE(assumptions, this), new RefType("Boolean",this, 0).TYPE(assumptions, this)); // while(expr){}; expr <. boolean ret.add(exprMustBeBool); ret.add(this.loop_block.TYPEStmt(assumptions)); this.setType(loop_block.getType()); diff --git a/src/de/dhbwstuttgart/syntaxtree/type/BoundedGenericTypeVar.java b/src/de/dhbwstuttgart/syntaxtree/type/BoundedGenericTypeVar.java index a815af3f..1dfef648 100755 --- a/src/de/dhbwstuttgart/syntaxtree/type/BoundedGenericTypeVar.java +++ b/src/de/dhbwstuttgart/syntaxtree/type/BoundedGenericTypeVar.java @@ -9,7 +9,6 @@ import de.dhbwstuttgart.typeinference.Menge; import de.dhbwstuttgart.syntaxtree.Class; import de.dhbwstuttgart.syntaxtree.SyntaxTreeNode; import de.dhbwstuttgart.typeinference.ConstraintsSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; diff --git a/src/de/dhbwstuttgart/syntaxtree/type/ExtendsWildcardType.java b/src/de/dhbwstuttgart/syntaxtree/type/ExtendsWildcardType.java index 22abeea0..4ae00f7f 100755 --- a/src/de/dhbwstuttgart/syntaxtree/type/ExtendsWildcardType.java +++ b/src/de/dhbwstuttgart/syntaxtree/type/ExtendsWildcardType.java @@ -163,4 +163,10 @@ public class ExtendsWildcardType extends WildcardType implements ITypeContainer, return new de.dhbwstuttgart.bytecode.WildcardType(this.innerType.get_Name(), "+"); } */ + + @Override + public String get_Name() { + return "? extends "+this.innerType.get_Name(); + } + } diff --git a/src/de/dhbwstuttgart/syntaxtree/type/GenericTypeVar.java b/src/de/dhbwstuttgart/syntaxtree/type/GenericTypeVar.java index d4e4d52a..c7ced871 100755 --- a/src/de/dhbwstuttgart/syntaxtree/type/GenericTypeVar.java +++ b/src/de/dhbwstuttgart/syntaxtree/type/GenericTypeVar.java @@ -11,7 +11,6 @@ import de.dhbwstuttgart.typeinference.ConstraintsSet; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; -import de.dhbwstuttgart.typeinference.SingleConstraint; import de.dhbwstuttgart.typeinference.TypeInsertable; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; diff --git a/src/de/dhbwstuttgart/syntaxtree/type/SuperWildcardType.java b/src/de/dhbwstuttgart/syntaxtree/type/SuperWildcardType.java index df10d990..dee1a9d9 100755 --- a/src/de/dhbwstuttgart/syntaxtree/type/SuperWildcardType.java +++ b/src/de/dhbwstuttgart/syntaxtree/type/SuperWildcardType.java @@ -2,6 +2,7 @@ package de.dhbwstuttgart.syntaxtree.type; import de.dhbwstuttgart.typeinference.Menge; import de.dhbwstuttgart.bytecode.ClassGenerator; +import de.dhbwstuttgart.parser.JavaClassName; import de.dhbwstuttgart.syntaxtree.SyntaxTreeNode; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; @@ -18,7 +19,7 @@ import de.dhbwstuttgart.typeinference.exceptions.DebugException; */ public class SuperWildcardType extends WildcardType implements ITypeContainer, IMatchable{ - + public SuperWildcardType(ObjectType innerType){ this(innerType.getOffset(), innerType); } @@ -168,5 +169,9 @@ public class SuperWildcardType extends WildcardType implements ITypeContainer, I return "-" + this.innerType.getBytecodeSignature(cg, rs); } + @Override + public String get_Name() { + return "? super "+this.innerType.get_Name(); + } } diff --git a/src/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java b/src/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java index 33d4babf..aa60576e 100755 --- a/src/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java +++ b/src/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java @@ -43,7 +43,7 @@ public class TypePlaceholder extends ObjectType private static String strNextName = "A"; // ino.end // ino.attribute.m_TypePlaceholdersRegistry.26788.declaration - private static Hashtable m_TypePlaceholdersRegistry = new Hashtable(); + private static Hashtable m_TypePlaceholdersRegistry = new Hashtable(); // ino.end private SyntaxTreeNode parent; @@ -102,10 +102,10 @@ public class TypePlaceholder extends ObjectType // ino.method.fresh.26800.body { TypePlaceholder typeVar = new TypePlaceholder(name, parent); - TypePlaceholder oldTPH = m_TypePlaceholdersRegistry.put(typeVar.getName(), typeVar); + TypePlaceholder oldTPH = m_TypePlaceholdersRegistry.put(typeVar.getName().toString(), typeVar); if(oldTPH != null){ oldTPH.name = new JavaClassName(makeNewName()); - m_TypePlaceholdersRegistry.put(oldTPH.getName(), oldTPH); + m_TypePlaceholdersRegistry.put(oldTPH.getName().toString(), oldTPH); } return typeVar; } @@ -121,7 +121,7 @@ public class TypePlaceholder extends ObjectType */ public static TypePlaceholder fresh(SyntaxTreeNode parent){ TypePlaceholder ret= new TypePlaceholder(makeNewName(), parent); - m_TypePlaceholdersRegistry.put(ret.getName(), ret); + m_TypePlaceholdersRegistry.put(ret.getName().toString(), ret); return ret; } @@ -260,7 +260,7 @@ public class TypePlaceholder extends ObjectType // ino.method.deleteRegistry.26839.body { m_TypePlaceholdersRegistry.clear(); - m_TypePlaceholdersRegistry = new Hashtable(); + m_TypePlaceholdersRegistry = new Hashtable(); } // ino.end @@ -328,7 +328,7 @@ public class TypePlaceholder extends ObjectType //auf den CSubstitution nicht registrierte Variablen zu //Exceptions fuehrt TypePlaceholder typeVar = new TypePlaceholder(makeNewName(), null); - m_TypePlaceholdersRegistry.put(typeVar.getName(), typeVar); + m_TypePlaceholdersRegistry.put(typeVar.getName().toString(), typeVar); return typeVar; //return new TypePlaceholder(makeNewName()); @@ -378,7 +378,7 @@ public class TypePlaceholder extends ObjectType //auf den CSubstitution nicht registrierte Variablen zu //Exceptions fuehrt TypePlaceholder typeVar = new TypePlaceholder(name, null); - m_TypePlaceholdersRegistry.put(typeVar.getName(), typeVar); + m_TypePlaceholdersRegistry.put(typeVar.getName().toString(), typeVar); return typeVar; //return new TypePlaceholder(name); diff --git a/src/de/dhbwstuttgart/syntaxtree/type/WildcardType.java b/src/de/dhbwstuttgart/syntaxtree/type/WildcardType.java index 262e1466..e21302fa 100755 --- a/src/de/dhbwstuttgart/syntaxtree/type/WildcardType.java +++ b/src/de/dhbwstuttgart/syntaxtree/type/WildcardType.java @@ -2,6 +2,7 @@ package de.dhbwstuttgart.syntaxtree.type; import de.dhbwstuttgart.typeinference.Menge; import de.dhbwstuttgart.bytecode.ClassGenerator; +import de.dhbwstuttgart.parser.JavaClassName; import de.dhbwstuttgart.syntaxtree.SyntaxTreeNode; import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; @@ -111,6 +112,9 @@ public class WildcardType extends Type{ return this.innerType.getBytecodeSignature(cg, rs); } - + @Override + public JavaClassName getName() { + return new JavaClassName(this.get_Name()); + } } diff --git a/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java b/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java index 7b611e2c..c68e4865 100755 --- a/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java +++ b/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java @@ -4,6 +4,7 @@ import java.util.Iterator; import java.util.Set; import java.util.Vector; import de.dhbwstuttgart.logger.Logger; +import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.logger.*; import de.dhbwstuttgart.typeinference.unify.Unifier; @@ -98,4 +99,14 @@ public class ConstraintsSet extends UndMenge implements Iterable getOderConstraints() { return this.constraintsSet; } + + public static UndConstraint createSingleConstraint(Type t1, Type t2){ + UndConstraint ret = new UndConstraint(); + ret.addConstraint(t1, t2); + return ret; + } + + public static UndConstraint createSingleConstraint(Pair pair) { + return createSingleConstraint(pair.TA1, pair.TA2); + } } diff --git a/src/de/dhbwstuttgart/typeinference/SingleConstraint.java b/src/de/dhbwstuttgart/typeinference/SingleConstraint.java deleted file mode 100755 index b8714689..00000000 --- a/src/de/dhbwstuttgart/typeinference/SingleConstraint.java +++ /dev/null @@ -1,71 +0,0 @@ -package de.dhbwstuttgart.typeinference; - -import java.util.Vector; - -import de.dhbwstuttgart.syntaxtree.type.GenericTypeVar; -import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.syntaxtree.type.Type; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.exceptions.DebugException; -import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; - - -/** - * Beschreibung von Herrn Plümicke: - * "The set of constraints consists of constraints of the form θ R θ' , where θ and - * θ' are Java types and R (R ∈ { < , > getSet() { - Menge> ret = new Menge<>(); - ret.add(new EinzelElement<>(constraintPair)); - return ret; - } - - public SingleConstraint(Pair toAdd) { - this.addConstraint(toAdd); - } - - public Pair getPair(){ - return constraintPair; - } - - @Override //Methode überschreiben, damit immer nur ein Vector mit nur einem Element zurückgeliefert wird. - public Menge getConstraintPairs(){ - Menge ret = new Menge(); - ret.add(constraintPair); - return ret; - } - - public void addConstraint(Pair toAdd){ - if(constraintPair != null)throw new DebugException("Ein Constraint darf nur aus einem ConstraintPair bestehen. Das hinzufügen von "+ toAdd + " ist nicht möglich."); - - Type p1 = toAdd.TA1; - Type p2 = toAdd.TA2; - if(p1==null || p2 == null)throw new NullPointerException(); - - constraintPair = new Pair(p1,p2); - } - - @Override - public String toString(){ - return ""+constraintPair.TA1.toString()+" < "+constraintPair.TA2.toString(); - } -} diff --git a/src/de/dhbwstuttgart/typeinference/TypeinferenceResultSet.java b/src/de/dhbwstuttgart/typeinference/TypeinferenceResultSet.java index 913d9d6b..3059529c 100755 --- a/src/de/dhbwstuttgart/typeinference/TypeinferenceResultSet.java +++ b/src/de/dhbwstuttgart/typeinference/TypeinferenceResultSet.java @@ -15,7 +15,6 @@ import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; import de.dhbwstuttgart.typeinference.typedeployment.TypeInsertPoint; import de.dhbwstuttgart.typeinference.typedeployment.TypeInsertSet; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; // ino.class.CTypeReconstructionResult.27238.description type=javadoc /** diff --git a/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java b/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java index b20cd6e6..f963e12f 100644 --- a/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java +++ b/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java @@ -41,4 +41,5 @@ public class UnifyUndConstraint extends UndMenge { public void add(MPair pair){ set.add(new EinzelElement<>(pair)); } + } diff --git a/src/de/dhbwstuttgart/typeinference/unify/Mapping.java b/src/de/dhbwstuttgart/typeinference/unify/Mapping.java index 603fb0f7..07206065 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Mapping.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Mapping.java @@ -6,6 +6,8 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; + public class Mapping { private HashMap backwardMap = new HashMap<>(); @@ -56,35 +58,14 @@ public class Mapping { return result.size() == pairs.size() ? Optional.of(result) : Optional.empty(); } - private de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator mapOp(de.dhbwstuttgart.typeinference.Pair.PairOperator op) { - /* - * TODO - * Warum hat der PairOp nur drei Werte? Wie wird SMALLERDOTWC etc im anderen Pair geregelt? - */ - - switch(op) { - case Equal: - return de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator.EQUALS; - case Smaller: - return de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator.SMALLER; - case SmallerExtends: - return de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator.SMALLERDOT; - default: - return de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator.EQUALS; - } + private PairOperator mapOp(PairOperator op) { + //TODO: Methode kann entfernt werden: + return op; } - private de.dhbwstuttgart.typeinference.Pair.PairOperator unmapOp(de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator op) { - switch(op) { - case EQUALS: - return de.dhbwstuttgart.typeinference.Pair.PairOperator.Equal; - case SMALLER: - return de.dhbwstuttgart.typeinference.Pair.PairOperator.Smaller; - case SMALLERDOT: - return de.dhbwstuttgart.typeinference.Pair.PairOperator.SmallerExtends; - default: - return de.dhbwstuttgart.typeinference.Pair.PairOperator.Equal; - } + private PairOperator unmapOp(PairOperator op) { + //TODO: Methode kann entfernt werden: + return op; } } diff --git a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java index 0461a0fc..297eadbf 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -22,7 +22,7 @@ import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.Unifier; -import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; public class RuleSet implements IRuleSet{ diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unify.java b/src/de/dhbwstuttgart/typeinference/unify/Unify.java index cb2cf3c4..891acd59 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unify.java @@ -24,7 +24,7 @@ import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; -import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.Unifier; diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java b/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java index 4cf3ceef..f4a79794 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java @@ -74,4 +74,5 @@ public final class ExtendsType extends UnifyType { public String toString() { return "? extends " + extendedType; } + } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java b/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java index 8283c685..48ed2891 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java @@ -60,4 +60,5 @@ public final class SuperType extends UnifyType { SuperType other = (SuperType) obj; return other.getSuperedType().equals(superedType); } + } diff --git a/test/unify/UnifyTypeFactoryTest.java b/test/unify/UnifyTypeFactoryTest.java new file mode 100644 index 00000000..15d6f5f5 --- /dev/null +++ b/test/unify/UnifyTypeFactoryTest.java @@ -0,0 +1,152 @@ +package unify; + +import static org.junit.Assert.*; + +import java.util.Set; + +import org.junit.Test; + +import de.dhbwstuttgart.syntaxtree.NullSyntaxTreeNode; +import de.dhbwstuttgart.syntaxtree.SyntaxTreeNode; +import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory; +import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; +import de.dhbwstuttgart.syntaxtree.type.FunN; +import de.dhbwstuttgart.syntaxtree.type.GenericTypeVar; +import de.dhbwstuttgart.syntaxtree.type.RefType; +import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; +import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; +import de.dhbwstuttgart.typeinference.ConstraintsSet; +import de.dhbwstuttgart.typeinference.Menge; +import de.dhbwstuttgart.typeinference.OderConstraint; +import de.dhbwstuttgart.typeinference.Pair; +import de.dhbwstuttgart.typeinference.UndConstraint; +import de.dhbwstuttgart.typeinference.UnifyConstraintsSet; +import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.SimpleType; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; + + +public class UnifyTypeFactoryTest { + private static TypeFactory tf = new TypeFactory(); + + @Test + public void convertConstraintSet(){ + ConstraintsSet cons = new ConstraintsSet(); + OderConstraint oCons = new OderConstraint(); + UndConstraint uCons = new UndConstraint(); + uCons.addConstraint(getSimpleRefType(), getSimpleRefType()); + oCons.addConstraint(uCons); + oCons.addConstraint(ConstraintsSet.createSingleConstraint(getPair())); + cons.add(oCons); + + checkConvertConstraintsSet(cons); + } + + @Test + public void convertMPair() { + MPair mp1 = getSimpleMPair(); + checkConvertMPair(mp1); + + TypePlaceholder tph1 = TypePlaceholder.fresh(new NullSyntaxTreeNode()); + TypePlaceholder tph2 = TypePlaceholder.fresh(new NullSyntaxTreeNode()); + + MPair mp2 = new MPair(getSimpleType(), tf.getPlaceholderType(tph1.getName().toString()), PairOperator.SMALLERDOT); + checkConvertMPair(mp2); + + MPair mp3 = new MPair(tf.getSuperType(getSimpleType()), getSimpleType(), PairOperator.SMALLERDOT); + checkConvertMPair(mp3); + + MPair mp4 = new MPair(tf.getPlaceholderType(tph2.getName().toString()), tf.getPlaceholderType(tph1.getName().toString()), PairOperator.SMALLERDOT); + checkConvertMPair(mp4); + + SimpleType typeWithParams = tf.getSimpleType("Test", getSimpleType()); + SimpleType typeWithTPHParams = tf.getSimpleType("Test", tf.getPlaceholderType("Test")); + MPair mp5 = new MPair(typeWithTPHParams, typeWithParams, PairOperator.SMALLERDOT); + checkConvertMPair(mp5); + } + + @Test + public void convertPair(){ + TypePlaceholder tph1 = TypePlaceholder.fresh(new NullSyntaxTreeNode()); + TypePlaceholder tph2 = TypePlaceholder.fresh(new NullSyntaxTreeNode()); + + Pair p1 = new Pair(getSimpleRefType(), getSimpleRefType()); + checkConvertPair(p1); + + Pair p2 = new Pair(tph1, tph2); + checkConvertPair(p1); + + ExtendsWildcardType ext = new ExtendsWildcardType(getSimpleRefType()); + SuperWildcardType sup = new SuperWildcardType(getSimpleRefType()); + Pair p3 = new Pair(ext, sup); + checkConvertPair(p1); + + GenericTypeVar gt = new GenericTypeVar("A", new NullSyntaxTreeNode(), 0); + de.dhbwstuttgart.syntaxtree.type.Void voidType = new de.dhbwstuttgart.syntaxtree.type.Void(new NullSyntaxTreeNode(), 0); + Pair p4 = new Pair(gt, voidType); + checkConvertPair(p1); + + Pair p5 = new Pair(new FunN(getSimpleRefType(), new Menge<>()), tph1); + checkConvertPair(p5); + } + + // Hilfsfunktionen: + + private static void checkConvertConstraintsSet(ConstraintsSet cons){ + Set> check = cons.cartesianProduct(); + + UnifyConstraintsSet converted = UnifyTypeFactory.convert(cons); + Set> cartesianProductOfConverted = converted.cartesianProduct(); + + assertTrue(cartesianProductOfConverted.size()==check.size()); + assertTrue(cartesianProductOfConverted.iterator().next().size()==check.iterator().next().size()); + + Set> controlSet = new Menge<>(); + for(Set pairs : cartesianProductOfConverted){ + Set tmpSet = new Menge<>(); + for(MPair mp : pairs){ + Pair p = checkConvertMPair(mp); + tmpSet.add(p); + } + controlSet.add(tmpSet); + } + assertTrue(controlSet.equals(check)); + } + + private static MPair checkConvertPair(Pair p){ + System.out.println("Checking Pair: "+p); + MPair mp = UnifyTypeFactory.convert(p); + assertTrue(p.TA1.get_Name().equals(mp.getLhsType().getName())); + assertTrue(p.TA2.get_Name().equals(mp.getRhsType().getName())); + return mp; + } + + private static Pair checkConvertMPair(MPair mp){ + System.out.println("Checking Pair: "+mp); + Pair p = UnifyTypeFactory.convert(mp); + assertTrue(p.TA1.get_Name().equals(mp.getLhsType().getName())); + assertTrue(p.TA2.get_Name().equals(mp.getRhsType().getName())); + return p; + } + + private static SimpleType getSimpleType(){ + return tf.getSimpleType("String"); + } + + private static MPair getSimpleMPair(){ + UnifyType lt = tf.getSimpleType("String"); + UnifyType rt = tf.getSimpleType("String"); + MPair ret = new MPair(lt, rt, PairOperator.SMALLERDOT); + return ret; + } + + private static Pair getPair(){ + return new Pair(getSimpleRefType(),getSimpleRefType()); + } + + private static RefType getSimpleRefType(){ + NullSyntaxTreeNode nullNode = new NullSyntaxTreeNode(); + return new RefType("java.lang.String",nullNode,nullNode.getOffset()); + } +} From 1bf208b833783d63821aa672bc848e5bddfedfae Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Fri, 1 Apr 2016 18:24:36 +0200 Subject: [PATCH 29/57] Merge mit refactoring --- test/unify/FiniteClosureTest.java | 53 +++++++++---------------------- 1 file changed, 15 insertions(+), 38 deletions(-) diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index a391adeb..87e648a5 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -11,7 +11,7 @@ import org.junit.Test; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.MPair; -import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; @@ -103,31 +103,15 @@ public class FiniteClosureTest { * smaller(Set) = * { HashSet, Set, TreeSet, LinkedHashSet } */ - -<<<<<<< HEAD + UnifyType t = tf.getPlaceholderType("T"); UnifyType setT = tf.getSimpleType("Set", t); UnifyType hashSetT = tf.getSimpleType("HashSet", t); UnifyType treeSetT = tf.getSimpleType("TreeSet", t); UnifyType linkedHashSetT = tf.getSimpleType("LinkedHashSet", t); - UnifyType hashSetExtT = tf.getSimpleType("HashSet", t); - UnifyType treeSetExtT = tf.getSimpleType("TreeSet", t); - UnifyType linkedHashSetExtT = tf.getSimpleType("LinkedHashSet", t); - UnifyType setExtT = tf.getSimpleType("Set", t); expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { - setT, hashSetT, treeSetT, linkedHashSetT, - setExtT, hashSetExtT, treeSetExtT, linkedHashSetExtT -======= - Type t = tf.getPlaceholderType("T"); - Type setT = tf.getSimpleType("Set", t); - Type hashSetT = tf.getSimpleType("HashSet", t); - Type treeSetT = tf.getSimpleType("TreeSet", t); - Type linkedHashSetT = tf.getSimpleType("LinkedHashSet", t); - - expectedResult = new HashSet<>(Arrays.stream(new Type[] { - setT, hashSetT, treeSetT, linkedHashSetT ->>>>>>> d89d06797e17a7a95f007fe24e9b6133b3b13179 + setT, hashSetT, treeSetT, linkedHashSetT }).collect(Collectors.toSet())); Assert.assertEquals(expectedResult, fc.smaller(setT)); @@ -169,27 +153,20 @@ public class FiniteClosureTest { * { HashSet, Set, TreeSet, LinkedHashSet, * HashSet, Set, TreeSet, LinkedHashSet } * - */ -<<<<<<< HEAD - + */ + UnifyType t1 = tf.getPlaceholderType("T1"); + UnifyType extT1 = tf.getExtendsType(t1); + UnifyType setExtT1 = tf.getSimpleType("Set", extT1); + UnifyType hashSetExtT1 = tf.getSimpleType("HashSet", extT1); + UnifyType treeSetExtT1 = tf.getSimpleType("TreeSet", extT1); + UnifyType linkedHashSetExtT1 = tf.getSimpleType("LinkedHashSet", extT1); + UnifyType setT1 = tf.getSimpleType("Set", t1); + UnifyType hashSetT1 = tf.getSimpleType("HashSet", t1); + UnifyType treeSetT1 = tf.getSimpleType("TreeSet", t1); + UnifyType linkedHashSetT1 = tf.getSimpleType("LinkedHashSet", t1); expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { - setT, hashSetT, treeSetT, linkedHashSetT, - setExtT, hashSetExtT, treeSetExtT, linkedHashSetExtT -======= - Type t1 = tf.getPlaceholderType("T1"); - Type extT1 = tf.getExtendsType(t1); - Type setExtT1 = tf.getSimpleType("Set", extT1); - Type hashSetExtT1 = tf.getSimpleType("HashSet", extT1); - Type treeSetExtT1 = tf.getSimpleType("TreeSet", extT1); - Type linkedHashSetExtT1 = tf.getSimpleType("LinkedHashSet", extT1); - Type setT1 = tf.getSimpleType("Set", t1); - Type hashSetT1 = tf.getSimpleType("HashSet", t1); - Type treeSetT1 = tf.getSimpleType("TreeSet", t1); - Type linkedHashSetT1 = tf.getSimpleType("LinkedHashSet", t1); - expectedResult = new HashSet<>(Arrays.stream(new Type[] { setT1, hashSetT1, treeSetT1, linkedHashSetT1, - setExtT1, hashSetExtT1, treeSetExtT1, linkedHashSetExtT1 ->>>>>>> d89d06797e17a7a95f007fe24e9b6133b3b13179 + setExtT1, hashSetExtT1, treeSetExtT1, linkedHashSetExtT1 }).collect(Collectors.toSet())); Assert.assertEquals(expectedResult, fc.smaller(setExtT1)); From 0be7534b98f9d8f0d1a1ea12b0ef30dcd79d58a9 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Sat, 2 Apr 2016 11:29:31 +0200 Subject: [PATCH 30/57] . --- .../syntaxtree/factory/Unify_FC_TTO_Builder.java | 8 +++++--- test/unify/UnifyTest.java | 3 ++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/Unify_FC_TTO_Builder.java b/src/de/dhbwstuttgart/syntaxtree/factory/Unify_FC_TTO_Builder.java index 524e729e..d8276f99 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/Unify_FC_TTO_Builder.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/Unify_FC_TTO_Builder.java @@ -14,11 +14,13 @@ public class Unify_FC_TTO_Builder { public void AddInheritance(Type t1, Type t2) { if(t1 instanceof RefType) - classes.add(new Class(t1.get_Name(), t1.getOffset())); + if(!classes.stream().anyMatch(x -> x.getName().equals(t1.getName()))) + classes.add(new Class(t1.get_Name(), t1.getOffset())); if(t2 instanceof RefType) - classes.add(new Class(t2.get_Name(), t2.getOffset())); - + if(!classes.stream().anyMatch(x -> x.getName().equals(t2.getName()))) + classes.add(new Class(t2.get_Name(), t2.getOffset())); + fc.add(new Pair(t1, t2)); } diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 3c5792a3..7e3cff74 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -50,8 +50,9 @@ public class UnifyTest extends Unify { Set eq = new HashSet(); Set> expected = new HashSet<>(); + expected.add(new HashSet<>()); Set> actual = unify(eq, fc); - Assert.assertEquals(actual, expected); + Assert.assertEquals(expected, actual); /* * Test 2: From 0d5b515a47747c8e834aec4f61abef2a1887bb4f Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Sun, 3 Apr 2016 16:53:45 +0200 Subject: [PATCH 31/57] added extra set level / fixed subst rule bug / --- .../typeinference/unify/RuleSet.java | 21 +- .../typeinference/unify/Unify.java | 298 +++++++---- .../typeinference/unifynew/Unify.java | 503 ------------------ test/unify/UnifyTest.java | 48 +- 4 files changed, 245 insertions(+), 625 deletions(-) delete mode 100644 src/de/dhbwstuttgart/typeinference/unifynew/Unify.java diff --git a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java index 3ae16c23..30150cd3 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -8,6 +8,7 @@ import java.util.List; import java.util.Optional; import java.util.Queue; import java.util.Set; +import java.util.Stack; import java.util.stream.Collectors; import junit.framework.Assert; @@ -530,15 +531,25 @@ public class RuleSet implements IRuleSet{ public Optional> subst(Set pairs) { HashMap typeMap = new HashMap<>(); + Stack occuringTypes = new Stack<>(); + for(MPair pair : pairs) { - UnifyType t1 = pair.getLhsType(); - UnifyType t2 = pair.getRhsType(); + occuringTypes.push(pair.getLhsType()); + occuringTypes.push(pair.getRhsType()); + } + + while(!occuringTypes.isEmpty()) { + UnifyType t1 = occuringTypes.pop(); if(!typeMap.containsKey(t1)) typeMap.put(t1, 0); - if(!typeMap.containsKey(t2)) - typeMap.put(t2, 0); typeMap.put(t1, typeMap.get(t1)+1); - typeMap.put(t2, typeMap.get(t2)+1); + + if(t1 instanceof ExtendsType) + occuringTypes.push(((ExtendsType) t1).getExtendedType()); + if(t1 instanceof SuperType) + occuringTypes.push(((SuperType) t1).getSuperedType()); + else + t1.getTypeParams().forEach(x -> occuringTypes.push(x)); } Queue result1 = new LinkedList(pairs); diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unify.java b/src/de/dhbwstuttgart/typeinference/unify/Unify.java index 891acd59..b4fb7bb9 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unify.java @@ -12,9 +12,6 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; -import de.dhbwstuttgart.typeinference.Menge; -import de.dhbwstuttgart.typeinference.Pair; -import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; import de.dhbwstuttgart.typeinference.unify.interfaces.ISetOperations; @@ -68,7 +65,7 @@ public class Unify { } // Add the set of [a =. Theta | (a=. Theta) in Eq2'] - Set bufferSet = eq2s.stream() + Set bufferSet = eq2s.stream() .filter(x -> x.getPairOp() == PairOperator.EQUALSDOT && x.getLhsType() instanceof PlaceholderType) .collect(Collectors.toSet()); @@ -80,7 +77,7 @@ public class Unify { // Sets that originate from pair pattern matching // Sets of the "second level" - Set>> secondLevelSets = calculatePairSets(eq2s, fc); + Set>>> secondLevelSets = calculatePairSets(eq2s, fc); /* Up to here, no cartesian products are calculated. * filters for pairs and sets can be applied here */ @@ -88,11 +85,13 @@ public class Unify { ISetOperations setOps = new GuavaSetOperations(); // Sub cartesian products of the second level (pattern matched) sets - for(Set> secondLevelSet : secondLevelSets) { - List> secondLevelSetList = new ArrayList<>(secondLevelSet); - topLevelSets.add(setOps.cartesianProduct(secondLevelSetList) - .stream().map(x -> new HashSet<>(x)) - .collect(Collectors.toCollection(HashSet::new))); + for(Set>> secondLevelSet : secondLevelSets) { + List>> secondLevelSetList = new ArrayList<>(secondLevelSet); + Set>> cartResult = setOps.cartesianProduct(secondLevelSetList); + + Set> flat = new HashSet<>(); + cartResult.stream().forEach(x -> flat.addAll(x)); + topLevelSets.add(flat); } // Cartesian product over all (up to 10) top level sets @@ -133,15 +132,29 @@ public class Unify { * b) Build the union over everything */ - for(Set eqss : changed) { + for(Set eqss : changed) eqPrimePrimeSet.addAll(this.unify(eqss, fc)); + + /* + * Step 7: Filter empty sets; + */ + return eqPrimePrimeSet.stream().filter(x -> isSolvedForm(x)).collect(Collectors.toCollection(HashSet::new)); + + } + + protected boolean isSolvedForm(Set eqPrimePrime) { + for(MPair pair : eqPrimePrime) { + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + + if(!(lhsType instanceof PlaceholderType)) + return false; + + if(pair.getPairOp() != PairOperator.EQUALSDOT && !(rhsType instanceof PlaceholderType)) + return false; } - /* - * Step 7: Filter result for solved pairs - */ - return eqPrimePrimeSet; - + return true; } protected Set applyTypeUnificationRules(Set eq, IFiniteClosure fc) { @@ -178,6 +191,13 @@ public class Unify { Optional opt = rules.reduceUpLow(pair); opt = opt.isPresent() ? opt : rules.reduceLow(pair); opt = opt.isPresent() ? opt : rules.reduceUp(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardLow(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardLowRight(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardUp(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardUpRight(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardLowUp(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardUpLow(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardLeft(pair); // One of the rules has been applied if(opt.isPresent()) { @@ -235,8 +255,8 @@ public class Unify { } - protected Set>> calculatePairSets(Set eq2s, IFiniteClosure fc) { - List>> result = new ArrayList<>(); + protected Set>>> calculatePairSets(Set eq2s, IFiniteClosure fc) { + List>>> result = new ArrayList<>(); // Init all 8 cases for(int i = 0; i < 8; i++) @@ -248,23 +268,23 @@ public class Unify { UnifyType lhsType = pair.getLhsType(); UnifyType rhsType = pair.getRhsType(); - // Case 1: (a <. Theta') + // Case 1: (a <. Theta') if(pairOp == PairOperator.SMALLERDOT && lhsType instanceof PlaceholderType) - result.get(0).add(unifyCase1((PlaceholderType) pair.getLhsType(), pair.getRhsType(), fc)); + result.get(0).add(unifyCase1((PlaceholderType) pair.getLhsType(), pair.getRhsType(), fc)); // Case 2: (a <.? ? ext Theta') else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof ExtendsType) result.get(1).add(unifyCase2((PlaceholderType) pair.getLhsType(), (ExtendsType) pair.getRhsType(), fc)); - // Case 3: (a <.? ? sup Theta') + // Case 3: (a <.? ? sup Theta') else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof SuperType) - result.get(2).add(unifyCase3((PlaceholderType) lhsType, (SuperType) rhsType, fc)); + result.get(2).add(unifyCase3((PlaceholderType) lhsType, (SuperType) rhsType, fc)); // Case 4: (a <.? Theta') else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType) result.get(3).add(unifyCase4((PlaceholderType) lhsType, rhsType, fc)); - // Case 5: (Theta <. a) + // Case 5: (Theta <. a) else if(pairOp == PairOperator.SMALLERDOT && rhsType instanceof PlaceholderType) result.get(4).add(unifyCase5(lhsType, (PlaceholderType) rhsType, fc)); @@ -281,66 +301,20 @@ public class Unify { result.get(7).add(unifyCase8(lhsType, (PlaceholderType) rhsType, fc)); } - return result.stream().filter(x -> x.size() > 0).collect(Collectors.toCollection(HashSet::new)); + return result.stream().map(x -> x.stream().filter(y -> y.size() > 0).collect(Collectors.toCollection(HashSet::new))) + .filter(x -> x.size() > 0).collect(Collectors.toCollection(HashSet::new)); } - protected Set unifyCase1(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { - Set result = new HashSet<>(); + protected Set> unifyCase1(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { + Set> result = new HashSet<>(); IUnify unify = new MartelliMontanariUnify(); Set cs = fc.getAllTypesByName(thetaPrime.getName()); for(UnifyType c : cs) { - // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); - thetaQs.add(c); // reflexive - - Set thetaQPrimes = new HashSet<>(); - TypeParams cParams = c.getTypeParams(); - if(cParams.size() == 0) - thetaQPrimes.add(c); - else { - ArrayList> candidateParams = new ArrayList<>(); - for(UnifyType param : cParams) - candidateParams.add(fc.grArg(param)); - - for(TypeParams tp : permuteParams(candidateParams)) - thetaQPrimes.add(c.setTypeParams(tp)); - } - - for(UnifyType tqp : thetaQPrimes) { - Optional opt = unify.unify(tqp, thetaPrime); - if (!opt.isPresent()) - continue; - - Unifier unifier = opt.get(); - Set> substitutions = unifier.getSubstitutions(); - for (Entry sigma : substitutions) - result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); - for (UnifyType tq : thetaQs) { - Set smaller = fc.smaller(unifier.apply(tq)); - smaller.stream().map(x -> new MPair(a, x, PairOperator.EQUALSDOT)) - .forEach(x -> result.add(x)); - } - - } - } - - return result; - } - - protected Set unifyCase2(PlaceholderType a, ExtendsType extThetaPrime, IFiniteClosure fc) { - Set result = new HashSet<>(); - IUnify unify = new MartelliMontanariUnify(); - - UnifyType thetaPrime = extThetaPrime.getExtendedType(); - Set cs = fc.getAllTypesByName(thetaPrime.getName()); - - for(UnifyType c : cs) { - - // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? + Set thetaQs = fc.getChildren(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); thetaQs.add(c); // reflexive Set thetaQPrimes = new HashSet<>(); @@ -355,57 +329,140 @@ public class Unify { for(TypeParams tp : permuteParams(candidateParams)) thetaQPrimes.add(c.setTypeParams(tp)); } - + for(UnifyType tqp : thetaQPrimes) { Optional opt = unify.unify(tqp, thetaPrime); if (!opt.isPresent()) continue; Unifier unifier = opt.get(); - Set> substitutions = unifier.getSubstitutions(); - for (Entry sigma : substitutions) - result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + Set substitutionSet = new HashSet<>(); + for (Entry sigma : unifier.getSubstitutions()) + substitutionSet.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + for (UnifyType tq : thetaQs) { - ExtendsType extTq = new ExtendsType(tq); - Set smaller = fc.smaller(unifier.apply(extTq)); - smaller.stream().map(x -> new MPair(a, x, PairOperator.EQUALSDOT)) - .forEach(x -> result.add(x)); - } + Set smaller = fc.smaller(unifier.apply(tq)); + for(UnifyType theta : smaller) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new MPair(a, theta, PairOperator.EQUALSDOT)); + resultPrime.addAll(substitutionSet); + result.add(resultPrime); + } + } + } } return result; } - - protected Set unifyCase3(PlaceholderType a, SuperType subThetaPrime, IFiniteClosure fc) { - Set result = new HashSet<>(); - for(UnifyType theta : fc.smArg(subThetaPrime)) - result.add(new MPair(a, theta, PairOperator.EQUALSDOT)); + + protected Set> unifyCase2(PlaceholderType a, ExtendsType extThetaPrime, IFiniteClosure fc) { + Set> result = new HashSet<>(); + IUnify unify = new MartelliMontanariUnify(); + + UnifyType thetaPrime = extThetaPrime.getExtendedType(); + Set cs = fc.getAllTypesByName(thetaPrime.getName()); + + for(UnifyType c : cs) { + + // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? + Set thetaQs = fc.getChildren(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + thetaQs.add(c); // reflexive + + Set thetaQPrimes = new HashSet<>(); + TypeParams cParams = c.getTypeParams(); + if(cParams.size() == 0) + thetaQPrimes.add(c); + else { + ArrayList> candidateParams = new ArrayList<>(); + for(UnifyType param : cParams) + candidateParams.add(fc.grArg(param)); + + for(TypeParams tp : permuteParams(candidateParams)) + thetaQPrimes.add(c.setTypeParams(tp)); + } + + for(UnifyType tqp : thetaQPrimes) { + Optional opt = unify.unify(tqp, thetaPrime); + if (!opt.isPresent()) + continue; + + Unifier unifier = opt.get(); + + Set substitutionSet = new HashSet<>(); + for (Entry sigma : unifier.getSubstitutions()) + substitutionSet.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + + for (UnifyType tq : thetaQs) { + ExtendsType extTq = new ExtendsType(tq); + Set smArg = fc.smArg(unifier.apply(extTq)); + for(UnifyType theta : smArg) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new MPair(a, theta, PairOperator.EQUALSDOT)); + resultPrime.addAll(substitutionSet); + result.add(resultPrime); + } + } + + } + } + return result; } - protected Set unifyCase4(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { - Set result = new HashSet<>(); - result.add(new MPair(a, thetaPrime, PairOperator.EQUALSDOT)); + protected Set> unifyCase3(PlaceholderType a, SuperType subThetaPrime, IFiniteClosure fc) { + Set> result = new HashSet<>(); + + UnifyType aPrime = PlaceholderType.freshPlaceholder(); + UnifyType supAPrime = new SuperType(aPrime); + for(UnifyType theta : fc.smArg(subThetaPrime)) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new MPair(a, aPrime, PairOperator.EQUALSDOT)); + resultPrime.add(new MPair(aPrime,theta, PairOperator.SMALLERDOT)); + result.add(resultPrime); + + resultPrime = new HashSet<>(); + resultPrime.add(new MPair(a, supAPrime, PairOperator.EQUALSDOT)); + resultPrime.add(new MPair(supAPrime,theta, PairOperator.SMALLERDOT)); + result.add(resultPrime); + } + return result; } - protected Set unifyCase5(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { - Set result = new HashSet<>(); - for(UnifyType thetaS : fc.greater(theta)) - result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + protected Set> unifyCase4(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { + Set> result = new HashSet<>(); + Set resultPrime = new HashSet<>(); + resultPrime.add(new MPair(a, thetaPrime, PairOperator.EQUALSDOT)); + result.add(resultPrime); + return result; } - protected Set unifyCase6(ExtendsType extTheta, PlaceholderType a, IFiniteClosure fc) { - Set result = new HashSet<>(); - for(UnifyType thetaS : fc.grArg(extTheta)) - result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + protected Set> unifyCase5(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { + Set> result = new HashSet<>(); + for(UnifyType thetaS : fc.greater(theta)) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + result.add(resultPrime); + } + return result; } - protected Set unifyCase7(SuperType supTheta, PlaceholderType a, IFiniteClosure fc) { - Set result = new HashSet<>(); + protected Set> unifyCase6(ExtendsType extTheta, PlaceholderType a, IFiniteClosure fc) { + Set> result = new HashSet<>(); + for(UnifyType thetaS : fc.grArg(extTheta)) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + result.add(resultPrime); + } + + return result; + } + + protected Set> unifyCase7(SuperType supTheta, PlaceholderType a, IFiniteClosure fc) { + Set> result = new HashSet<>(); IUnify unify = new MartelliMontanariUnify(); UnifyType theta = supTheta.getSuperedType(); @@ -413,8 +470,8 @@ public class Unify { for(UnifyType c : cs) { - // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.smaller(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? + Set thetaQs = fc.getChildren(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); thetaQs.add(c); // reflexive Set thetaQPrimes = new HashSet<>(); @@ -436,13 +493,20 @@ public class Unify { continue; Unifier unifier = opt.get(); - Set> substitutions = unifier.getSubstitutions(); - for (Entry sigma : substitutions) - result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + + Set substitutionSet = new HashSet<>(); + for (Entry sigma : unifier.getSubstitutions()) + substitutionSet.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + for (UnifyType tq : thetaQs) { Set smaller = fc.smaller(unifier.apply(tq)); - smaller.stream().map(x -> new MPair(a, new SuperType(x), PairOperator.EQUALSDOT)) - .forEach(x -> result.add(x)); + + for(UnifyType thetaPrime : smaller) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new MPair(a, new SuperType(thetaPrime), PairOperator.EQUALSDOT)); + resultPrime.addAll(substitutionSet); + result.add(resultPrime); + } } } @@ -451,10 +515,14 @@ public class Unify { return result; } - protected Set unifyCase8(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { - Set result = new HashSet<>(); - for(UnifyType thetaS : fc.grArg(theta)) - result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + protected Set> unifyCase8(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { + Set> result = new HashSet<>(); + for(UnifyType thetaS : fc.grArg(theta)) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + result.add(resultPrime); + } + return result; } @@ -464,7 +532,7 @@ public class Unify { return result; } - private void permuteParams(ArrayList> candidates, int idx, Set result, UnifyType[] current) { + private void permuteParams(ArrayList> candidates, int idx, Set result, UnifyType[] current) { if(candidates.size() == idx) { result.add(new TypeParams(Arrays.copyOf(current, current.length))); return; @@ -476,5 +544,5 @@ public class Unify { current[idx] = t; permuteParams(candidates, idx+1, result, current); } - } + } } diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java deleted file mode 100644 index 34e5e161..00000000 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java +++ /dev/null @@ -1,503 +0,0 @@ -package de.dhbwstuttgart.typeinference.unifynew; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import de.dhbwstuttgart.typeinference.unify.GuavaSetOperations; -import de.dhbwstuttgart.typeinference.unify.MartelliMontanariUnify; -import de.dhbwstuttgart.typeinference.unify.RuleSet; -import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; -import de.dhbwstuttgart.typeinference.unify.interfaces.ISetOperations; -import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; -import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; -import de.dhbwstuttgart.typeinference.unify.model.MPair; -import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; -import de.dhbwstuttgart.typeinference.unify.model.SuperType; -import de.dhbwstuttgart.typeinference.unify.model.UnifyType; -import de.dhbwstuttgart.typeinference.unify.model.PairOperator; -import de.dhbwstuttgart.typeinference.unify.model.TypeParams; -import de.dhbwstuttgart.typeinference.unify.model.Unifier; - - -/** - * Implementation of the type unification algorithm - * @author Florian Steurer - */ -public class Unify { - - public Set> unify(Set eq, IFiniteClosure fc) { - /* - * Step 1: Repeated application of reduce, adapt, erase, swap - */ - - Set eq0 = applyTypeUnificationRules(eq, fc); - - /* - * Step 2 and 3: Create a subset eq1s of pairs where both sides are TPH and eq2s of the other pairs - */ - - Set eq1s = new HashSet<>(); - Set eq2s = new HashSet<>(); - splitEq(eq0, eq1s, eq2s); - - /* - * Step 4: Create possible typings - * - * "Manche Autoren identifizieren die Paare (a, (b,c)) und ((a,b),c) - * mit dem geordneten Tripel (a,b,c), wodurch das kartesische Produkt auch assoziativ wird." - Wikipedia - */ - - // There are up to 10 toplevel set. 8 of 10 are the result of the - // cartesian product of the sets created by pattern matching. - List>> topLevelSets = new ArrayList<>(); - - if(eq1s.size() != 0) { - Set> wrap = new HashSet<>(); - wrap.add(eq1s); - topLevelSets.add(wrap); // Add Eq1' - } - - // Add the set of [a =. Theta | (a=. Theta) in Eq2'] - Set bufferSet = eq2s.stream() - .filter(x -> x.getPairOp() == PairOperator.EQUALSDOT && x.getLhsType() instanceof PlaceholderType) - .collect(Collectors.toSet()); - - if(bufferSet.size() != 0) { - Set> wrap = new HashSet<>(); - wrap.add(bufferSet); - topLevelSets.add(wrap); - } - - // Sets that originate from pair pattern matching - // Sets of the "second level" - Set>> secondLevelSets = calculatePairSets(eq2s, fc); - - /* Up to here, no cartesian products are calculated. - * filters for pairs and sets can be applied here */ - - ISetOperations setOps = new GuavaSetOperations(); - - // Sub cartesian products of the second level (pattern matched) sets - for(Set> secondLevelSet : secondLevelSets) { - List> secondLevelSetList = new ArrayList<>(secondLevelSet); - topLevelSets.add(setOps.cartesianProduct(secondLevelSetList) - .stream().map(x -> new HashSet<>(x)) - .collect(Collectors.toCollection(HashSet::new))); - } - - // Cartesian product over all (up to 10) top level sets - Set>> eqPrimeSet = setOps.cartesianProduct(topLevelSets) - .stream().map(x -> new HashSet<>(x)) - .collect(Collectors.toCollection(HashSet::new)); - //System.out.println(result); - - /* - * Step 5: Substitution - */ - - /* - * TODO hier das ergebnis schonh flach machen? (wird im unify old (glaub ich) so gemacht) - */ - Set> eqPrimeSetFlat = new HashSet<>(); - for(Set> setToFlatten : eqPrimeSet) { - Set buffer = new HashSet<>(); - setToFlatten.stream().forEach(x -> buffer.addAll(x)); - eqPrimeSetFlat.add(buffer); - } - - IRuleSet rules = new RuleSet(fc); - Set> changed = new HashSet<>(); - Set> eqPrimePrimeSet = new HashSet<>(); - - for(Set eqPrime : eqPrimeSetFlat) { - Optional> eqPrimePrime = rules.subst(eqPrime); - - if(eqPrimePrime.isPresent()) - changed.add(eqPrimePrime.get()); - else - eqPrimePrimeSet.add(eqPrime); - } - - /* - * Step 6 a) Restart for pairs where subst was applied - * b) Build the union over everything - */ - - for(Set eqss : changed) - eqPrimePrimeSet.addAll(this.unify(eqss, fc)); - - /* - * Step 7: Filter empty sets; - */ - return eqPrimePrimeSet.stream().filter(x -> isSolvedForm(x)).collect(Collectors.toCollection(HashSet::new)); - - } - - protected boolean isSolvedForm(Set eqPrimePrime) { - for(MPair pair : eqPrimePrime) { - UnifyType lhsType = pair.getLhsType(); - UnifyType rhsType = pair.getRhsType(); - - if(!(lhsType instanceof PlaceholderType)) - return false; - - if(pair.getPairOp() != PairOperator.EQUALSDOT && !(rhsType instanceof PlaceholderType)) - return false; - } - - return true; - } - - protected Set applyTypeUnificationRules(Set eq, IFiniteClosure fc) { - - /* - * Rule Application Strategy: - * - * 1. Swap all pairs and erase all erasable pairs - * 2. Apply all possible rules to a single pair, then move it to the result set. - * Iterating over pairs first, then iterating over rules prevents the application - * of rules to a "finished" pair over and over. - * 2.1 Apply all rules repeatedly except for erase rules. If - * the application of a rule creates new pairs, check immediately - * against the erase rules. - */ - - - LinkedHashSet targetSet = new LinkedHashSet(); - LinkedList eqQueue = new LinkedList<>(); - IRuleSet rules = new RuleSet(fc); - - /* - * Swap all pairs and erase all erasable pairs - */ - eq.forEach(x -> swapAddOrErase(x, rules, eqQueue)); - - /* - * Apply rules until the queue is empty - */ - while(!eqQueue.isEmpty()) { - MPair pair = eqQueue.pollFirst(); - - // ReduceUp, ReduceLow, ReduceUpLow - Optional opt = rules.reduceUpLow(pair); - opt = opt.isPresent() ? opt : rules.reduceLow(pair); - opt = opt.isPresent() ? opt : rules.reduceUp(pair); - opt = opt.isPresent() ? opt : rules.reduceWildcardLow(pair); - opt = opt.isPresent() ? opt : rules.reduceWildcardLowRight(pair); - opt = opt.isPresent() ? opt : rules.reduceWildcardUp(pair); - opt = opt.isPresent() ? opt : rules.reduceWildcardUpRight(pair); - opt = opt.isPresent() ? opt : rules.reduceWildcardLowUp(pair); - opt = opt.isPresent() ? opt : rules.reduceWildcardUpLow(pair); - opt = opt.isPresent() ? opt : rules.reduceWildcardLeft(pair); - - // One of the rules has been applied - if(opt.isPresent()) { - swapAddOrErase(opt.get(), rules, eqQueue); - continue; - } - - // Reduce1, Reduce2, ReduceExt, ReduceSup, ReduceEq - Optional> optSet = rules.reduce1(pair); - optSet = optSet.isPresent() ? optSet : rules.reduce2(pair); - optSet = optSet.isPresent() ? optSet : rules.reduceExt(pair); - optSet = optSet.isPresent() ? optSet : rules.reduceSup(pair); - optSet = optSet.isPresent() ? optSet : rules.reduceEq(pair); - - // One of the rules has been applied - if(optSet.isPresent()) { - optSet.get().forEach(x -> swapAddOrErase(x, rules, eqQueue)); - continue; - } - - // Adapt, AdaptExt, AdaptSup - opt = rules.adapt(pair); - opt = opt.isPresent() ? opt : rules.adaptExt(pair); - opt = opt.isPresent() ? opt : rules.adaptSup(pair); - - // One of the rules has been applied - if(opt.isPresent()) { - swapAddOrErase(opt.get(), rules, eqQueue); - continue; - } - - // None of the rules has been applied - targetSet.add(pair); - } - - return targetSet; - } - - protected void swapAddOrErase(MPair pair, IRuleSet rules, Collection collection) { - Optional opt = rules.swap(pair); - MPair pair2 = opt.isPresent() ? opt.get() : pair; - - if(rules.erase1(pair2) || rules.erase3(pair2) || rules.erase2(pair2)) - return; - - collection.add(pair2); - } - - protected void splitEq(Set eq, Set eq1s, Set eq2s) { - for(MPair pair : eq) - if(pair.getLhsType() instanceof PlaceholderType && pair.getRhsType() instanceof PlaceholderType) - eq1s.add(pair); - else - eq2s.add(pair); - } - - - protected Set>> calculatePairSets(Set eq2s, IFiniteClosure fc) { - List>> result = new ArrayList<>(); - - // Init all 8 cases - for(int i = 0; i < 8; i++) - result.add(new HashSet<>()); - - for(MPair pair : eq2s) { - - PairOperator pairOp = pair.getPairOp(); - UnifyType lhsType = pair.getLhsType(); - UnifyType rhsType = pair.getRhsType(); - - // Case 1: (a <. Theta') - if(pairOp == PairOperator.SMALLERDOT && lhsType instanceof PlaceholderType) - result.get(0).add(unifyCase1((PlaceholderType) pair.getLhsType(), pair.getRhsType(), fc)); - - // Case 2: (a <.? ? ext Theta') - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof ExtendsType) - result.get(1).add(unifyCase2((PlaceholderType) pair.getLhsType(), (ExtendsType) pair.getRhsType(), fc)); - - // Case 3: (a <.? ? sup Theta') - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof SuperType) - result.get(2).add(unifyCase3((PlaceholderType) lhsType, (SuperType) rhsType, fc)); - - // Case 4: (a <.? Theta') - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType) - result.get(3).add(unifyCase4((PlaceholderType) lhsType, rhsType, fc)); - - // Case 5: (Theta <. a) - else if(pairOp == PairOperator.SMALLERDOT && rhsType instanceof PlaceholderType) - result.get(4).add(unifyCase5(lhsType, (PlaceholderType) rhsType, fc)); - - // Case 6: (? ext Theta <.? a) - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof ExtendsType && rhsType instanceof PlaceholderType) - result.get(5).add(unifyCase6((ExtendsType) lhsType, (PlaceholderType) rhsType, fc)); - - // Case 7: (? sup Theta <.? a) - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof SuperType && rhsType instanceof PlaceholderType) - result.get(6).add(unifyCase7((SuperType) lhsType, (PlaceholderType) rhsType, fc)); - - // Case 8: (Theta <.? a) - else if(pairOp == PairOperator.SMALLERDOTWC && rhsType instanceof PlaceholderType) - result.get(7).add(unifyCase8(lhsType, (PlaceholderType) rhsType, fc)); - } - - return result.stream().map(x -> x.stream().filter(y -> y.size() > 0).collect(Collectors.toCollection(HashSet::new))) - .filter(x -> x.size() > 0).collect(Collectors.toCollection(HashSet::new)); - } - - protected Set unifyCase1(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { - Set result = new HashSet<>(); - IUnify unify = new MartelliMontanariUnify(); - - Set cs = fc.getAllTypesByName(thetaPrime.getName()); - - for(UnifyType c : cs) { - - // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.getChildren(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); - thetaQs.add(c); // reflexive - - Set thetaQPrimes = new HashSet<>(); - TypeParams cParams = c.getTypeParams(); - if(cParams.size() == 0) - thetaQPrimes.add(c); - else { - ArrayList> candidateParams = new ArrayList<>(); - for(UnifyType param : cParams) - candidateParams.add(fc.grArg(param)); - - for(TypeParams tp : permuteParams(candidateParams)) - thetaQPrimes.add(c.setTypeParams(tp)); - } - - for(UnifyType tqp : thetaQPrimes) { - Optional opt = unify.unify(tqp, thetaPrime); - if (!opt.isPresent()) - continue; - - Unifier unifier = opt.get(); - Set> substitutions = unifier.getSubstitutions(); - for (Entry sigma : substitutions) - result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); - for (UnifyType tq : thetaQs) { - Set smaller = fc.smaller(unifier.apply(tq)); - smaller.stream().map(x -> new MPair(a, x, PairOperator.EQUALSDOT)) - .forEach(x -> result.add(x)); - } - - } - } - - return result; - } - - protected Set unifyCase2(PlaceholderType a, ExtendsType extThetaPrime, IFiniteClosure fc) { - Set result = new HashSet<>(); - IUnify unify = new MartelliMontanariUnify(); - - UnifyType thetaPrime = extThetaPrime.getExtendedType(); - Set cs = fc.getAllTypesByName(thetaPrime.getName()); - - for(UnifyType c : cs) { - - // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.getChildren(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); - thetaQs.add(c); // reflexive - - Set thetaQPrimes = new HashSet<>(); - TypeParams cParams = c.getTypeParams(); - if(cParams.size() == 0) - thetaQPrimes.add(c); - else { - ArrayList> candidateParams = new ArrayList<>(); - for(UnifyType param : cParams) - candidateParams.add(fc.grArg(param)); - - for(TypeParams tp : permuteParams(candidateParams)) - thetaQPrimes.add(c.setTypeParams(tp)); - } - - for(UnifyType tqp : thetaQPrimes) { - Optional opt = unify.unify(tqp, thetaPrime); - if (!opt.isPresent()) - continue; - - Unifier unifier = opt.get(); - Set> substitutions = unifier.getSubstitutions(); - for (Entry sigma : substitutions) - result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); - for (UnifyType tq : thetaQs) { - ExtendsType extTq = new ExtendsType(tq); - Set smaller = fc.smaller(unifier.apply(extTq)); - smaller.stream().map(x -> new MPair(a, x, PairOperator.EQUALSDOT)) - .forEach(x -> result.add(x)); - } - - } - } - - return result; - } - - protected Set unifyCase3(PlaceholderType a, SuperType subThetaPrime, IFiniteClosure fc) { - Set result = new HashSet<>(); - for(UnifyType theta : fc.smArg(subThetaPrime)) - result.add(new MPair(a, theta, PairOperator.EQUALSDOT)); - return result; - } - - protected Set unifyCase4(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { - Set result = new HashSet<>(); - result.add(new MPair(a, thetaPrime, PairOperator.EQUALSDOT)); - return result; - } - - protected Set unifyCase5(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { - Set result = new HashSet<>(); - for(UnifyType thetaS : fc.greater(theta)) - result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); - return result; - } - - protected Set unifyCase6(ExtendsType extTheta, PlaceholderType a, IFiniteClosure fc) { - Set result = new HashSet<>(); - for(UnifyType thetaS : fc.grArg(extTheta)) - result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); - return result; - } - - protected Set unifyCase7(SuperType supTheta, PlaceholderType a, IFiniteClosure fc) { - Set result = new HashSet<>(); - IUnify unify = new MartelliMontanariUnify(); - - UnifyType theta = supTheta.getSuperedType(); - Set cs = fc.getAllTypesByName(theta.getName()); - - for(UnifyType c : cs) { - - // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.getChildren(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); - thetaQs.add(c); // reflexive - - Set thetaQPrimes = new HashSet<>(); - TypeParams cParams = c.getTypeParams(); - if(cParams.size() == 0) - thetaQPrimes.add(c); - else { - ArrayList> candidateParams = new ArrayList<>(); - for(UnifyType param : cParams) - candidateParams.add(fc.grArg(param)); - - for(TypeParams tp : permuteParams(candidateParams)) - thetaQPrimes.add(c.setTypeParams(tp)); - } - - for(UnifyType tqp : thetaQPrimes) { - Optional opt = unify.unify(tqp, theta); - if (!opt.isPresent()) - continue; - - Unifier unifier = opt.get(); - Set> substitutions = unifier.getSubstitutions(); - for (Entry sigma : substitutions) - result.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); - for (UnifyType tq : thetaQs) { - Set smaller = fc.smaller(unifier.apply(tq)); - smaller.stream().map(x -> new MPair(a, new SuperType(x), PairOperator.EQUALSDOT)) - .forEach(x -> result.add(x)); - } - - } - } - - return result; - } - - protected Set unifyCase8(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { - Set result = new HashSet<>(); - for(UnifyType thetaS : fc.grArg(theta)) - result.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); - return result; - } - - protected Set permuteParams(ArrayList> candidates) { - Set result = new HashSet<>(); - permuteParams(candidates, 0, result, new UnifyType[candidates.size()]); - return result; - } - - private void permuteParams(ArrayList> candidates, int idx, Set result, UnifyType[] current) { - if(candidates.size() == idx) { - result.add(new TypeParams(Arrays.copyOf(current, current.length))); - return; - } - - Set localCandidates = candidates.get(idx); - - for(UnifyType t : localCandidates) { - current[idx] = t; - permuteParams(candidates, idx+1, result, current); - } - } -} diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 05677dbc..d5172970 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -174,6 +174,30 @@ public class UnifyTest extends Unify { Assert.assertEquals(expected, actual); + /* + * Test 8: + * + * (a <.? ? extends Number) + */ + + UnifyType extInteger = tf.getExtendsType(integer); + UnifyType extDouble = tf.getExtendsType(doubl); + + eq = new HashSet<>(); + eq.add(new MPair(tphA, extNumber, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new MPair(tphA, extNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, extInteger, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, extDouble, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, doubl, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, integer, PairOperator.EQUALSDOT)); + addAsSet(expected, new MPair(tphA, number, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + /* * Test 8: * @@ -187,7 +211,7 @@ public class UnifyTest extends Unify { actual = unify(eq, fc); - Assert.assertEquals(expected, actual); + //Assert.assertEquals(expected, actual); /* * Test 9: @@ -202,7 +226,7 @@ public class UnifyTest extends Unify { actual = unify(eq, fc); - Assert.assertEquals(expected, actual); + //Assert.assertEquals(expected, actual); /* * Test 10: @@ -280,6 +304,26 @@ public class UnifyTest extends Unify { System.out.println(actual); //Assert.assertEquals(actual, expected); + /* + * Test 8: + * + * (a <.? ? sup b) + * (b = Number) + */ + + UnifyType supB = tf.getSuperType(tphB); + eq = new HashSet<>(); + eq.add(new MPair(tphA, supB, PairOperator.SMALLERDOTWC)); + eq.add(new MPair(tphB, number, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(expected, actual); + + /* * Test 2: * From 6c2d71d005f4031a8c52d101711235fc55a4c701 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Sun, 3 Apr 2016 17:36:44 +0200 Subject: [PATCH 32/57] random with seed --- .../typeinference/unify/model/PlaceholderType.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java index 55da2325..aa401b8a 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java @@ -11,6 +11,7 @@ public final class PlaceholderType extends UnifyType{ protected static final HashSet EXISTING_PLACEHOLDERS = new HashSet(); protected static String nextName = "gen_"; + protected static Random rnd = new Random(43558747548978L); public PlaceholderType(String name) { super(name); @@ -30,7 +31,7 @@ public final class PlaceholderType extends UnifyType{ * Returns random char between 'a' and 'z' */ private static char randomChar() { - return (char) (new Random().nextInt(22) + 97); + return (char) (rnd.nextInt(22) + 97); } @Override From 20d1106e07523ace6966e7fa170673ebed1e95bd Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Sun, 3 Apr 2016 22:43:55 +0200 Subject: [PATCH 33/57] refactored Types // --- .../syntaxtree/factory/UnifyTypeFactory.java | 12 +-- .../typeinference/unify/RuleSet.java | 83 +++++++++--------- .../typeinference/unify/Unify.java | 41 ++++++--- .../unify/interfaces/IFiniteClosure.java | 6 +- .../unify/model/ExtendsType.java | 34 ++++---- .../unify/model/FiniteClosure.java | 4 +- .../unify/model/PlaceholderType.java | 15 +++- .../{SimpleType.java => ReferenceType.java} | 14 ++-- .../typeinference/unify/model/SuperType.java | 27 +++--- test/unify/RuleSetTest.java | 84 +++++++++---------- test/unify/StandardUnifyTest.java | 1 - test/unify/TypeFactory.java | 14 ++-- test/unify/UnifyTest.java | 36 ++++++-- test/unify/UnifyTypeFactoryTest.java | 8 +- 14 files changed, 216 insertions(+), 163 deletions(-) rename src/de/dhbwstuttgart/typeinference/unify/model/{SimpleType.java => ReferenceType.java} (64%) diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 193c8589..df903209 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -32,7 +32,7 @@ import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; -import de.dhbwstuttgart.typeinference.unify.model.SimpleType; +import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; @@ -82,9 +82,9 @@ public class UnifyTypeFactory { for(Type pT : t.getParaList()){ params.add(UnifyTypeFactory.convert(pT)); } - ret = new SimpleType(t.get_Name(),new TypeParams(params)); + ret = new ReferenceType(t.get_Name(),new TypeParams(params)); }else{ - ret = new SimpleType(t.get_Name()); + ret = new ReferenceType(t.get_Name()); } return ret; } @@ -102,7 +102,7 @@ public class UnifyTypeFactory { } public static UnifyType convert(GenericTypeVar t){ - return new SimpleType(t.get_Name()); + return new ReferenceType(t.get_Name()); } public static UnifyConstraintsSet convert(ConstraintsSet constraints) { @@ -146,7 +146,7 @@ public class UnifyTypeFactory { return new Pair(tl, tr, mp.getPairOp()); } - public static Type convert(SimpleType t) { + public static Type convert(ReferenceType t) { return new RefType(t.getName(),null,0); } @@ -165,7 +165,7 @@ public class UnifyTypeFactory { } public static Type convert(UnifyType t) { - if(t instanceof SimpleType)return convert((SimpleType) t); + if(t instanceof ReferenceType)return convert((ReferenceType) t); if(t instanceof SuperType)return convert((SuperType) t); if(t instanceof ExtendsType)return convert((ExtendsType) t); if(t instanceof PlaceholderType)return convert((PlaceholderType) t); diff --git a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java index 30150cd3..d0710675 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -4,7 +4,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; -import java.util.List; import java.util.Optional; import java.util.Queue; import java.util.Set; @@ -18,9 +17,10 @@ import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; import de.dhbwstuttgart.typeinference.unify.model.FunNType; import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; -import de.dhbwstuttgart.typeinference.unify.model.SimpleType; +import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; +import de.dhbwstuttgart.typeinference.unify.model.WildcardType; import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.Unifier; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; @@ -43,7 +43,7 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); UnifyType lhsType = pair.getLhsType(); - if(!(lhsType instanceof SimpleType) && !(lhsType instanceof PlaceholderType)) + if(!(lhsType instanceof ReferenceType) && !(lhsType instanceof PlaceholderType)) return Optional.empty(); return Optional.of(new MPair(lhsType, ((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT)); @@ -59,7 +59,7 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); UnifyType rhsType = pair.getRhsType(); - if(!(rhsType instanceof SimpleType) && !(rhsType instanceof PlaceholderType)) + if(!(rhsType instanceof ReferenceType) && !(rhsType instanceof PlaceholderType)) return Optional.empty(); return Optional.of(new MPair(((ExtendsType) lhsType).getExtendedType(), rhsType, PairOperator.SMALLERDOT)); @@ -89,7 +89,7 @@ public class RuleSet implements IRuleSet{ UnifyType x = pair.getLhsType(); UnifyType sTypeX; - if(x instanceof SimpleType) + if(x instanceof ReferenceType) sTypeX = x; else if(x instanceof ExtendsType) sTypeX = ((ExtendsType) x).getExtendedType(); @@ -141,7 +141,7 @@ public class RuleSet implements IRuleSet{ UnifyType x = pair.getLhsType(); UnifyType sTypeX; - if(x instanceof SimpleType) + if(x instanceof ReferenceType) sTypeX = x; else if(x instanceof SuperType) sTypeX = ((SuperType) x).getSuperedType(); @@ -221,15 +221,15 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); UnifyType c = pair.getLhsType(); - if(!(c instanceof SimpleType)) + if(!(c instanceof ReferenceType)) return Optional.empty(); UnifyType d = pair.getRhsType(); - if(!(d instanceof SimpleType)) + if(!(d instanceof ReferenceType)) return Optional.empty(); - SimpleType lhsSType = (SimpleType) c; - SimpleType rhsSType = (SimpleType) d; + ReferenceType lhsSType = (ReferenceType) c; + ReferenceType rhsSType = (ReferenceType) d; if(lhsSType.getTypeParams().empty() || lhsSType.getTypeParams().size() != rhsSType.getTypeParams().size()) return Optional.empty(); @@ -265,14 +265,17 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); UnifyType lhsType = pair.getLhsType(); - SimpleType lhsSType; + ReferenceType lhsSType; - if(lhsType instanceof SimpleType) - lhsSType = (SimpleType) lhsType; - else if(lhsType instanceof ExtendsType) - lhsSType = (SimpleType) ((ExtendsType) lhsType).getExtendedType(); - else if(lhsType instanceof SuperType) - lhsSType = (SimpleType) ((SuperType) lhsType).getSuperedType(); + if(lhsType instanceof ReferenceType) + lhsSType = (ReferenceType) lhsType; + else if(lhsType instanceof WildcardType) { + UnifyType lhsSTypeRaw = ((WildcardType) lhsType).getWildcardedType(); + if(lhsSTypeRaw instanceof ReferenceType) + lhsSType = (ReferenceType) lhsSTypeRaw; + else + return Optional.empty(); + } else return Optional.empty(); @@ -280,14 +283,17 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); UnifyType rhsType = pair.getLhsType(); - SimpleType rhsSType; + ReferenceType rhsSType; - if(rhsType instanceof SimpleType) - rhsSType = (SimpleType) rhsType; - else if(rhsType instanceof ExtendsType) - rhsSType = (SimpleType) ((ExtendsType) rhsType).getExtendedType(); - else if(rhsType instanceof SuperType) - rhsSType = (SimpleType) ((SuperType) rhsType).getSuperedType(); + if(rhsType instanceof ReferenceType) + rhsSType = (ReferenceType) rhsType; + else if(rhsType instanceof WildcardType) { + UnifyType rhsSTypeRaw = ((WildcardType) rhsType).getWildcardedType(); + if(rhsSTypeRaw instanceof ReferenceType) + rhsSType = (ReferenceType) rhsSTypeRaw; + else + return Optional.empty(); + } else return Optional.empty(); @@ -314,11 +320,11 @@ public class RuleSet implements IRuleSet{ return false; UnifyType lhsType = pair.getLhsType(); - if(!(lhsType instanceof SimpleType) && !(lhsType instanceof PlaceholderType)) + if(!(lhsType instanceof ReferenceType) && !(lhsType instanceof PlaceholderType)) return false; UnifyType rhsType = pair.getRhsType(); - if(!(rhsType instanceof SimpleType) && !(rhsType instanceof PlaceholderType)) + if(!(rhsType instanceof ReferenceType) && !(rhsType instanceof PlaceholderType)) return false; return finiteClosure.greater(lhsType).contains(rhsType); @@ -363,11 +369,11 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); UnifyType typeD = pair.getLhsType(); - if(!(typeD instanceof SimpleType)) + if(!(typeD instanceof ReferenceType)) return Optional.empty(); UnifyType typeDs = pair.getRhsType(); - if(!(typeDs instanceof SimpleType)) + if(!(typeDs instanceof ReferenceType)) return Optional.empty(); if(typeD.getTypeParams().size() == 0 || typeDs.getTypeParams().size() == 0) @@ -409,7 +415,7 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); UnifyType typeD = pair.getLhsType(); - if(!(typeD instanceof SimpleType) && !(typeD instanceof ExtendsType)) + if(!(typeD instanceof ReferenceType) && !(typeD instanceof ExtendsType)) return Optional.empty(); UnifyType typeExtDs = pair.getRhsType(); @@ -420,7 +426,7 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); UnifyType typeDgen; - if(typeD instanceof SimpleType) + if(typeD instanceof ReferenceType) typeDgen = finiteClosure.getLeftHandedType(typeD).orElse(null); else { Optional opt = finiteClosure.getLeftHandedType(((ExtendsType) typeD).getExtendedType()); @@ -455,7 +461,7 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); UnifyType typeDs = pair.getLhsType(); - if(!(typeDs instanceof SimpleType) && !(typeDs instanceof SuperType)) + if(!(typeDs instanceof ReferenceType) && !(typeDs instanceof SuperType)) return Optional.empty(); UnifyType typeSupD = pair.getRhsType(); @@ -484,7 +490,7 @@ public class RuleSet implements IRuleSet{ // New RHS UnifyType newRhs = null; - if(typeDs instanceof SimpleType) + if(typeDs instanceof ReferenceType) newRhs = new ExtendsType(typeDs); else newRhs = new ExtendsType(((SuperType) typeDs).getSuperedType()); @@ -600,7 +606,7 @@ public class RuleSet implements IRuleSet{ UnifyType lhsType = pair.getLhsType(); UnifyType rhsType = pair.getRhsType(); - if(!(lhsType instanceof SimpleType) || !(rhsType instanceof ExtendsType)) + if(!(lhsType instanceof ReferenceType) || !(rhsType instanceof ExtendsType)) return Optional.empty(); return Optional.of(new MPair(lhsType, ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT)); @@ -626,7 +632,7 @@ public class RuleSet implements IRuleSet{ UnifyType lhsType = pair.getLhsType(); UnifyType rhsType = pair.getRhsType(); - if(!(lhsType instanceof SimpleType) || !(rhsType instanceof SuperType)) + if(!(lhsType instanceof ReferenceType) || !(rhsType instanceof SuperType)) return Optional.empty(); return Optional.of(new MPair(((SuperType) rhsType).getSuperedType(), lhsType, PairOperator.SMALLERDOTWC)); @@ -664,16 +670,13 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); UnifyType rhsType = pair.getRhsType(); - if(!(rhsType instanceof SimpleType)) + if(!(rhsType instanceof ReferenceType)) return Optional.empty(); UnifyType lhsType = pair.getLhsType(); - if(lhsType instanceof SuperType) - return Optional.of(new MPair(((SuperType) lhsType).getSuperedType(), rhsType, PairOperator.EQUALSDOT)); - - if(lhsType instanceof ExtendsType) - return Optional.of(new MPair(((ExtendsType) lhsType).getExtendedType(), rhsType, PairOperator.EQUALSDOT)); + if(lhsType instanceof WildcardType) + return Optional.of(new MPair(((WildcardType) lhsType).getWildcardedType(), rhsType, PairOperator.EQUALSDOT)); return Optional.empty(); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unify.java b/src/de/dhbwstuttgart/typeinference/unify/Unify.java index b4fb7bb9..d781a2a4 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unify.java @@ -73,11 +73,18 @@ public class Unify { Set> wrap = new HashSet<>(); wrap.add(bufferSet); topLevelSets.add(wrap); + eq2s.removeAll(bufferSet); } // Sets that originate from pair pattern matching // Sets of the "second level" - Set>>> secondLevelSets = calculatePairSets(eq2s, fc); + Set undefinedPairs = new HashSet<>(); + Set>>> secondLevelSets = calculatePairSets(eq2s, fc, undefinedPairs); + + // If pairs occured that did not match one of the cartesian product cases, + // those pairs are contradictory and the unification is impossible. + if(!undefinedPairs.isEmpty()) + return new HashSet<>(); /* Up to here, no cartesian products are calculated. * filters for pairs and sets can be applied here */ @@ -104,9 +111,6 @@ public class Unify { * Step 5: Substitution */ - /* - * TODO hier das ergebnis schonh flach machen? (wird im unify old (glaub ich) so gemacht) - */ Set> eqPrimeSetFlat = new HashSet<>(); for(Set> setToFlatten : eqPrimeSet) { Set buffer = new HashSet<>(); @@ -121,10 +125,16 @@ public class Unify { for(Set eqPrime : eqPrimeSetFlat) { Optional> eqPrimePrime = rules.subst(eqPrime); - if(eqPrimePrime.isPresent()) + if(eqPrime.equals(eq)) + eqPrimePrimeSet.add(eqPrime); + else if(eqPrimePrime.isPresent()) + eqPrimePrimeSet.addAll(this.unify(eqPrimePrime.get(), fc)); + else + eqPrimePrimeSet.addAll(this.unify(eqPrime, fc)); + /*if(eqPrimePrime.isPresent()) changed.add(eqPrimePrime.get()); else - eqPrimePrimeSet.add(eqPrime); + eqPrimePrimeSet.add(eqPrime);*/ } /* @@ -255,9 +265,9 @@ public class Unify { } - protected Set>>> calculatePairSets(Set eq2s, IFiniteClosure fc) { + protected Set>>> calculatePairSets(Set eq2s, IFiniteClosure fc, Set undefined) { List>>> result = new ArrayList<>(); - + // Init all 8 cases for(int i = 0; i < 8; i++) result.add(new HashSet<>()); @@ -299,6 +309,12 @@ public class Unify { // Case 8: (Theta <.? a) else if(pairOp == PairOperator.SMALLERDOTWC && rhsType instanceof PlaceholderType) result.get(7).add(unifyCase8(lhsType, (PlaceholderType) rhsType, fc)); + // Case unknown: If a pair fits no other case, then the type unification has failed. + // Through application of the rules, every pair should have one of the above forms. + // Pairs that do not have one of the aboves form are contradictory. + else + undefined.add(pair); + } return result.stream().map(x -> x.stream().filter(y -> y.size() > 0).collect(Collectors.toCollection(HashSet::new))) @@ -415,17 +431,18 @@ public class Unify { UnifyType aPrime = PlaceholderType.freshPlaceholder(); UnifyType supAPrime = new SuperType(aPrime); - for(UnifyType theta : fc.smArg(subThetaPrime)) { + UnifyType thetaPrime = subThetaPrime.getSuperedType(); + //for(UnifyType theta : fc.smArg(subThetaPrime)) { Set resultPrime = new HashSet<>(); resultPrime.add(new MPair(a, aPrime, PairOperator.EQUALSDOT)); - resultPrime.add(new MPair(aPrime,theta, PairOperator.SMALLERDOT)); + resultPrime.add(new MPair(thetaPrime, aPrime, PairOperator.SMALLERDOT)); result.add(resultPrime); resultPrime = new HashSet<>(); resultPrime.add(new MPair(a, supAPrime, PairOperator.EQUALSDOT)); - resultPrime.add(new MPair(supAPrime,theta, PairOperator.SMALLERDOT)); + resultPrime.add(new MPair(thetaPrime, aPrime, PairOperator.SMALLERDOT)); result.add(resultPrime); - } + //} return result; } diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java index 06e12a36..bd15999a 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java @@ -6,7 +6,7 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; import de.dhbwstuttgart.typeinference.unify.model.FunNType; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; -import de.dhbwstuttgart.typeinference.unify.model.SimpleType; +import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; @@ -38,8 +38,8 @@ public interface IFiniteClosure { */ public Set smArg(UnifyType type); - public Set grArg(SimpleType type); - public Set smArg(SimpleType type); + public Set grArg(ReferenceType type); + public Set smArg(ReferenceType type); public Set grArg(ExtendsType type); public Set smArg(ExtendsType type); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java b/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java index f4a79794..847abfd5 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java @@ -7,38 +7,28 @@ import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; /** * An extends wildcard type "? extends T". */ -public final class ExtendsType extends UnifyType { - - /** - * The extended type - */ - private UnifyType extendedType; +public final class ExtendsType extends WildcardType { /** * Creates a new extends wildcard type. * @param extendedType The extended type e.g. Integer in "? extends Integer" */ public ExtendsType(UnifyType extendedType) { - super("? extends " + extendedType.getName(), extendedType.getTypeParams()); - this.extendedType = extendedType; + super("? extends " + extendedType.getName(), extendedType, extendedType.getTypeParams()); } - - /** - * Gets the type extended by this wildcard e.g. "Integer" for "? extends Integer" - * @return The extended type. - */ + public UnifyType getExtendedType() { - return extendedType; + return wildcardedType; } @Override public TypeParams getTypeParams() { - return extendedType.getTypeParams(); + return wildcardedType.getTypeParams(); } @Override public UnifyType setTypeParams(TypeParams newTp) { - return new ExtendsType(extendedType.setTypeParams(newTp)); + return new ExtendsType(wildcardedType.setTypeParams(newTp)); } @Override @@ -53,12 +43,16 @@ public final class ExtendsType extends UnifyType { @Override UnifyType apply(Unifier unif) { - return new ExtendsType(extendedType.apply(unif)); + return new ExtendsType(wildcardedType.apply(unif)); } @Override public int hashCode() { - return extendedType.hashCode() + 17; + /* + * It is important that the prime that is added is different to the prime added in hashCode() of SuperType. + * Otherwise ? extends T and ? super T have the same hashCode() for every Type T. + */ + return wildcardedType.hashCode() + 229; } @Override @@ -67,12 +61,12 @@ public final class ExtendsType extends UnifyType { return false; ExtendsType other = (ExtendsType) obj; - return other.getExtendedType().equals(extendedType); + return other.getWildcardedType().equals(wildcardedType); } @Override public String toString() { - return "? extends " + extendedType; + return "? extends " + wildcardedType; } } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index a4c5a51d..5ef8c93a 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -214,7 +214,7 @@ public class FiniteClosure implements IFiniteClosure { } @Override - public Set grArg(SimpleType type) { + public Set grArg(ReferenceType type) { Set result = new HashSet(); result.add(type); @@ -268,7 +268,7 @@ public class FiniteClosure implements IFiniteClosure { } @Override - public Set smArg(SimpleType type) { + public Set smArg(ReferenceType type) { Set result = new HashSet(); result.add(type); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java index aa401b8a..f45a4a13 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java @@ -13,9 +13,18 @@ public final class PlaceholderType extends UnifyType{ protected static String nextName = "gen_"; protected static Random rnd = new Random(43558747548978L); + private final boolean IsGenerated; + public PlaceholderType(String name) { super(name); EXISTING_PLACEHOLDERS.add(name); + IsGenerated = false; + } + + protected PlaceholderType(String name, boolean isGenerated) { + super(name); + EXISTING_PLACEHOLDERS.add(name); + IsGenerated = isGenerated; } public static PlaceholderType freshPlaceholder() { @@ -24,7 +33,7 @@ public final class PlaceholderType extends UnifyType{ while(EXISTING_PLACEHOLDERS.contains(name)); nextName += randomChar(); - return new PlaceholderType(name); + return new PlaceholderType(name, true); } /** @@ -33,6 +42,10 @@ public final class PlaceholderType extends UnifyType{ private static char randomChar() { return (char) (rnd.nextInt(22) + 97); } + + public boolean isGenerated() { + return IsGenerated; + } @Override Set smArg(IFiniteClosure fc) { diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java b/src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java similarity index 64% rename from src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java rename to src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java index 62d3ca1c..fd5a0ec1 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java @@ -4,12 +4,12 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -public final class SimpleType extends UnifyType { - public SimpleType(String name, UnifyType... typeParams) { +public final class ReferenceType extends UnifyType { + public ReferenceType(String name, UnifyType... typeParams) { super(name, new TypeParams(typeParams)); } - public SimpleType(String name, TypeParams params) { + public ReferenceType(String name, TypeParams params) { super(name, params); } @@ -25,12 +25,12 @@ public final class SimpleType extends UnifyType { @Override UnifyType apply(Unifier unif) { - return new SimpleType(typeName, typeParams.apply(unif)); + return new ReferenceType(typeName, typeParams.apply(unif)); } @Override public UnifyType setTypeParams(TypeParams newTp) { - return new SimpleType(new String(typeName), newTp); + return new ReferenceType(new String(typeName), newTp); } @Override @@ -40,10 +40,10 @@ public final class SimpleType extends UnifyType { @Override public boolean equals(Object obj) { - if(!(obj instanceof SimpleType)) + if(!(obj instanceof ReferenceType)) return false; - SimpleType other = (SimpleType) obj; + ReferenceType other = (ReferenceType) obj; if(!other.getName().equals(typeName)) return false; diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java b/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java index 48ed2891..51f640c9 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java @@ -4,32 +4,30 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -public final class SuperType extends UnifyType { - - private UnifyType superedType; +public final class SuperType extends WildcardType { + public SuperType(UnifyType superedType) { - super("? super " + superedType.getName(), superedType.getTypeParams()); - this.superedType = superedType; + super("? super " + superedType.getName(), superedType, superedType.getTypeParams()); } public UnifyType getSuperedType() { - return superedType; + return wildcardedType; } @Override public String toString() { - return "? super " + superedType; + return "? super " + wildcardedType; } @Override public TypeParams getTypeParams() { - return superedType.getTypeParams(); + return wildcardedType.getTypeParams(); } @Override public UnifyType setTypeParams(TypeParams newTp) { - return new SuperType(superedType.setTypeParams(newTp)); + return new SuperType(wildcardedType.setTypeParams(newTp)); } @Override @@ -44,12 +42,16 @@ public final class SuperType extends UnifyType { @Override UnifyType apply(Unifier unif) { - return new SuperType(superedType.apply(unif)); + return new SuperType(wildcardedType.apply(unif)); } @Override public int hashCode() { - return superedType.hashCode() + 17; + /* + * It is important that the prime that is added is different to the prime added in hashCode() of ExtendsType. + * Otherwise ? extends T and ? super T have the same hashCode() for every Type T. + */ + return wildcardedType.hashCode() + 3917; } @Override @@ -58,7 +60,6 @@ public final class SuperType extends UnifyType { return false; SuperType other = (SuperType) obj; - return other.getSuperedType().equals(superedType); + return other.getSuperedType().equals(wildcardedType); } - } diff --git a/test/unify/RuleSetTest.java b/test/unify/RuleSetTest.java index 0ae1d49c..dad10d5d 100644 --- a/test/unify/RuleSetTest.java +++ b/test/unify/RuleSetTest.java @@ -12,7 +12,7 @@ import de.dhbwstuttgart.typeinference.unify.RuleSet; import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; import de.dhbwstuttgart.typeinference.unify.model.MPair; -import de.dhbwstuttgart.typeinference.unify.model.SimpleType; +import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; @@ -139,15 +139,15 @@ public class RuleSetTest { */ // C - SimpleType c1 = tf.getSimpleType("C", "T1", "T2", "T3", "T4"); + ReferenceType c1 = tf.getSimpleType("C", "T1", "T2", "T3", "T4"); // D - SimpleType d1 = tf.getSimpleType("D", "T4", "T1", "T2", "T3"); - SimpleType buffer = tf.getSimpleType("Buffer"); + ReferenceType d1 = tf.getSimpleType("D", "T4", "T1", "T2", "T3"); + ReferenceType buffer = tf.getSimpleType("Buffer"); //C - SimpleType c2 = tf.getSimpleType("C", tf.getSimpleType("Int"), tf.getExtendsType(tf.getSimpleType("Double")), tf.getPlaceholderType("M"), tf.getPlaceholderType("N")); + ReferenceType c2 = tf.getSimpleType("C", tf.getSimpleType("Int"), tf.getExtendsType(tf.getSimpleType("Double")), tf.getPlaceholderType("M"), tf.getPlaceholderType("N")); //D, Number, Double, N> - SimpleType d2 = tf.getSimpleType("D", tf.getSuperType(tf.getSimpleType("HashSet", "Int")), tf.getSimpleType("Number"), tf.getSimpleType("Double"), tf.getPlaceholderType("N")); + ReferenceType d2 = tf.getSimpleType("D", tf.getSuperType(tf.getSimpleType("HashSet", "Int")), tf.getSimpleType("Number"), tf.getSimpleType("Double"), tf.getPlaceholderType("N")); // C<...> < buffer < D<...> fcb.add(c1, buffer); @@ -195,9 +195,9 @@ public class RuleSetTest { System.out.println("----- Reduce2 ------"); // C - SimpleType c1 = tf.getSimpleType("C", tf.getPlaceholderType("T1"), tf.getSimpleType("SType1"), tf.getExtendsType(tf.getSimpleType("SType1"))); + ReferenceType c1 = tf.getSimpleType("C", tf.getPlaceholderType("T1"), tf.getSimpleType("SType1"), tf.getExtendsType(tf.getSimpleType("SType1"))); // C - SimpleType c2 = tf.getSimpleType("C", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); + ReferenceType c2 = tf.getSimpleType("C", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); MPair pair1 = new MPair(c1, c2, PairOperator.EQUALSDOT); MPair pair2 = new MPair(tf.getExtendsType(c1), tf.getExtendsType(c2), PairOperator.EQUALSDOT); @@ -217,7 +217,7 @@ public class RuleSetTest { * Negative Tests */ - SimpleType d1 = tf.getSimpleType("D", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); + ReferenceType d1 = tf.getSimpleType("D", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); pair1 = new MPair(d1, c1, PairOperator.EQUALSDOT); // Case 1: D =. C pair2 = new MPair(tf.getExtendsType(c1), c2, PairOperator.EQUALSDOT); // Case 2: ? extends C =. C pair3 = new MPair(tf.getExtendsType(c1), tf.getSuperType(c2), PairOperator.EQUALSDOT); // Case 3: ? extends C =. ? super C @@ -239,13 +239,13 @@ public class RuleSetTest { */ // X - SimpleType x1 = tf.getSimpleType("X", "T1", "T2", "T3", "T4"); + ReferenceType x1 = tf.getSimpleType("X", "T1", "T2", "T3", "T4"); // Y - SimpleType y1 = tf.getSimpleType("Y", "T4", "T1", "T2", "T3"); - SimpleType buffer = tf.getSimpleType("Buffer"); + ReferenceType y1 = tf.getSimpleType("Y", "T4", "T1", "T2", "T3"); + ReferenceType buffer = tf.getSimpleType("Buffer"); //X - SimpleType x2 = tf.getSimpleType("X", tf.getSimpleType("Int"), tf.getExtendsType(tf.getSimpleType("Double")), tf.getPlaceholderType("M"), tf.getPlaceholderType("N")); + ReferenceType x2 = tf.getSimpleType("X", tf.getSimpleType("Int"), tf.getExtendsType(tf.getSimpleType("Double")), tf.getPlaceholderType("M"), tf.getPlaceholderType("N")); //? extends Y, Number, Double, N> ExtendsType extY1 = tf.getExtendsType(tf.getSimpleType("Y", tf.getSuperType(tf.getSimpleType("HashSet", "Int")), tf.getSimpleType("Number"), tf.getSimpleType("Double"), tf.getPlaceholderType("N"))); @@ -301,13 +301,13 @@ public class RuleSetTest { */ // X - SimpleType x1 = tf.getSimpleType("X", "T1", "T2", "T3", "T4"); + ReferenceType x1 = tf.getSimpleType("X", "T1", "T2", "T3", "T4"); // Y - SimpleType y1 = tf.getSimpleType("Y", "T4", "T1", "T2", "T3"); - SimpleType buffer = tf.getSimpleType("Buffer"); + ReferenceType y1 = tf.getSimpleType("Y", "T4", "T1", "T2", "T3"); + ReferenceType buffer = tf.getSimpleType("Buffer"); //X - SimpleType x2 = tf.getSimpleType("X", tf.getSimpleType("Int"), tf.getExtendsType(tf.getSimpleType("Double")), tf.getPlaceholderType("M"), tf.getPlaceholderType("N")); + ReferenceType x2 = tf.getSimpleType("X", tf.getSimpleType("Int"), tf.getExtendsType(tf.getSimpleType("Double")), tf.getPlaceholderType("M"), tf.getPlaceholderType("N")); //? super Y, Number, Double, N> SuperType supY1 = tf.getSuperType(tf.getSimpleType("Y", tf.getSuperType(tf.getSimpleType("HashSet", "Int")), tf.getSimpleType("Number"), tf.getSimpleType("Double"), tf.getPlaceholderType("N"))); @@ -365,9 +365,9 @@ public class RuleSetTest { System.out.println("----- ReduceEq ------"); // C - SimpleType c1 = tf.getSimpleType("C", tf.getPlaceholderType("T1"), tf.getSimpleType("SType1"), tf.getExtendsType(tf.getSimpleType("SType1"))); + ReferenceType c1 = tf.getSimpleType("C", tf.getPlaceholderType("T1"), tf.getSimpleType("SType1"), tf.getExtendsType(tf.getSimpleType("SType1"))); // C - SimpleType c2 = tf.getSimpleType("C", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); + ReferenceType c2 = tf.getSimpleType("C", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); MPair pair = new MPair(c1, c2, PairOperator.SMALLERDOTWC); Optional> res = rules.reduceEq(pair); @@ -378,7 +378,7 @@ public class RuleSetTest { */ // Case 1: D <.? C - SimpleType d1 = tf.getSimpleType("D", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); + ReferenceType d1 = tf.getSimpleType("D", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); pair = new MPair(d1, c1, PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceEq(pair).isPresent()); @@ -521,9 +521,9 @@ public class RuleSetTest { TypeFactory tf = new TypeFactory(); FiniteClosureBuilder fcb = new FiniteClosureBuilder(); - SimpleType t1 = tf.getSimpleType("Type1", "T", "U"); - SimpleType t2 = tf.getSimpleType("Type2", "T"); - SimpleType t3 = tf.getSimpleType("Type3", tf.getPlaceholderType("T"), tf.getSimpleType("Integer")); + ReferenceType t1 = tf.getSimpleType("Type1", "T", "U"); + ReferenceType t2 = tf.getSimpleType("Type2", "T"); + ReferenceType t3 = tf.getSimpleType("Type3", tf.getPlaceholderType("T"), tf.getSimpleType("Integer")); fcb.add(t1, t2); fcb.add(t2, t3); @@ -534,9 +534,9 @@ public class RuleSetTest { * Positive Tests */ - SimpleType c1 = tf.getSimpleType("Type1", "String", "Double"); - SimpleType c2 = tf.getSimpleType("Type2", "Object"); - SimpleType c3 = tf.getSimpleType("Type3", "Object", "Number"); + ReferenceType c1 = tf.getSimpleType("Type1", "String", "Double"); + ReferenceType c2 = tf.getSimpleType("Type2", "Object"); + ReferenceType c3 = tf.getSimpleType("Type3", "Object", "Number"); MPair pair1 = new MPair(c1, c2, PairOperator.SMALLERDOT); MPair pair2 = new MPair(c2, c3, PairOperator.SMALLERDOT); @@ -565,11 +565,11 @@ public class RuleSetTest { TypeFactory tf = new TypeFactory(); FiniteClosureBuilder fcb = new FiniteClosureBuilder(); - SimpleType t1 = tf.getSimpleType("Type1", "T", "U"); - SimpleType t2 = tf.getSimpleType("Type2", "T"); - SimpleType t3 = tf.getSimpleType("Type3", tf.getPlaceholderType("T"), tf.getSimpleType("Integer")); - SimpleType t32 = tf.getSimpleType("Type3", "T", "U"); - SimpleType t4 = tf.getSimpleType("Object"); + ReferenceType t1 = tf.getSimpleType("Type1", "T", "U"); + ReferenceType t2 = tf.getSimpleType("Type2", "T"); + ReferenceType t3 = tf.getSimpleType("Type3", tf.getPlaceholderType("T"), tf.getSimpleType("Integer")); + ReferenceType t32 = tf.getSimpleType("Type3", "T", "U"); + ReferenceType t4 = tf.getSimpleType("Object"); fcb.add(t1, t2); fcb.add(t2, t3); @@ -581,9 +581,9 @@ public class RuleSetTest { * Positive Tests */ - SimpleType c1 = tf.getSimpleType("Type1", "String", "Double"); - SimpleType c2 = tf.getSimpleType("Type2", "Object"); - SimpleType c3 = tf.getSimpleType("Type3", "Object", "Number"); + ReferenceType c1 = tf.getSimpleType("Type1", "String", "Double"); + ReferenceType c2 = tf.getSimpleType("Type2", "Object"); + ReferenceType c3 = tf.getSimpleType("Type3", "Object", "Number"); ExtendsType extc1 = new ExtendsType(c1); ExtendsType extc2 = new ExtendsType(c2); ExtendsType extc3 = new ExtendsType(c3); @@ -627,11 +627,11 @@ public class RuleSetTest { TypeFactory tf = new TypeFactory(); FiniteClosureBuilder fcb = new FiniteClosureBuilder(); - SimpleType t1 = tf.getSimpleType("Type1", "T", "U"); - SimpleType t2 = tf.getSimpleType("Type2", "T"); - SimpleType t3 = tf.getSimpleType("Type3", tf.getPlaceholderType("T"), tf.getSimpleType("Integer")); - SimpleType t32 = tf.getSimpleType("Type3", "T", "U"); - SimpleType t4 = tf.getSimpleType("Object"); + ReferenceType t1 = tf.getSimpleType("Type1", "T", "U"); + ReferenceType t2 = tf.getSimpleType("Type2", "T"); + ReferenceType t3 = tf.getSimpleType("Type3", tf.getPlaceholderType("T"), tf.getSimpleType("Integer")); + ReferenceType t32 = tf.getSimpleType("Type3", "T", "U"); + ReferenceType t4 = tf.getSimpleType("Object"); fcb.add(t1, t2); fcb.add(t2, t3); @@ -643,9 +643,9 @@ public class RuleSetTest { * Positive Tests */ - SimpleType c1 = tf.getSimpleType("Type1", "String", "Double"); - SimpleType c2 = tf.getSimpleType("Type2", "Object"); - SimpleType c3 = tf.getSimpleType("Type3", "Object", "Number"); + ReferenceType c1 = tf.getSimpleType("Type1", "String", "Double"); + ReferenceType c2 = tf.getSimpleType("Type2", "Object"); + ReferenceType c3 = tf.getSimpleType("Type3", "Object", "Number"); SuperType supc1 = new SuperType(c1); SuperType supc2 = new SuperType(c2); SuperType supc3 = new SuperType(c3); diff --git a/test/unify/StandardUnifyTest.java b/test/unify/StandardUnifyTest.java index ac6e5c0c..b8e8a479 100644 --- a/test/unify/StandardUnifyTest.java +++ b/test/unify/StandardUnifyTest.java @@ -11,7 +11,6 @@ import de.dhbwstuttgart.typeinference.unify.MartelliMontanariUnify; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; -import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; public class StandardUnifyTest { diff --git a/test/unify/TypeFactory.java b/test/unify/TypeFactory.java index 965e324d..099638e7 100644 --- a/test/unify/TypeFactory.java +++ b/test/unify/TypeFactory.java @@ -5,7 +5,7 @@ import java.util.stream.Collectors; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; -import de.dhbwstuttgart.typeinference.unify.model.SimpleType; +import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; @@ -19,16 +19,16 @@ public class TypeFactory { return new SuperType(superedType); } - public SimpleType getSimpleType(String name) { - return new SimpleType(name); + public ReferenceType getSimpleType(String name) { + return new ReferenceType(name); } - public SimpleType getSimpleType(String name, UnifyType... typeParams) { - return new SimpleType(name, typeParams); + public ReferenceType getSimpleType(String name, UnifyType... typeParams) { + return new ReferenceType(name, typeParams); } - public SimpleType getSimpleType(String name, String... typeParams) { - return new SimpleType(name, Arrays.stream(typeParams).map(x -> getPlaceholderType(x)).collect(Collectors.toList()).toArray(new UnifyType[0])); + public ReferenceType getSimpleType(String name, String... typeParams) { + return new ReferenceType(name, Arrays.stream(typeParams).map(x -> getPlaceholderType(x)).collect(Collectors.toList()).toArray(new UnifyType[0])); } public PlaceholderType getPlaceholderType(String name) { diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index d5172970..3e3e51d1 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -12,6 +12,7 @@ import de.dhbwstuttgart.typeinference.unify.Unify; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import junit.framework.Assert; @@ -128,6 +129,7 @@ public class UnifyTest extends Unify { addAsSet(expected, new MPair(tphA, supObject, PairOperator.EQUALSDOT)); actual = unify(eq, fc); + actual = filterGeneratedTPHsMultiple(actual); Assert.assertEquals(expected, actual); @@ -208,10 +210,11 @@ public class UnifyTest extends Unify { eq.add(new MPair(integer, number, PairOperator.SMALLERDOT)); expected = new HashSet<>(); + expected.add(new HashSet<>()); actual = unify(eq, fc); - //Assert.assertEquals(expected, actual); + Assert.assertEquals(expected, actual); /* * Test 9: @@ -226,7 +229,7 @@ public class UnifyTest extends Unify { actual = unify(eq, fc); - //Assert.assertEquals(expected, actual); + Assert.assertEquals(expected, actual); /* * Test 10: @@ -260,7 +263,22 @@ public class UnifyTest extends Unify { actual = unify(eq, fc); Assert.assertEquals(expected, actual); - + + /* + * Test 11: + * + * (a <.? ? super b) + */ + + eq = new HashSet<>(); + eq.add(new MPair(tphA, tf.getSuperType(tphB), PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new MPair(tphA, tf.getSuperType(tphB), PairOperator.SMALLERDOTWC)); + + actual = unify(eq, fc); + + System.out.println(actual); } @Test @@ -320,8 +338,8 @@ public class UnifyTest extends Unify { actual = unify(eq, fc); - System.out.println(actual); - //Assert.assertEquals(expected, actual); + //System.out.println(actual); + Assert.assertEquals(expected, actual); /* @@ -425,6 +443,14 @@ public class UnifyTest extends Unify { System.out.println(result); } + private Set> filterGeneratedTPHsMultiple(Set> set) { + return set.stream().map(x -> filterGeneratedTPHs(x)).collect(Collectors.toSet()); + } + + private Set filterGeneratedTPHs(Set set) { + return set.stream().filter(x -> !((x.getRhsType() instanceof PlaceholderType) && ((PlaceholderType) x.getRhsType()).isGenerated())). + filter(x -> !((x.getLhsType() instanceof PlaceholderType) && ((PlaceholderType) x.getLhsType()).isGenerated())).collect(Collectors.toSet()); + } private void addAsSet(Set> addTo, MPair... mPairs) { addTo.add(new HashSet<>(Arrays.stream(mPairs).collect(Collectors.toSet()))); diff --git a/test/unify/UnifyTypeFactoryTest.java b/test/unify/UnifyTypeFactoryTest.java index 15d6f5f5..8bfac1a9 100644 --- a/test/unify/UnifyTypeFactoryTest.java +++ b/test/unify/UnifyTypeFactoryTest.java @@ -23,7 +23,7 @@ import de.dhbwstuttgart.typeinference.UndConstraint; import de.dhbwstuttgart.typeinference.UnifyConstraintsSet; import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; -import de.dhbwstuttgart.typeinference.unify.model.SimpleType; +import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; @@ -60,8 +60,8 @@ public class UnifyTypeFactoryTest { MPair mp4 = new MPair(tf.getPlaceholderType(tph2.getName().toString()), tf.getPlaceholderType(tph1.getName().toString()), PairOperator.SMALLERDOT); checkConvertMPair(mp4); - SimpleType typeWithParams = tf.getSimpleType("Test", getSimpleType()); - SimpleType typeWithTPHParams = tf.getSimpleType("Test", tf.getPlaceholderType("Test")); + ReferenceType typeWithParams = tf.getSimpleType("Test", getSimpleType()); + ReferenceType typeWithTPHParams = tf.getSimpleType("Test", tf.getPlaceholderType("Test")); MPair mp5 = new MPair(typeWithTPHParams, typeWithParams, PairOperator.SMALLERDOT); checkConvertMPair(mp5); } @@ -130,7 +130,7 @@ public class UnifyTypeFactoryTest { return p; } - private static SimpleType getSimpleType(){ + private static ReferenceType getSimpleType(){ return tf.getSimpleType("String"); } From 2c642cb6ef5298bf7220cb4cea7c3dff9a559249 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Sun, 3 Apr 2016 22:57:11 +0200 Subject: [PATCH 34/57] permute params test with assert --- test/unify/UnifyTest.java | 65 ++++++++++++++++++++------------------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 3e3e51d1..b4aaa86e 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -263,22 +263,6 @@ public class UnifyTest extends Unify { actual = unify(eq, fc); Assert.assertEquals(expected, actual); - - /* - * Test 11: - * - * (a <.? ? super b) - */ - - eq = new HashSet<>(); - eq.add(new MPair(tphA, tf.getSuperType(tphB), PairOperator.SMALLERDOTWC)); - - expected = new HashSet<>(); - addAsSet(expected, new MPair(tphA, tf.getSuperType(tphB), PairOperator.SMALLERDOTWC)); - - actual = unify(eq, fc); - - System.out.println(actual); } @Test @@ -338,8 +322,8 @@ public class UnifyTest extends Unify { actual = unify(eq, fc); - //System.out.println(actual); - Assert.assertEquals(expected, actual); + System.out.println(actual); + //Assert.assertEquals(expected, actual); /* @@ -357,7 +341,7 @@ public class UnifyTest extends Unify { expected = new HashSet<>(); actual = unify(eq, fc); - System.out.println(actual); + //System.out.println(actual); //Assert.assertEquals(actual, expected); /* @@ -373,7 +357,7 @@ public class UnifyTest extends Unify { expected = new HashSet<>(); actual = unify(eq, fc); - System.out.println(actual); + //System.out.println(actual); //Assert.assertEquals(actual, expected); /* @@ -394,7 +378,7 @@ public class UnifyTest extends Unify { expected = new HashSet<>(); actual = unify(eq, fc); - System.out.println(actual); + //System.out.println(actual); //Assert.assertEquals(actual, expected); @@ -420,27 +404,46 @@ public class UnifyTest extends Unify { TypeFactory tf = new TypeFactory(); ArrayList> candidates = new ArrayList<>(); + UnifyType p11 = tf.getPlaceholderType("p11"); + UnifyType p12 = tf.getExtendsType(tf.getSimpleType("p12")); + UnifyType p13 = tf.getSimpleType("p13"); + UnifyType p21 = tf.getPlaceholderType("p21"); + UnifyType p22 = tf.getPlaceholderType("p22"); + UnifyType p31 = tf.getSimpleType("p31", "T"); + Set p1 = new HashSet<>(); - p1.add(tf.getPlaceholderType("p11")); - p1.add(tf.getExtendsType(tf.getSimpleType("p12"))); - p1.add(tf.getSimpleType("p13")); + p1.add(p11); + p1.add(p12); + p1.add(p13); Set p2 = new HashSet<>(); - p2.add(tf.getPlaceholderType("p21")); - p2.add(tf.getPlaceholderType("p22")); + p2.add(p21); + p2.add(p22); Set p3 = new HashSet<>(); - p3.add(tf.getSimpleType("p31", "T")); - p3.add(tf.getSimpleType("p32")); + p3.add(p31); candidates.add(p1); candidates.add(p2); candidates.add(p3); + + + /* + * Expected Result: + * { | x in { p11, p12, p13}, y in { p21, p22 }, z in { p31 }} + */ + Set expected = Arrays.stream(new TypeParams[] { + new TypeParams(p11, p21, p31), + new TypeParams(p11, p22, p31), + new TypeParams(p12, p21, p31), + new TypeParams(p12, p22, p31), + new TypeParams(p13, p21, p31), + new TypeParams(p13, p22, p31) + }).collect(Collectors.toSet()); - Set result = permuteParams(candidates); + Set actual = permuteParams(candidates); - - System.out.println(result); + Assert.assertEquals(expected, actual); } private Set> filterGeneratedTPHsMultiple(Set> set) { From 2e3042925232a05adb6a7b94427e3980066a7b73 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 4 Apr 2016 10:18:34 +0200 Subject: [PATCH 35/57] added wildcardtype --- .../unify/model/WildcardType.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java b/src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java new file mode 100644 index 00000000..08c49783 --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java @@ -0,0 +1,34 @@ +package de.dhbwstuttgart.typeinference.unify.model; + +public abstract class WildcardType extends UnifyType { + + protected UnifyType wildcardedType; + + protected WildcardType(String name, UnifyType wildcardedType, UnifyType[] typeParams) { + super(name, typeParams); + this.wildcardedType = wildcardedType; + } + + protected WildcardType(String name, UnifyType wildcardedType, TypeParams p) { + super(name, p); + this.wildcardedType = wildcardedType; + } + + public UnifyType getWildcardedType() { + return wildcardedType; + } + + @Override + public int hashCode() { + return wildcardedType.hashCode() + getName().hashCode() + 17; + } + + @Override + public boolean equals(Object obj) { + if(!(obj instanceof WildcardType)) + return false; + + WildcardType other = (WildcardType) obj; + return other.getWildcardedType().equals(wildcardedType); + } +} From 6793b0bd242db84c7749276c5760138405e54f95 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 4 Apr 2016 11:23:14 +0200 Subject: [PATCH 36/57] rename mpair to unify pair / refactoring --- .../dhbwstuttgart/syntaxtree/SourceFile.java | 20 +- .../syntaxtree/factory/UnifyTypeFactory.java | 16 +- .../typeinference/UnifyConstraintsSet.java | 12 +- .../typeinference/UnifyOderConstraint.java | 14 +- .../typeinference/UnifySingleConstraint.java | 18 +- .../typeinference/UnifyUndConstraint.java | 14 +- .../typeinference/unify/Mapping.java | 10 +- .../unify/MartelliMontanariUnify.java | 26 +- .../typeinference/unify/RuleSet.java | 132 ++++---- .../typeinference/unify/Unifier.java | 4 +- .../typeinference/unify/Unify.java | 162 ++++----- .../unify/interfaces/IRuleSet.java | 54 +-- .../unify/model/FiniteClosure.java | 14 +- .../typeinference/unify/model/Unifier.java | 4 +- .../model/{MPair.java => UnifyPair.java} | 27 +- test/unify/FiniteClosureBuilder.java | 6 +- test/unify/FiniteClosureTest.java | 2 +- test/unify/RuleSetTest.java | 264 +++++++-------- test/unify/StandardUnifyTest.java | 4 +- test/unify/UnifyOldTest.java | 317 +----------------- test/unify/UnifyTest.java | 124 +++---- test/unify/UnifyTypeFactoryTest.java | 28 +- 22 files changed, 472 insertions(+), 800 deletions(-) rename src/de/dhbwstuttgart/typeinference/unify/model/{MPair.java => UnifyPair.java} (53%) diff --git a/src/de/dhbwstuttgart/syntaxtree/SourceFile.java b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java index 11d5f8c5..d271fd84 100755 --- a/src/de/dhbwstuttgart/syntaxtree/SourceFile.java +++ b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java @@ -55,7 +55,7 @@ import de.dhbwstuttgart.typeinference.exceptions.DebugException; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; import de.dhbwstuttgart.typeinference.unify.Unify; import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; @@ -261,9 +261,9 @@ public class SourceFile UnifyConstraintsSet unifyConstraints = UnifyTypeFactory.convert(oderConstraints); //Unmögliche ConstraintsSets aussortieren durch Unifizierung - Function,Menge>> unifier = (pairs)->{ - Menge> retValue = new Menge<>(); - Set> unifiedPairs = new Unify().unify(pairs, finiteClosure); + Function,Menge>> unifier = (pairs)->{ + Menge> retValue = new Menge<>(); + Set> unifiedPairs = new Unify().unify(pairs, finiteClosure); return retValue;}; //oderConstraints.filterWrongConstraints(unifier); @@ -276,7 +276,7 @@ public class SourceFile //////////////// //Karthesisches Produkt bilden: //////////////// - Set> xConstraints = unifyConstraints.cartesianProduct(); + Set> xConstraints = unifyConstraints.cartesianProduct(); @@ -288,7 +288,7 @@ public class SourceFile // Unifizierung der Constraints: ////////////////////////////// boolean unifyFail = true; - for(Set constraints : xConstraints){ + for(Set constraints : xConstraints){ //Alle durch das Karthesische Produkt entstandenen Möglichkeiten durchgehen: //Menge> result = new Menge>(); @@ -358,16 +358,16 @@ public class SourceFile return cardprodret; }); */ - Set> unifyResult = new Unify().unify(constraints, finiteClosure); + Set> unifyResult = new Unify().unify(constraints, finiteClosure); - Menge> convertedResult = unifyResult.parallelStream().>map((Set resultSet)->{ - Menge innerConvert = resultSet.stream().map((MPair mp)->UnifyTypeFactory.convert(mp)) + Menge> convertedResult = unifyResult.parallelStream().>map((Set resultSet)->{ + Menge innerConvert = resultSet.stream().map((UnifyPair mp)->UnifyTypeFactory.convert(mp)) .collect(Menge::new, Menge::add, Menge::addAll); return innerConvert; }).collect(Menge::new, Menge::add, Menge::addAll); Menge convertedConstraints = constraints.stream().map( - (MPair mp)->{return UnifyTypeFactory.convert(mp);} + (UnifyPair mp)->{return UnifyTypeFactory.convert(mp);} ).collect(Menge::new, Menge::add, Menge::addAll); //Dann den Ergebnissen anfügen diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index df903209..0e0da3fc 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -29,7 +29,7 @@ import de.dhbwstuttgart.typeinference.assumptions.ClassAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; @@ -43,7 +43,7 @@ public class UnifyTypeFactory { private final static NullSyntaxTreeNode NULL_NODE = new NullSyntaxTreeNode(); public static FiniteClosure generateFC(TypeAssumptions fromAss){ - HashSet pairs = new HashSet<>(); + HashSet pairs = new HashSet<>(); for(ClassAssumption cAss : fromAss.getClassAssumptions()){ UnifyType tl = UnifyTypeFactory.convert(cAss.getAssumedClass().getType()); RefType superClass = cAss.getAssumedClass().getSuperClass(); @@ -55,8 +55,8 @@ public class UnifyTypeFactory { return new FiniteClosure(pairs); } - public static MPair smaller(UnifyType tl, UnifyType tr){ - return new MPair(tl, tr, PairOperator.SMALLER); + public static UnifyPair smaller(UnifyType tl, UnifyType tr){ + return new UnifyPair(tl, tr, PairOperator.SMALLER); } public static UnifyType convert(Type t){ @@ -129,18 +129,18 @@ public class UnifyTypeFactory { return ret; } - public static MPair convert(EinzelElement p) { + public static UnifyPair convert(EinzelElement p) { return convert(p.getItem()); } - public static MPair convert(Pair p) { + public static UnifyPair convert(Pair p) { if(!p.OperatorSmaller())throw new NotImplementedException(); - MPair ret = smaller(UnifyTypeFactory.convert(p.TA1) + UnifyPair ret = smaller(UnifyTypeFactory.convert(p.TA1) , UnifyTypeFactory.convert(p.TA2)); return ret; } - public static Pair convert(MPair mp) { + public static Pair convert(UnifyPair mp) { Type tl = UnifyTypeFactory.convert(mp.getLhsType()); Type tr = UnifyTypeFactory.convert(mp.getRhsType()); return new Pair(tl, tr, mp.getPairOp()); diff --git a/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java b/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java index 16aa7b8d..5c7ed8b7 100644 --- a/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java +++ b/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java @@ -6,9 +6,9 @@ import java.util.Vector; import de.dhbwstuttgart.logger.Logger; import de.dhbwstuttgart.logger.*; import de.dhbwstuttgart.typeinference.unify.Unifier; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; -public class UnifyConstraintsSet extends UndMenge implements Iterable{ +public class UnifyConstraintsSet extends UndMenge implements Iterable{ private static final Logger log = Logger.getLogger(UnifyConstraintsSet.class.getName()); private Menge constraintsSet; @@ -53,18 +53,18 @@ public class UnifyConstraintsSet extends UndMenge implements Iterable uCons = this.filterUndConstraints(); - Vector alleUndConstraints = new Vector<>(); + Vector alleUndConstraints = new Vector<>(); for(UnifyUndConstraint undConstraint : uCons){ alleUndConstraints.addAll(undConstraint.getConstraintPairs()); } this.filterWrongConstraints( (pairs)->{ - Set undConstraintsUndPairs = new Menge<>(); + Set undConstraintsUndPairs = new Menge<>(); undConstraintsUndPairs.addAll(pairs); undConstraintsUndPairs.addAll(alleUndConstraints); log.debug("Versuche Pairs auszusondern:\n"+pairs, Section.TYPEINFERENCE); log.debug("Unifiziere:\n"+undConstraintsUndPairs, Section.TYPEINFERENCE); - Set> unifyResult = unifier.apply(undConstraintsUndPairs); + Set> unifyResult = unifier.apply(undConstraintsUndPairs); return unifyResult; }); } @@ -90,7 +90,7 @@ public class UnifyConstraintsSet extends UndMenge implements Iterable> getSet() { + public Menge> getSet() { return this.constraintsSet; } } diff --git a/src/de/dhbwstuttgart/typeinference/UnifyOderConstraint.java b/src/de/dhbwstuttgart/typeinference/UnifyOderConstraint.java index 2d3c9375..49dbf6de 100644 --- a/src/de/dhbwstuttgart/typeinference/UnifyOderConstraint.java +++ b/src/de/dhbwstuttgart/typeinference/UnifyOderConstraint.java @@ -9,9 +9,9 @@ import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.typeinference.unify.Unifier; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; -public class UnifyOderConstraint extends OderMenge{ +public class UnifyOderConstraint extends OderMenge{ private Set oderConstraintPairs; private final static Logger logger = Logger.getLogger(UnifyOderConstraint.class.getName()); @@ -38,8 +38,8 @@ public class UnifyOderConstraint extends OderMenge{ * Liefert alle in diesem OderConstraint enthaltene Constraints. Dabei gehen die Verkn�pfungen (Oder/Und) verloren. * @return */ - public Menge getConstraintPairs(){ - Menge ret = new Menge(); + public Menge getConstraintPairs(){ + Menge ret = new Menge(); for(UnifyUndConstraint oC : this.oderConstraintPairs){ ret.addAll(oC.getConstraintPairs()); } @@ -50,7 +50,7 @@ public class UnifyOderConstraint extends OderMenge{ * Falls die Type des toAdd-Pairs nicht vom Typ RefType bzw. TypePlaceholder sind, so werden sie in einen RefType umgewandelt. * @param toAdd */ - public void addConstraint(MPair toAdd){ + public void addConstraint(UnifyPair toAdd){ oderConstraintPairs.add(new UnifySingleConstraint(toAdd)); } @@ -86,7 +86,7 @@ public class UnifyOderConstraint extends OderMenge{ void filterWrongConstraints(Unifier unifier) { Set filteredConstraints = new Menge<>(); for(UnifyUndConstraint cons : this.getUndConstraints()){ - Set> unifierResult = unifier.apply(cons.getConstraintPairs()); + Set> unifierResult = unifier.apply(cons.getConstraintPairs()); if(!unifierResult.isEmpty()){ filteredConstraints.add(cons); }else{ @@ -104,7 +104,7 @@ public class UnifyOderConstraint extends OderMenge{ } @Override - public Set> getSet() { + public Set> getSet() { return this.oderConstraintPairs; } diff --git a/src/de/dhbwstuttgart/typeinference/UnifySingleConstraint.java b/src/de/dhbwstuttgart/typeinference/UnifySingleConstraint.java index 66cc2bbc..2860d32f 100644 --- a/src/de/dhbwstuttgart/typeinference/UnifySingleConstraint.java +++ b/src/de/dhbwstuttgart/typeinference/UnifySingleConstraint.java @@ -8,36 +8,36 @@ import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.typeinference.exceptions.DebugException; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; public class UnifySingleConstraint extends UnifyUndConstraint{ - private MPair constraintPair; //entspricht θ condition θ' + private UnifyPair constraintPair; //entspricht θ condition θ' @Override - public Menge> getSet() { - Menge> ret = new Menge<>(); + public Menge> getSet() { + Menge> ret = new Menge<>(); ret.add(new EinzelElement<>(constraintPair)); return ret; } - public UnifySingleConstraint(MPair toAdd) { + public UnifySingleConstraint(UnifyPair toAdd) { this.addConstraint(toAdd); } - public MPair getPair(){ + public UnifyPair getPair(){ return constraintPair; } @Override //Methode überschreiben, damit immer nur ein Vector mit nur einem Element zurückgeliefert wird. - public Menge getConstraintPairs(){ - Menge ret = new Menge<>(); + public Menge getConstraintPairs(){ + Menge ret = new Menge<>(); ret.add(constraintPair); return ret; } - public void addConstraint(MPair toAdd){ + public void addConstraint(UnifyPair toAdd){ if(constraintPair != null)throw new DebugException("Ein Constraint darf nur aus einem ConstraintPair bestehen. Das hinzufügen von "+ toAdd + " ist nicht möglich."); constraintPair = toAdd; diff --git a/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java b/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java index f963e12f..d13ead18 100644 --- a/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java +++ b/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java @@ -7,24 +7,24 @@ import java.util.Vector; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.typeinference.exceptions.DebugException; import de.dhbwstuttgart.typeinference.unify.Unifier; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; /** * Stellt ein Constraint dar, welches aus mehreren Constraint-Paaren besteht. Diese gelten alle stets gleichzeitig / sind per "Und" miteinander verknüpft. * @author janulrich * */ -public class UnifyUndConstraint extends UndMenge { +public class UnifyUndConstraint extends UndMenge { - Menge> set = new Menge<>(); + Menge> set = new Menge<>(); @Override - public Menge> getSet() { + public Menge> getSet() { return set; } - public Set getConstraintPairs() { - Set> ret = this.cartesianProduct(); + public Set getConstraintPairs() { + Set> ret = this.cartesianProduct(); if(ret.size() != 1){ //UndConstraints enthalten nur SingleConstraints, wodurch das Karthesische Produkt nur aus einem Element bestehen kann. throw new DebugException("Fehler in ConstraintPairs-Bildung"); @@ -38,7 +38,7 @@ public class UnifyUndConstraint extends UndMenge { return ret; } - public void add(MPair pair){ + public void add(UnifyPair pair){ set.add(new EinzelElement<>(pair)); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/Mapping.java b/src/de/dhbwstuttgart/typeinference/unify/Mapping.java index 5c9be501..b6ec1e34 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Mapping.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Mapping.java @@ -24,15 +24,15 @@ public class Mapping { return forwardMap.get(type); } - public de.dhbwstuttgart.typeinference.unify.model.MPair map(de.dhbwstuttgart.typeinference.Pair pair) { - return new de.dhbwstuttgart.typeinference.unify.model.MPair(forwardMap.get(pair.TA1), forwardMap.get(pair.TA2), mapOp(pair.GetOperator())); + public de.dhbwstuttgart.typeinference.unify.model.UnifyPair map(de.dhbwstuttgart.typeinference.Pair pair) { + return new de.dhbwstuttgart.typeinference.unify.model.UnifyPair(forwardMap.get(pair.TA1), forwardMap.get(pair.TA2), mapOp(pair.GetOperator())); } public Set mapTypeSet(Set types) { return types.stream().map(this::map).collect(Collectors.toCollection(HashSet::new)); } - public Set mapPairSet(Set pairs) { + public Set mapPairSet(Set pairs) { return pairs.stream().map(this::map).collect(Collectors.toCollection(HashSet::new)); } @@ -40,7 +40,7 @@ public class Mapping { return irreversible.contains(type) ? Optional.of(backwardMap.get(type)) : Optional.empty(); } - public Optional unmap(de.dhbwstuttgart.typeinference.unify.model.MPair mpair) { + public Optional unmap(de.dhbwstuttgart.typeinference.unify.model.UnifyPair mpair) { de.dhbwstuttgart.typeinference.unify.model.UnifyType lhs = mpair.getLhsType(); de.dhbwstuttgart.typeinference.unify.model.UnifyType rhs = mpair.getRhsType(); @@ -54,7 +54,7 @@ public class Mapping { return result.size() == types.size() ? Optional.of(result) : Optional.empty(); } - public Optional> unmapPairSet(Set pairs) { + public Optional> unmapPairSet(Set pairs) { Set result = pairs.stream().map(this::unmap).filter(x -> x.isPresent()).map(x -> x.get()).collect(Collectors.toCollection(HashSet::new)); return result.size() == pairs.size() ? Optional.of(result) : Optional.empty(); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java b/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java index 22759fbc..3531b716 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java @@ -10,7 +10,7 @@ import java.util.Set; import java.util.stream.Collectors; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; @@ -28,12 +28,12 @@ public class MartelliMontanariUnify implements IUnify { if(terms.size() < 2) return Optional.of(Unifier.Identity()); - ArrayList termsQ = new ArrayList(); + ArrayList termsQ = new ArrayList(); Iterator iter = terms.iterator(); UnifyType prev = iter.next(); while(iter.hasNext()) { UnifyType next = iter.next(); - termsQ.add(new MPair(prev, next, PairOperator.EQUALSDOT)); + termsQ.add(new UnifyPair(prev, next, PairOperator.EQUALSDOT)); prev = next; } @@ -41,14 +41,14 @@ public class MartelliMontanariUnify implements IUnify { int idx = 0; while(idx < termsQ.size()) { - MPair pair = termsQ.get(idx); + UnifyPair pair = termsQ.get(idx); if(delete(pair)) { termsQ.remove(idx); continue; } - Optional> optSet = decompose(pair); + Optional> optSet = decompose(pair); if(optSet == null) return Optional.empty(); // Unification failed @@ -59,7 +59,7 @@ public class MartelliMontanariUnify implements IUnify { continue; } - Optional optPair = swap(pair); + Optional optPair = swap(pair); if(optPair.isPresent()) { termsQ.add(optPair.get()); @@ -88,12 +88,12 @@ public class MartelliMontanariUnify implements IUnify { return Optional.of(mgu); } - private boolean delete(MPair pair) { + private boolean delete(UnifyPair pair) { return pair.getRhsType().equals(pair.getLhsType()); } - private Optional> decompose(MPair pair) { - Set result = new HashSet<>(); + private Optional> decompose(UnifyPair pair) { + Set result = new HashSet<>(); UnifyType rhs = pair.getRhsType(); UnifyType lhs = pair.getLhsType(); @@ -112,22 +112,22 @@ public class MartelliMontanariUnify implements IUnify { return Optional.empty(); for(int i = 0; i < rhsTypeParams.size(); i++) - result.add(new MPair(rhsTypeParams.get(i), lhsTypeParams.get(i), PairOperator.EQUALSDOT)); + result.add(new UnifyPair(rhsTypeParams.get(i), lhsTypeParams.get(i), PairOperator.EQUALSDOT)); return Optional.of(result); } - private Optional swap(MPair pair) { + private Optional swap(UnifyPair pair) { UnifyType rhs = pair.getRhsType(); UnifyType lhs = pair.getLhsType(); if(!(lhs instanceof PlaceholderType) && (rhs instanceof PlaceholderType)) - return Optional.of(new MPair(rhs, lhs, PairOperator.EQUALSDOT)); + return Optional.of(new UnifyPair(rhs, lhs, PairOperator.EQUALSDOT)); return Optional.empty(); } - private Optional> eliminate(MPair pair) { + private Optional> eliminate(UnifyPair pair) { UnifyType rhs = pair.getRhsType(); UnifyType lhs = pair.getLhsType(); diff --git a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java index d0710675..9ce84a43 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -15,7 +15,7 @@ import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; import de.dhbwstuttgart.typeinference.unify.model.FunNType; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; @@ -34,7 +34,7 @@ public class RuleSet implements IRuleSet{ } @Override - public Optional reduceUp(MPair pair) { + public Optional reduceUp(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); @@ -46,11 +46,11 @@ public class RuleSet implements IRuleSet{ if(!(lhsType instanceof ReferenceType) && !(lhsType instanceof PlaceholderType)) return Optional.empty(); - return Optional.of(new MPair(lhsType, ((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT)); + return Optional.of(new UnifyPair(lhsType, ((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT)); } @Override - public Optional reduceLow(MPair pair) { + public Optional reduceLow(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); @@ -62,11 +62,11 @@ public class RuleSet implements IRuleSet{ if(!(rhsType instanceof ReferenceType) && !(rhsType instanceof PlaceholderType)) return Optional.empty(); - return Optional.of(new MPair(((ExtendsType) lhsType).getExtendedType(), rhsType, PairOperator.SMALLERDOT)); + return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(), rhsType, PairOperator.SMALLERDOT)); } @Override - public Optional reduceUpLow(MPair pair) { + public Optional reduceUpLow(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); @@ -78,11 +78,11 @@ public class RuleSet implements IRuleSet{ if(!(rhsType instanceof SuperType)) return Optional.empty(); - return Optional.of(new MPair(((ExtendsType) lhsType).getExtendedType(),((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT)); + return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(),((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT)); } @Override - public Optional> reduceExt(MPair pair) { + public Optional> reduceExt(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); @@ -125,16 +125,16 @@ public class RuleSet implements IRuleSet{ if(pi.length == 0) return Optional.empty(); - Set result = new HashSet<>(); + Set result = new HashSet<>(); for(int rhsIdx = 0; rhsIdx < extYParams.size(); rhsIdx++) - result.add(new MPair(xParams.get(pi[rhsIdx]), extYParams.get(rhsIdx), PairOperator.SMALLERDOTWC)); + result.add(new UnifyPair(xParams.get(pi[rhsIdx]), extYParams.get(rhsIdx), PairOperator.SMALLERDOTWC)); return Optional.of(result); } @Override - public Optional> reduceSup(MPair pair) { + public Optional> reduceSup(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); @@ -171,7 +171,7 @@ public class RuleSet implements IRuleSet{ TypeParams supYParams = supY.getTypeParams(); TypeParams xParams = x.getTypeParams(); - Set result = new HashSet<>(); + Set result = new HashSet<>(); int[] pi = pi(xParams, supYParams); @@ -179,13 +179,13 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); for(int rhsIdx = 0; rhsIdx < supYParams.size(); rhsIdx++) - result.add(new MPair(supYParams.get(rhsIdx), xParams.get(pi[rhsIdx]), PairOperator.SMALLERDOTWC)); + result.add(new UnifyPair(supYParams.get(rhsIdx), xParams.get(pi[rhsIdx]), PairOperator.SMALLERDOTWC)); return Optional.of(result); } @Override - public Optional> reduceEq(MPair pair) { + public Optional> reduceEq(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); @@ -205,18 +205,18 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); // Keine Permutation wie im Paper nötig - Set result = new HashSet<>(); + Set result = new HashSet<>(); TypeParams lhsTypeParams = lhsType.getTypeParams(); TypeParams rhsTypeParams = rhsType.getTypeParams(); for(int i = 0; i < lhsTypeParams.size(); i++) - result.add(new MPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT)); + result.add(new UnifyPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT)); return Optional.of(result); } @Override - public Optional> reduce1(MPair pair) { + public Optional> reduce1(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); @@ -251,16 +251,16 @@ public class RuleSet implements IRuleSet{ TypeParams rhsTypeParams = d.getTypeParams(); TypeParams lhsTypeParams = c.getTypeParams(); - Set result = new HashSet<>(); + Set result = new HashSet<>(); for(int rhsIdx = 0; rhsIdx < rhsTypeParams.size(); rhsIdx++) - result.add(new MPair(lhsTypeParams.get(pi[rhsIdx]), rhsTypeParams.get(rhsIdx), PairOperator.SMALLERDOTWC)); + result.add(new UnifyPair(lhsTypeParams.get(pi[rhsIdx]), rhsTypeParams.get(rhsIdx), PairOperator.SMALLERDOTWC)); return Optional.of(result); } @Override - public Optional> reduce2(MPair pair) { + public Optional> reduce2(UnifyPair pair) { if(pair.getPairOp() != PairOperator.EQUALSDOT) return Optional.empty(); @@ -304,18 +304,18 @@ public class RuleSet implements IRuleSet{ //if(rhsSType.getTypeParams().size() != lhsSType.getTypeParams().size()) // return Optional.empty(); - Set result = new HashSet<>(); + Set result = new HashSet<>(); TypeParams rhsTypeParams = rhsSType.getTypeParams(); TypeParams lhsTypeParams = lhsSType.getTypeParams(); for(int i = 0; i < rhsTypeParams.size(); i++) - result.add(new MPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT)); + result.add(new UnifyPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT)); return Optional.of(result); } @Override - public boolean erase1(MPair pair) { + public boolean erase1(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOT) return false; @@ -331,7 +331,7 @@ public class RuleSet implements IRuleSet{ } @Override - public boolean erase2(MPair pair) { + public boolean erase2(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return false; @@ -342,7 +342,7 @@ public class RuleSet implements IRuleSet{ } @Override - public boolean erase3(MPair pair) { + public boolean erase3(UnifyPair pair) { if(pair.getPairOp() != PairOperator.EQUALSDOT) return false; @@ -350,7 +350,7 @@ public class RuleSet implements IRuleSet{ } @Override - public Optional swap(MPair pair) { + public Optional swap(UnifyPair pair) { if(pair.getPairOp() != PairOperator.EQUALSDOT) return Optional.empty(); @@ -360,11 +360,11 @@ public class RuleSet implements IRuleSet{ if(!(pair.getRhsType() instanceof PlaceholderType)) return Optional.empty(); - return Optional.of(new MPair(pair.getRhsType(), pair.getLhsType(), PairOperator.EQUALSDOT)); + return Optional.of(new UnifyPair(pair.getRhsType(), pair.getLhsType(), PairOperator.EQUALSDOT)); } @Override - public Optional adapt(MPair pair) { + public Optional adapt(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); @@ -406,11 +406,11 @@ public class RuleSet implements IRuleSet{ for(int i = 1; i < typeDParams.size(); i++) unif.Add((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i)); - return Optional.of(new MPair(unif.apply(newLhs), typeDs, PairOperator.SMALLERDOT)); + return Optional.of(new UnifyPair(unif.apply(newLhs), typeDs, PairOperator.SMALLERDOT)); } @Override - public Optional adaptExt(MPair pair) { + public Optional adaptExt(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); @@ -452,11 +452,11 @@ public class RuleSet implements IRuleSet{ for(int i = 1; i < typeDParams.size(); i++) unif.Add((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i)); - return Optional.of(new MPair(unif.apply(newLhs), typeExtDs, PairOperator.SMALLERDOTWC)); + return Optional.of(new UnifyPair(unif.apply(newLhs), typeExtDs, PairOperator.SMALLERDOTWC)); } @Override - public Optional adaptSup(MPair pair) { + public Optional adaptSup(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); @@ -504,7 +504,7 @@ public class RuleSet implements IRuleSet{ for(int i = 1; i < typeDParams.size(); i++) unif.Add((PlaceholderType) typeSupDsgenParams.get(i), typeDParams.get(i)); - return Optional.of(new MPair(unif.apply(newLhs), newRhs, PairOperator.SMALLERDOTWC)); + return Optional.of(new UnifyPair(unif.apply(newLhs), newRhs, PairOperator.SMALLERDOTWC)); } /** @@ -534,12 +534,12 @@ public class RuleSet implements IRuleSet{ } @Override - public Optional> subst(Set pairs) { + public Optional> subst(Set pairs) { HashMap typeMap = new HashMap<>(); Stack occuringTypes = new Stack<>(); - for(MPair pair : pairs) { + for(UnifyPair pair : pairs) { occuringTypes.push(pair.getLhsType()); occuringTypes.push(pair.getRhsType()); } @@ -558,12 +558,12 @@ public class RuleSet implements IRuleSet{ t1.getTypeParams().forEach(x -> occuringTypes.push(x)); } - Queue result1 = new LinkedList(pairs); - ArrayList result = new ArrayList(); + Queue result1 = new LinkedList(pairs); + ArrayList result = new ArrayList(); boolean applied = false; while(!result1.isEmpty()) { - MPair pair = result1.poll(); + UnifyPair pair = result1.poll(); PlaceholderType lhsType = null; UnifyType rhsType; @@ -587,7 +587,7 @@ public class RuleSet implements IRuleSet{ } @Override - public Optional reduceWildcardLow(MPair pair) { + public Optional reduceWildcardLow(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); @@ -596,11 +596,11 @@ public class RuleSet implements IRuleSet{ if(!(lhsType instanceof ExtendsType) || !(rhsType instanceof ExtendsType)) return Optional.empty(); - return Optional.of(new MPair(((ExtendsType) lhsType).getExtendedType(), ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT)); + return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(), ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT)); } @Override - public Optional reduceWildcardLowRight(MPair pair) { + public Optional reduceWildcardLowRight(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); @@ -609,11 +609,11 @@ public class RuleSet implements IRuleSet{ if(!(lhsType instanceof ReferenceType) || !(rhsType instanceof ExtendsType)) return Optional.empty(); - return Optional.of(new MPair(lhsType, ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT)); + return Optional.of(new UnifyPair(lhsType, ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT)); } @Override - public Optional reduceWildcardUp(MPair pair) { + public Optional reduceWildcardUp(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); @@ -622,11 +622,11 @@ public class RuleSet implements IRuleSet{ if(!(lhsType instanceof SuperType) || !(rhsType instanceof SuperType)) return Optional.empty(); - return Optional.of(new MPair(((SuperType) rhsType).getSuperedType(), ((SuperType) lhsType).getSuperedType(), PairOperator.SMALLERDOT)); + return Optional.of(new UnifyPair(((SuperType) rhsType).getSuperedType(), ((SuperType) lhsType).getSuperedType(), PairOperator.SMALLERDOT)); } @Override - public Optional reduceWildcardUpRight(MPair pair) { + public Optional reduceWildcardUpRight(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); @@ -635,11 +635,11 @@ public class RuleSet implements IRuleSet{ if(!(lhsType instanceof ReferenceType) || !(rhsType instanceof SuperType)) return Optional.empty(); - return Optional.of(new MPair(((SuperType) rhsType).getSuperedType(), lhsType, PairOperator.SMALLERDOTWC)); + return Optional.of(new UnifyPair(((SuperType) rhsType).getSuperedType(), lhsType, PairOperator.SMALLERDOTWC)); } @Override - public Optional reduceWildcardLowUp(MPair pair) { + public Optional reduceWildcardLowUp(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); @@ -648,11 +648,11 @@ public class RuleSet implements IRuleSet{ if(!(lhsType instanceof ExtendsType) || !(rhsType instanceof SuperType)) return Optional.empty(); - return Optional.of(new MPair(((ExtendsType) lhsType).getExtendedType(), ((SuperType) rhsType).getSuperedType(), PairOperator.EQUALSDOT)); + return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(), ((SuperType) rhsType).getSuperedType(), PairOperator.EQUALSDOT)); } @Override - public Optional reduceWildcardUpLow(MPair pair) { + public Optional reduceWildcardUpLow(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); @@ -661,11 +661,11 @@ public class RuleSet implements IRuleSet{ if(!(lhsType instanceof SuperType) || !(rhsType instanceof ExtendsType)) return Optional.empty(); - return Optional.of(new MPair(((SuperType) lhsType).getSuperedType(), ((ExtendsType) rhsType).getExtendedType(), PairOperator.EQUALSDOT)); + return Optional.of(new UnifyPair(((SuperType) lhsType).getSuperedType(), ((ExtendsType) rhsType).getExtendedType(), PairOperator.EQUALSDOT)); } @Override - public Optional reduceWildcardLeft(MPair pair) { + public Optional reduceWildcardLeft(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); @@ -676,13 +676,13 @@ public class RuleSet implements IRuleSet{ UnifyType lhsType = pair.getLhsType(); if(lhsType instanceof WildcardType) - return Optional.of(new MPair(((WildcardType) lhsType).getWildcardedType(), rhsType, PairOperator.EQUALSDOT)); + return Optional.of(new UnifyPair(((WildcardType) lhsType).getWildcardedType(), rhsType, PairOperator.EQUALSDOT)); return Optional.empty(); } @Override - public Optional> reduceFunN(MPair pair) { + public Optional> reduceFunN(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); @@ -698,17 +698,17 @@ public class RuleSet implements IRuleSet{ if(funNLhsType.getN() != funNRhsType.getN()) return Optional.empty(); - Set result = new HashSet(); + Set result = new HashSet(); - result.add(new MPair(funNLhsType.getTypeParams().get(0), funNRhsType.getTypeParams().get(0), PairOperator.SMALLERDOT)); + result.add(new UnifyPair(funNLhsType.getTypeParams().get(0), funNRhsType.getTypeParams().get(0), PairOperator.SMALLERDOT)); for(int i = 1; i < funNLhsType.getTypeParams().size(); i++) - result.add(new MPair(funNRhsType.getTypeParams().get(i), funNLhsType.getTypeParams().get(i), PairOperator.SMALLERDOT)); + result.add(new UnifyPair(funNRhsType.getTypeParams().get(i), funNLhsType.getTypeParams().get(i), PairOperator.SMALLERDOT)); return Optional.of(result); } @Override - public Optional> greaterFunN(MPair pair) { + public Optional> greaterFunN(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); @@ -720,22 +720,22 @@ public class RuleSet implements IRuleSet{ FunNType funNLhsType = (FunNType) lhsType; - Set result = new HashSet(); + Set result = new HashSet(); UnifyType[] freshPlaceholders = new UnifyType[funNLhsType.getTypeParams().size()]; for(int i = 0; i < freshPlaceholders.length; i++) freshPlaceholders[i] = PlaceholderType.freshPlaceholder(); - result.add(new MPair(funNLhsType.getTypeParams().get(0), freshPlaceholders[0], PairOperator.SMALLERDOT)); + result.add(new UnifyPair(funNLhsType.getTypeParams().get(0), freshPlaceholders[0], PairOperator.SMALLERDOT)); for(int i = 1; i < funNLhsType.getTypeParams().size(); i++) - result.add(new MPair(freshPlaceholders[i], funNLhsType.getTypeParams().get(i), PairOperator.SMALLERDOT)); - result.add(new MPair(rhsType, funNLhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT)); + result.add(new UnifyPair(freshPlaceholders[i], funNLhsType.getTypeParams().get(i), PairOperator.SMALLERDOT)); + result.add(new UnifyPair(rhsType, funNLhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT)); return Optional.of(result); } @Override - public Optional> smallerFunN(MPair pair) { + public Optional> smallerFunN(UnifyPair pair) { if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); @@ -747,16 +747,16 @@ public class RuleSet implements IRuleSet{ FunNType funNRhsType = (FunNType) rhsType; - Set result = new HashSet(); + Set result = new HashSet(); UnifyType[] freshPlaceholders = new UnifyType[funNRhsType.getTypeParams().size()]; for(int i = 0; i < freshPlaceholders.length; i++) freshPlaceholders[i] = PlaceholderType.freshPlaceholder(); - result.add(new MPair(freshPlaceholders[0], funNRhsType.getTypeParams().get(0), PairOperator.SMALLERDOT)); + result.add(new UnifyPair(freshPlaceholders[0], funNRhsType.getTypeParams().get(0), PairOperator.SMALLERDOT)); for(int i = 1; i < funNRhsType.getTypeParams().size(); i++) - result.add(new MPair(funNRhsType.getTypeParams().get(i), freshPlaceholders[i], PairOperator.SMALLERDOT)); - result.add(new MPair(lhsType, funNRhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT)); + result.add(new UnifyPair(funNRhsType.getTypeParams().get(i), freshPlaceholders[i], PairOperator.SMALLERDOT)); + result.add(new UnifyPair(lhsType, funNRhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT)); return Optional.of(result); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/Unifier.java index b348b28c..0a08a210 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unifier.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unifier.java @@ -2,10 +2,10 @@ package de.dhbwstuttgart.typeinference.unify; import java.util.Set; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; public interface Unifier { - public Set> apply (Set E); + public Set> apply (Set E); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unify.java b/src/de/dhbwstuttgart/typeinference/unify/Unify.java index d781a2a4..6f4fa514 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unify.java @@ -17,7 +17,7 @@ import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; import de.dhbwstuttgart.typeinference.unify.interfaces.ISetOperations; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; @@ -32,19 +32,19 @@ import de.dhbwstuttgart.typeinference.unify.model.Unifier; */ public class Unify { - public Set> unify(Set eq, IFiniteClosure fc) { + public Set> unify(Set eq, IFiniteClosure fc) { /* * Step 1: Repeated application of reduce, adapt, erase, swap */ - Set eq0 = applyTypeUnificationRules(eq, fc); + Set eq0 = applyTypeUnificationRules(eq, fc); /* * Step 2 and 3: Create a subset eq1s of pairs where both sides are TPH and eq2s of the other pairs */ - Set eq1s = new HashSet<>(); - Set eq2s = new HashSet<>(); + Set eq1s = new HashSet<>(); + Set eq2s = new HashSet<>(); splitEq(eq0, eq1s, eq2s); /* @@ -56,21 +56,21 @@ public class Unify { // There are up to 10 toplevel set. 8 of 10 are the result of the // cartesian product of the sets created by pattern matching. - List>> topLevelSets = new ArrayList<>(); + List>> topLevelSets = new ArrayList<>(); if(eq1s.size() != 0) { - Set> wrap = new HashSet<>(); + Set> wrap = new HashSet<>(); wrap.add(eq1s); topLevelSets.add(wrap); // Add Eq1' } // Add the set of [a =. Theta | (a=. Theta) in Eq2'] - Set bufferSet = eq2s.stream() + Set bufferSet = eq2s.stream() .filter(x -> x.getPairOp() == PairOperator.EQUALSDOT && x.getLhsType() instanceof PlaceholderType) .collect(Collectors.toSet()); if(bufferSet.size() != 0) { - Set> wrap = new HashSet<>(); + Set> wrap = new HashSet<>(); wrap.add(bufferSet); topLevelSets.add(wrap); eq2s.removeAll(bufferSet); @@ -78,8 +78,8 @@ public class Unify { // Sets that originate from pair pattern matching // Sets of the "second level" - Set undefinedPairs = new HashSet<>(); - Set>>> secondLevelSets = calculatePairSets(eq2s, fc, undefinedPairs); + Set undefinedPairs = new HashSet<>(); + Set>>> secondLevelSets = calculatePairSets(eq2s, fc, undefinedPairs); // If pairs occured that did not match one of the cartesian product cases, // those pairs are contradictory and the unification is impossible. @@ -92,17 +92,17 @@ public class Unify { ISetOperations setOps = new GuavaSetOperations(); // Sub cartesian products of the second level (pattern matched) sets - for(Set>> secondLevelSet : secondLevelSets) { - List>> secondLevelSetList = new ArrayList<>(secondLevelSet); - Set>> cartResult = setOps.cartesianProduct(secondLevelSetList); + for(Set>> secondLevelSet : secondLevelSets) { + List>> secondLevelSetList = new ArrayList<>(secondLevelSet); + Set>> cartResult = setOps.cartesianProduct(secondLevelSetList); - Set> flat = new HashSet<>(); + Set> flat = new HashSet<>(); cartResult.stream().forEach(x -> flat.addAll(x)); topLevelSets.add(flat); } // Cartesian product over all (up to 10) top level sets - Set>> eqPrimeSet = setOps.cartesianProduct(topLevelSets) + Set>> eqPrimeSet = setOps.cartesianProduct(topLevelSets) .stream().map(x -> new HashSet<>(x)) .collect(Collectors.toCollection(HashSet::new)); //System.out.println(result); @@ -111,19 +111,19 @@ public class Unify { * Step 5: Substitution */ - Set> eqPrimeSetFlat = new HashSet<>(); - for(Set> setToFlatten : eqPrimeSet) { - Set buffer = new HashSet<>(); + Set> eqPrimeSetFlat = new HashSet<>(); + for(Set> setToFlatten : eqPrimeSet) { + Set buffer = new HashSet<>(); setToFlatten.stream().forEach(x -> buffer.addAll(x)); eqPrimeSetFlat.add(buffer); } IRuleSet rules = new RuleSet(fc); - Set> changed = new HashSet<>(); - Set> eqPrimePrimeSet = new HashSet<>(); + Set> changed = new HashSet<>(); + Set> eqPrimePrimeSet = new HashSet<>(); - for(Set eqPrime : eqPrimeSetFlat) { - Optional> eqPrimePrime = rules.subst(eqPrime); + for(Set eqPrime : eqPrimeSetFlat) { + Optional> eqPrimePrime = rules.subst(eqPrime); if(eqPrime.equals(eq)) eqPrimePrimeSet.add(eqPrime); @@ -142,7 +142,7 @@ public class Unify { * b) Build the union over everything */ - for(Set eqss : changed) + for(Set eqss : changed) eqPrimePrimeSet.addAll(this.unify(eqss, fc)); /* @@ -152,8 +152,8 @@ public class Unify { } - protected boolean isSolvedForm(Set eqPrimePrime) { - for(MPair pair : eqPrimePrime) { + protected boolean isSolvedForm(Set eqPrimePrime) { + for(UnifyPair pair : eqPrimePrime) { UnifyType lhsType = pair.getLhsType(); UnifyType rhsType = pair.getRhsType(); @@ -167,7 +167,7 @@ public class Unify { return true; } - protected Set applyTypeUnificationRules(Set eq, IFiniteClosure fc) { + protected Set applyTypeUnificationRules(Set eq, IFiniteClosure fc) { /* * Rule Application Strategy: @@ -182,8 +182,8 @@ public class Unify { */ - LinkedHashSet targetSet = new LinkedHashSet(); - LinkedList eqQueue = new LinkedList<>(); + LinkedHashSet targetSet = new LinkedHashSet(); + LinkedList eqQueue = new LinkedList<>(); IRuleSet rules = new RuleSet(fc); /* @@ -195,10 +195,10 @@ public class Unify { * Apply rules until the queue is empty */ while(!eqQueue.isEmpty()) { - MPair pair = eqQueue.pollFirst(); + UnifyPair pair = eqQueue.pollFirst(); // ReduceUp, ReduceLow, ReduceUpLow - Optional opt = rules.reduceUpLow(pair); + Optional opt = rules.reduceUpLow(pair); opt = opt.isPresent() ? opt : rules.reduceLow(pair); opt = opt.isPresent() ? opt : rules.reduceUp(pair); opt = opt.isPresent() ? opt : rules.reduceWildcardLow(pair); @@ -216,7 +216,7 @@ public class Unify { } // Reduce1, Reduce2, ReduceExt, ReduceSup, ReduceEq - Optional> optSet = rules.reduce1(pair); + Optional> optSet = rules.reduce1(pair); optSet = optSet.isPresent() ? optSet : rules.reduce2(pair); optSet = optSet.isPresent() ? optSet : rules.reduceExt(pair); optSet = optSet.isPresent() ? optSet : rules.reduceSup(pair); @@ -246,9 +246,9 @@ public class Unify { return targetSet; } - protected void swapAddOrErase(MPair pair, IRuleSet rules, Collection collection) { - Optional opt = rules.swap(pair); - MPair pair2 = opt.isPresent() ? opt.get() : pair; + protected void swapAddOrErase(UnifyPair pair, IRuleSet rules, Collection collection) { + Optional opt = rules.swap(pair); + UnifyPair pair2 = opt.isPresent() ? opt.get() : pair; if(rules.erase1(pair2) || rules.erase3(pair2) || rules.erase2(pair2)) return; @@ -256,8 +256,8 @@ public class Unify { collection.add(pair2); } - protected void splitEq(Set eq, Set eq1s, Set eq2s) { - for(MPair pair : eq) + protected void splitEq(Set eq, Set eq1s, Set eq2s) { + for(UnifyPair pair : eq) if(pair.getLhsType() instanceof PlaceholderType && pair.getRhsType() instanceof PlaceholderType) eq1s.add(pair); else @@ -265,14 +265,14 @@ public class Unify { } - protected Set>>> calculatePairSets(Set eq2s, IFiniteClosure fc, Set undefined) { - List>>> result = new ArrayList<>(); + protected Set>>> calculatePairSets(Set eq2s, IFiniteClosure fc, Set undefined) { + List>>> result = new ArrayList<>(); // Init all 8 cases for(int i = 0; i < 8; i++) result.add(new HashSet<>()); - for(MPair pair : eq2s) { + for(UnifyPair pair : eq2s) { PairOperator pairOp = pair.getPairOp(); UnifyType lhsType = pair.getLhsType(); @@ -321,8 +321,8 @@ public class Unify { .filter(x -> x.size() > 0).collect(Collectors.toCollection(HashSet::new)); } - protected Set> unifyCase1(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { - Set> result = new HashSet<>(); + protected Set> unifyCase1(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { + Set> result = new HashSet<>(); IUnify unify = new MartelliMontanariUnify(); Set cs = fc.getAllTypesByName(thetaPrime.getName()); @@ -352,15 +352,15 @@ public class Unify { continue; Unifier unifier = opt.get(); - Set substitutionSet = new HashSet<>(); + Set substitutionSet = new HashSet<>(); for (Entry sigma : unifier.getSubstitutions()) - substitutionSet.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); for (UnifyType tq : thetaQs) { Set smaller = fc.smaller(unifier.apply(tq)); for(UnifyType theta : smaller) { - Set resultPrime = new HashSet<>(); - resultPrime.add(new MPair(a, theta, PairOperator.EQUALSDOT)); + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, theta, PairOperator.EQUALSDOT)); resultPrime.addAll(substitutionSet); result.add(resultPrime); } @@ -372,8 +372,8 @@ public class Unify { return result; } - protected Set> unifyCase2(PlaceholderType a, ExtendsType extThetaPrime, IFiniteClosure fc) { - Set> result = new HashSet<>(); + protected Set> unifyCase2(PlaceholderType a, ExtendsType extThetaPrime, IFiniteClosure fc) { + Set> result = new HashSet<>(); IUnify unify = new MartelliMontanariUnify(); UnifyType thetaPrime = extThetaPrime.getExtendedType(); @@ -405,16 +405,16 @@ public class Unify { Unifier unifier = opt.get(); - Set substitutionSet = new HashSet<>(); + Set substitutionSet = new HashSet<>(); for (Entry sigma : unifier.getSubstitutions()) - substitutionSet.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); for (UnifyType tq : thetaQs) { ExtendsType extTq = new ExtendsType(tq); Set smArg = fc.smArg(unifier.apply(extTq)); for(UnifyType theta : smArg) { - Set resultPrime = new HashSet<>(); - resultPrime.add(new MPair(a, theta, PairOperator.EQUALSDOT)); + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, theta, PairOperator.EQUALSDOT)); resultPrime.addAll(substitutionSet); result.add(resultPrime); } @@ -426,60 +426,60 @@ public class Unify { return result; } - protected Set> unifyCase3(PlaceholderType a, SuperType subThetaPrime, IFiniteClosure fc) { - Set> result = new HashSet<>(); + protected Set> unifyCase3(PlaceholderType a, SuperType subThetaPrime, IFiniteClosure fc) { + Set> result = new HashSet<>(); UnifyType aPrime = PlaceholderType.freshPlaceholder(); UnifyType supAPrime = new SuperType(aPrime); UnifyType thetaPrime = subThetaPrime.getSuperedType(); //for(UnifyType theta : fc.smArg(subThetaPrime)) { - Set resultPrime = new HashSet<>(); - resultPrime.add(new MPair(a, aPrime, PairOperator.EQUALSDOT)); - resultPrime.add(new MPair(thetaPrime, aPrime, PairOperator.SMALLERDOT)); + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, aPrime, PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(thetaPrime, aPrime, PairOperator.SMALLERDOT)); result.add(resultPrime); resultPrime = new HashSet<>(); - resultPrime.add(new MPair(a, supAPrime, PairOperator.EQUALSDOT)); - resultPrime.add(new MPair(thetaPrime, aPrime, PairOperator.SMALLERDOT)); + resultPrime.add(new UnifyPair(a, supAPrime, PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(thetaPrime, aPrime, PairOperator.SMALLERDOT)); result.add(resultPrime); //} return result; } - protected Set> unifyCase4(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { - Set> result = new HashSet<>(); - Set resultPrime = new HashSet<>(); - resultPrime.add(new MPair(a, thetaPrime, PairOperator.EQUALSDOT)); + protected Set> unifyCase4(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { + Set> result = new HashSet<>(); + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, thetaPrime, PairOperator.EQUALSDOT)); result.add(resultPrime); return result; } - protected Set> unifyCase5(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { - Set> result = new HashSet<>(); + protected Set> unifyCase5(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { + Set> result = new HashSet<>(); for(UnifyType thetaS : fc.greater(theta)) { - Set resultPrime = new HashSet<>(); - resultPrime.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, thetaS, PairOperator.EQUALSDOT)); result.add(resultPrime); } return result; } - protected Set> unifyCase6(ExtendsType extTheta, PlaceholderType a, IFiniteClosure fc) { - Set> result = new HashSet<>(); + protected Set> unifyCase6(ExtendsType extTheta, PlaceholderType a, IFiniteClosure fc) { + Set> result = new HashSet<>(); for(UnifyType thetaS : fc.grArg(extTheta)) { - Set resultPrime = new HashSet<>(); - resultPrime.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, thetaS, PairOperator.EQUALSDOT)); result.add(resultPrime); } return result; } - protected Set> unifyCase7(SuperType supTheta, PlaceholderType a, IFiniteClosure fc) { - Set> result = new HashSet<>(); + protected Set> unifyCase7(SuperType supTheta, PlaceholderType a, IFiniteClosure fc) { + Set> result = new HashSet<>(); IUnify unify = new MartelliMontanariUnify(); UnifyType theta = supTheta.getSuperedType(); @@ -511,16 +511,16 @@ public class Unify { Unifier unifier = opt.get(); - Set substitutionSet = new HashSet<>(); + Set substitutionSet = new HashSet<>(); for (Entry sigma : unifier.getSubstitutions()) - substitutionSet.add(new MPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); for (UnifyType tq : thetaQs) { Set smaller = fc.smaller(unifier.apply(tq)); for(UnifyType thetaPrime : smaller) { - Set resultPrime = new HashSet<>(); - resultPrime.add(new MPair(a, new SuperType(thetaPrime), PairOperator.EQUALSDOT)); + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, new SuperType(thetaPrime), PairOperator.EQUALSDOT)); resultPrime.addAll(substitutionSet); result.add(resultPrime); } @@ -532,11 +532,11 @@ public class Unify { return result; } - protected Set> unifyCase8(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { - Set> result = new HashSet<>(); + protected Set> unifyCase8(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { + Set> result = new HashSet<>(); for(UnifyType thetaS : fc.grArg(theta)) { - Set resultPrime = new HashSet<>(); - resultPrime.add(new MPair(a, thetaS, PairOperator.EQUALSDOT)); + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, thetaS, PairOperator.EQUALSDOT)); result.add(resultPrime); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java index 23c444e0..11c98481 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java @@ -3,46 +3,46 @@ package de.dhbwstuttgart.typeinference.unify.interfaces; import java.util.Optional; import java.util.Set; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; public interface IRuleSet { - public Optional reduceUp(MPair pair); - public Optional reduceLow(MPair pair); - public Optional reduceUpLow(MPair pair); - public Optional> reduceExt(MPair pair); - public Optional> reduceSup(MPair pair); - public Optional> reduceEq(MPair pair); - public Optional> reduce1(MPair pair); - public Optional> reduce2(MPair pair); + public Optional reduceUp(UnifyPair pair); + public Optional reduceLow(UnifyPair pair); + public Optional reduceUpLow(UnifyPair pair); + public Optional> reduceExt(UnifyPair pair); + public Optional> reduceSup(UnifyPair pair); + public Optional> reduceEq(UnifyPair pair); + public Optional> reduce1(UnifyPair pair); + public Optional> reduce2(UnifyPair pair); /* * Missing Rules */ - public Optional reduceWildcardLow(MPair pair); - public Optional reduceWildcardLowRight(MPair pair); - public Optional reduceWildcardUp(MPair pair); - public Optional reduceWildcardUpRight(MPair pair); - public Optional reduceWildcardLowUp(MPair pair); - public Optional reduceWildcardUpLow(MPair pair); - public Optional reduceWildcardLeft(MPair pair); + public Optional reduceWildcardLow(UnifyPair pair); + public Optional reduceWildcardLowRight(UnifyPair pair); + public Optional reduceWildcardUp(UnifyPair pair); + public Optional reduceWildcardUpRight(UnifyPair pair); + public Optional reduceWildcardLowUp(UnifyPair pair); + public Optional reduceWildcardUpLow(UnifyPair pair); + public Optional reduceWildcardLeft(UnifyPair pair); /* * FunN Rules */ - public Optional> reduceFunN(MPair pair); - public Optional> greaterFunN(MPair pair); - public Optional> smallerFunN(MPair pair); + public Optional> reduceFunN(UnifyPair pair); + public Optional> greaterFunN(UnifyPair pair); + public Optional> smallerFunN(UnifyPair pair); - public boolean erase1(MPair pair); - public boolean erase2(MPair pair); - public boolean erase3(MPair pair); + public boolean erase1(UnifyPair pair); + public boolean erase2(UnifyPair pair); + public boolean erase3(UnifyPair pair); - public Optional swap(MPair pair); + public Optional swap(UnifyPair pair); - public Optional adapt(MPair pair); - public Optional adaptExt(MPair pair); - public Optional adaptSup(MPair pair); + public Optional adapt(UnifyPair pair); + public Optional adaptExt(UnifyPair pair); + public Optional adaptSup(UnifyPair pair); - public Optional> subst(Set pair); + public Optional> subst(Set pair); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 5ef8c93a..6fff42cc 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -4,32 +4,30 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; -import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; - + import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; import de.dhbwstuttgart.typeinference.unify.MartelliMontanariUnify; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; -import de.dhbwstuttgart.typeinference.unify.model.PairOperator; public class FiniteClosure implements IFiniteClosure { private HashMap> inheritanceGraph; private HashMap>> strInheritanceGraph; - private Set pairs; + private Set pairs; private Set basicTypes; //TODO im konstruktor mitgeben um typenabzuhandeln die keine extends beziehung haben. (Damit die FC diese Typen auch kennt) //(ALternative: immer die extends zu object beziehung einfügen) - public FiniteClosure(Set pairs) { + public FiniteClosure(Set pairs) { this.pairs = new HashSet<>(pairs); inheritanceGraph = new HashMap>(); // Build the transitive closure of the inheritance tree - for(MPair pair : pairs) { + for(UnifyPair pair : pairs) { if(pair.getPairOp() != PairOperator.SMALLER) continue; @@ -328,7 +326,7 @@ public class FiniteClosure implements IFiniteClosure { if(!strInheritanceGraph.containsKey(t.getName())) return false; - for(MPair pair : pairs) + for(UnifyPair pair : pairs) if(pair.getLhsType().equals(t)) return true; @@ -347,7 +345,7 @@ public class FiniteClosure implements IFiniteClosure { if(!strInheritanceGraph.containsKey(t.getName())) return Optional.empty(); - for(MPair pair : pairs) + for(UnifyPair pair : pairs) if(pair.getLhsType().getName().equals(t.getName())) return Optional.of(pair.getLhsType()); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java index 971566e6..a46ee6d3 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java @@ -37,8 +37,8 @@ public class Unifier implements Function /*, Set*/ return t.apply(this); } - public MPair apply(MPair p) { - return new MPair(this.apply(p.getLhsType()), this.apply(p.getRhsType()), p.getPairOp()); + public UnifyPair apply(UnifyPair p) { + return new UnifyPair(this.apply(p.getLhsType()), this.apply(p.getRhsType()), p.getPairOp()); } public boolean hasSubstitute(PlaceholderType t) { diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/MPair.java b/src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java similarity index 53% rename from src/de/dhbwstuttgart/typeinference/unify/model/MPair.java rename to src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java index 254ba142..cdc7b818 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/MPair.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java @@ -1,6 +1,6 @@ package de.dhbwstuttgart.typeinference.unify.model; -public class MPair { +public class UnifyPair { private UnifyType lhs; private UnifyType rhs; @@ -12,7 +12,7 @@ public class MPair { pairOp = PairOperator.SMALLER; }*/ - public MPair(UnifyType t1, UnifyType t2, PairOperator op) { + public UnifyPair(UnifyType t1, UnifyType t2, PairOperator op) { lhs = t1; rhs = t2; pairOp = op; @@ -32,33 +32,16 @@ public class MPair { @Override public boolean equals(Object obj) { - if(!(obj instanceof MPair)) + if(!(obj instanceof UnifyPair)) return false; - MPair other = (MPair) obj; + UnifyPair other = (UnifyPair) obj; return other.getPairOp() == pairOp && other.getLhsType().equals(lhs) && other.getRhsType().equals(rhs); } - - /** - * Substitutes the occurrences of Type t on the left or right side of the pair with the Type subst. - * @param t Type to be replaced. - * @param subst The type replacing t. - * @return A pair where occurrences of t are replaced by subst. - */ - public MPair substitute(UnifyType t, UnifyType subst) { - UnifyType newlhs = lhs; - if(lhs.equals(t)) newlhs = subst; - - UnifyType newrhs = rhs; - if(rhs.equals(t)) newrhs = subst; - - if(newlhs == lhs && newrhs == rhs) return this; - return new MPair(newlhs, newrhs, pairOp); - } - + @Override public int hashCode() { return 17 + 31 * lhs.hashCode() + 31 * rhs.hashCode() + 31 * pairOp.hashCode(); diff --git a/test/unify/FiniteClosureBuilder.java b/test/unify/FiniteClosureBuilder.java index dcda97fd..8b8b5f73 100644 --- a/test/unify/FiniteClosureBuilder.java +++ b/test/unify/FiniteClosureBuilder.java @@ -5,16 +5,16 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; public class FiniteClosureBuilder { - private Set pairs = new HashSet<>(); + private Set pairs = new HashSet<>(); public void add(UnifyType sub, UnifyType sup) { - pairs.add(new MPair(sub, sup, PairOperator.SMALLER)); + pairs.add(new UnifyPair(sub, sup, PairOperator.SMALLER)); } public IFiniteClosure getFiniteClosure() { diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index 87e648a5..519cf509 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -10,7 +10,7 @@ import org.junit.Assert; import org.junit.Test; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; diff --git a/test/unify/RuleSetTest.java b/test/unify/RuleSetTest.java index dad10d5d..0dc9f319 100644 --- a/test/unify/RuleSetTest.java +++ b/test/unify/RuleSetTest.java @@ -11,7 +11,7 @@ import org.junit.Test; import de.dhbwstuttgart.typeinference.unify.RuleSet; import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; @@ -28,14 +28,14 @@ public class RuleSetTest { * Positive Tests */ - MPair reduce1 = new MPair(tf.getSimpleType("type"), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair reduce2 = new MPair(tf.getPlaceholderType("T"), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair reduce1 = new UnifyPair(tf.getSimpleType("type"), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair reduce2 = new UnifyPair(tf.getPlaceholderType("T"), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair expected1 = new MPair(tf.getSimpleType("type"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair expected2 = new MPair(tf.getPlaceholderType("T"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair expected1 = new UnifyPair(tf.getSimpleType("type"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair expected2 = new UnifyPair(tf.getPlaceholderType("T"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - Optional opt1 = rules.reduceUp(reduce1); - Optional opt2 = rules.reduceUp(reduce2); + Optional opt1 = rules.reduceUp(reduce1); + Optional opt2 = rules.reduceUp(reduce2); Assert.assertTrue(opt1.isPresent()); Assert.assertTrue(opt2.isPresent()); @@ -46,10 +46,10 @@ public class RuleSetTest { * Negative Tests */ - MPair noreduce1 = new MPair(tf.getSuperType(tf.getSimpleType("type")), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair noreduce2 = new MPair(tf.getPlaceholderType("T"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair noreduce3 = new MPair(tf.getPlaceholderType("T"), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair noreduce4 = new MPair(tf.getPlaceholderType("T"), tf.getSuperType(tf.getSimpleType("type")), PairOperator.EQUALSDOT); + UnifyPair noreduce1 = new UnifyPair(tf.getSuperType(tf.getSimpleType("type")), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair noreduce2 = new UnifyPair(tf.getPlaceholderType("T"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair noreduce3 = new UnifyPair(tf.getPlaceholderType("T"), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair noreduce4 = new UnifyPair(tf.getPlaceholderType("T"), tf.getSuperType(tf.getSimpleType("type")), PairOperator.EQUALSDOT); Assert.assertFalse(rules.reduceUp(noreduce1).isPresent()); Assert.assertFalse(rules.reduceUp(noreduce2).isPresent()); @@ -65,14 +65,14 @@ public class RuleSetTest { /* * Positive Tests */ - MPair reduce1 = new MPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair reduce2 = new MPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getPlaceholderType("T"), PairOperator.SMALLERDOT); + UnifyPair reduce1 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair reduce2 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getPlaceholderType("T"), PairOperator.SMALLERDOT); - MPair expected1 = new MPair(tf.getSimpleType("type"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair expected2 = new MPair(tf.getSimpleType("type"), tf.getPlaceholderType("T"), PairOperator.SMALLERDOT); + UnifyPair expected1 = new UnifyPair(tf.getSimpleType("type"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair expected2 = new UnifyPair(tf.getSimpleType("type"), tf.getPlaceholderType("T"), PairOperator.SMALLERDOT); - Optional opt1 = rules.reduceLow(reduce1); - Optional opt2 = rules.reduceLow(reduce2); + Optional opt1 = rules.reduceLow(reduce1); + Optional opt2 = rules.reduceLow(reduce2); Assert.assertTrue(opt1.isPresent()); Assert.assertTrue(opt2.isPresent()); @@ -82,10 +82,10 @@ public class RuleSetTest { /* * Negative Tests */ - MPair noreduce1 = new MPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair noreduce2 = new MPair(tf.getPlaceholderType("T"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair noreduce3 = new MPair(tf.getSuperType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair noreduce4 = new MPair(tf.getExtendsType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.EQUALSDOT); + UnifyPair noreduce1 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair noreduce2 = new UnifyPair(tf.getPlaceholderType("T"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair noreduce3 = new UnifyPair(tf.getSuperType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair noreduce4 = new UnifyPair(tf.getExtendsType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.EQUALSDOT); Assert.assertFalse(rules.reduceLow(noreduce1).isPresent()); Assert.assertFalse(rules.reduceLow(noreduce2).isPresent()); @@ -101,14 +101,14 @@ public class RuleSetTest { /* * Positive Tests */ - MPair reduce1 = new MPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair reduce2 = new MPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getSuperType(tf.getPlaceholderType("T")), PairOperator.SMALLERDOT); + UnifyPair reduce1 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair reduce2 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getSuperType(tf.getPlaceholderType("T")), PairOperator.SMALLERDOT); - MPair expected1 = new MPair(tf.getSimpleType("type"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair expected2 = new MPair(tf.getSimpleType("type"), tf.getPlaceholderType("T"), PairOperator.SMALLERDOT); + UnifyPair expected1 = new UnifyPair(tf.getSimpleType("type"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair expected2 = new UnifyPair(tf.getSimpleType("type"), tf.getPlaceholderType("T"), PairOperator.SMALLERDOT); - Optional opt1 = rules.reduceUpLow(reduce1); - Optional opt2 = rules.reduceUpLow(reduce2); + Optional opt1 = rules.reduceUpLow(reduce1); + Optional opt2 = rules.reduceUpLow(reduce2); Assert.assertTrue(opt1.isPresent()); Assert.assertTrue(opt2.isPresent()); @@ -118,10 +118,10 @@ public class RuleSetTest { /* * Negative Tests */ - MPair noreduce1 = new MPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair noreduce2 = new MPair(tf.getSuperType(tf.getPlaceholderType("T")), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair noreduce3 = new MPair(tf.getSuperType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair noreduce4 = new MPair(tf.getExtendsType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.EQUALSDOT); + UnifyPair noreduce1 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair noreduce2 = new UnifyPair(tf.getSuperType(tf.getPlaceholderType("T")), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair noreduce3 = new UnifyPair(tf.getSuperType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair noreduce4 = new UnifyPair(tf.getExtendsType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.EQUALSDOT); Assert.assertFalse(rules.reduceUpLow(noreduce1).isPresent()); Assert.assertFalse(rules.reduceUpLow(noreduce2).isPresent()); @@ -154,13 +154,13 @@ public class RuleSetTest { fcb.add(buffer, d1); IRuleSet rules = new RuleSet(fcb.getFiniteClosure()); - MPair pair = new MPair(c2, d2, PairOperator.SMALLERDOT); + UnifyPair pair = new UnifyPair(c2, d2, PairOperator.SMALLERDOT); System.out.println("------ Reduce1 ------"); - Optional> res = rules.reduce1(pair); + Optional> res = rules.reduce1(pair); System.out.println(res); - pair = new MPair(c2, c2, PairOperator.SMALLERDOT); + pair = new UnifyPair(c2, c2, PairOperator.SMALLERDOT); res = rules.reduce1(pair); System.out.println(res); @@ -169,17 +169,17 @@ public class RuleSetTest { */ // Case 1: D <. C and C <* D - pair = new MPair(d2, c2, PairOperator.SMALLERDOT); + pair = new UnifyPair(d2, c2, PairOperator.SMALLERDOT); Assert.assertFalse(rules.reduce1(pair).isPresent()); // Case 2: D =. C - pair = new MPair(c2, d2, PairOperator.EQUALSDOT); + pair = new UnifyPair(c2, d2, PairOperator.EQUALSDOT); Assert.assertFalse(rules.reduce1(pair).isPresent()); // Case 3: C <. D and !(C <* D) fcb.clear(); rules = new RuleSet(fcb.getFiniteClosure()); - pair = new MPair(c1, d1, PairOperator.SMALLERDOT); + pair = new UnifyPair(c1, d1, PairOperator.SMALLERDOT); Assert.assertFalse(rules.reduce1(pair).isPresent()); } @@ -199,17 +199,17 @@ public class RuleSetTest { // C ReferenceType c2 = tf.getSimpleType("C", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); - MPair pair1 = new MPair(c1, c2, PairOperator.EQUALSDOT); - MPair pair2 = new MPair(tf.getExtendsType(c1), tf.getExtendsType(c2), PairOperator.EQUALSDOT); - MPair pair3 = new MPair(tf.getSuperType(c1), tf.getSuperType(c2), PairOperator.EQUALSDOT); + UnifyPair pair1 = new UnifyPair(c1, c2, PairOperator.EQUALSDOT); + UnifyPair pair2 = new UnifyPair(tf.getExtendsType(c1), tf.getExtendsType(c2), PairOperator.EQUALSDOT); + UnifyPair pair3 = new UnifyPair(tf.getSuperType(c1), tf.getSuperType(c2), PairOperator.EQUALSDOT); - Optional> opt1 = rules.reduce2(pair1); + Optional> opt1 = rules.reduce2(pair1); System.out.println(opt1); - Optional> opt2 = rules.reduce2(pair2); + Optional> opt2 = rules.reduce2(pair2); System.out.println(opt2); - Optional> opt3 = rules.reduce2(pair3); + Optional> opt3 = rules.reduce2(pair3); System.out.println(opt3); @@ -218,10 +218,10 @@ public class RuleSetTest { */ ReferenceType d1 = tf.getSimpleType("D", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); - pair1 = new MPair(d1, c1, PairOperator.EQUALSDOT); // Case 1: D =. C - pair2 = new MPair(tf.getExtendsType(c1), c2, PairOperator.EQUALSDOT); // Case 2: ? extends C =. C - pair3 = new MPair(tf.getExtendsType(c1), tf.getSuperType(c2), PairOperator.EQUALSDOT); // Case 3: ? extends C =. ? super C - MPair pair4 = new MPair(c1, c2, PairOperator.SMALLERDOT); // Case 4: C <. C + pair1 = new UnifyPair(d1, c1, PairOperator.EQUALSDOT); // Case 1: D =. C + pair2 = new UnifyPair(tf.getExtendsType(c1), c2, PairOperator.EQUALSDOT); // Case 2: ? extends C =. C + pair3 = new UnifyPair(tf.getExtendsType(c1), tf.getSuperType(c2), PairOperator.EQUALSDOT); // Case 3: ? extends C =. ? super C + UnifyPair pair4 = new UnifyPair(c1, c2, PairOperator.SMALLERDOT); // Case 4: C <. C Assert.assertFalse(rules.reduceEq(pair1).isPresent()); Assert.assertFalse(rules.reduceEq(pair2).isPresent()); @@ -254,18 +254,18 @@ public class RuleSetTest { fcb.add(buffer, y1); IRuleSet rules = new RuleSet(fcb.getFiniteClosure()); - MPair pair1 = new MPair(x2, extY1, PairOperator.SMALLERDOTWC); - MPair pair2 = new MPair(tf.getExtendsType(x2), extY1, PairOperator.SMALLERDOTWC); - MPair pair3 = new MPair(extY1, extY1, PairOperator.SMALLERDOTWC); + UnifyPair pair1 = new UnifyPair(x2, extY1, PairOperator.SMALLERDOTWC); + UnifyPair pair2 = new UnifyPair(tf.getExtendsType(x2), extY1, PairOperator.SMALLERDOTWC); + UnifyPair pair3 = new UnifyPair(extY1, extY1, PairOperator.SMALLERDOTWC); System.out.println("------ ReduceExt ------"); - Optional> opt1 = rules.reduceExt(pair1); + Optional> opt1 = rules.reduceExt(pair1); System.out.println(opt1); - Optional> opt2 = rules.reduceExt(pair2); + Optional> opt2 = rules.reduceExt(pair2); System.out.println(opt2); - Optional> opt3 = rules.reduceExt(pair3); + Optional> opt3 = rules.reduceExt(pair3); System.out.println(opt3); /* @@ -273,21 +273,21 @@ public class RuleSetTest { */ // Case 1: X <.? Y - pair1 = new MPair(x2, extY1.getExtendedType(), PairOperator.SMALLERDOTWC); + pair1 = new UnifyPair(x2, extY1.getExtendedType(), PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceExt(pair1).isPresent()); // Case 2: X =. ? super Y - pair2 = new MPair(x2, extY1, PairOperator.EQUALSDOT); + pair2 = new UnifyPair(x2, extY1, PairOperator.EQUALSDOT); Assert.assertFalse(rules.reduceExt(pair2).isPresent()); // Case 3: ? extends Y <.? ? extends X - pair3 = new MPair(extY1, tf.getExtendsType(x2), PairOperator.SMALLERDOTWC); + pair3 = new UnifyPair(extY1, tf.getExtendsType(x2), PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceExt(pair3).isPresent()); // Case 4: X <. ? extends Y and ? extends Y not in grArg(X) fcb.clear(); rules = new RuleSet(fcb.getFiniteClosure()); - pair1 = new MPair(x2, extY1, PairOperator.SMALLERDOTWC); + pair1 = new UnifyPair(x2, extY1, PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceExt(pair1).isPresent()); } @@ -316,18 +316,18 @@ public class RuleSetTest { fcb.add(buffer, x1); IRuleSet rules = new RuleSet(fcb.getFiniteClosure()); - MPair pair1 = new MPair(x2, supY1, PairOperator.SMALLERDOTWC); - MPair pair2 = new MPair(tf.getSuperType(x2), supY1, PairOperator.SMALLERDOTWC); - MPair pair3 = new MPair(supY1, supY1, PairOperator.SMALLERDOTWC); + UnifyPair pair1 = new UnifyPair(x2, supY1, PairOperator.SMALLERDOTWC); + UnifyPair pair2 = new UnifyPair(tf.getSuperType(x2), supY1, PairOperator.SMALLERDOTWC); + UnifyPair pair3 = new UnifyPair(supY1, supY1, PairOperator.SMALLERDOTWC); System.out.println("------ ReduceSup ------"); - Optional> opt1 = rules.reduceSup(pair1); + Optional> opt1 = rules.reduceSup(pair1); System.out.println(opt1); - Optional> opt2 = rules.reduceSup(pair2); + Optional> opt2 = rules.reduceSup(pair2); System.out.println(opt2); - Optional> opt3 = rules.reduceSup(pair3); + Optional> opt3 = rules.reduceSup(pair3); System.out.println(opt3); /* @@ -335,21 +335,21 @@ public class RuleSetTest { */ // Case 1: X <.? Y - pair1 = new MPair(x2, supY1.getSuperedType(), PairOperator.SMALLERDOTWC); + pair1 = new UnifyPair(x2, supY1.getSuperedType(), PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceSup(pair1).isPresent()); // Case 2: X =. ? super Y - pair2 = new MPair(x2, supY1, PairOperator.EQUALSDOT); + pair2 = new UnifyPair(x2, supY1, PairOperator.EQUALSDOT); Assert.assertFalse(rules.reduceSup(pair2).isPresent()); // Case 3: ? super Y <.? ? super X - pair3 = new MPair(supY1, tf.getSuperType(x2), PairOperator.SMALLERDOTWC); + pair3 = new UnifyPair(supY1, tf.getSuperType(x2), PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceSup(pair3).isPresent()); // Case 4: X <. ? super Y and ? super Y not in grArg(X) fcb.clear(); rules = new RuleSet(fcb.getFiniteClosure()); - pair1 = new MPair(x2, supY1, PairOperator.SMALLERDOTWC); + pair1 = new UnifyPair(x2, supY1, PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceSup(pair1).isPresent()); } @@ -369,8 +369,8 @@ public class RuleSetTest { // C ReferenceType c2 = tf.getSimpleType("C", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); - MPair pair = new MPair(c1, c2, PairOperator.SMALLERDOTWC); - Optional> res = rules.reduceEq(pair); + UnifyPair pair = new UnifyPair(c1, c2, PairOperator.SMALLERDOTWC); + Optional> res = rules.reduceEq(pair); System.out.println(res); /* @@ -379,11 +379,11 @@ public class RuleSetTest { // Case 1: D <.? C ReferenceType d1 = tf.getSimpleType("D", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); - pair = new MPair(d1, c1, PairOperator.SMALLERDOTWC); + pair = new UnifyPair(d1, c1, PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceEq(pair).isPresent()); // Case 2: C <. C - pair = new MPair(c1, c2, PairOperator.SMALLERDOT); + pair = new UnifyPair(c1, c2, PairOperator.SMALLERDOT); Assert.assertFalse(rules.reduceEq(pair).isPresent()); } @@ -395,9 +395,9 @@ public class RuleSetTest { /* * Positive Tests */ - MPair erase1 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("Collection"), PairOperator.SMALLERDOT); - MPair erase2 = new MPair(tf.getSimpleType("HashSet", "T"), tf.getSimpleType("Collection"), PairOperator.SMALLERDOT); - MPair erase3 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); + UnifyPair erase1 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("Collection"), PairOperator.SMALLERDOT); + UnifyPair erase2 = new UnifyPair(tf.getSimpleType("HashSet", "T"), tf.getSimpleType("Collection"), PairOperator.SMALLERDOT); + UnifyPair erase3 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); Assert.assertTrue(rules.erase1(erase1)); Assert.assertTrue(rules.erase1(erase2)); @@ -406,9 +406,9 @@ public class RuleSetTest { /* * Negative Tests */ - MPair noerase1 = new MPair(tf.getSimpleType("Collection"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); - MPair noerase2 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("Collection"), PairOperator.EQUALSDOT); - MPair noerase3 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("Collection"), PairOperator.SMALLERDOTWC); + UnifyPair noerase1 = new UnifyPair(tf.getSimpleType("Collection"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); + UnifyPair noerase2 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("Collection"), PairOperator.EQUALSDOT); + UnifyPair noerase3 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("Collection"), PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.erase1(noerase1)); Assert.assertFalse(rules.erase1(noerase2)); @@ -423,11 +423,11 @@ public class RuleSetTest { /* * Positive Tests */ - MPair erase1 = new MPair(tf.getSimpleType("List", "T"), tf.getExtendsType(tf.getSimpleType("Collection")), PairOperator.SMALLERDOTWC); - MPair erase2 = new MPair(tf.getSimpleType("Collection"), tf.getSuperType(tf.getSimpleType("HashSet", "T")), PairOperator.SMALLERDOTWC); - MPair erase3 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOTWC); - MPair erase4 = new MPair(tf.getExtendsType(tf.getSimpleType("LinkedList", "T")), tf.getExtendsType(tf.getSimpleType("List", "T")), PairOperator.SMALLERDOTWC); - MPair erase5 = new MPair(tf.getSuperType(tf.getSimpleType("List", "T")), tf.getSuperType(tf.getSimpleType("Stack", "T")), PairOperator.SMALLERDOTWC); + UnifyPair erase1 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getExtendsType(tf.getSimpleType("Collection")), PairOperator.SMALLERDOTWC); + UnifyPair erase2 = new UnifyPair(tf.getSimpleType("Collection"), tf.getSuperType(tf.getSimpleType("HashSet", "T")), PairOperator.SMALLERDOTWC); + UnifyPair erase3 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOTWC); + UnifyPair erase4 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("LinkedList", "T")), tf.getExtendsType(tf.getSimpleType("List", "T")), PairOperator.SMALLERDOTWC); + UnifyPair erase5 = new UnifyPair(tf.getSuperType(tf.getSimpleType("List", "T")), tf.getSuperType(tf.getSimpleType("Stack", "T")), PairOperator.SMALLERDOTWC); Assert.assertTrue(rules.erase2(erase1)); @@ -439,10 +439,10 @@ public class RuleSetTest { /* * Negative Tests */ - MPair noerase1 = new MPair(tf.getSimpleType("Collection"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOTWC); - MPair noerase2 = new MPair(tf.getSuperType(tf.getSimpleType("List", "T")), tf.getSimpleType("ArrayList", "T"), PairOperator.SMALLERDOTWC); - MPair noerase3 = new MPair(tf.getExtendsType(tf.getSimpleType("List", "T")), tf.getSuperType(tf.getSimpleType("List", "T")), PairOperator.SMALLERDOTWC); - MPair noerase4 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); + UnifyPair noerase1 = new UnifyPair(tf.getSimpleType("Collection"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOTWC); + UnifyPair noerase2 = new UnifyPair(tf.getSuperType(tf.getSimpleType("List", "T")), tf.getSimpleType("ArrayList", "T"), PairOperator.SMALLERDOTWC); + UnifyPair noerase3 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("List", "T")), tf.getSuperType(tf.getSimpleType("List", "T")), PairOperator.SMALLERDOTWC); + UnifyPair noerase4 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); Assert.assertFalse(rules.erase2(noerase1)); Assert.assertFalse(rules.erase2(noerase2)); @@ -458,8 +458,8 @@ public class RuleSetTest { /* * Positive Tests */ - MPair erase1 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.EQUALSDOT); - MPair erase2 = new MPair(tf.getPlaceholderType("W"), tf.getPlaceholderType("W"), PairOperator.EQUALSDOT); + UnifyPair erase1 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.EQUALSDOT); + UnifyPair erase2 = new UnifyPair(tf.getPlaceholderType("W"), tf.getPlaceholderType("W"), PairOperator.EQUALSDOT); Assert.assertTrue(rules.erase3(erase1)); Assert.assertTrue(rules.erase3(erase2)); @@ -467,8 +467,8 @@ public class RuleSetTest { /* * Negative Tests */ - MPair noerase1 = new MPair(tf.getSimpleType("Collection"), tf.getSimpleType("List", "T"), PairOperator.EQUALSDOT); - MPair noerase2 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); + UnifyPair noerase1 = new UnifyPair(tf.getSimpleType("Collection"), tf.getSimpleType("List", "T"), PairOperator.EQUALSDOT); + UnifyPair noerase2 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); Assert.assertFalse(rules.erase3(noerase1)); Assert.assertFalse(rules.erase3(noerase2)); @@ -482,14 +482,14 @@ public class RuleSetTest { /* * Positive Tests */ - MPair swap1 = new MPair(tf.getExtendsType(tf.getSimpleType("MyClass")), tf.getPlaceholderType("P"), PairOperator.EQUALSDOT); - MPair swap2 = new MPair(tf.getSimpleType("MyClass"), tf.getPlaceholderType("X"), PairOperator.EQUALSDOT); + UnifyPair swap1 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("MyClass")), tf.getPlaceholderType("P"), PairOperator.EQUALSDOT); + UnifyPair swap2 = new UnifyPair(tf.getSimpleType("MyClass"), tf.getPlaceholderType("X"), PairOperator.EQUALSDOT); - MPair expected1 = new MPair(tf.getPlaceholderType("P"), tf.getExtendsType(tf.getSimpleType("MyClass")), PairOperator.EQUALSDOT); - MPair expected2 = new MPair(tf.getPlaceholderType("X"), tf.getSimpleType("MyClass"), PairOperator.EQUALSDOT); + UnifyPair expected1 = new UnifyPair(tf.getPlaceholderType("P"), tf.getExtendsType(tf.getSimpleType("MyClass")), PairOperator.EQUALSDOT); + UnifyPair expected2 = new UnifyPair(tf.getPlaceholderType("X"), tf.getSimpleType("MyClass"), PairOperator.EQUALSDOT); - Optional opt1 = rules.swap(swap1); - Optional opt2 = rules.swap(swap2); + Optional opt1 = rules.swap(swap1); + Optional opt2 = rules.swap(swap2); // swap((? extends MyClass =. P)) = (P =. MyClass) Assert.assertEquals(opt1.get(), expected1); @@ -500,15 +500,15 @@ public class RuleSetTest { /* * Negative Tests */ - MPair noswap1 = new MPair(tf.getPlaceholderType("Z"), tf.getPlaceholderType("X"), PairOperator.EQUALSDOT); - MPair noswap2 = new MPair(tf.getSimpleType("MyClass"), tf.getExtendsType(tf.getPlaceholderType("X")), PairOperator.EQUALSDOT); - MPair noswap3 = new MPair( tf.getPlaceholderType("X"), tf.getSimpleType("MyClass"), PairOperator.EQUALSDOT); - MPair noswap4 = new MPair(tf.getSimpleType("MyClass"), tf.getPlaceholderType("X"), PairOperator.SMALLERDOT); + UnifyPair noswap1 = new UnifyPair(tf.getPlaceholderType("Z"), tf.getPlaceholderType("X"), PairOperator.EQUALSDOT); + UnifyPair noswap2 = new UnifyPair(tf.getSimpleType("MyClass"), tf.getExtendsType(tf.getPlaceholderType("X")), PairOperator.EQUALSDOT); + UnifyPair noswap3 = new UnifyPair( tf.getPlaceholderType("X"), tf.getSimpleType("MyClass"), PairOperator.EQUALSDOT); + UnifyPair noswap4 = new UnifyPair(tf.getSimpleType("MyClass"), tf.getPlaceholderType("X"), PairOperator.SMALLERDOT); opt1 = rules.swap(noswap1); opt2 = rules.swap(noswap2); - Optional opt3 = rules.swap(noswap3); - Optional opt4 = rules.swap(noswap4); + Optional opt3 = rules.swap(noswap3); + Optional opt4 = rules.swap(noswap4); Assert.assertFalse(opt1.isPresent()); Assert.assertFalse(opt2.isPresent()); @@ -538,9 +538,9 @@ public class RuleSetTest { ReferenceType c2 = tf.getSimpleType("Type2", "Object"); ReferenceType c3 = tf.getSimpleType("Type3", "Object", "Number"); - MPair pair1 = new MPair(c1, c2, PairOperator.SMALLERDOT); - MPair pair2 = new MPair(c2, c3, PairOperator.SMALLERDOT); - MPair pair3 = new MPair(c1, c3, PairOperator.SMALLERDOT); + UnifyPair pair1 = new UnifyPair(c1, c2, PairOperator.SMALLERDOT); + UnifyPair pair2 = new UnifyPair(c2, c3, PairOperator.SMALLERDOT); + UnifyPair pair3 = new UnifyPair(c1, c3, PairOperator.SMALLERDOT); System.out.println("------ Adapt ------"); System.out.println(rules.adapt(pair1)); @@ -551,9 +551,9 @@ public class RuleSetTest { * Negative Tests */ - MPair noAdapt1 = new MPair(c2, c1, PairOperator.SMALLERDOT); - MPair noAdapt2 = new MPair(c1, c1, PairOperator.SMALLERDOT); - MPair noAdapt3 = new MPair(c1, c2, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt1 = new UnifyPair(c2, c1, PairOperator.SMALLERDOT); + UnifyPair noAdapt2 = new UnifyPair(c1, c1, PairOperator.SMALLERDOT); + UnifyPair noAdapt3 = new UnifyPair(c1, c2, PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.adapt(noAdapt1).isPresent()); Assert.assertFalse(rules.adapt(noAdapt2).isPresent()); @@ -588,13 +588,13 @@ public class RuleSetTest { ExtendsType extc2 = new ExtendsType(c2); ExtendsType extc3 = new ExtendsType(c3); - MPair pair1 = new MPair(c1, extc2, PairOperator.SMALLERDOTWC); - MPair pair2 = new MPair(c2, extc3, PairOperator.SMALLERDOTWC); - MPair pair3 = new MPair(c1, extc3, PairOperator.SMALLERDOTWC); - MPair pair4 = new MPair(extc1, extc2, PairOperator.SMALLERDOTWC); - MPair pair5 = new MPair(extc2, extc3, PairOperator.SMALLERDOTWC); - MPair pair6 = new MPair(extc1, extc3, PairOperator.SMALLERDOTWC); - MPair pair7 = new MPair(extc1, extc1, PairOperator.SMALLERDOTWC); + UnifyPair pair1 = new UnifyPair(c1, extc2, PairOperator.SMALLERDOTWC); + UnifyPair pair2 = new UnifyPair(c2, extc3, PairOperator.SMALLERDOTWC); + UnifyPair pair3 = new UnifyPair(c1, extc3, PairOperator.SMALLERDOTWC); + UnifyPair pair4 = new UnifyPair(extc1, extc2, PairOperator.SMALLERDOTWC); + UnifyPair pair5 = new UnifyPair(extc2, extc3, PairOperator.SMALLERDOTWC); + UnifyPair pair6 = new UnifyPair(extc1, extc3, PairOperator.SMALLERDOTWC); + UnifyPair pair7 = new UnifyPair(extc1, extc1, PairOperator.SMALLERDOTWC); System.out.println("------ AdaptExt ------"); System.out.println(rules.adaptExt(pair1)); @@ -609,11 +609,11 @@ public class RuleSetTest { * Negative Tests */ - MPair noAdapt1 = new MPair(extc2, extc1, PairOperator.SMALLERDOTWC); - MPair noAdapt2 = new MPair(extc1, c2, PairOperator.SMALLERDOTWC); - MPair noAdapt3 = new MPair(tf.getSuperType(c1), extc2, PairOperator.SMALLERDOTWC); - MPair noAdapt4 = new MPair(extc3, extc1, PairOperator.SMALLERDOTWC); - MPair noAdapt5 = new MPair(c1, extc2, PairOperator.SMALLERDOT); + UnifyPair noAdapt1 = new UnifyPair(extc2, extc1, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt2 = new UnifyPair(extc1, c2, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt3 = new UnifyPair(tf.getSuperType(c1), extc2, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt4 = new UnifyPair(extc3, extc1, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt5 = new UnifyPair(c1, extc2, PairOperator.SMALLERDOT); Assert.assertFalse(rules.adaptExt(noAdapt1).isPresent()); Assert.assertFalse(rules.adaptExt(noAdapt2).isPresent()); @@ -650,13 +650,13 @@ public class RuleSetTest { SuperType supc2 = new SuperType(c2); SuperType supc3 = new SuperType(c3); - MPair pair1 = new MPair(c2, supc1, PairOperator.SMALLERDOTWC); - MPair pair2 = new MPair(c3, supc2, PairOperator.SMALLERDOTWC); - MPair pair3 = new MPair(c3, supc1, PairOperator.SMALLERDOTWC); - MPair pair4 = new MPair(supc2, supc1, PairOperator.SMALLERDOTWC); - MPair pair5 = new MPair(supc3, supc2, PairOperator.SMALLERDOTWC); - MPair pair6 = new MPair(supc3, supc1, PairOperator.SMALLERDOTWC); - MPair pair7 = new MPair(supc1, supc1, PairOperator.SMALLERDOTWC); + UnifyPair pair1 = new UnifyPair(c2, supc1, PairOperator.SMALLERDOTWC); + UnifyPair pair2 = new UnifyPair(c3, supc2, PairOperator.SMALLERDOTWC); + UnifyPair pair3 = new UnifyPair(c3, supc1, PairOperator.SMALLERDOTWC); + UnifyPair pair4 = new UnifyPair(supc2, supc1, PairOperator.SMALLERDOTWC); + UnifyPair pair5 = new UnifyPair(supc3, supc2, PairOperator.SMALLERDOTWC); + UnifyPair pair6 = new UnifyPair(supc3, supc1, PairOperator.SMALLERDOTWC); + UnifyPair pair7 = new UnifyPair(supc1, supc1, PairOperator.SMALLERDOTWC); System.out.println("------ AdaptSup ------"); System.out.println(rules.adaptSup(pair1)); @@ -671,11 +671,11 @@ public class RuleSetTest { * Negative Tests */ - MPair noAdapt1 = new MPair(supc2, supc1, PairOperator.SMALLERDOTWC); - MPair noAdapt2 = new MPair(supc1, c2, PairOperator.SMALLERDOTWC); - MPair noAdapt3 = new MPair(tf.getExtendsType(c1), supc2, PairOperator.SMALLERDOTWC); - MPair noAdapt4 = new MPair(supc3, supc1, PairOperator.SMALLERDOTWC); - MPair noAdapt5 = new MPair(c1, supc2, PairOperator.SMALLERDOT); + UnifyPair noAdapt1 = new UnifyPair(supc2, supc1, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt2 = new UnifyPair(supc1, c2, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt3 = new UnifyPair(tf.getExtendsType(c1), supc2, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt4 = new UnifyPair(supc3, supc1, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt5 = new UnifyPair(c1, supc2, PairOperator.SMALLERDOT); Assert.assertFalse(rules.adaptExt(noAdapt1).isPresent()); Assert.assertFalse(rules.adaptExt(noAdapt2).isPresent()); diff --git a/test/unify/StandardUnifyTest.java b/test/unify/StandardUnifyTest.java index b8e8a479..2664324c 100644 --- a/test/unify/StandardUnifyTest.java +++ b/test/unify/StandardUnifyTest.java @@ -9,7 +9,7 @@ import org.junit.Test; import de.dhbwstuttgart.typeinference.unify.MartelliMontanariUnify; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public class StandardUnifyTest { @@ -28,7 +28,7 @@ public class StandardUnifyTest { UnifyType f = tf.getSimpleType("f", x); // {f = y} - Set terms = new HashSet(); + Set terms = new HashSet(); System.out.println(unify.unify(f, y).get()); diff --git a/test/unify/UnifyOldTest.java b/test/unify/UnifyOldTest.java index a2de8ce0..e07f303c 100644 --- a/test/unify/UnifyOldTest.java +++ b/test/unify/UnifyOldTest.java @@ -7,15 +7,10 @@ import org.junit.Test; import de.dhbwstuttgart.syntaxtree.factory.UnifyPairMengenBuilder; import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory; import de.dhbwstuttgart.syntaxtree.factory.Unify_FC_TTO_Builder; -import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; -import de.dhbwstuttgart.syntaxtree.type.ObjectType; +import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; -import de.dhbwstuttgart.syntaxtree.type.Type; -import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.syntaxtree.type.WildcardType; import de.dhbwstuttgart.typeinference.Menge; import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.unify.Unify; @@ -25,318 +20,15 @@ public class UnifyOldTest { @Test public void unifyTest1() { // Init Factories and Builders + UnifyTypeFactory typeFactory = new UnifyTypeFactory(); Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); -<<<<<<< HEAD - /* - * Test a <. Boolean - */ - - // Init Types - RefType boolT = this.GetSimpleType("java.lang.Boolean"); - TypePlaceholder aTph = this.GetTypePlaceholder("a"); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(aTph, boolT, PairOperator.Equal); - resultBuilder.addPair(aTph, this.GetExtendsType(boolT), - PairOperator.Equal); - Menge> expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(aTph, boolT); - Menge> actualResult = Unify.unify( - assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test b <. a, a <. Boolean - */ - - // Init Types - boolT = this.GetSimpleType("java.lang.Boolean"); - aTph = this.GetTypePlaceholder("a"); - TypePlaceholder bTph = this.GetTypePlaceholder("b"); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(aTph, boolT, PairOperator.Equal); - resultBuilder.addPair(aTph, this.GetExtendsType(boolT), - PairOperator.Equal); - resultBuilder.addPair(bTph, boolT, PairOperator.Equal); - resultBuilder.addPair(bTph, this.GetExtendsType(boolT), - PairOperator.Equal); - expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(bTph, aTph); - assumptionBuilder.addPair(aTph, boolT); - actualResult = Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - // NOTE: Elemente im actualResult sind nicht unique - // Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test b <. a, a <. b - */ - - aTph = this.GetTypePlaceholder("a"); - bTph = this.GetTypePlaceholder("b"); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(bTph, aTph); - resultBuilder.addPair(aTph, bTph); - - Menge buffer = resultBuilder.getPairMenge(); - expectedResult = new Menge>(); - expectedResult.add(buffer); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(bTph, aTph); - assumptionBuilder.addPair(aTph, bTph); - actualResult = Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test Integer <. a, a <. Boolean - */ - - RefType intT = this.GetSimpleType("java.lang.Integer"); - boolT = this.GetSimpleType("java.lang.Boolean"); - aTph = this.GetTypePlaceholder("a"); - bTph = this.GetTypePlaceholder("b"); - - // Expected Result - resultBuilder.clear(); - expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(intT, aTph); - assumptionBuilder.addPair(aTph, boolT); - actualResult = Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - } - - @Test - public void unifyTestGenerics() { - - // Init Factories and Builders - Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); - UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); - UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); - - /* - * Test a <. MyClass - */ - - TypePlaceholder aTph = this.GetTypePlaceholder("a"); - RefType myType = this.GetSimpleType("MyClass", - this.GetTypePlaceholder("T"), - this.GetTypePlaceholder("F")); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(aTph, myType, PairOperator.Equal); - resultBuilder.addPair(aTph, this.GetExtendsType(myType)); - Menge> expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(aTph, myType); - Menge> actualResult = Unify.unify( - assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test List> <. List - */ - - TypePlaceholder tTph = this.GetTypePlaceholder("T"); - RefType list = this.GetSimpleType("List", tTph); - RefType listlist = this.GetSimpleType("List", list); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(this.GetExtendsType(list), tTph, - PairOperator.Equal); - expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(listlist, list); - actualResult = Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO()); - - System.out.println(expectedResult); - System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test List <. List> - */ - } - - @Test - public void unifyTestInheritance() { - - // Init Factories and Builders - Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); - UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); - UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); - - // Init Types - RefType tBool = this.GetSimpleType("java.lang.Boolean"); - RefType tString = this.GetSimpleType("java.lang.String"); - RefType tInt = this.GetSimpleType("java.lang.Integer"); - TypePlaceholder tphA = this.GetTypePlaceholder("a"); - - // Build inheritance hierachy - // Bool <. String <. Int - fcBuilder.AddInheritance(tBool, tString); - fcBuilder.AddInheritance(tString, tInt); - - // Build Assumptions - assumptionBuilder.addPair(tphA, tString); - - // Build expected result - resultBuilder.addPair(tphA, tBool, PairOperator.Equal); - resultBuilder.addPair(tphA, this.GetExtendsType(tBool), - PairOperator.Equal); - resultBuilder.addPair(tphA, tString, PairOperator.Equal); - resultBuilder.addPair(tphA, this.GetExtendsType(tString), - PairOperator.Equal); - - // Assert - Menge> actualResult = Unify.unify( - assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); - - // System.out.println(actualResult); - // System.out.println("-------------------"); - // System.out.println(resultBuilder.getNestedPairMenge()); - - Assert.assertTrue(mengeEquals(resultBuilder.getNestedPairMenge(), - actualResult)); - } - - @Test - public void unifyTestWildcards() { - - } - - private static boolean mengeEquals(Menge> m1, - Menge> m2) { - if (m1.size() != m2.size()) - return false; - - return containsAll(m1, m2) && containsAll(m2, m1); - } - - private static boolean containsAll(Menge> m1, - Menge> m2) { - for (Menge elem : m2) - if (!contains(m1, elem)) - return false; - return true; - } - - private static boolean contains(Menge> m1, Menge m2) { - for (Menge elem : m1) - if (mengePairEquals(elem, m2)) - return true; - return false; - } - - private static boolean mengePairEquals(Menge m1, Menge m2) { - if (m1.size() != m2.size()) - return false; - - return containsAllPair(m1, m2) && containsAllPair(m2, m1); - } - - private static boolean containsAllPair(Menge m1, Menge m2) { - for (Pair elem : m1) - if (contains(m2, elem)) - return true; - return false; - } - - private static boolean contains(Menge m, Pair p) { - for (Pair elem : m) - if (pairEquals(elem, p)) - return true; - return false; - - } - - private static boolean pairEquals(Pair p1, Pair p2) { - return (p1.TA1.equals(p2.TA1) && p1.TA2.equals(p2.TA2)) - || (p1.TA1.equals(p2.TA2) && p1.TA2.equals(p2.TA1)); - } - - - private RefType GetSimpleType(String name, Type... parameters) { - if(parameters.length == 0) - return new RefType(name, null, 0); - - Menge typeParams = new Menge(); - - for(Type t : parameters) - typeParams.add(t); - - return new RefType(name, typeParams, null, 0); - } - - private ExtendsWildcardType GetExtendsType(ObjectType extendedType) { - return new ExtendsWildcardType(extendedType); - } - - private SuperWildcardType GetSuperType(ObjectType superedType) { - return new SuperWildcardType(superedType); - } - - private WildcardType GetWildcardType() { - return new WildcardType(null, null, 0); - } - - private TypePlaceholder GetTypePlaceholder(String name) { - return TypePlaceholder.backdoorCreate(name); - } -======= TypePlaceholder a = typeFactory.GetTypePlaceholder("a"); ExtendsWildcardType extA = typeFactory.GetExtendsType(a); - TypePlaceholder b = typeFactory.GetTypePlaceholder("b"); - ExtendsWildcardType extB = typeFactory.GetExtendsType(b); + TypePlaceholder b = typeFactory.GetTypePlaceholder("a"); + ExtendsWildcardType extB = typeFactory.GetExtendsType(a); RefType integer = typeFactory.GetSimpleType("Integer"); SuperWildcardType supInt = typeFactory.GetSuperType(integer); RefType listsupint = typeFactory.GetSimpleType("List", supInt); @@ -643,6 +335,5 @@ public class UnifyOldTest { // return (p1.TA1.equals(p2.TA1) && p1.TA2.equals(p2.TA2)) // || (p1.TA1.equals(p2.TA2) && p1.TA2.equals(p2.TA1)); // } ->>>>>>> d89d06797e17a7a95f007fe24e9b6133b3b13179 } diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index b4aaa86e..0ee466e4 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -10,7 +10,7 @@ import org.junit.Test; import de.dhbwstuttgart.typeinference.unify.Unify; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; @@ -48,10 +48,10 @@ public class UnifyTest extends Unify { * unify({ }) = { } */ - Set eq = new HashSet(); - Set> expected = new HashSet<>(); + Set eq = new HashSet(); + Set> expected = new HashSet<>(); expected.add(new HashSet<>()); - Set> actual = unify(eq, fc); + Set> actual = unify(eq, fc); Assert.assertEquals(expected, actual); /* @@ -62,12 +62,12 @@ public class UnifyTest extends Unify { UnifyType tphA = tf.getPlaceholderType("a"); eq = new HashSet<>(); - eq.add(new MPair(tphA, number, PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(tphA, number, PairOperator.SMALLERDOT)); expected = new HashSet<>(); - addAsSet(expected, new MPair(tphA, number, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, integer, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, doubl, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, integer, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, doubl, PairOperator.EQUALSDOT)); actual = unify(eq, fc); @@ -80,12 +80,12 @@ public class UnifyTest extends Unify { */ eq = new HashSet<>(); - eq.add(new MPair(integer, tphA, PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(integer, tphA, PairOperator.SMALLERDOT)); expected = new HashSet<>(); - addAsSet(expected, new MPair(tphA, integer, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, number, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, object, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, integer, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, object, PairOperator.EQUALSDOT)); actual = unify(eq, fc); @@ -99,10 +99,10 @@ public class UnifyTest extends Unify { */ eq = new HashSet<>(); - eq.add(new MPair(tphA, number, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphA, number, PairOperator.SMALLERDOTWC)); expected = new HashSet<>(); - addAsSet(expected, new MPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); actual = unify(eq, fc); @@ -118,15 +118,15 @@ public class UnifyTest extends Unify { UnifyType supNumber = tf.getSuperType(number); UnifyType supObject = tf.getSuperType(object); eq = new HashSet<>(); - eq.add(new MPair(tphA, supInteger, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphA, supInteger, PairOperator.SMALLERDOTWC)); expected = new HashSet<>(); - addAsSet(expected, new MPair(tphA, integer, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, number, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, object, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, supInteger, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, supNumber, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, supObject, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, integer, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, object, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, supInteger, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, supNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, supObject, PairOperator.EQUALSDOT)); actual = unify(eq, fc); actual = filterGeneratedTPHsMultiple(actual); @@ -144,15 +144,15 @@ public class UnifyTest extends Unify { UnifyType extNumber = tf.getExtendsType(number); UnifyType extObject = tf.getExtendsType(object); UnifyType supDouble = tf.getSuperType(doubl); - eq.add(new MPair(number, tphA, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(number, tphA, PairOperator.SMALLERDOTWC)); expected = new HashSet<>(); - addAsSet(expected, new MPair(tphA, number, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, extNumber, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, extObject, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, supInteger, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, supDouble, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, supNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, extNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, extObject, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, supInteger, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, supDouble, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, supNumber, PairOperator.EQUALSDOT)); actual = unify(eq, fc); @@ -165,11 +165,11 @@ public class UnifyTest extends Unify { */ eq = new HashSet<>(); - eq.add(new MPair(extNumber, tphA, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(extNumber, tphA, PairOperator.SMALLERDOTWC)); expected = new HashSet<>(); - addAsSet(expected, new MPair(tphA, extNumber, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, extObject, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, extNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, extObject, PairOperator.EQUALSDOT)); actual = unify(eq, fc); @@ -186,15 +186,15 @@ public class UnifyTest extends Unify { UnifyType extDouble = tf.getExtendsType(doubl); eq = new HashSet<>(); - eq.add(new MPair(tphA, extNumber, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphA, extNumber, PairOperator.SMALLERDOTWC)); expected = new HashSet<>(); - addAsSet(expected, new MPair(tphA, extNumber, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, extInteger, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, extDouble, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, doubl, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, integer, PairOperator.EQUALSDOT)); - addAsSet(expected, new MPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, extNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, extInteger, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, extDouble, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, doubl, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, integer, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); actual = unify(eq, fc); @@ -207,7 +207,7 @@ public class UnifyTest extends Unify { */ eq = new HashSet<>(); - eq.add(new MPair(integer, number, PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(integer, number, PairOperator.SMALLERDOT)); expected = new HashSet<>(); expected.add(new HashSet<>()); @@ -223,7 +223,7 @@ public class UnifyTest extends Unify { */ eq = new HashSet<>(); - eq.add(new MPair(integer, number, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(integer, number, PairOperator.SMALLERDOTWC)); expected = new HashSet<>(); @@ -239,10 +239,10 @@ public class UnifyTest extends Unify { UnifyType tphB = tf.getPlaceholderType("b"); eq = new HashSet<>(); - eq.add(new MPair(tphA, tphB, PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(tphA, tphB, PairOperator.SMALLERDOT)); expected = new HashSet<>(); - addAsSet(expected, new MPair(tphA, tphB, PairOperator.SMALLERDOT)); + addAsSet(expected, new UnifyPair(tphA, tphB, PairOperator.SMALLERDOT)); actual = unify(eq, fc); @@ -255,10 +255,10 @@ public class UnifyTest extends Unify { */ eq = new HashSet<>(); - eq.add(new MPair(tphA, tphB, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphA, tphB, PairOperator.SMALLERDOTWC)); expected = new HashSet<>(); - addAsSet(expected, new MPair(tphA, tphB, PairOperator.SMALLERDOTWC)); + addAsSet(expected, new UnifyPair(tphA, tphB, PairOperator.SMALLERDOTWC)); actual = unify(eq, fc); @@ -296,12 +296,12 @@ public class UnifyTest extends Unify { UnifyType extB = tf.getExtendsType(tphB); UnifyType extNum = tf.getExtendsType(number); - Set eq = new HashSet(); - eq.add(new MPair(tf.getSimpleType("Vector", tphA), tf.getSimpleType("Vector", extB), PairOperator.SMALLERDOT)); - eq.add(new MPair(tf.getSimpleType("List", tphB), tf.getSimpleType("List", extNum), PairOperator.SMALLERDOT)); + Set eq = new HashSet(); + eq.add(new UnifyPair(tf.getSimpleType("Vector", tphA), tf.getSimpleType("Vector", extB), PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(tf.getSimpleType("List", tphB), tf.getSimpleType("List", extNum), PairOperator.SMALLERDOT)); - Set> expected = new HashSet<>(); - Set> actual = unify(eq, fc); + Set> expected = new HashSet<>(); + Set> actual = unify(eq, fc); System.out.println(actual); //Assert.assertEquals(actual, expected); @@ -315,8 +315,8 @@ public class UnifyTest extends Unify { UnifyType supB = tf.getSuperType(tphB); eq = new HashSet<>(); - eq.add(new MPair(tphA, supB, PairOperator.SMALLERDOTWC)); - eq.add(new MPair(tphB, number, PairOperator.EQUALSDOT)); + eq.add(new UnifyPair(tphA, supB, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphB, number, PairOperator.EQUALSDOT)); expected = new HashSet<>(); @@ -335,8 +335,8 @@ public class UnifyTest extends Unify { UnifyType extA = tf.getExtendsType(tphA); - eq = new HashSet(); - eq.add(new MPair(tf.getSimpleType("Vector", extA), tf.getSimpleType("Vector", extNum), PairOperator.SMALLERDOT)); + eq = new HashSet(); + eq.add(new UnifyPair(tf.getSimpleType("Vector", extA), tf.getSimpleType("Vector", extNum), PairOperator.SMALLERDOT)); expected = new HashSet<>(); actual = unify(eq, fc); @@ -351,8 +351,8 @@ public class UnifyTest extends Unify { * */ - eq = new HashSet(); - eq.add(new MPair(tf.getSimpleType("Vector", extNum), tf.getSimpleType("Vector", extA), PairOperator.SMALLERDOT)); + eq = new HashSet(); + eq.add(new UnifyPair(tf.getSimpleType("Vector", extNum), tf.getSimpleType("Vector", extA), PairOperator.SMALLERDOT)); expected = new HashSet<>(); actual = unify(eq, fc); @@ -370,10 +370,10 @@ public class UnifyTest extends Unify { * ? extends Number <.? b */ - eq = new HashSet(); - eq.add(new MPair(tf.getSimpleType("LinkedList", number), tf.getSimpleType("Deque", tphA), PairOperator.SMALLERDOT)); - eq.add(new MPair(tf.getSimpleType("Deque", tphA), tf.getSimpleType("Queue", tphB), PairOperator.SMALLERDOT)); - eq.add(new MPair(extNum, tphB, PairOperator.SMALLERDOTWC)); + eq = new HashSet(); + eq.add(new UnifyPair(tf.getSimpleType("LinkedList", number), tf.getSimpleType("Deque", tphA), PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(tf.getSimpleType("Deque", tphA), tf.getSimpleType("Queue", tphB), PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(extNum, tphB, PairOperator.SMALLERDOTWC)); expected = new HashSet<>(); actual = unify(eq, fc); @@ -446,16 +446,16 @@ public class UnifyTest extends Unify { Assert.assertEquals(expected, actual); } - private Set> filterGeneratedTPHsMultiple(Set> set) { + private Set> filterGeneratedTPHsMultiple(Set> set) { return set.stream().map(x -> filterGeneratedTPHs(x)).collect(Collectors.toSet()); } - private Set filterGeneratedTPHs(Set set) { + private Set filterGeneratedTPHs(Set set) { return set.stream().filter(x -> !((x.getRhsType() instanceof PlaceholderType) && ((PlaceholderType) x.getRhsType()).isGenerated())). filter(x -> !((x.getLhsType() instanceof PlaceholderType) && ((PlaceholderType) x.getLhsType()).isGenerated())).collect(Collectors.toSet()); } - private void addAsSet(Set> addTo, MPair... mPairs) { + private void addAsSet(Set> addTo, UnifyPair... mPairs) { addTo.add(new HashSet<>(Arrays.stream(mPairs).collect(Collectors.toSet()))); } } diff --git a/test/unify/UnifyTypeFactoryTest.java b/test/unify/UnifyTypeFactoryTest.java index 8bfac1a9..10e5582c 100644 --- a/test/unify/UnifyTypeFactoryTest.java +++ b/test/unify/UnifyTypeFactoryTest.java @@ -21,7 +21,7 @@ import de.dhbwstuttgart.typeinference.OderConstraint; import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.UndConstraint; import de.dhbwstuttgart.typeinference.UnifyConstraintsSet; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; @@ -45,24 +45,24 @@ public class UnifyTypeFactoryTest { @Test public void convertMPair() { - MPair mp1 = getSimpleMPair(); + UnifyPair mp1 = getSimpleMPair(); checkConvertMPair(mp1); TypePlaceholder tph1 = TypePlaceholder.fresh(new NullSyntaxTreeNode()); TypePlaceholder tph2 = TypePlaceholder.fresh(new NullSyntaxTreeNode()); - MPair mp2 = new MPair(getSimpleType(), tf.getPlaceholderType(tph1.getName().toString()), PairOperator.SMALLERDOT); + UnifyPair mp2 = new UnifyPair(getSimpleType(), tf.getPlaceholderType(tph1.getName().toString()), PairOperator.SMALLERDOT); checkConvertMPair(mp2); - MPair mp3 = new MPair(tf.getSuperType(getSimpleType()), getSimpleType(), PairOperator.SMALLERDOT); + UnifyPair mp3 = new UnifyPair(tf.getSuperType(getSimpleType()), getSimpleType(), PairOperator.SMALLERDOT); checkConvertMPair(mp3); - MPair mp4 = new MPair(tf.getPlaceholderType(tph2.getName().toString()), tf.getPlaceholderType(tph1.getName().toString()), PairOperator.SMALLERDOT); + UnifyPair mp4 = new UnifyPair(tf.getPlaceholderType(tph2.getName().toString()), tf.getPlaceholderType(tph1.getName().toString()), PairOperator.SMALLERDOT); checkConvertMPair(mp4); ReferenceType typeWithParams = tf.getSimpleType("Test", getSimpleType()); ReferenceType typeWithTPHParams = tf.getSimpleType("Test", tf.getPlaceholderType("Test")); - MPair mp5 = new MPair(typeWithTPHParams, typeWithParams, PairOperator.SMALLERDOT); + UnifyPair mp5 = new UnifyPair(typeWithTPHParams, typeWithParams, PairOperator.SMALLERDOT); checkConvertMPair(mp5); } @@ -97,15 +97,15 @@ public class UnifyTypeFactoryTest { Set> check = cons.cartesianProduct(); UnifyConstraintsSet converted = UnifyTypeFactory.convert(cons); - Set> cartesianProductOfConverted = converted.cartesianProduct(); + Set> cartesianProductOfConverted = converted.cartesianProduct(); assertTrue(cartesianProductOfConverted.size()==check.size()); assertTrue(cartesianProductOfConverted.iterator().next().size()==check.iterator().next().size()); Set> controlSet = new Menge<>(); - for(Set pairs : cartesianProductOfConverted){ + for(Set pairs : cartesianProductOfConverted){ Set tmpSet = new Menge<>(); - for(MPair mp : pairs){ + for(UnifyPair mp : pairs){ Pair p = checkConvertMPair(mp); tmpSet.add(p); } @@ -114,15 +114,15 @@ public class UnifyTypeFactoryTest { assertTrue(controlSet.equals(check)); } - private static MPair checkConvertPair(Pair p){ + private static UnifyPair checkConvertPair(Pair p){ System.out.println("Checking Pair: "+p); - MPair mp = UnifyTypeFactory.convert(p); + UnifyPair mp = UnifyTypeFactory.convert(p); assertTrue(p.TA1.get_Name().equals(mp.getLhsType().getName())); assertTrue(p.TA2.get_Name().equals(mp.getRhsType().getName())); return mp; } - private static Pair checkConvertMPair(MPair mp){ + private static Pair checkConvertMPair(UnifyPair mp){ System.out.println("Checking Pair: "+mp); Pair p = UnifyTypeFactory.convert(mp); assertTrue(p.TA1.get_Name().equals(mp.getLhsType().getName())); @@ -134,10 +134,10 @@ public class UnifyTypeFactoryTest { return tf.getSimpleType("String"); } - private static MPair getSimpleMPair(){ + private static UnifyPair getSimpleMPair(){ UnifyType lt = tf.getSimpleType("String"); UnifyType rt = tf.getSimpleType("String"); - MPair ret = new MPair(lt, rt, PairOperator.SMALLERDOT); + UnifyPair ret = new UnifyPair(lt, rt, PairOperator.SMALLERDOT); return ret; } From e1c925b9bcdc4889ad8b2b4b7a755486e598d5d6 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Wed, 6 Apr 2016 12:42:15 +0200 Subject: [PATCH 37/57] =?UTF-8?q?Unn=C3=B6tige=20Kommentare=20l=C3=B6schen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/de/dhbwstuttgart/syntaxtree/Class.java | 43 ++++------------------ 1 file changed, 7 insertions(+), 36 deletions(-) diff --git a/src/de/dhbwstuttgart/syntaxtree/Class.java b/src/de/dhbwstuttgart/syntaxtree/Class.java index 3c93f2c7..eabd9094 100755 --- a/src/de/dhbwstuttgart/syntaxtree/Class.java +++ b/src/de/dhbwstuttgart/syntaxtree/Class.java @@ -169,47 +169,21 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I { this.superif = superif; } - - // ino.attribute.superclassid.23014.decldescription type=line - // private Status status; - // ino.end - // ino.attribute.superclassid.23014.declaration - public UsedId superclassid = (SourceFile.READ_OBJECT_SUPERCLASSES_FROM_JRE?UsedId.createFromQualifiedName("Object",-1):null); - // ino.end - // ino.attribute.class_block.23020.decldescription type=line - // private Class java; - // ino.end - // ino.attribute.class_block.23020.declaration - private Block class_block; - // ino.end - // ino.attribute.paralist.23023.declaration - //private Menge paralist = new Menge(); // Parameterliste 'class xy{}' wird gespeichert - // ino.end - // ino.attribute.parahash.23026.declaration - private Hashtable parahash = new Hashtable(); // parametrisierten Attrib. werden mit den Paramet.aus paralist verk. - // ino.end - // ino.attribute.isFirstLocalVarDecl.23029.declaration - public static boolean isFirstLocalVarDecl; //Hilfsvariable fuer Offsets, hoth - // ino.end - //private Menge genericClassParameters=new Menge(); - - // ino.attribute.containedTypes.23032.decldescription type=line + public UsedId superclassid = (SourceFile.READ_OBJECT_SUPERCLASSES_FROM_JRE?UsedId.createFromQualifiedName("Object",-1):null); + + private Block class_block; + + private Hashtable parahash = new Hashtable(); // parametrisierten Attrib. werden mit den Paramet.aus paralist verk. + + public static boolean isFirstLocalVarDecl; //Hilfsvariable fuer Offsets, hoth // PL 05-07-30 eingefuegt. Vektor aller Typdeklarationen, die in der Klasse // vorkommen. Wird in der Studienarbeit von Andreas Stadelmeier nur für Verifizierung der Tests eingesetzt. - // ino.end - // ino.attribute.containedTypes.23032.declaration private Menge containedTypes = new Menge(); - // ino.end - // ino.attribute.usedIdsToCheck.23035.declaration private Menge usedIdsToCheck = new Menge(); - // ino.end private TypeAssumptions typeAssumptions = null;//muss mit null Initialisiert werden. Darf nur über getTypeAssumptions abgerufen werden. - // ino.attribute.parserlog.23038.declaration - //protected Logger parselog = Logger.getLogger("parser"); - // ino.end protected Logger typinferenzLog = Logger.getLogger(Class.class.getName()); private SyntaxTreeNode parent; private Menge fielddecl = new Menge(); @@ -218,10 +192,7 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I private RefType superClass; - // ino.method.Class.23041.definition public Class(String name, int offset) - // ino.end - // ino.method.Class.23041.body { this.name = name; if(name.equals("java.lang.Object")){ From 8d69f6c82b6f70f24d4503378d133a9949a0610e Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Thu, 7 Apr 2016 14:30:23 +0200 Subject: [PATCH 38/57] adapt rule fixed --- .../typeinference/unify/RuleSet.java | 8 ++--- .../typeinference/unify/model/FunNType.java | 23 ++++++++++---- .../typeinference/unify/model/Node.java | 2 +- .../typeinference/unify/model/Unifier.java | 2 +- test/unify/UnifyTest.java | 30 +++++++++++++++++-- 5 files changed, 51 insertions(+), 14 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java index 9ce84a43..e18e6156 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -376,8 +376,8 @@ public class RuleSet implements IRuleSet{ if(!(typeDs instanceof ReferenceType)) return Optional.empty(); - if(typeD.getTypeParams().size() == 0 || typeDs.getTypeParams().size() == 0) - return Optional.empty(); + /*if(typeD.getTypeParams().size() == 0 || typeDs.getTypeParams().size() == 0) + return Optional.empty();*/ if(typeD.getName().equals(typeDs.getName())) return Optional.empty(); @@ -402,8 +402,8 @@ public class RuleSet implements IRuleSet{ TypeParams typeDParams = typeD.getTypeParams(); TypeParams typeDgenParams = typeDgen.getTypeParams(); - Unifier unif = new Unifier((PlaceholderType) typeDgenParams.get(0), typeDParams.get(0)); - for(int i = 1; i < typeDParams.size(); i++) + Unifier unif = Unifier.Identity(); + for(int i = 0; i < typeDParams.size(); i++) unif.Add((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i)); return Optional.of(new UnifyPair(unif.apply(newLhs), typeDs, PairOperator.SMALLERDOT)); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java b/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java index e62fd6ce..cb431cf9 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java @@ -6,17 +6,28 @@ import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; public class FunNType extends UnifyType { - public FunNType(TypeParams p) { + protected FunNType(TypeParams p) { super("FuN", p); - if(p.size() == 0) - throw new IllegalArgumentException("Function types need at least one type parameter"); } + public static FunNType getFunNType(TypeParams tp) { + if(!validateTypeParams(tp)) + throw new IllegalArgumentException("Invalid TypeParams for a FunNType: " + tp); + return new FunNType(tp); + } + + private static boolean validateTypeParams(TypeParams tp) { + if(tp.size() == 0) + return false; + for(UnifyType t : tp) + if(t instanceof WildcardType) + return false; + return true; + } + @Override public UnifyType setTypeParams(TypeParams newTp) { - if(newTp.size() == 0) - throw new IllegalArgumentException("Function types need at least one type parameter"); - return new FunNType(newTp); + return getFunNType(newTp); } public int getN() { diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/Node.java b/src/de/dhbwstuttgart/typeinference/unify/model/Node.java index 7010ec32..d338d16b 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/Node.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/Node.java @@ -4,7 +4,7 @@ import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; -public class Node { +class Node { private T content; private HashSet> predecessors = new HashSet<>(); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java index a46ee6d3..33f9daec 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java @@ -45,7 +45,7 @@ public class Unifier implements Function /*, Set*/ return substitutions.containsKey(t); } - public UnifyType getSubstitute(UnifyType t) { + public UnifyType getSubstitute(PlaceholderType t) { return substitutions.get(t); } diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 0ee466e4..3d091f5e 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -380,13 +380,39 @@ public class UnifyTest extends Unify { //System.out.println(actual); //Assert.assertEquals(actual, expected); - - } @Test public void unifyTestComplex() { + /* + * INIT + */ + TypeFactory tf = new TypeFactory(); + FiniteClosureBuilder fcb = new FiniteClosureBuilder(); + + UnifyType tphT = tf.getPlaceholderType("T"); + UnifyType vector = tf.getSimpleType("Vector", tphT); + UnifyType number = tf.getSimpleType("Number"); + UnifyType integer = tf.getSimpleType("Integer"); + UnifyType object = tf.getSimpleType("Object"); + UnifyType matrix = tf.getSimpleType("Matrix"); + UnifyType vectorvectorint = tf.getSimpleType("Vector", tf.getSimpleType("Vector", integer)); + + fcb.add(integer, number); + fcb.add(matrix, vectorvectorint); + fcb.add(vector, object); + + IFiniteClosure fc = fcb.getFiniteClosure(); + + Set eq = new HashSet(); + eq.add(new UnifyPair(tf.getSimpleType("Matrix"), tf.getSimpleType("Vector", tf.getPlaceholderType("a")), PairOperator.SMALLERDOT)); + + Set> expected = new HashSet<>(); + Set> actual = unify(eq, fc); + + System.out.println("Test Matrix:"); + System.out.println(actual); } @Test From 44318ee5d8985484c555e441353f4c63829ed759 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Thu, 7 Apr 2016 14:39:07 +0200 Subject: [PATCH 39/57] =?UTF-8?q?Aufr=C3=A4umen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dhbwstuttgart/syntaxtree/SourceFile.java | 3 +- .../syntaxtree/factory/UnifyTypeFactory.java | 6 +- .../typeinference/ConstraintsSet.java | 2 +- .../typeinference/OderConstraint.java | 2 +- .../typeinference/OderMenge.java | 2 +- .../typeinference/UndConstraint.java | 2 +- .../typeinference/UnifyConstraintsSet.java | 6 +- .../typeinference/UnifyOderConstraint.java | 4 +- .../typeinference/UnifyUndConstraint.java | 2 +- ...fier.java => Unifikationsalgorithmus.java} | 2 +- .../unify/model/FiniteClosure.java | 5 ++ test/bytecode/types/Overloading2.jav | 18 +++++ test/bytecode/types/Overloading2Test.java | 71 +++++++++++++++++++ .../MultipleTypesInsertTester.java | 3 +- test/unify/UnifyTypeFactoryTest.java | 5 ++ 15 files changed, 117 insertions(+), 16 deletions(-) rename src/de/dhbwstuttgart/typeinference/unify/{Unifier.java => Unifikationsalgorithmus.java} (81%) create mode 100644 test/bytecode/types/Overloading2.jav create mode 100644 test/bytecode/types/Overloading2Test.java diff --git a/src/de/dhbwstuttgart/syntaxtree/SourceFile.java b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java index d271fd84..2892773f 100755 --- a/src/de/dhbwstuttgart/syntaxtree/SourceFile.java +++ b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java @@ -279,7 +279,8 @@ public class SourceFile Set> xConstraints = unifyConstraints.cartesianProduct(); - + + typinferenzLog.debug("Finite Closure: "+finiteClosure, Section.TYPEINFERENCE); typinferenzLog.debug("Karthesisches Produkt der Constraints: "+xConstraints, Section.TYPEINFERENCE); //finiteClosure.generateFullyNamedTypes(globalAssumptions); diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 0e0da3fc..1f14bb34 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -49,13 +49,13 @@ public class UnifyTypeFactory { RefType superClass = cAss.getAssumedClass().getSuperClass(); if(superClass != null){ UnifyType tr = UnifyTypeFactory.convert(superClass); - pairs.add(smaller(tl, tr)); + pairs.add(generateSmallerPair(tl, tr)); } } return new FiniteClosure(pairs); } - public static UnifyPair smaller(UnifyType tl, UnifyType tr){ + public static UnifyPair generateSmallerPair(UnifyType tl, UnifyType tr){ return new UnifyPair(tl, tr, PairOperator.SMALLER); } @@ -135,7 +135,7 @@ public class UnifyTypeFactory { public static UnifyPair convert(Pair p) { if(!p.OperatorSmaller())throw new NotImplementedException(); - UnifyPair ret = smaller(UnifyTypeFactory.convert(p.TA1) + UnifyPair ret = generateSmallerPair(UnifyTypeFactory.convert(p.TA1) , UnifyTypeFactory.convert(p.TA2)); return ret; } diff --git a/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java b/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java index c68e4865..e9f9918d 100755 --- a/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java +++ b/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java @@ -6,7 +6,7 @@ import java.util.Vector; import de.dhbwstuttgart.logger.Logger; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.logger.*; -import de.dhbwstuttgart.typeinference.unify.Unifier; +import de.dhbwstuttgart.typeinference.unify.Unifikationsalgorithmus; public class ConstraintsSet extends UndMenge implements Iterable{ private static final Logger log = Logger.getLogger(ConstraintsSet.class.getName()); diff --git a/src/de/dhbwstuttgart/typeinference/OderConstraint.java b/src/de/dhbwstuttgart/typeinference/OderConstraint.java index e9187b39..9c741ec8 100755 --- a/src/de/dhbwstuttgart/typeinference/OderConstraint.java +++ b/src/de/dhbwstuttgart/typeinference/OderConstraint.java @@ -8,7 +8,7 @@ import de.dhbwstuttgart.logger.Section; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.unify.Unifier; +import de.dhbwstuttgart.typeinference.unify.Unifikationsalgorithmus; public class OderConstraint extends OderMenge{ private Set oderConstraintPairs; diff --git a/src/de/dhbwstuttgart/typeinference/OderMenge.java b/src/de/dhbwstuttgart/typeinference/OderMenge.java index 842c78a3..d6083480 100644 --- a/src/de/dhbwstuttgart/typeinference/OderMenge.java +++ b/src/de/dhbwstuttgart/typeinference/OderMenge.java @@ -10,7 +10,7 @@ import de.dhbwstuttgart.logger.Section; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.unify.Unifier; +import de.dhbwstuttgart.typeinference.unify.Unifikationsalgorithmus; public abstract class OderMenge implements KomplexeMenge{ diff --git a/src/de/dhbwstuttgart/typeinference/UndConstraint.java b/src/de/dhbwstuttgart/typeinference/UndConstraint.java index 35468bd7..a53f0998 100755 --- a/src/de/dhbwstuttgart/typeinference/UndConstraint.java +++ b/src/de/dhbwstuttgart/typeinference/UndConstraint.java @@ -6,7 +6,7 @@ import java.util.Vector; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.typeinference.exceptions.DebugException; -import de.dhbwstuttgart.typeinference.unify.Unifier; +import de.dhbwstuttgart.typeinference.unify.Unifikationsalgorithmus; /** * Stellt ein Constraint dar, welches aus mehreren Constraint-Paaren besteht. Diese gelten alle stets gleichzeitig / sind per "Und" miteinander verknüpft. diff --git a/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java b/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java index 5c7ed8b7..b19a0197 100644 --- a/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java +++ b/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java @@ -5,7 +5,7 @@ import java.util.Set; import java.util.Vector; import de.dhbwstuttgart.logger.Logger; import de.dhbwstuttgart.logger.*; -import de.dhbwstuttgart.typeinference.unify.Unifier; +import de.dhbwstuttgart.typeinference.unify.Unifikationsalgorithmus; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; public class UnifyConstraintsSet extends UndMenge implements Iterable{ @@ -37,7 +37,7 @@ public class UnifyConstraintsSet extends UndMenge implements Iterable return constraintsSet.iterator(); } - public void filterWrongConstraints(Unifier unify) { + public void filterWrongConstraints(Unifikationsalgorithmus unify) { /* * Das ConstraintsSet enthält nur OderConstraints, welche UND-Verknüpft sind. * Hier werden Constraints in den OderConstraints kontrolliert: @@ -51,7 +51,7 @@ public class UnifyConstraintsSet extends UndMenge implements Iterable * Nimmt alle UndConstraints und filtert mithilfe dieser die falschen Constraints aus den OderConstraints * @param unifier */ - public void unifyUndConstraints(Unifier unifier) { + public void unifyUndConstraints(Unifikationsalgorithmus unifier) { Vector uCons = this.filterUndConstraints(); Vector alleUndConstraints = new Vector<>(); for(UnifyUndConstraint undConstraint : uCons){ diff --git a/src/de/dhbwstuttgart/typeinference/UnifyOderConstraint.java b/src/de/dhbwstuttgart/typeinference/UnifyOderConstraint.java index 49dbf6de..4955ea93 100644 --- a/src/de/dhbwstuttgart/typeinference/UnifyOderConstraint.java +++ b/src/de/dhbwstuttgart/typeinference/UnifyOderConstraint.java @@ -8,7 +8,7 @@ import de.dhbwstuttgart.logger.Section; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.unify.Unifier; +import de.dhbwstuttgart.typeinference.unify.Unifikationsalgorithmus; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; public class UnifyOderConstraint extends OderMenge{ @@ -83,7 +83,7 @@ public class UnifyOderConstraint extends OderMenge{ * welche keinen Sinn ergeben, also beim unifizieren scheitern. * @param unifier - Wird für die Unifizierung benutzt */ - void filterWrongConstraints(Unifier unifier) { + void filterWrongConstraints(Unifikationsalgorithmus unifier) { Set filteredConstraints = new Menge<>(); for(UnifyUndConstraint cons : this.getUndConstraints()){ Set> unifierResult = unifier.apply(cons.getConstraintPairs()); diff --git a/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java b/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java index d13ead18..f1ed0548 100644 --- a/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java +++ b/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java @@ -6,7 +6,7 @@ import java.util.Vector; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.typeinference.exceptions.DebugException; -import de.dhbwstuttgart.typeinference.unify.Unifier; +import de.dhbwstuttgart.typeinference.unify.Unifikationsalgorithmus; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; /** diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/Unifikationsalgorithmus.java similarity index 81% rename from src/de/dhbwstuttgart/typeinference/unify/Unifier.java rename to src/de/dhbwstuttgart/typeinference/unify/Unifikationsalgorithmus.java index 0a08a210..39c25e57 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unifier.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unifikationsalgorithmus.java @@ -4,7 +4,7 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; -public interface Unifier { +public interface Unifikationsalgorithmus { public Set> apply (Set E); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 6fff42cc..d5aaaf72 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -383,4 +383,9 @@ public class FiniteClosure implements IFiniteClosure { permuteParams(candidates, idx+1, result, current); } } + + @Override + public String toString(){ + return this.inheritanceGraph.toString(); + } } diff --git a/test/bytecode/types/Overloading2.jav b/test/bytecode/types/Overloading2.jav new file mode 100644 index 00000000..86961c95 --- /dev/null +++ b/test/bytecode/types/Overloading2.jav @@ -0,0 +1,18 @@ +import java.util.Vector; + +class Overloading2{ + + String method(Vector v) { + return v; + } + + Integer method(Vector v) { + return v; + } + + public static void main(String[] args){ + Overloading2 t; + t = new Overloading2(); + t.method(new Vector()); + } +} \ No newline at end of file diff --git a/test/bytecode/types/Overloading2Test.java b/test/bytecode/types/Overloading2Test.java new file mode 100644 index 00000000..aed1c45d --- /dev/null +++ b/test/bytecode/types/Overloading2Test.java @@ -0,0 +1,71 @@ +package bytecode.types; + +import static org.junit.Assert.*; + +import java.io.File; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Vector; + +import org.junit.Test; + +import bytecode.SourceFileBytecodeTest; + +public class Overloading2Test extends SourceFileBytecodeTest{ + @Override + protected void init() { + testName = "Overloading2"; + rootDirectory = System.getProperty("user.dir")+"/test/bytecode/types/"; + } + + + @Test + public void testString() { + try{ + ClassLoader classLoader = getClassLoader(); + + Class cls = classLoader.loadClass(testName); + + Object obj = cls.newInstance(); + + File file = new File(rootDirectory); + URL url = file.toURL(); + URL[] urls = new URL[]{url}; + + Class stringVector = classLoader.loadClass("java%util%Vector%%java%lang%String%"); + + Class[] params = new Class[1]; + params[0] = stringVector; + + Method method = cls.getDeclaredMethod("method", params); + method.invoke(obj, stringVector.newInstance()); + assertTrue(true); + }catch(Exception e){ + throw new RuntimeException(e); + } + } + + @Test + public void testInteger() { + try{ + ClassLoader classLoader = getClassLoader(); + + Class cls = classLoader.loadClass(testName); + + Object obj = cls.newInstance(); + + Class integerVector = classLoader.loadClass("java%util%Vector%%java%lang%Integer%"); + + Class[] params = new Class[1]; + params[0] = integerVector; + + Method method = cls.getDeclaredMethod("method", params); + method.invoke(obj, integerVector.newInstance()); + assertTrue(true); + }catch(Exception e){ + throw new RuntimeException(e); + } + } + +} diff --git a/test/plugindevelopment/TypeInsertTests/MultipleTypesInsertTester.java b/test/plugindevelopment/TypeInsertTests/MultipleTypesInsertTester.java index db3346a1..4542f9f0 100755 --- a/test/plugindevelopment/TypeInsertTests/MultipleTypesInsertTester.java +++ b/test/plugindevelopment/TypeInsertTests/MultipleTypesInsertTester.java @@ -102,12 +102,13 @@ public class MultipleTypesInsertTester extends TypeInsertTester{ } catch (IOException | yyException e) { e.printStackTrace(); TestCase.fail(); + }finally{ + writeLog(sourceFileToInfere+".log"); } for(String containString : mustContain){ TestCase.assertTrue("\""+containString+"\" muss in den inferierten Lösungen vorkommen",gesamterSrc.contains(containString)); } - writeLog(sourceFileToInfere+".log"); } private static void writeLog(String toFile){ diff --git a/test/unify/UnifyTypeFactoryTest.java b/test/unify/UnifyTypeFactoryTest.java index 10e5582c..2cf5bc53 100644 --- a/test/unify/UnifyTypeFactoryTest.java +++ b/test/unify/UnifyTypeFactoryTest.java @@ -30,6 +30,11 @@ import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public class UnifyTypeFactoryTest { private static TypeFactory tf = new TypeFactory(); + @Test + public void convertUnifyTypes(){ + //UnifyType ut = + } + @Test public void convertConstraintSet(){ ConstraintsSet cons = new ConstraintsSet(); From 284447aad2c78bbfabd020a0465920777d54e079 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Thu, 7 Apr 2016 21:45:27 +0200 Subject: [PATCH 40/57] removed unify old test --- test/unify/UnifyOldTest.java | 339 ----------------------------------- 1 file changed, 339 deletions(-) delete mode 100644 test/unify/UnifyOldTest.java diff --git a/test/unify/UnifyOldTest.java b/test/unify/UnifyOldTest.java deleted file mode 100644 index e07f303c..00000000 --- a/test/unify/UnifyOldTest.java +++ /dev/null @@ -1,339 +0,0 @@ -package unify; - -import junit.framework.Assert; - -import org.junit.Test; - -import de.dhbwstuttgart.syntaxtree.factory.UnifyPairMengenBuilder; -import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory; -import de.dhbwstuttgart.syntaxtree.factory.Unify_FC_TTO_Builder; -import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; -import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.Menge; -import de.dhbwstuttgart.typeinference.Pair; -import de.dhbwstuttgart.typeinference.unify.Unify; - -public class UnifyOldTest { - - @Test - public void unifyTest1() { - // Init Factories and Builders - UnifyTypeFactory typeFactory = new UnifyTypeFactory(); - Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); - UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); - UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); - - TypePlaceholder a = typeFactory.GetTypePlaceholder("a"); - ExtendsWildcardType extA = typeFactory.GetExtendsType(a); - TypePlaceholder b = typeFactory.GetTypePlaceholder("a"); - ExtendsWildcardType extB = typeFactory.GetExtendsType(a); - RefType integer = typeFactory.GetSimpleType("Integer"); - SuperWildcardType supInt = typeFactory.GetSuperType(integer); - RefType listsupint = typeFactory.GetSimpleType("List", supInt); - RefType number = typeFactory.GetSimpleType("Number"); - RefType object = typeFactory.GetSimpleType("XObjectX"); - ExtendsWildcardType extNum = typeFactory.GetExtendsType(number); - RefType intlist = typeFactory.GetSimpleType("List", integer); - RefType alist = typeFactory.GetSimpleType("List", a); - RefType extBlist = typeFactory.GetSimpleType("List", extB); - RefType blist = typeFactory.GetSimpleType("List", b); - RefType extNumlist = typeFactory.GetSimpleType("List", extNum); - - fcBuilder.AddInheritance(number, object); - fcBuilder.AddInheritance(integer, number); - - - assumptionBuilder.addPair(alist, extBlist, PairOperator.Smaller); - assumptionBuilder.addPair(blist, extNumlist, PairOperator.Smaller); - - System.out.println(Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO())); - } -// -// @Test -// public void unifyTestSimpleTypes() { -// // Init Factories and Builders -// UnifyTypeFactory typeFactory = new UnifyTypeFactory(); -// Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); -// UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); -// UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); -// -// /* -// * Test a <. Boolean -// */ -// -// // Init Types -// RefType boolT = typeFactory.GetSimpleType("java.lang.Boolean"); -// TypePlaceholder aTph = typeFactory.GetTypePlaceholder("a"); -// -// // Expected Result -// resultBuilder.clear(); -// resultBuilder.addPair(aTph, boolT, PairOperator.Equal); -// resultBuilder.addPair(aTph, typeFactory.GetExtendsType(boolT), -// PairOperator.Equal); -// Menge> expectedResult = resultBuilder.getNestedPairMenge(); -// -// // Actual Result -// assumptionBuilder.clear(); -// assumptionBuilder.addPair(aTph, boolT); -// Menge> actualResult = Unify.unify( -// assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); -// -// // System.out.println(expectedResult); -// // System.out.println(actualResult); -// -// Assert.assertTrue(mengeEquals(expectedResult, actualResult)); -// -// /* -// * Test b <. a, a <. Boolean -// */ -// -// // Init Types -// boolT = typeFactory.GetSimpleType("java.lang.Boolean"); -// aTph = typeFactory.GetTypePlaceholder("a"); -// TypePlaceholder bTph = typeFactory.GetTypePlaceholder("b"); -// -// // Expected Result -// resultBuilder.clear(); -// resultBuilder.addPair(aTph, boolT, PairOperator.Equal); -// resultBuilder.addPair(aTph, typeFactory.GetExtendsType(boolT), -// PairOperator.Equal); -// resultBuilder.addPair(bTph, boolT, PairOperator.Equal); -// resultBuilder.addPair(bTph, typeFactory.GetExtendsType(boolT), -// PairOperator.Equal); -// expectedResult = resultBuilder.getNestedPairMenge(); -// -// // Actual Result -// assumptionBuilder.clear(); -// assumptionBuilder.addPair(bTph, aTph); -// assumptionBuilder.addPair(aTph, boolT); -// actualResult = Unify.unify(assumptionBuilder.getPairMenge(), -// fcBuilder.Get_FC_TTO()); -// -// // System.out.println(expectedResult); -// // System.out.println(actualResult); -// -// // NOTE: Elemente im actualResult sind nicht unique -// // Assert.assertTrue(mengeEquals(expectedResult, actualResult)); -// -// /* -// * Test b <. a, a <. b -// */ -// -// aTph = typeFactory.GetTypePlaceholder("a"); -// bTph = typeFactory.GetTypePlaceholder("b"); -// -// // Expected Result -// resultBuilder.clear(); -// resultBuilder.addPair(bTph, aTph); -// resultBuilder.addPair(aTph, bTph); -// -// Menge buffer = resultBuilder.getPairMenge(); -// expectedResult = new Menge>(); -// expectedResult.add(buffer); -// -// // Actual Result -// assumptionBuilder.clear(); -// assumptionBuilder.addPair(bTph, aTph); -// assumptionBuilder.addPair(aTph, bTph); -// actualResult = Unify.unify(assumptionBuilder.getPairMenge(), -// fcBuilder.Get_FC_TTO()); -// -// // System.out.println(expectedResult); -// // System.out.println(actualResult); -// -// Assert.assertTrue(mengeEquals(expectedResult, actualResult)); -// -// /* -// * Test Integer <. a, a <. Boolean -// */ -// -// RefType intT = typeFactory.GetSimpleType("java.lang.Integer"); -// boolT = typeFactory.GetSimpleType("java.lang.Boolean"); -// aTph = typeFactory.GetTypePlaceholder("a"); -// bTph = typeFactory.GetTypePlaceholder("b"); -// -// // Expected Result -// resultBuilder.clear(); -// expectedResult = resultBuilder.getNestedPairMenge(); -// -// // Actual Result -// assumptionBuilder.clear(); -// assumptionBuilder.addPair(intT, aTph); -// assumptionBuilder.addPair(aTph, boolT); -// actualResult = Unify.unify(assumptionBuilder.getPairMenge(), -// fcBuilder.Get_FC_TTO()); -// -// // System.out.println(expectedResult); -// // System.out.println(actualResult); -// -// Assert.assertTrue(mengeEquals(expectedResult, actualResult)); -// -// } -// -// @Test -// public void unifyTestGenerics() { -// -// // Init Factories and Builders -// UnifyTypeFactory typeFactory = new UnifyTypeFactory(); -// Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); -// UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); -// UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); -// -// /* -// * Test a <. MyClass -// */ -// -// TypePlaceholder aTph = typeFactory.GetTypePlaceholder("a"); -// RefType myType = typeFactory.GetSimpleType("MyClass", -// typeFactory.GetTypePlaceholder("T"), -// typeFactory.GetTypePlaceholder("F")); -// -// // Expected Result -// resultBuilder.clear(); -// resultBuilder.addPair(aTph, myType, PairOperator.Equal); -// resultBuilder.addPair(aTph, typeFactory.GetExtendsType(myType)); -// Menge> expectedResult = resultBuilder.getNestedPairMenge(); -// -// // Actual Result -// assumptionBuilder.clear(); -// assumptionBuilder.addPair(aTph, myType); -// Menge> actualResult = Unify.unify( -// assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); -// -// // System.out.println(expectedResult); -// // System.out.println(actualResult); -// -// Assert.assertTrue(mengeEquals(expectedResult, actualResult)); -// -// /* -// * Test List> <. List -// */ -// -// TypePlaceholder tTph = typeFactory.GetTypePlaceholder("T"); -// RefType list = typeFactory.GetSimpleType("List", tTph); -// RefType listlist = typeFactory.GetSimpleType("List", list); -// -// // Expected Result -// resultBuilder.clear(); -// resultBuilder.addPair(typeFactory.GetExtendsType(list), tTph, -// PairOperator.Equal); -// expectedResult = resultBuilder.getNestedPairMenge(); -// -// // Actual Result -// assumptionBuilder.clear(); -// assumptionBuilder.addPair(listlist, list); -// actualResult = Unify.unify(assumptionBuilder.getPairMenge(), -// fcBuilder.Get_FC_TTO()); -// -// System.out.println(expectedResult); -// System.out.println(actualResult); -// -// Assert.assertTrue(mengeEquals(expectedResult, actualResult)); -// -// /* -// * Test List <. List> -// */ -// } -// -// @Test -// public void unifyTestInheritance() { -// -// // Init Factories and Builders -// UnifyTypeFactory typeFactory = new UnifyTypeFactory(); -// Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); -// UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); -// UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); -// -// // Init Types -// RefType tBool = typeFactory.GetSimpleType("java.lang.Boolean"); -// RefType tString = typeFactory.GetSimpleType("java.lang.String"); -// RefType tInt = typeFactory.GetSimpleType("java.lang.Integer"); -// TypePlaceholder tphA = typeFactory.GetTypePlaceholder("a"); -// -// // Build inheritance hierachy -// // Bool <. String <. Int -// fcBuilder.AddInheritance(tBool, tString); -// fcBuilder.AddInheritance(tString, tInt); -// -// // Build Assumptions -// assumptionBuilder.addPair(tphA, tString); -// -// // Build expected result -// resultBuilder.addPair(tphA, tBool, PairOperator.Equal); -// resultBuilder.addPair(tphA, typeFactory.GetExtendsType(tBool), -// PairOperator.Equal); -// resultBuilder.addPair(tphA, tString, PairOperator.Equal); -// resultBuilder.addPair(tphA, typeFactory.GetExtendsType(tString), -// PairOperator.Equal); -// -// // Assert -// Menge> actualResult = Unify.unify( -// assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); -// -// // System.out.println(actualResult); -// // System.out.println("-------------------"); -// // System.out.println(resultBuilder.getNestedPairMenge()); -// -// Assert.assertTrue(mengeEquals(resultBuilder.getNestedPairMenge(), -// actualResult)); -// } -// -// @Test -// public void unifyTestWildcards() { -// -// } -// -// private static boolean mengeEquals(Menge> m1, -// Menge> m2) { -// if (m1.size() != m2.size()) -// return false; -// -// return containsAll(m1, m2) && containsAll(m2, m1); -// } -// -// private static boolean containsAll(Menge> m1, -// Menge> m2) { -// for (Menge elem : m2) -// if (!contains(m1, elem)) -// return false; -// return true; -// } -// -// private static boolean contains(Menge> m1, Menge m2) { -// for (Menge elem : m1) -// if (mengePairEquals(elem, m2)) -// return true; -// return false; -// } -// -// private static boolean mengePairEquals(Menge m1, Menge m2) { -// if (m1.size() != m2.size()) -// return false; -// -// return containsAllPair(m1, m2) && containsAllPair(m2, m1); -// } -// -// private static boolean containsAllPair(Menge m1, Menge m2) { -// for (Pair elem : m1) -// if (contains(m2, elem)) -// return true; -// return false; -// } -// -// private static boolean contains(Menge m, Pair p) { -// for (Pair elem : m) -// if (pairEquals(elem, p)) -// return true; -// return false; -// -// } -// -// private static boolean pairEquals(Pair p1, Pair p2) { -// return (p1.TA1.equals(p2.TA1) && p1.TA2.equals(p2.TA2)) -// || (p1.TA1.equals(p2.TA2) && p1.TA2.equals(p2.TA1)); -// } - -} From 53cfb4b046d664ea34bd188f390b47ce5309ff5e Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Thu, 7 Apr 2016 22:24:35 +0200 Subject: [PATCH 41/57] Support for FunN in FC added // swap for unifiers --- .../unify/model/FiniteClosure.java | 76 +++++++++++++++---- .../typeinference/unify/model/FunNType.java | 17 ++++- .../unify/model/ReferenceType.java | 4 +- .../typeinference/unify/model/SuperType.java | 2 - .../typeinference/unify/model/TypeParams.java | 3 + .../typeinference/unify/model/Unifier.java | 12 +++ test/unify/FiniteClosureTest.java | 33 +++++++- test/unify/TypeFactory.java | 7 ++ 8 files changed, 132 insertions(+), 22 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 6fff42cc..2ac30e19 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -65,6 +65,13 @@ public class FiniteClosure implements IFiniteClosure { */ @Override public Set smaller(UnifyType type) { + if(type instanceof FunNType) + return computeSmallerFunN((FunNType) type); + + return computeSmaller(type); + } + + private Set computeSmaller(UnifyType type) { if(inheritanceGraph.containsKey(type)) { Set result = new HashSet<>(); result.add(type); @@ -82,8 +89,7 @@ public class FiniteClosure implements IFiniteClosure { for (UnifyType param : type.getTypeParams()) paramCandidates.add(smArg(param)); - Set permResult = new HashSet<>(); - permuteParams(paramCandidates, 0, permResult, new UnifyType[paramCandidates.size()]); + Set permResult = permuteParams(paramCandidates); for (TypeParams newParams : permResult) result1.add(type.setTypeParams(newParams));} @@ -94,16 +100,18 @@ public class FiniteClosure implements IFiniteClosure { strInheritanceGraph.get(type.getName()).forEach(x -> candidates.add(x.getContent())); for(UnifyType typePrime : result1) { - for (UnifyType theta2 : candidates) { - Optional sigma2 = unify.unify(typePrime, theta2); - if (!sigma2.isPresent()) + for (UnifyType theta2 : candidates) { + Optional sigma2Opt = unify.unify(typePrime, theta2); + if (!sigma2Opt.isPresent()) continue; + Unifier sigma2 = sigma2Opt.get(); + sigma2.swapPlaceholderSubstitutions(typePrime.getTypeParams().toArray()); if(type.equals(theta2)) continue; Set theta1s = smaller(theta2); for (UnifyType theta1 : theta1s) { // Because only the most general type is calculated, sigma1 = sigma2 - UnifyType sigma1Theta1 = sigma2.get().apply(theta1); + UnifyType sigma1Theta1 = sigma2.apply(theta1); result2.add(sigma1Theta1); } } @@ -118,8 +126,7 @@ public class FiniteClosure implements IFiniteClosure { for (UnifyType param : t.getTypeParams()) paramCandidates.add(smArg(param)); - Set permResult = new HashSet<>(); - permuteParams(paramCandidates, 0, permResult, new UnifyType[paramCandidates.size()]); + Set permResult = permuteParams(paramCandidates); for (TypeParams newParams : permResult) { UnifyType tPrime = t.setTypeParams(newParams); @@ -127,19 +134,44 @@ public class FiniteClosure implements IFiniteClosure { result3.add(t); else result3.addAll(smaller(tPrime)); - } + } } return result3; } + + private Set computeSmallerFunN(FunNType type) { + Set result = new HashSet<>(); + + // if T = T' then T <=* T' + result.add(type); + + ArrayList> paramCandidates = new ArrayList<>(); + paramCandidates.add(smaller(type.getTypeParams().get(0))); + for (int i = 1; i < type.getTypeParams().size(); i++) + paramCandidates.add(greater(type.getTypeParams().get(i))); + + Set permResult = permuteParams(paramCandidates); + + for (TypeParams newParams : permResult) + result.add(type.setTypeParams(newParams)); + + return result; + } /** * Returns all types of the finite closure that are supertypes of the argument. * @return The set of supertypes of the argument. */ @Override - public Set greater(UnifyType type) { + public Set greater(UnifyType type) { + if(type instanceof FunNType) + return computeGreaterFunN((FunNType) type); + return computeGreater(type); + } + + protected Set computeGreater(UnifyType type) { IUnify unify = new MartelliMontanariUnify(); Set result1 = new HashSet<>(); @@ -166,22 +198,25 @@ public class FiniteClosure implements IFiniteClosure { for(UnifyType typePrime : result1) { for (UnifyType theta2 : candidates) { - Optional sigma2 = unify.unify(typePrime, theta2); - if (!sigma2.isPresent()) + Optional sigma2Opt = unify.unify(typePrime, theta2); + if (!sigma2Opt.isPresent()) continue; if(type.equals(theta2)) continue; + + Unifier sigma2 = sigma2Opt.get(); + sigma2.swapPlaceholderSubstitutions(typePrime.getTypeParams().toArray()); Set theta1s = greater(theta2); for (UnifyType theta1 : theta1s) { // Because only the most general type is calculated, sigma1 = sigma2 - UnifyType sigma1Theta1 = sigma2.get().apply(theta1); + UnifyType sigma1Theta1 = sigma2.apply(theta1); result2.add(sigma1Theta1); } } } } - result2.addAll(result1); + result2.addAll(result1); Set result3 = new HashSet<>(); for(UnifyType t : result2) { @@ -203,8 +238,13 @@ public class FiniteClosure implements IFiniteClosure { } return result3; - } + + protected Set computeGreaterFunN(FunNType type) { + // TODO Auto-generated method stub + return null; + } + @Override public Set grArg(UnifyType type) { @@ -370,6 +410,12 @@ public class FiniteClosure implements IFiniteClosure { return result; } + protected Set permuteParams(ArrayList> candidates) { + Set result = new HashSet<>(); + permuteParams(candidates, 0, result, new UnifyType[candidates.size()]); + return result; + } + protected void permuteParams(ArrayList> candidates, int idx, Set result, UnifyType[] current) { if(candidates.size() == idx) { result.add(new TypeParams(Arrays.copyOf(current, current.length))); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java b/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java index cb431cf9..3363be75 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java @@ -43,13 +43,26 @@ public class FunNType extends UnifyType { Set grArg(IFiniteClosure fc) { return fc.grArg(this); } - + @Override UnifyType apply(Unifier unif) { // TODO Auto-generated method stub return null; } - // TODO equals und hashcode + @Override + public int hashCode() { + return 31 + typeParams.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if(!(obj instanceof FunNType)) + return false; + + FunNType other = (FunNType) obj; + + return other.getTypeParams().equals(typeParams); + } } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java b/src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java index fd5a0ec1..4f557b53 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java @@ -22,7 +22,7 @@ public final class ReferenceType extends UnifyType { Set grArg(IFiniteClosure fc) { return fc.grArg(this); } - + @Override UnifyType apply(Unifier unif) { return new ReferenceType(typeName, typeParams.apply(unif)); @@ -35,7 +35,7 @@ public final class ReferenceType extends UnifyType { @Override public int hashCode() { - return typeName.hashCode(); + return 31 + 17 * typeName.hashCode() + 17 * typeParams.hashCode(); } @Override diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java b/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java index 51f640c9..363dbbf6 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java @@ -5,8 +5,6 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; public final class SuperType extends WildcardType { - - public SuperType(UnifyType superedType) { super("? super " + superedType.getName(), superedType, superedType.getTypeParams()); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java b/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java index 0f39a621..f5b7686b 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java @@ -77,6 +77,9 @@ public final class TypeParams implements Iterable{ return new TypeParams(newparams); } + public UnifyType[] toArray() { + return Arrays.copyOf(typeParams, typeParams.length); + } @Override public Iterator iterator() { diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java index 33f9daec..cccaf591 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java @@ -52,6 +52,18 @@ public class Unifier implements Function /*, Set*/ public Set> getSubstitutions() { return substitutions.entrySet(); } + + public void swapPlaceholderSubstitutions(UnifyType... targetParams) { + for(UnifyType tph : targetParams) { + if(!(tph instanceof PlaceholderType)) + continue; + if(substitutions.containsKey(tph) && substitutions.get(tph) instanceof PlaceholderType) { + PlaceholderType newLhs = (PlaceholderType) substitutions.get(tph); + substitutions.remove(tph); + substitutions.put(newLhs, tph); + } + } + } @Override public String toString() { diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index 519cf509..25cd417e 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -169,6 +169,7 @@ public class FiniteClosureTest { setExtT1, hashSetExtT1, treeSetExtT1, linkedHashSetExtT1 }).collect(Collectors.toSet())); + System.out.println(fc.smaller(setExtT1)); Assert.assertEquals(expectedResult, fc.smaller(setExtT1)); /* @@ -395,7 +396,37 @@ public class FiniteClosureTest { Assert.assertEquals(82, actual.size()); Assert.assertTrue(actual.contains(myMapExtInt)); - Assert.assertTrue(actual.contains(myMapInt)); + Assert.assertTrue(actual.contains(myMapInt)); + + /* + * Test Case 16: + * + * smaller(FunN) = + * { FunN, FunN, + * FunN, FunN, + * FunN, FunN, + * FunN, FunN } + */ + + UnifyType object = tf.getSimpleType("Object"); + + fcb = new FiniteClosureBuilder(); + fcb.add(integer, number); + fcb.add(number, object); + fc = fcb.getCollectionExample(); + + UnifyType funNNumber = tf.getFunNType(number, number, number); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + tf.getFunNType(number, number, number), tf.getFunNType(number, object, number), + tf.getFunNType(number, number, object), tf.getFunNType(number, object, object), + tf.getFunNType(integer, number, number), tf.getFunNType(integer, object, number), + tf.getFunNType(integer, number, object), tf.getFunNType(integer, object, object), + }).collect(Collectors.toSet())); + + actual = fc.smaller(funNNumber); + System.out.println(actual); + Assert.assertEquals(expectedResult, actual); + } @Test diff --git a/test/unify/TypeFactory.java b/test/unify/TypeFactory.java index 099638e7..881222c8 100644 --- a/test/unify/TypeFactory.java +++ b/test/unify/TypeFactory.java @@ -4,9 +4,11 @@ import java.util.Arrays; import java.util.stream.Collectors; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; +import de.dhbwstuttgart.typeinference.unify.model.FunNType; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; +import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public class TypeFactory { @@ -34,4 +36,9 @@ public class TypeFactory { public PlaceholderType getPlaceholderType(String name) { return new PlaceholderType(name); } + + public FunNType getFunNType(UnifyType... typeParams) { + return FunNType.getFunNType(new TypeParams(typeParams)); + } + } From b7f41c4d135bb6148d2d2ed635ee0d85e75a722d Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Thu, 7 Apr 2016 22:30:30 +0200 Subject: [PATCH 42/57] funN greater --- .../unify/model/FiniteClosure.java | 18 +++++++++-- test/unify/FiniteClosureTest.java | 32 +++++++++++++++++-- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 2ac30e19..5575dcf6 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -241,8 +241,22 @@ public class FiniteClosure implements IFiniteClosure { } protected Set computeGreaterFunN(FunNType type) { - // TODO Auto-generated method stub - return null; + Set result = new HashSet<>(); + + // if T = T' then T <=* T' + result.add(type); + + ArrayList> paramCandidates = new ArrayList<>(); + paramCandidates.add(greater(type.getTypeParams().get(0))); + for (int i = 1; i < type.getTypeParams().size(); i++) + paramCandidates.add(smaller(type.getTypeParams().get(i))); + + Set permResult = permuteParams(paramCandidates); + + for (TypeParams newParams : permResult) + result.add(type.setTypeParams(newParams)); + + return result; } diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index 25cd417e..f6dff401 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -169,7 +169,7 @@ public class FiniteClosureTest { setExtT1, hashSetExtT1, treeSetExtT1, linkedHashSetExtT1 }).collect(Collectors.toSet())); - System.out.println(fc.smaller(setExtT1)); + //System.out.println(fc.smaller(setExtT1)); Assert.assertEquals(expectedResult, fc.smaller(setExtT1)); /* @@ -424,7 +424,7 @@ public class FiniteClosureTest { }).collect(Collectors.toSet())); actual = fc.smaller(funNNumber); - System.out.println(actual); + //System.out.println(actual); Assert.assertEquals(expectedResult, actual); } @@ -664,6 +664,34 @@ public class FiniteClosureTest { * greater(SortedMap, ? super List>) = * */ + + /* + * Test Case 14: + * + * greater(FunN) = + * { FunN, FunN, + * FunN, FunN, + * FunN, FunN, + * FunN, FunN } + */ + + UnifyType object = tf.getSimpleType("Object"); + + fcb = new FiniteClosureBuilder(); + fcb.add(integer, number); + fcb.add(number, object); + fc = fcb.getCollectionExample(); + + UnifyType funNNumber = tf.getFunNType(number, number, number); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + tf.getFunNType(number, number, number), tf.getFunNType(number, integer, number), + tf.getFunNType(number, number, integer), tf.getFunNType(number, integer, integer), + tf.getFunNType(object, number, number), tf.getFunNType(object, integer, number), + tf.getFunNType(object, number, integer), tf.getFunNType(object, integer, integer) + }).collect(Collectors.toSet())); + + actual = fc.greater(funNNumber); + Assert.assertEquals(expectedResult, actual); } @Test From 3a2a5510b974eca3c844ed3e5624f6661a567701 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Thu, 7 Apr 2016 22:32:42 +0200 Subject: [PATCH 43/57] removed printLn-tests fuer smArg und grArg --- test/unify/FiniteClosureTest.java | 36 ------------------------------- 1 file changed, 36 deletions(-) diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index f6dff401..0ad0a107 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -693,40 +693,4 @@ public class FiniteClosureTest { actual = fc.greater(funNNumber); Assert.assertEquals(expectedResult, actual); } - - @Test - public void testGrArg() { - IFiniteClosure fc = new FiniteClosureBuilder().getCollectionExample(); - TypeFactory tf = new TypeFactory(); - - System.out.println("\n\n----- GrArg Test -----"); - System.out.println("GrArg(List) = " + fc.grArg(tf.getSimpleType("List", "T"))); - System.out.println("GrArg(? extends List) = " + fc.grArg(tf.getExtendsType(tf.getSimpleType("List", "T")))); - System.out.println("GrArg(? super List) = " + fc.grArg(tf.getSuperType(tf.getSimpleType("List", "T")))); - } - - - @Test - public void testSmArg() { - IFiniteClosure fc = new FiniteClosureBuilder().getCollectionExample(); - TypeFactory tf = new TypeFactory(); - - System.out.println("\n\n----- SmArg Test -----"); - System.out.println("SmArg(List) = " + fc.smArg(tf.getSimpleType("List", "T"))); - System.out.println("SmArg(? extends List) = " + fc.smArg(tf.getExtendsType(tf.getSimpleType("List", "T")))); - System.out.println("SmArg(? super List) = " + fc.smArg(tf.getSuperType(tf.getSimpleType("List", "T")))); - } - - @Test - public void testGetGenericType() { - // TODO - } - - private void printDiff(Set expected, Set actual) { - System.out.println("Diff:"); - System.out.println("In expected but not in actual:"); - Set expected1 = new HashSet<>(expected); - expected1.removeAll(actual); - System.out.println(expected1); - } } From e06888f5f7f69482d3f26ff9dd1d014f1449ea4c Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Thu, 7 Apr 2016 22:33:14 +0200 Subject: [PATCH 44/57] organized imports --- test/unify/FiniteClosureTest.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index 0ad0a107..b58b9298 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -2,17 +2,13 @@ package unify; import java.util.Arrays; import java.util.HashSet; -import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Test; -import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; -import de.dhbwstuttgart.typeinference.unify.model.PairOperator; -import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; +import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public class FiniteClosureTest { From 5c73224f8f8583c31f5ed6a6b106d8136ca137fb Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Fri, 8 Apr 2016 18:04:11 +0200 Subject: [PATCH 45/57] support for extended case 1 // tests // bugfix in "big" cases --- .../typeinference/unify/Unify.java | 38 +++--- test/unify/UnifyTest.java | 126 +++++++++++++++--- 2 files changed, 123 insertions(+), 41 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unify.java b/src/de/dhbwstuttgart/typeinference/unify/Unify.java index 6f4fa514..b0e3d7a9 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unify.java @@ -327,12 +327,9 @@ public class Unify { Set cs = fc.getAllTypesByName(thetaPrime.getName()); - for(UnifyType c : cs) { - - // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.getChildren(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); - thetaQs.add(c); // reflexive - + for(UnifyType c : cs) { + Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); + Set thetaQPrimes = new HashSet<>(); TypeParams cParams = c.getTypeParams(); if(cParams.size() == 0) @@ -352,6 +349,7 @@ public class Unify { continue; Unifier unifier = opt.get(); + unifier.swapPlaceholderSubstitutions(thetaPrime.getTypeParams().toArray()); Set substitutionSet = new HashSet<>(); for (Entry sigma : unifier.getSubstitutions()) substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); @@ -360,7 +358,15 @@ public class Unify { Set smaller = fc.smaller(unifier.apply(tq)); for(UnifyType theta : smaller) { Set resultPrime = new HashSet<>(); - resultPrime.add(new UnifyPair(a, theta, PairOperator.EQUALSDOT)); + + UnifyType[] freshTphs = new UnifyType[theta.getTypeParams().size()]; + for(int i = 0; i < freshTphs.length; i++) { + freshTphs[i] = PlaceholderType.freshPlaceholder(); + resultPrime.add(new UnifyPair(freshTphs[i], theta.getTypeParams().get(i), PairOperator.SMALLERDOTWC)); + } + + UnifyType freshTheta = theta.setTypeParams(new TypeParams(freshTphs)); + resultPrime.add(new UnifyPair(a, freshTheta, PairOperator.EQUALSDOT)); resultPrime.addAll(substitutionSet); result.add(resultPrime); } @@ -379,12 +385,9 @@ public class Unify { UnifyType thetaPrime = extThetaPrime.getExtendedType(); Set cs = fc.getAllTypesByName(thetaPrime.getName()); - for(UnifyType c : cs) { - - // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.getChildren(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); - thetaQs.add(c); // reflexive - + for(UnifyType c : cs) { + Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); + Set thetaQPrimes = new HashSet<>(); TypeParams cParams = c.getTypeParams(); if(cParams.size() == 0) @@ -485,12 +488,9 @@ public class Unify { UnifyType theta = supTheta.getSuperedType(); Set cs = fc.getAllTypesByName(theta.getName()); - for(UnifyType c : cs) { - - // Wenn die fc nach spezifikation funktioniert ist das hier nicht mehr nötig? - Set thetaQs = fc.getChildren(c).stream().filter(x -> x.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); - thetaQs.add(c); // reflexive - + for(UnifyType c : cs) { + Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); + Set thetaQPrimes = new HashSet<>(); TypeParams cParams = c.getTypeParams(); if(cParams.size() == 0) diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 3d091f5e..1a9ec729 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -129,6 +129,8 @@ public class UnifyTest extends Unify { addAsSet(expected, new UnifyPair(tphA, supObject, PairOperator.EQUALSDOT)); actual = unify(eq, fc); + System.out.println("? super Integer"); + System.out.println(actual); actual = filterGeneratedTPHsMultiple(actual); Assert.assertEquals(expected, actual); @@ -278,9 +280,9 @@ public class UnifyTest extends Unify { UnifyType integer = tf.getSimpleType("Integer"); UnifyType doubl = tf.getSimpleType("Double"); - fcb.add(number, object); + //fcb.add(number, object); fcb.add(integer, number); - fcb.add(doubl, number); + //fcb.add(doubl, number); IFiniteClosure fc = fcb.getCollectionExample(); @@ -289,6 +291,10 @@ public class UnifyTest extends Unify { * * (Vector <. Vector) * (List <. List) + * + * Expected: + * {(b = Number), (a = Number)}, {(b = Number), (a = Integer)}, {(b = Number), (a = Integer)} + * (b = Integer), */ UnifyType tphA = tf.getPlaceholderType("a"); @@ -305,26 +311,7 @@ public class UnifyTest extends Unify { System.out.println(actual); //Assert.assertEquals(actual, expected); - - /* - * Test 8: - * - * (a <.? ? sup b) - * (b = Number) - */ - - UnifyType supB = tf.getSuperType(tphB); - eq = new HashSet<>(); - eq.add(new UnifyPair(tphA, supB, PairOperator.SMALLERDOTWC)); - eq.add(new UnifyPair(tphB, number, PairOperator.EQUALSDOT)); - - expected = new HashSet<>(); - - actual = unify(eq, fc); - - System.out.println(actual); - //Assert.assertEquals(expected, actual); - + /* * Test 2: @@ -382,6 +369,101 @@ public class UnifyTest extends Unify { //Assert.assertEquals(actual, expected); } + /** + * These are tests that specifically test cases where the old unify algorithm was incomplete. + */ + @Test + public void unifyTestExtension() { + /* + * INIT + */ + TypeFactory tf = new TypeFactory(); + FiniteClosureBuilder fcb = new FiniteClosureBuilder(); + + UnifyType number = tf.getSimpleType("Number"); + UnifyType object = tf.getSimpleType("Object"); + UnifyType integer = tf.getSimpleType("Integer"); + UnifyType doubl = tf.getSimpleType("Double"); + + //fcb.add(number, object); + fcb.add(integer, number); + //fcb.add(doubl, number); + + IFiniteClosure fc = fcb.getCollectionExample(); + + + /* + * Test 1: + * This is a Test for the extension of case 1 in the cartesian product of step 4. + * + * (a <. Vector) + * (List <. List) + * + * Expected: + * (b = Integer), (a = Vector) + * (b = ? extends Integer), (a = Vector), + * (b = ? extends Integer), (a = Vector), + * (b = ? super Integer), (a = Vector) + * (b = ? super Integer), (a = Vector) + * (b = ? super Integer), (a = Vector) + * (b = ? super Integer), (a = Vector) + * (b = ? extends Number), (a = Vector) + * (b = ? extends Number), (a = Vector) + * (b = ? extends Number), (a = Vector) + * (b = ? extends Number), (a = Vector) + */ + + UnifyType tphA = tf.getPlaceholderType("a"); + UnifyType tphB = tf.getPlaceholderType("b"); + UnifyType extB = tf.getExtendsType(tphB); + UnifyType extNum = tf.getExtendsType(number); + + Set eq = new HashSet(); + eq.add(new UnifyPair(tphA, tf.getSimpleType("Stack", tphB), PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(tf.getSimpleType("List", integer), tf.getSimpleType("List", tphB), PairOperator.SMALLERDOT)); + + Set> expected = new HashSet<>(); + Set> actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(actual, expected); + + /* + * Test 2: + * + * This is a test for th extension of case 2 of the cartesian product of step 4. + * + * TODO + */ + + /* + * Test 3: + * This is a test for the extension of case 3 of the cartesian product of step 4. + * + * (a <.? ? sup b) + * (b = Number) + */ + + UnifyType supB = tf.getSuperType(tphB); + eq = new HashSet<>(); + eq.add(new UnifyPair(tphA, supB, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphB, number, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(expected, actual); + + /* + * Test 4: + * This is a test for the extension of case 4 of the cartesian product of step 4. + * + * + */ + } + @Test public void unifyTestComplex() { /* From 41b3e4f6c2a9555e5f3ac13357bbce7df0fe4ec0 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Fri, 8 Apr 2016 18:28:34 +0200 Subject: [PATCH 46/57] extended case 5 --- .../typeinference/unify/Unify.java | 9 ++++++- test/unify/UnifyTest.java | 25 ++++++++++++++++--- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unify.java b/src/de/dhbwstuttgart/typeinference/unify/Unify.java index b0e3d7a9..6048fbe2 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unify.java @@ -463,7 +463,14 @@ public class Unify { Set> result = new HashSet<>(); for(UnifyType thetaS : fc.greater(theta)) { Set resultPrime = new HashSet<>(); - resultPrime.add(new UnifyPair(a, thetaS, PairOperator.EQUALSDOT)); + + UnifyType[] freshTphs = new UnifyType[thetaS.getTypeParams().size()]; + for(int i = 0; i < freshTphs.length; i++) { + freshTphs[i] = PlaceholderType.freshPlaceholder(); + resultPrime.add(new UnifyPair(thetaS.getTypeParams().get(i), freshTphs[i], PairOperator.SMALLERDOTWC)); + } + + resultPrime.add(new UnifyPair(a, thetaS.setTypeParams(new TypeParams(freshTphs)), PairOperator.EQUALSDOT)); result.add(resultPrime); } diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 1a9ec729..a9773809 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -457,11 +457,28 @@ public class UnifyTest extends Unify { //Assert.assertEquals(expected, actual); /* - * Test 4: - * This is a test for the extension of case 4 of the cartesian product of step 4. - * - * + * Case 4 has no extension */ + + /* + * Test 5: + * This is a test for the extension of case 5 of the cartesian product of step 4. + * + * Vector <. a + * b =. Number + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(tf.getSimpleType("HashSet", tphB), tphA, PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(tphB, number, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(expected, actual); + } @Test From d080eb4a0a51bf4810c9b651eb17f15bff11fe42 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Fri, 8 Apr 2016 18:48:35 +0200 Subject: [PATCH 47/57] extended case 6 --- .../typeinference/unify/Unify.java | 14 ++++++++----- test/unify/StandardUnifyTest.java | 2 -- test/unify/UnifyTest.java | 21 ++++++++++++++++++- 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unify.java b/src/de/dhbwstuttgart/typeinference/unify/Unify.java index 6048fbe2..b9c1d9b1 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unify.java @@ -479,11 +479,15 @@ public class Unify { protected Set> unifyCase6(ExtendsType extTheta, PlaceholderType a, IFiniteClosure fc) { Set> result = new HashSet<>(); - for(UnifyType thetaS : fc.grArg(extTheta)) { - Set resultPrime = new HashSet<>(); - resultPrime.add(new UnifyPair(a, thetaS, PairOperator.EQUALSDOT)); - result.add(resultPrime); - } + //for(UnifyType thetaS : fc.smaller(extTheta.getExtendedType())) { + UnifyType freshTph = PlaceholderType.freshPlaceholder(); + UnifyType extFreshTph = new ExtendsType(freshTph); + + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, extFreshTph, PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(extTheta.getExtendedType(), freshTph, PairOperator.SMALLERDOT)); + result.add(resultPrime); + //} return result; } diff --git a/test/unify/StandardUnifyTest.java b/test/unify/StandardUnifyTest.java index 2664324c..83f8abe1 100644 --- a/test/unify/StandardUnifyTest.java +++ b/test/unify/StandardUnifyTest.java @@ -32,8 +32,6 @@ public class StandardUnifyTest { System.out.println(unify.unify(f, y).get()); - // TODO ist das ergebnis { (x -> ? extends a), (y -> g) } in der richtigen form oder - // muss es { (x -> ? extends a), (y -> g) } sein? // {f,x> = f} UnifyType g = tf.getSimpleType("g", "x"); UnifyType f1 = tf.getSimpleType("f", g, x); diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index a9773809..6f0597fd 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -174,7 +174,7 @@ public class UnifyTest extends Unify { addAsSet(expected, new UnifyPair(tphA, extObject, PairOperator.EQUALSDOT)); actual = unify(eq, fc); - + actual = filterGeneratedTPHsMultiple(actual); Assert.assertEquals(expected, actual); @@ -479,6 +479,25 @@ public class UnifyTest extends Unify { System.out.println(actual); //Assert.assertEquals(expected, actual); + /* + * Test 6: + * This is a test for the extension of case 6 of the cartesian product of step 4. + * + * ? extends b <.? a + * b =. Integer + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(extB, tphA, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphB, integer, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(expected, actual); + } @Test From 23e0be25725aa5c3110c3b4c195b98541ddeee3c Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Sat, 9 Apr 2016 15:07:41 +0200 Subject: [PATCH 48/57] extended all cases / fixed random placeholder generation --- .../typeinference/unify/Unify.java | 284 +++++++++++------- .../unify/model/PlaceholderType.java | 2 +- test/unify/UnifyTest.java | 69 ++++- 3 files changed, 244 insertions(+), 111 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unify.java b/src/de/dhbwstuttgart/typeinference/unify/Unify.java index b9c1d9b1..6d7d978d 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unify.java @@ -119,22 +119,26 @@ public class Unify { } IRuleSet rules = new RuleSet(fc); - Set> changed = new HashSet<>(); + Set> restartSet = new HashSet<>(); Set> eqPrimePrimeSet = new HashSet<>(); for(Set eqPrime : eqPrimeSetFlat) { Optional> eqPrimePrime = rules.subst(eqPrime); - if(eqPrime.equals(eq)) + /*if (eqPrime.equals(eq)) eqPrimePrimeSet.add(eqPrime); - else if(eqPrimePrime.isPresent()) - eqPrimePrimeSet.addAll(this.unify(eqPrimePrime.get(), fc)); + else if(eqPrimePrime.isPresent()) { + Set> subUnifyResult = unify(eqPrimePrime.get(), fc); + eqPrimePrimeSet.addAll(subUnifyResult); + } else - eqPrimePrimeSet.addAll(this.unify(eqPrime, fc)); - /*if(eqPrimePrime.isPresent()) - changed.add(eqPrimePrime.get()); + eqPrimePrimeSet.addAll(this.unify(eqPrime, fc));*/ + if(eqPrimePrime.isPresent()) + restartSet.add(eqPrimePrime.get()); + else if(!isSolvedForm(eqPrime)) + restartSet.add(eqPrime); else - eqPrimePrimeSet.add(eqPrime);*/ + eqPrimePrimeSet.add(eqPrime); } /* @@ -142,7 +146,7 @@ public class Unify { * b) Build the union over everything */ - for(Set eqss : changed) + for(Set eqss : restartSet) eqPrimePrimeSet.addAll(this.unify(eqss, fc)); /* @@ -326,16 +330,36 @@ public class Unify { IUnify unify = new MartelliMontanariUnify(); Set cs = fc.getAllTypesByName(thetaPrime.getName()); + cs.add(thetaPrime); for(UnifyType c : cs) { Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); - + thetaQs.add(thetaPrime); + Set thetaQPrimes = new HashSet<>(); TypeParams cParams = c.getTypeParams(); if(cParams.size() == 0) thetaQPrimes.add(c); else { ArrayList> candidateParams = new ArrayList<>(); + + /* + * TODO Optimierungsmöglichkeit: + * + * An dieser Stelle gibt es Raum für Optimierung. + * Z.B. resultiert (a <. C) durch Permutation der Parameter mit grArg in: + * (a = C, b' <.? ? extends Number) + * (a = C, b' <.? ? extends Integer) + * (a = C, b' <.? Integer) + * usw... + * + * Der erste Fall ist am allgemeinsten und schließt alle anderen Fälle mit ein. Jeder Fall resultiert in einem + * rekursiven Aufruf des Unify. Es würde reichen nur den allgemeinsten Fall zu betrachten da dieser den Lösungraum + * der anderen Fälle miteinschließt. + * + * (Gibt es einen einzigen maximalen fall? Wsl. ? super x (x möglichst klein) und ? ext y (y möglichst groß)) + */ + for(UnifyType param : cParams) candidateParams.add(fc.grArg(param)); @@ -354,18 +378,20 @@ public class Unify { for (Entry sigma : unifier.getSubstitutions()) substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + List freshTphs = new ArrayList<>(); for (UnifyType tq : thetaQs) { Set smaller = fc.smaller(unifier.apply(tq)); for(UnifyType theta : smaller) { Set resultPrime = new HashSet<>(); - UnifyType[] freshTphs = new UnifyType[theta.getTypeParams().size()]; - for(int i = 0; i < freshTphs.length; i++) { - freshTphs[i] = PlaceholderType.freshPlaceholder(); - resultPrime.add(new UnifyPair(freshTphs[i], theta.getTypeParams().get(i), PairOperator.SMALLERDOTWC)); + //UnifyType[] freshTphs = new UnifyType[theta.getTypeParams().size()]; + for(int i = 0; i < theta.getTypeParams().size(); i++) { + if(freshTphs.size()-1 < i) + freshTphs.add(PlaceholderType.freshPlaceholder()); + resultPrime.add(new UnifyPair(freshTphs.get(i), theta.getTypeParams().get(i), PairOperator.SMALLERDOTWC)); } - UnifyType freshTheta = theta.setTypeParams(new TypeParams(freshTphs)); + UnifyType freshTheta = theta.setTypeParams(new TypeParams(freshTphs.toArray(new UnifyType[0]))); resultPrime.add(new UnifyPair(a, freshTheta, PairOperator.EQUALSDOT)); resultPrime.addAll(substitutionSet); result.add(resultPrime); @@ -380,53 +406,74 @@ public class Unify { protected Set> unifyCase2(PlaceholderType a, ExtendsType extThetaPrime, IFiniteClosure fc) { Set> result = new HashSet<>(); - IUnify unify = new MartelliMontanariUnify(); + UnifyType aPrime = PlaceholderType.freshPlaceholder(); + UnifyType extAPrime = new ExtendsType(aPrime); UnifyType thetaPrime = extThetaPrime.getExtendedType(); - Set cs = fc.getAllTypesByName(thetaPrime.getName()); - - for(UnifyType c : cs) { - Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); - - Set thetaQPrimes = new HashSet<>(); - TypeParams cParams = c.getTypeParams(); - if(cParams.size() == 0) - thetaQPrimes.add(c); - else { - ArrayList> candidateParams = new ArrayList<>(); - for(UnifyType param : cParams) - candidateParams.add(fc.grArg(param)); + //for(UnifyType theta : fc.smArg(subThetaPrime)) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, aPrime, PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(aPrime, thetaPrime, PairOperator.SMALLERDOT)); + result.add(resultPrime); - for(TypeParams tp : permuteParams(candidateParams)) - thetaQPrimes.add(c.setTypeParams(tp)); - } - - for(UnifyType tqp : thetaQPrimes) { - Optional opt = unify.unify(tqp, thetaPrime); - if (!opt.isPresent()) - continue; - - Unifier unifier = opt.get(); - - Set substitutionSet = new HashSet<>(); - for (Entry sigma : unifier.getSubstitutions()) - substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); - - for (UnifyType tq : thetaQs) { - ExtendsType extTq = new ExtendsType(tq); - Set smArg = fc.smArg(unifier.apply(extTq)); - for(UnifyType theta : smArg) { - Set resultPrime = new HashSet<>(); - resultPrime.add(new UnifyPair(a, theta, PairOperator.EQUALSDOT)); - resultPrime.addAll(substitutionSet); - result.add(resultPrime); - } - } - - } - } + resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, extAPrime, PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(aPrime, thetaPrime, PairOperator.SMALLERDOT)); + result.add(resultPrime); + //} return result; + +// Set> result = new HashSet<>(); +// IUnify unify = new MartelliMontanariUnify(); +// +// UnifyType thetaPrime = extThetaPrime.getExtendedType(); +// Set cs = fc.getAllTypesByName(thetaPrime.getName()); +// cs.add(thetaPrime); +// +// for(UnifyType c : cs) { +// Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); +// thetaQs.add(thetaPrime); +// +// Set thetaQPrimes = new HashSet<>(); +// TypeParams cParams = c.getTypeParams(); +// if(cParams.size() == 0) +// thetaQPrimes.add(c); +// else { +// ArrayList> candidateParams = new ArrayList<>(); +// for(UnifyType param : cParams) +// candidateParams.add(fc.grArg(param)); +// +// for(TypeParams tp : permuteParams(candidateParams)) +// thetaQPrimes.add(c.setTypeParams(tp)); +// } +// +// for(UnifyType tqp : thetaQPrimes) { +// Optional opt = unify.unify(tqp, thetaPrime); +// if (!opt.isPresent()) +// continue; +// +// Unifier unifier = opt.get(); +// +// Set substitutionSet = new HashSet<>(); +// for (Entry sigma : unifier.getSubstitutions()) +// substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); +// +// for (UnifyType tq : thetaQs) { +// ExtendsType extTq = new ExtendsType(tq); +// Set smArg = fc.smArg(unifier.apply(extTq)); +// for(UnifyType theta : smArg) { +// Set resultPrime = new HashSet<>(); +// resultPrime.add(new UnifyPair(a, theta, PairOperator.EQUALSDOT)); +// resultPrime.addAll(substitutionSet); +// result.add(resultPrime); +// } +// } +// +// } +// } +// +// return result; } protected Set> unifyCase3(PlaceholderType a, SuperType subThetaPrime, IFiniteClosure fc) { @@ -494,62 +541,89 @@ public class Unify { protected Set> unifyCase7(SuperType supTheta, PlaceholderType a, IFiniteClosure fc) { Set> result = new HashSet<>(); - IUnify unify = new MartelliMontanariUnify(); + UnifyType aPrime = PlaceholderType.freshPlaceholder(); + UnifyType supAPrime = new SuperType(aPrime); UnifyType theta = supTheta.getSuperedType(); - Set cs = fc.getAllTypesByName(theta.getName()); - - for(UnifyType c : cs) { - Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); - - Set thetaQPrimes = new HashSet<>(); - TypeParams cParams = c.getTypeParams(); - if(cParams.size() == 0) - thetaQPrimes.add(c); - else { - ArrayList> candidateParams = new ArrayList<>(); - for(UnifyType param : cParams) - candidateParams.add(fc.grArg(param)); - - for(TypeParams tp : permuteParams(candidateParams)) - thetaQPrimes.add(c.setTypeParams(tp)); - } - - for(UnifyType tqp : thetaQPrimes) { - Optional opt = unify.unify(tqp, theta); - if (!opt.isPresent()) - continue; - - Unifier unifier = opt.get(); - - Set substitutionSet = new HashSet<>(); - for (Entry sigma : unifier.getSubstitutions()) - substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); - - for (UnifyType tq : thetaQs) { - Set smaller = fc.smaller(unifier.apply(tq)); - - for(UnifyType thetaPrime : smaller) { - Set resultPrime = new HashSet<>(); - resultPrime.add(new UnifyPair(a, new SuperType(thetaPrime), PairOperator.EQUALSDOT)); - resultPrime.addAll(substitutionSet); - result.add(resultPrime); - } - } - - } - } + //for(UnifyType theta : fc.smArg(subThetaPrime)) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, supAPrime, PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(aPrime, theta, PairOperator.SMALLERDOT)); + result.add(resultPrime); + //} return result; + +// Set> result = new HashSet<>(); +// IUnify unify = new MartelliMontanariUnify(); +// +// UnifyType theta = supTheta.getSuperedType(); +// Set cs = fc.getAllTypesByName(theta.getName()); +// cs.add(theta); +// +// for(UnifyType c : cs) { +// Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); +// thetaQs.add(theta); +// +// Set thetaQPrimes = new HashSet<>(); +// TypeParams cParams = c.getTypeParams(); +// if(cParams.size() == 0) +// thetaQPrimes.add(c); +// else { +// ArrayList> candidateParams = new ArrayList<>(); +// for(UnifyType param : cParams) +// candidateParams.add(fc.grArg(param)); +// +// for(TypeParams tp : permuteParams(candidateParams)) +// thetaQPrimes.add(c.setTypeParams(tp)); +// } +// +// for(UnifyType tqp : thetaQPrimes) { +// Optional opt = unify.unify(tqp, theta); +// if (!opt.isPresent()) +// continue; +// +// Unifier unifier = opt.get(); +// +// Set substitutionSet = new HashSet<>(); +// for (Entry sigma : unifier.getSubstitutions()) +// substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); +// +// for (UnifyType tq : thetaQs) { +// Set smaller = fc.smaller(unifier.apply(tq)); +// +// for(UnifyType thetaPrime : smaller) { +// Set resultPrime = new HashSet<>(); +// resultPrime.add(new UnifyPair(a, new SuperType(thetaPrime), PairOperator.EQUALSDOT)); +// resultPrime.addAll(substitutionSet); +// result.add(resultPrime); +// } +// } +// +// } +// } +// +// return result; } protected Set> unifyCase8(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { Set> result = new HashSet<>(); - for(UnifyType thetaS : fc.grArg(theta)) { - Set resultPrime = new HashSet<>(); - resultPrime.add(new UnifyPair(a, thetaS, PairOperator.EQUALSDOT)); - result.add(resultPrime); - } + //for(UnifyType thetaS : fc.grArg(theta)) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, theta, PairOperator.EQUALSDOT)); + result.add(resultPrime); + + UnifyType freshTph = PlaceholderType.freshPlaceholder(); + resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, new ExtendsType(freshTph), PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(theta, freshTph, PairOperator.SMALLERDOT)); + result.add(resultPrime); + + resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, new SuperType(freshTph), PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(freshTph, theta, PairOperator.SMALLERDOT)); + result.add(resultPrime); + //} return result; } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java index f45a4a13..879fe87d 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java @@ -31,7 +31,7 @@ public final class PlaceholderType extends UnifyType{ String name = nextName + randomChar(); while(EXISTING_PLACEHOLDERS.contains(name)); - nextName += randomChar(); + name += randomChar(); return new PlaceholderType(name, true); } diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 6f0597fd..666731b8 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -157,6 +157,7 @@ public class UnifyTest extends Unify { addAsSet(expected, new UnifyPair(tphA, supNumber, PairOperator.EQUALSDOT)); actual = unify(eq, fc); + actual = filterGeneratedTPHsMultiple(actual); Assert.assertEquals(expected, actual); @@ -199,6 +200,7 @@ public class UnifyTest extends Unify { addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); actual = unify(eq, fc); + actual = filterGeneratedTPHsMultiple(actual); Assert.assertEquals(expected, actual); @@ -309,7 +311,7 @@ public class UnifyTest extends Unify { Set> expected = new HashSet<>(); Set> actual = unify(eq, fc); - System.out.println(actual); + //System.out.println(actual); //Assert.assertEquals(actual, expected); @@ -343,8 +345,8 @@ public class UnifyTest extends Unify { expected = new HashSet<>(); actual = unify(eq, fc); - - //System.out.println(actual); + + System.out.println(actual); //Assert.assertEquals(actual, expected); /* @@ -384,8 +386,10 @@ public class UnifyTest extends Unify { UnifyType object = tf.getSimpleType("Object"); UnifyType integer = tf.getSimpleType("Integer"); UnifyType doubl = tf.getSimpleType("Double"); + UnifyType mygeneric = tf.getSimpleType("MyGeneric", "T"); - //fcb.add(number, object); + + fcb.add(mygeneric, object); fcb.add(integer, number); //fcb.add(doubl, number); @@ -433,9 +437,21 @@ public class UnifyTest extends Unify { * * This is a test for th extension of case 2 of the cartesian product of step 4. * - * TODO + * (a <.? ? ext b) + * (b =. Number) */ + eq = new HashSet<>(); + eq.add(new UnifyPair(tphA, extB, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphB, number, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + System.out.println("Case 2"); + System.out.println(actual); + /* * Test 3: * This is a test for the extension of case 3 of the cartesian product of step 4. @@ -453,6 +469,8 @@ public class UnifyTest extends Unify { actual = unify(eq, fc); + + System.out.println("Case 3"); System.out.println(actual); //Assert.assertEquals(expected, actual); @@ -498,6 +516,47 @@ public class UnifyTest extends Unify { System.out.println(actual); //Assert.assertEquals(expected, actual); + /* + * Test 7: + * This is a test for the extension of case 7 of the cartesian product of step 4. + * + * ? sup b <.? a + * b =. Number + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(supB, tphA, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphB, number, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + System.out.println("Case 7"); + System.out.println(actual); + //Assert.assertEquals(expected, actual); + + + /* + * Test 8: + * This is a test for the extension of case 8 of the cartesian product of step 4. + * + * MyGeneric <.? a + * b =. Integer + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(tf.getSimpleType("MyGeneric", extB), tphA, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphB, number, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + System.out.println("Case 8:"); + System.out.println(actual); + //Assert.assertEquals(expected, actual); + } @Test From 64247b689b268fedd0de202adc49ab9ba5ace030 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Sun, 10 Apr 2016 14:52:07 +0200 Subject: [PATCH 49/57] signature from getLeftHandedType from type to string --- .../dhbwstuttgart/typeinference/unify/RuleSet.java | 14 +++++++------- .../unify/interfaces/IFiniteClosure.java | 2 +- .../typeinference/unify/model/FiniteClosure.java | 6 +++--- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java index e18e6156..0765b9b7 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -104,7 +104,7 @@ public class RuleSet implements IRuleSet{ if(x.getTypeParams().empty() || extY.getTypeParams().size() != x.getTypeParams().size()) return Optional.empty(); - UnifyType xFromFc = finiteClosure.getLeftHandedType(sTypeX).orElse(null); + UnifyType xFromFc = finiteClosure.getLeftHandedType(sTypeX.getName()).orElse(null); if(xFromFc == null || !xFromFc.getTypeParams().arePlaceholders()) return Optional.empty(); @@ -156,7 +156,7 @@ public class RuleSet implements IRuleSet{ if(x.getTypeParams().empty() || supY.getTypeParams().size() != x.getTypeParams().size()) return Optional.empty(); - UnifyType xFromFc = finiteClosure.getLeftHandedType(sTypeX).orElse(null); + UnifyType xFromFc = finiteClosure.getLeftHandedType(sTypeX.getName()).orElse(null); if(xFromFc == null || !xFromFc.getTypeParams().arePlaceholders()) return Optional.empty(); @@ -234,7 +234,7 @@ public class RuleSet implements IRuleSet{ if(lhsSType.getTypeParams().empty() || lhsSType.getTypeParams().size() != rhsSType.getTypeParams().size()) return Optional.empty(); - UnifyType cFromFc = finiteClosure.getLeftHandedType(c).orElse(null); + UnifyType cFromFc = finiteClosure.getLeftHandedType(c.getName()).orElse(null); if(cFromFc == null || !cFromFc.getTypeParams().arePlaceholders()) return Optional.empty(); @@ -383,7 +383,7 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); - Optional opt = finiteClosure.getLeftHandedType(typeD); + Optional opt = finiteClosure.getLeftHandedType(typeD.getName()); if(!opt.isPresent()) return Optional.empty(); @@ -427,9 +427,9 @@ public class RuleSet implements IRuleSet{ UnifyType typeDgen; if(typeD instanceof ReferenceType) - typeDgen = finiteClosure.getLeftHandedType(typeD).orElse(null); + typeDgen = finiteClosure.getLeftHandedType(typeD.getName()).orElse(null); else { - Optional opt = finiteClosure.getLeftHandedType(((ExtendsType) typeD).getExtendedType()); + Optional opt = finiteClosure.getLeftHandedType(((ExtendsType) typeD).getExtendedType().getName()); typeDgen = opt.isPresent() ? new ExtendsType(opt.get()) : null; } @@ -472,7 +472,7 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); - Optional opt = finiteClosure.getLeftHandedType(((SuperType) typeSupD).getSuperedType()); + Optional opt = finiteClosure.getLeftHandedType(((SuperType) typeSupD).getSuperedType().getName()); if(!opt.isPresent()) return Optional.empty(); diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java index bd15999a..cb95ac41 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java @@ -53,7 +53,7 @@ public interface IFiniteClosure { public Set grArg(FunNType type); public Set smArg(FunNType type); - public Optional getLeftHandedType(UnifyType t); + public Optional getLeftHandedType(String typeName); public Set getAncestors(UnifyType t); public Set getChildren(UnifyType t); public Set getAllTypesByName(String typeName); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 5575dcf6..0ef5d2a3 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -395,12 +395,12 @@ public class FiniteClosure implements IFiniteClosure { } @Override - public Optional getLeftHandedType(UnifyType t) { - if(!strInheritanceGraph.containsKey(t.getName())) + public Optional getLeftHandedType(String typeName) { + if(!strInheritanceGraph.containsKey(typeName)) return Optional.empty(); for(UnifyPair pair : pairs) - if(pair.getLhsType().getName().equals(t.getName())) + if(pair.getLhsType().getName().equals(typeName)) return Optional.of(pair.getLhsType()); return Optional.empty(); From 5dd90cb30ca6ff3590c1ca04e2cf190b7c8ddfe3 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 11 Apr 2016 09:56:06 +0200 Subject: [PATCH 50/57] refactored standard unification --- .../unify/MartelliMontanariUnify.java | 96 ++++++------------- .../typeinference/unify/Unify.java | 6 +- 2 files changed, 31 insertions(+), 71 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java b/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java index 3531b716..d1cca70f 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java @@ -42,27 +42,38 @@ public class MartelliMontanariUnify implements IUnify { int idx = 0; while(idx < termsQ.size()) { UnifyPair pair = termsQ.get(idx); + UnifyType rhsType = pair.getRhsType(); + UnifyType lhsType = pair.getLhsType(); + TypeParams rhsTypeParams = rhsType.getTypeParams(); + TypeParams lhsTypeParams = lhsType.getTypeParams(); - if(delete(pair)) { + // DELETE + if(pair.getRhsType().equals(pair.getLhsType())) { termsQ.remove(idx); continue; } - Optional> optSet = decompose(pair); - - if(optSet == null) - return Optional.empty(); // Unification failed - - if(optSet.isPresent()) { - termsQ.addAll(optSet.get()); + // REDUCE + if(!(rhsType instanceof PlaceholderType) && !(lhsType instanceof PlaceholderType) + && (rhsTypeParams.size() != 0 || lhsTypeParams.size() != 0)) { + Set result = new HashSet<>(); + + if(!rhsType.getName().equals(lhsType.getName())) + return Optional.empty(); // conflict + if(rhsTypeParams.size() != lhsTypeParams.size()) + return Optional.empty(); // conflict + + for(int i = 0; i < rhsTypeParams.size(); i++) + result.add(new UnifyPair(rhsTypeParams.get(i), lhsTypeParams.get(i), PairOperator.EQUALSDOT)); + + termsQ.addAll(result); idx = idx+1 == termsQ.size() ? 0 : idx+1; continue; } - - Optional optPair = swap(pair); - - if(optPair.isPresent()) { - termsQ.add(optPair.get()); + + // SWAP + if(!(lhsType instanceof PlaceholderType) && (rhsType instanceof PlaceholderType)) { + termsQ.add(new UnifyPair(rhsType, lhsType, PairOperator.EQUALSDOT)); idx = idx+1 == termsQ.size() ? 0 : idx+1; continue; } @@ -72,11 +83,9 @@ public class MartelliMontanariUnify implements IUnify { && pair.getRhsType().getTypeParams().occurs((PlaceholderType) pair.getLhsType())) return Optional.empty(); - Optional> optUni = eliminate(pair); - - if(optUni.isPresent()) { - Entry substitution = optUni.get(); - mgu.Add(substitution.getKey(), substitution.getValue()); + // SUBST + if(lhsType instanceof PlaceholderType) { + mgu.Add((PlaceholderType) lhsType, rhsType); termsQ = termsQ.stream().map(mgu::apply).collect(Collectors.toCollection(ArrayList::new)); idx = idx+1 == termsQ.size() ? 0 : idx+1; continue; @@ -87,55 +96,4 @@ public class MartelliMontanariUnify implements IUnify { return Optional.of(mgu); } - - private boolean delete(UnifyPair pair) { - return pair.getRhsType().equals(pair.getLhsType()); - } - - private Optional> decompose(UnifyPair pair) { - Set result = new HashSet<>(); - - UnifyType rhs = pair.getRhsType(); - UnifyType lhs = pair.getLhsType(); - - TypeParams rhsTypeParams = rhs.getTypeParams(); - TypeParams lhsTypeParams = lhs.getTypeParams(); - - if(!(rhs instanceof PlaceholderType) && !(lhs instanceof PlaceholderType)) { - if(!rhs.getName().equals(lhs.getName())) - return null; // conflict - if(rhsTypeParams.size() != lhsTypeParams.size()) - return null; // conflict; - } - - if(rhsTypeParams.size() == 0 || lhsTypeParams.size() == 0) - return Optional.empty(); - - for(int i = 0; i < rhsTypeParams.size(); i++) - result.add(new UnifyPair(rhsTypeParams.get(i), lhsTypeParams.get(i), PairOperator.EQUALSDOT)); - - return Optional.of(result); - } - - private Optional swap(UnifyPair pair) { - UnifyType rhs = pair.getRhsType(); - UnifyType lhs = pair.getLhsType(); - - if(!(lhs instanceof PlaceholderType) && (rhs instanceof PlaceholderType)) - return Optional.of(new UnifyPair(rhs, lhs, PairOperator.EQUALSDOT)); - - return Optional.empty(); - } - - private Optional> eliminate(UnifyPair pair) { - UnifyType rhs = pair.getRhsType(); - UnifyType lhs = pair.getLhsType(); - - // TODO only apply when lhs is element of vars(termsQ)? - - if(!(lhs instanceof PlaceholderType)) - return Optional.empty(); - - return Optional.of(new AbstractMap.SimpleImmutableEntry((PlaceholderType) lhs, rhs)); - } } diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unify.java b/src/de/dhbwstuttgart/typeinference/unify/Unify.java index 6d7d978d..704a1a4e 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unify.java @@ -347,7 +347,7 @@ public class Unify { * TODO Optimierungsmöglichkeit: * * An dieser Stelle gibt es Raum für Optimierung. - * Z.B. resultiert (a <. C) durch Permutation der Parameter mit grArg in: + * Z.B. resultiert (a <. C) durch Permutation der Parameter mit grArg und smaller in: * (a = C, b' <.? ? extends Number) * (a = C, b' <.? ? extends Integer) * (a = C, b' <.? Integer) @@ -357,7 +357,9 @@ public class Unify { * rekursiven Aufruf des Unify. Es würde reichen nur den allgemeinsten Fall zu betrachten da dieser den Lösungraum * der anderen Fälle miteinschließt. * - * (Gibt es einen einzigen maximalen fall? Wsl. ? super x (x möglichst klein) und ? ext y (y möglichst groß)) + * Prüfen: + * Gibt es einen einzigen maximalen Fall? + * Wahrscheinlich gibt es 2: ? super x (x möglichst klein) und ? ext y (y möglichst groß)) */ for(UnifyType param : cParams) From 6616d78dcbec6564284f612759625300efc48bc8 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 11 Apr 2016 09:56:29 +0200 Subject: [PATCH 51/57] . --- .../typeinference/unify/MartelliMontanariUnify.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java b/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java index d1cca70f..94ea0188 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java @@ -1,21 +1,19 @@ package de.dhbwstuttgart.typeinference.unify; -import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; -import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; -import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; -import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.Unifier; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; /** * Implementation of the Martelli-Montanari unification algorithm. From aa692c2f255eb51be3b859314ffd986c7980e576 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 11 Apr 2016 15:30:01 +0200 Subject: [PATCH 52/57] comments --- .../unify/interfaces/IFiniteClosure.java | 4 +++ .../unify/interfaces/IRuleSet.java | 27 +++++++++++++++++-- .../unify/interfaces/ISetOperations.java | 8 ++++++ .../unify/interfaces/IUnify.java | 12 +++++++++ 4 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java index cb95ac41..dcb6c4d1 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java @@ -10,6 +10,10 @@ import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; +/** + * + * @author Florian Steurer + */ public interface IFiniteClosure { /** diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java index 11c98481..26ea0dce 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java @@ -5,6 +5,10 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; +/** + * Contains the inference rules that are applied to the set Eq. + * @author Florian Steurer + */ public interface IRuleSet { public Optional reduceUp(UnifyPair pair); @@ -17,7 +21,7 @@ public interface IRuleSet { public Optional> reduce2(UnifyPair pair); /* - * Missing Rules + * Missing Reduce-Rules for Wildcards */ public Optional reduceWildcardLow(UnifyPair pair); public Optional reduceWildcardLowRight(UnifyPair pair); @@ -34,8 +38,22 @@ public interface IRuleSet { public Optional> greaterFunN(UnifyPair pair); public Optional> smallerFunN(UnifyPair pair); + /** + * Checks whether the erase1-Rule applies to the pair. + * @return True if the pair is erasable, false otherwise. + */ public boolean erase1(UnifyPair pair); + + /** + * Checks whether the erase2-Rule applies to the pair. + * @return True if the pair is erasable, false otherwise. + */ public boolean erase2(UnifyPair pair); + + /** + * Checks whether the erase3-Rule applies to the pair. + * @return True if the pair is erasable, false otherwise. + */ public boolean erase3(UnifyPair pair); public Optional swap(UnifyPair pair); @@ -44,5 +62,10 @@ public interface IRuleSet { public Optional adaptExt(UnifyPair pair); public Optional adaptSup(UnifyPair pair); - public Optional> subst(Set pair); + /** + * Applies the subst-Rule to a set of pairs (usually Eq'). + * @param pairs The set of pairs where the subst rule should apply. + * @return An optional of the modified set, if there were any substitutions. An empty optional if there were no substitutions. + */ + public Optional> subst(Set pairs); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/ISetOperations.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/ISetOperations.java index caed79e4..4a98aaba 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/ISetOperations.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/ISetOperations.java @@ -3,6 +3,14 @@ package de.dhbwstuttgart.typeinference.unify.interfaces; import java.util.List; import java.util.Set; +/** + * Contains operations on sets. + * @author Florian Steurer + */ public interface ISetOperations { + /** + * Calculates the cartesian product of the sets. + * @return The cartesian product + */ Set> cartesianProduct(List> sets); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java index ef8775b1..524608f5 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java @@ -14,8 +14,20 @@ import de.dhbwstuttgart.typeinference.unify.model.Unifier; */ public interface IUnify { + /** + * Finds the most general unifier sigma of the set {t1,...,tn} so that + * sigma(t1) = sigma(t2) = ... = sigma(tn). + * @param terms The set of terms to be unified + * @return An optional of the most general unifier if it exists or an empty optional if there is no unifier. + */ public Optional unify(Set terms); + /** + * Finds the most general unifier sigma of the set {t1,...,tn} so that + * sigma(t1) = sigma(t2) = ... = sigma(tn). + * @param terms The set of terms to be unified + * @return An optional of the most general unifier if it exists or an empty optional if there is no unifier. + */ default public Optional unify(UnifyType... terms) { return unify(Arrays.stream(terms).collect(Collectors.toSet())); } From 044e6fbc3feee49a65c69beda64fc616547512ab Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 11 Apr 2016 16:05:36 +0200 Subject: [PATCH 53/57] comments & refactoring --- .../unify/GuavaSetOperations.java | 6 +++ .../unify/MartelliMontanariUnify.java | 44 +++++++++++-------- .../typeinference/unify/RuleSet.java | 17 ++++++- .../typeinference/unify/Unify.java | 4 +- .../unify/model/FiniteClosure.java | 2 +- 5 files changed, 51 insertions(+), 22 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/GuavaSetOperations.java b/src/de/dhbwstuttgart/typeinference/unify/GuavaSetOperations.java index ba456841..b51fb648 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/GuavaSetOperations.java +++ b/src/de/dhbwstuttgart/typeinference/unify/GuavaSetOperations.java @@ -7,10 +7,16 @@ import com.google.common.collect.Sets; import de.dhbwstuttgart.typeinference.unify.interfaces.ISetOperations; +/** + * Implements set operations using google guava. + * @author DH10STF + * + */ public class GuavaSetOperations implements ISetOperations { @Override public Set> cartesianProduct(List> sets) { + // Wraps the call to google guava return Sets.cartesianProduct(sets); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java b/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java index 94ea0188..ae017235 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java @@ -23,69 +23,77 @@ public class MartelliMontanariUnify implements IUnify { @Override public Optional unify(Set terms) { + // Sets with less than 2 terms are trivially unified if(terms.size() < 2) return Optional.of(Unifier.Identity()); - ArrayList termsQ = new ArrayList(); + // For the the set of terms {t1,...,tn}, + // build a list of equations {(t1 = t2), (t2 = t3), (t3 = t4), ....} + ArrayList termsList = new ArrayList(); Iterator iter = terms.iterator(); UnifyType prev = iter.next(); while(iter.hasNext()) { UnifyType next = iter.next(); - termsQ.add(new UnifyPair(prev, next, PairOperator.EQUALSDOT)); + termsList.add(new UnifyPair(prev, next, PairOperator.EQUALSDOT)); prev = next; } + // Start with the identity unifier. Substitutions will be added later. Unifier mgu = Unifier.Identity(); + // Apply rules while possible int idx = 0; - while(idx < termsQ.size()) { - UnifyPair pair = termsQ.get(idx); + while(idx < termsList.size()) { + UnifyPair pair = termsList.get(idx); UnifyType rhsType = pair.getRhsType(); UnifyType lhsType = pair.getLhsType(); TypeParams rhsTypeParams = rhsType.getTypeParams(); TypeParams lhsTypeParams = lhsType.getTypeParams(); - // DELETE + // DELETE - Rule if(pair.getRhsType().equals(pair.getLhsType())) { - termsQ.remove(idx); - continue; + termsList.remove(idx); + continue; } - // REDUCE + // REDUCE - Rule if(!(rhsType instanceof PlaceholderType) && !(lhsType instanceof PlaceholderType) && (rhsTypeParams.size() != 0 || lhsTypeParams.size() != 0)) { Set result = new HashSet<>(); + // f<...> = g<...> with f != g are not unifiable if(!rhsType.getName().equals(lhsType.getName())) return Optional.empty(); // conflict + // f = f are not unifiable if(rhsTypeParams.size() != lhsTypeParams.size()) return Optional.empty(); // conflict + // Unpack the arguments for(int i = 0; i < rhsTypeParams.size(); i++) result.add(new UnifyPair(rhsTypeParams.get(i), lhsTypeParams.get(i), PairOperator.EQUALSDOT)); - - termsQ.addAll(result); - idx = idx+1 == termsQ.size() ? 0 : idx+1; + + termsList.remove(idx); + termsList.addAll(result); continue; } - // SWAP + // SWAP - Rule if(!(lhsType instanceof PlaceholderType) && (rhsType instanceof PlaceholderType)) { - termsQ.add(new UnifyPair(rhsType, lhsType, PairOperator.EQUALSDOT)); - idx = idx+1 == termsQ.size() ? 0 : idx+1; + termsList.remove(idx); + termsList.add(new UnifyPair(rhsType, lhsType, PairOperator.EQUALSDOT)); continue; } - // Occurs-Check + // OCCURS-CHECK if(pair.getLhsType() instanceof PlaceholderType && pair.getRhsType().getTypeParams().occurs((PlaceholderType) pair.getLhsType())) return Optional.empty(); - // SUBST + // SUBST - Rule if(lhsType instanceof PlaceholderType) { mgu.Add((PlaceholderType) lhsType, rhsType); - termsQ = termsQ.stream().map(mgu::apply).collect(Collectors.toCollection(ArrayList::new)); - idx = idx+1 == termsQ.size() ? 0 : idx+1; + termsList = termsList.stream().map(mgu::apply).collect(Collectors.toCollection(ArrayList::new)); + idx = idx+1 == termsList.size() ? 0 : idx+1; continue; } diff --git a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java index 0765b9b7..82ee9683 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -25,16 +25,26 @@ import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.Unifier; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; +/** + * Implementation of the type inference rules. + * @author Florian Steurer + * + */ public class RuleSet implements IRuleSet{ - + protected IFiniteClosure finiteClosure; + /** + * Creates a new instance that uses the specified FC for greater, grArg, etc. + * @param fc The FC that is used for greater, grArg, etc. + */ public RuleSet(IFiniteClosure fc) { finiteClosure = fc; } @Override public Optional reduceUp(UnifyPair pair) { + // Check if reduce up is applicable if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); @@ -46,11 +56,13 @@ public class RuleSet implements IRuleSet{ if(!(lhsType instanceof ReferenceType) && !(lhsType instanceof PlaceholderType)) return Optional.empty(); + // Rule is applicable, unpack the SuperType return Optional.of(new UnifyPair(lhsType, ((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT)); } @Override public Optional reduceLow(UnifyPair pair) { + // Check if rule is applicable if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); @@ -62,11 +74,13 @@ public class RuleSet implements IRuleSet{ if(!(rhsType instanceof ReferenceType) && !(rhsType instanceof PlaceholderType)) return Optional.empty(); + // Rule is applicable, unpack the ExtendsType return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(), rhsType, PairOperator.SMALLERDOT)); } @Override public Optional reduceUpLow(UnifyPair pair) { + // Check if rule is applicable if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); @@ -78,6 +92,7 @@ public class RuleSet implements IRuleSet{ if(!(rhsType instanceof SuperType)) return Optional.empty(); + // Rule is applicable, unpack both sides return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(),((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT)); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unify.java b/src/de/dhbwstuttgart/typeinference/unify/Unify.java index 704a1a4e..0d2014b9 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unify.java @@ -32,6 +32,8 @@ import de.dhbwstuttgart.typeinference.unify.model.Unifier; */ public class Unify { + protected ISetOperations setOps = new GuavaSetOperations(); + public Set> unify(Set eq, IFiniteClosure fc) { /* * Step 1: Repeated application of reduce, adapt, erase, swap @@ -89,8 +91,6 @@ public class Unify { /* Up to here, no cartesian products are calculated. * filters for pairs and sets can be applied here */ - ISetOperations setOps = new GuavaSetOperations(); - // Sub cartesian products of the second level (pattern matched) sets for(Set>> secondLevelSet : secondLevelSets) { List>> secondLevelSetList = new ArrayList<>(secondLevelSet); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 0ef5d2a3..f06fead7 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -18,7 +18,7 @@ public class FiniteClosure implements IFiniteClosure { private HashMap> inheritanceGraph; private HashMap>> strInheritanceGraph; private Set pairs; - private Set basicTypes; + //private Set basicTypes; //TODO im konstruktor mitgeben um typenabzuhandeln die keine extends beziehung haben. (Damit die FC diese Typen auch kennt) //(ALternative: immer die extends zu object beziehung einfügen) From 0313d297e1b67315978f12dab00d58bde9210239 Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 11 Apr 2016 16:26:59 +0200 Subject: [PATCH 54/57] comments and refactoring --- .../unify/model/ExtendsType.java | 2 +- .../unify/model/PlaceholderType.java | 4 +- .../typeinference/unify/model/SuperType.java | 2 +- .../typeinference/unify/model/Unifier.java | 2 +- .../typeinference/unify/model/UnifyType.java | 51 +++++++++++++++++-- .../unify/model/WildcardType.java | 25 ++++++--- 6 files changed, 69 insertions(+), 17 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java b/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java index 847abfd5..9416d786 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java @@ -14,7 +14,7 @@ public final class ExtendsType extends WildcardType { * @param extendedType The extended type e.g. Integer in "? extends Integer" */ public ExtendsType(UnifyType extendedType) { - super("? extends " + extendedType.getName(), extendedType, extendedType.getTypeParams()); + super("? extends " + extendedType.getName(), extendedType); } public UnifyType getExtendedType() { diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java index 879fe87d..ddb7d273 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java @@ -16,13 +16,13 @@ public final class PlaceholderType extends UnifyType{ private final boolean IsGenerated; public PlaceholderType(String name) { - super(name); + super(name, new TypeParams()); EXISTING_PLACEHOLDERS.add(name); IsGenerated = false; } protected PlaceholderType(String name, boolean isGenerated) { - super(name); + super(name, new TypeParams()); EXISTING_PLACEHOLDERS.add(name); IsGenerated = isGenerated; } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java b/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java index 363dbbf6..7c557ade 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java @@ -6,7 +6,7 @@ import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; public final class SuperType extends WildcardType { public SuperType(UnifyType superedType) { - super("? super " + superedType.getName(), superedType, superedType.getTypeParams()); + super("? super " + superedType.getName(), superedType); } public UnifyType getSuperedType() { diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java index cccaf591..f5af52d0 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java @@ -17,7 +17,7 @@ public class Unifier implements Function /*, Set*/ /** * Identity function as an "unifier". */ - public Unifier() { + protected Unifier() { } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java b/src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java index 341eabd1..4f1965eb 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java @@ -4,35 +4,76 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; +/** + * Represents a java type. + * @author Florian Steurer + */ public abstract class UnifyType { + /** + * The name of the type e.q. "Integer", "? extends Integer" or "List" for (List) + */ protected final String typeName; + + /** + * The type parameters of the type. + */ protected final TypeParams typeParams; - protected UnifyType(String name, UnifyType... typeParams) { - typeName = name; - this.typeParams = new TypeParams(typeParams); - } - + /** + * Creates a new instance + * @param name Name of the type (e.q. List for List, Integer or ? extends Integer) + * @param typeParams Parameters of the type (e.q. for List) + */ protected UnifyType(String name, TypeParams p) { typeName = name; typeParams = p; } + /** + * Returns the name of the type. + * @return The name e.q. List for List, Integer or ? extends Integer + */ public String getName() { return typeName; } + /** + * The parameters of the type. + * @return Parameters of the type, e.q. for List. + */ public TypeParams getTypeParams() { return typeParams; } + /** + * Returns a new type that equals this type except for the type parameters. + * @param newTp The type params of the new type. + * @return A new type object. + */ public abstract UnifyType setTypeParams(TypeParams newTp); + /** + * Implementation of the visitor-pattern. Returns the set of smArg + * by calling the most specific overload in the FC. + * @param fc The FC that is called. + * @return The set that is smArg(this) + */ abstract Set smArg(IFiniteClosure fc); + /** + * Implementation of the visitor-pattern. Returns the set of grArg + * by calling the most specific overload in the FC. + * @param fc The FC that is called. + * @return The set that is grArg(this) + */ abstract Set grArg(IFiniteClosure fc); + /** + * Applies a unifier to this object. + * @param unif The unifier + * @return A UnifyType, that may or may not be a new object, that has its subtypes substituted. + */ abstract UnifyType apply(Unifier unif); @Override diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java b/src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java index 08c49783..9db59498 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java @@ -1,19 +1,30 @@ package de.dhbwstuttgart.typeinference.unify.model; +/** + * A wildcard type that is either a ExtendsType or a SuperType. + * @author Florian Steurer + */ public abstract class WildcardType extends UnifyType { + /** + * The wildcarded type, e.q. Integer for ? extends Integer. Never a wildcard type itself. + */ protected UnifyType wildcardedType; - protected WildcardType(String name, UnifyType wildcardedType, UnifyType[] typeParams) { - super(name, typeParams); - this.wildcardedType = wildcardedType; - } - - protected WildcardType(String name, UnifyType wildcardedType, TypeParams p) { - super(name, p); + /** + * Creates a new instance. + * @param name The name of the type, e.q. ? extends Integer + * @param wildcardedType The wildcarded type, e.q. Integer for ? extends Integer. Never a wildcard type itself. + */ + protected WildcardType(String name, UnifyType wildcardedType) { + super(name, wildcardedType.getTypeParams()); this.wildcardedType = wildcardedType; } + /** + * Returns the wildcarded type, e.q. Integer for ? extends Integer. + * @return The wildcarded type. Never a wildcard type itself. + */ public UnifyType getWildcardedType() { return wildcardedType; } From 55f288022aeffeac9e56c5579d74844cfa9dabad Mon Sep 17 00:00:00 2001 From: Florian Steurer Date: Mon, 11 Apr 2016 16:31:55 +0200 Subject: [PATCH 55/57] commenting, refactoring --- .../typeinference/unify/model/UnifyPair.java | 42 +++++++++++++++---- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java b/src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java index cdc7b818..ed2c95ef 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java @@ -1,31 +1,55 @@ package de.dhbwstuttgart.typeinference.unify.model; +/** + * A pair which contains two types and an operator, e.q. (Integer <. a). + * @author Florian Steurer + */ public class UnifyPair { + /** + * The type on the left hand side of the pair. + */ private UnifyType lhs; + + /** + * The type on the right hand side of the pair. + */ private UnifyType rhs; + + /** + * The operator that determines the relation between the left and right hand side type. + */ private PairOperator pairOp; - /*public MPair(Type t1, Type t2) { - lhs = t1; - rhs = t2; - pairOp = PairOperator.SMALLER; - }*/ - - public UnifyPair(UnifyType t1, UnifyType t2, PairOperator op) { - lhs = t1; - rhs = t2; + /** + * Creates a new instance of the pair. + * @param lhs The type on the left hand side of the pair. + * @param rhs The type on the right hand side of the pair. + * @param op The operator that determines the relation between the left and right hand side type. + */ + public UnifyPair(UnifyType lhs, UnifyType rhs, PairOperator op) { + this.lhs = lhs; + this.rhs = rhs; pairOp = op; } + /** + * Returns the type on the left hand side of the pair. + */ public UnifyType getLhsType() { return lhs; } + /** + * Returns the type on the right hand side of the pair. + */ public UnifyType getRhsType() { return rhs; } + /** + * Returns the operator that determines the relation between the left and right hand side type. + */ public PairOperator getPairOp() { return pairOp; } From 3bb2153b6ad4a894aa4869c7f9b21a54676e5082 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Mon, 11 Apr 2016 18:36:43 +0200 Subject: [PATCH 56/57] Java Parser an umbenennung anpassen --- src/de/dhbwstuttgart/parser/JavaParser.jay | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/de/dhbwstuttgart/parser/JavaParser.jay b/src/de/dhbwstuttgart/parser/JavaParser.jay index 553ad069..b4f760e7 100755 --- a/src/de/dhbwstuttgart/parser/JavaParser.jay +++ b/src/de/dhbwstuttgart/parser/JavaParser.jay @@ -1693,7 +1693,7 @@ assignment :lefthandside assignmentoperator assignmentexpr { de.dhbwstuttgart.logger.Logger.getLogger("parser").debug("\nParser --> Zuweisung1!\n", Section.PARSER); Assign Ass = new Assign($1.getOffset(),$1.getVariableLength()); - LocalOrFieldVar LOFV = new LocalOrFieldVar($1.getOffset(),$1.getVariableLength()); + LocalOrFieldVarOrClassname LOFV = new LocalOrFieldVarOrClassname($1.getOffset(),$1.getVariableLength()); LOFV.set_UsedId($1); //auskommentiert von Andreas Stadelmeier (a10023) LOFV.setType(TypePlaceholder.fresh()); //auskommentiert von Andreas Stadelmeier (a10023) Ass.setType(TypePlaceholder.fresh()); @@ -1717,7 +1717,7 @@ assignment :lefthandside assignmentoperator assignmentexpr | lefthandside assignmentoperator classinstancecreationexpression { Assign Ass =new Assign($1.getOffset(),$1.getVariableLength()); - LocalOrFieldVar LOFV = new LocalOrFieldVar($1.getOffset(),$1.getVariableLength()); + LocalOrFieldVarOrClassname LOFV = new LocalOrFieldVarOrClassname($1.getOffset(),$1.getVariableLength()); LOFV.set_UsedId($1); //auskommentiert von Andreas Stadelmeier (a10023) LOFV.setType(TypePlaceholder.fresh()); //auskommentiert von Andreas Stadelmeier (a10023) Ass.setType(TypePlaceholder.fresh()); @@ -1939,7 +1939,7 @@ methodinvocation: rec = new Receiver(INSTVA); } else if ($1.get_Name().size() == 2) { - LocalOrFieldVar LOFV = new LocalOrFieldVar($1.getOffset(),$1.getVariableLength()); + LocalOrFieldVarOrClassname LOFV = new LocalOrFieldVarOrClassname($1.getOffset(),$1.getVariableLength()); $1.removeLast(); LOFV.set_UsedId($1); //auskommentiert von Andreas Stadelmeier (a10023) LOFV.setType(TypePlaceholder.fresh()); @@ -1969,7 +1969,7 @@ methodinvocation: rec = new Receiver(INSTVA); } else if ($1.get_Name().size() == 2) { - LocalOrFieldVar LOFV = new LocalOrFieldVar($1.getOffset(),$1.getVariableLength()); + LocalOrFieldVarOrClassname LOFV = new LocalOrFieldVarOrClassname($1.getOffset(),$1.getVariableLength()); $1.removeLast(); LOFV.set_UsedId($1); //auskommentiert von Andreas Stadelmeier (a10023) LOFV.setType(TypePlaceholder.fresh()); @@ -2105,7 +2105,7 @@ postfixexpression :primary $$ = INSTVA; } else { - LocalOrFieldVar Postincexpr = new LocalOrFieldVar($1.getOffset(),$1.getVariableLength()); + LocalOrFieldVarOrClassname Postincexpr = new LocalOrFieldVarOrClassname($1.getOffset(),$1.getVariableLength()); Postincexpr.set_UsedId($1); //auskommentiert von Andreas Stadelmeier (a10023) Postincexpr.setType(TypePlaceholder.fresh()); $$=Postincexpr; From f630f93a3da5dcafc55b86f175a9fc4063cb11f0 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Tue, 12 Apr 2016 10:06:58 +0200 Subject: [PATCH 57/57] =?UTF-8?q?Debug=20Ausgabe=20anf=C3=BCgen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/de/dhbwstuttgart/syntaxtree/SourceFile.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/de/dhbwstuttgart/syntaxtree/SourceFile.java b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java index 2892773f..bc4c39ef 100755 --- a/src/de/dhbwstuttgart/syntaxtree/SourceFile.java +++ b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java @@ -359,6 +359,7 @@ public class SourceFile return cardprodret; }); */ + typinferenzLog.debug("\nUnifiziere Constraints:\n"+constraints, Section.TYPEINFERENCE); Set> unifyResult = new Unify().unify(constraints, finiteClosure); Menge> convertedResult = unifyResult.parallelStream().>map((Set resultSet)->{