From 1f825360dfc8f19fd48baa8a23ed7df8401f679b Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Thu, 17 Mar 2016 16:54:43 +0100 Subject: [PATCH 01/13] =?UTF-8?q?Test=20GenerateFiniteClosure=20anf=C3=BCg?= =?UTF-8?q?en?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dhbwstuttgart/syntaxtree/SourceFile.java | 6 +- .../syntaxtree/factory/UnifyTypeFactory.java | 79 +++++++++---- .../assumptions/TypeAssumptions.java | 27 ----- .../unify/interfaces/IFiniteClosure.java | 30 ++--- .../unify/interfaces/IUnify.java | 6 +- .../unify/model/ExtendsType.java | 16 +-- .../unify/model/FiniteClosure.java | 86 +++++++------- .../typeinference/unify/model/MPair.java | 16 +-- .../unify/model/PlaceholderType.java | 10 +- .../typeinference/unify/model/SimpleType.java | 12 +- .../typeinference/unify/model/SuperType.java | 16 +-- .../typeinference/unify/model/TypeParams.java | 26 ++--- .../typeinference/unify/model/Unifier.java | 16 +-- .../unify/model/{Type.java => UnifyType.java} | 16 +-- .../typeinference/unifynew/Mapping.java | 18 +-- .../unifynew/MartelliMontanariUnify.java | 30 ++--- .../typeinference/unifynew/RuleSet.java | 106 +++++++++--------- .../typeinference/unifynew/Unify.java | 48 ++++---- test/unify/FiniteClosureBuilder.java | 31 +++-- test/unify/FiniteClosureTest.java | 3 +- test/unify/GenerateFiniteClosure.java | 47 ++++++++ test/unify/RuleSetTest.java | 1 - test/unify/StandardUnifyTest.java | 17 ++- .../unifynew => test/unify}/TypeFactory.java | 12 +- test/unify/UnifyOldTest.java | 95 ++++++++++------ test/unify/UnifyTest.java | 13 +-- 26 files changed, 433 insertions(+), 350 deletions(-) rename src/de/dhbwstuttgart/typeinference/unify/model/{Type.java => UnifyType.java} (61%) create mode 100644 test/unify/GenerateFiniteClosure.java rename {src/de/dhbwstuttgart/typeinference/unifynew => test/unify}/TypeFactory.java (72%) diff --git a/src/de/dhbwstuttgart/syntaxtree/SourceFile.java b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java index 2ec26b2e..cea600d1 100755 --- a/src/de/dhbwstuttgart/syntaxtree/SourceFile.java +++ b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java @@ -301,11 +301,7 @@ public class SourceFile * Erstellt die Finite Closure * @return FC_TTO-Object, welches die Finite Closure repräsentiert */ - // ino.end - // ino.method.makeFC.21403.definition public FC_TTO makeFC( TypeAssumptions ass ) - // ino.end - // ino.method.makeFC.21403.body { // Menge FC bilden @@ -850,7 +846,7 @@ public class SourceFile * @param withSuptypes - Gibt an, ob auch die subklassen der Packages den Assumptions angefügt werden sollen. * @return */ - private TypeAssumptions makeBasicAssumptionsFromJRE(Menge imports, boolean withSubtypes) + public TypeAssumptions makeBasicAssumptionsFromJRE(Menge imports, boolean withSubtypes) // ino.end // ino.method.makeBasicAssumptionsFromJRE.21409.body { diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 6bbd023f..c718a7bf 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -1,6 +1,10 @@ package de.dhbwstuttgart.syntaxtree.factory; +import java.util.HashSet; + +import de.dhbwstuttgart.myexception.NotImplementedException; import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; +import de.dhbwstuttgart.syntaxtree.type.GenericTypeVar; import de.dhbwstuttgart.syntaxtree.type.ObjectType; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; @@ -8,34 +12,71 @@ import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.WildcardType; import de.dhbwstuttgart.typeinference.Menge; +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.PlaceholderType; +import de.dhbwstuttgart.typeinference.unify.model.SimpleType; +import de.dhbwstuttgart.typeinference.unify.model.SuperType; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public class UnifyTypeFactory { - - public 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); + + public static FiniteClosure generateFC(TypeAssumptions fromAss){ + HashSet pairs = new HashSet<>(); + for(ClassAssumption cAss : fromAss.getClassAssumptions()){ + UnifyType tl = UnifyTypeFactory.convert(cAss.getAssumedClass().getType()); + Type superClass = cAss.getAssumedClass().getSuperClass(); + if(superClass != null){ + UnifyType tr = UnifyTypeFactory.convert(superClass); + pairs.add(smaller(tl, tr)); + } + } + return new FiniteClosure(pairs); } - public ExtendsWildcardType GetExtendsType(ObjectType extendedType) { - return new ExtendsWildcardType(extendedType); + public static MPair smaller(UnifyType tl, UnifyType tr){ + return new MPair(tl, tr,MPair.PairOperator.SMALLER); } - public SuperWildcardType GetSuperType(ObjectType superedType) { - return new SuperWildcardType(superedType); + public static UnifyType convert(Type t){ + //Es wurde versucht ein Typ umzuwandeln, welcher noch nicht von der Factory abgedeckt ist + if(t instanceof GenericTypeVar){ + return UnifyTypeFactory.convert((GenericTypeVar)t); + } + System.out.println("Der Typ "+t+" kann nicht umgewandelt werden"); + throw new NotImplementedException(); } - public WildcardType GetWildcardType() { - return new WildcardType(null, null, 0); + public static UnifyType convert(RefType t){ + UnifyType ret; + if(t.getParaList() != null && t.getParaList().size() > 0){ + Menge params = new Menge<>(); + for(Type pT : t.getParaList()){ + params.add(UnifyTypeFactory.convert(pT)); + } + ret = new SimpleType(t.get_Name(),params.toArray()); + }else{ + ret = new SimpleType(t.get_Name()); + } + return ret; } - public TypePlaceholder GetTypePlaceholder(String name) { - return TypePlaceholder.backdoorCreate(name); + public static UnifyType convert(TypePlaceholder tph){ + return new PlaceholderType(tph.get_Name()); + } + + public static UnifyType convert(ExtendsWildcardType t){ + return new ExtendsType(UnifyTypeFactory.convert(t.get_ExtendsType())); + } + + public static UnifyType convert(SuperWildcardType t){ + return new SuperType(UnifyTypeFactory.convert(t.get_SuperType())); + } + + public static UnifyType convert(GenericTypeVar t){ + return new SimpleType(t.get_Name()); } } diff --git a/src/de/dhbwstuttgart/typeinference/assumptions/TypeAssumptions.java b/src/de/dhbwstuttgart/typeinference/assumptions/TypeAssumptions.java index d80ad80c..ca74c835 100755 --- a/src/de/dhbwstuttgart/typeinference/assumptions/TypeAssumptions.java +++ b/src/de/dhbwstuttgart/typeinference/assumptions/TypeAssumptions.java @@ -89,33 +89,6 @@ public class TypeAssumptions { return null; } - /** - * Ermittelt alle bekannten Methoden mit dem Namen withName - * @param withName - * @return - */ - @Deprecated - public Menge getMethods2(String withName){ - //TODO: Implementieren - return new Menge(); - } - - /** - * Liefert den Typ einer lokalen Variable. Zuerst werden die Parameter dieses AssumptionSets durchsucht, dann die lokalen Variablen. Anschließend die Felder der, "this" repräsentierenden Klasse - * @param withName - * @return - */ - @Deprecated - public Type getTypeOfLocalVar2(String withName){ - //TODO: Implementieren - return null; - } - - - - - - /** * Sucht nach Assumptions zu einer Methode mit dem Namen methodName und parameterCount Parametern. * @param methodName diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java index 62b65b27..fa640eb8 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java @@ -7,7 +7,7 @@ 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.SuperType; -import de.dhbwstuttgart.typeinference.unify.model.Type; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public interface IFiniteClosure { @@ -15,40 +15,40 @@ public interface IFiniteClosure { * Returns all types of the finite closure that are subtypes of the argument. * @return The set of subtypes of the argument. */ - public Set smaller(Type type); + public Set smaller(UnifyType type); /** * Returns all types of the finite closure that are supertypes of the argument. * @return The set of supertypes of the argument. */ - public Set greater(Type type); + public Set greater(UnifyType type); /** * Wo passt Type rein? * @param type * @return */ - public Set grArg(Type type); + public Set grArg(UnifyType type); /** * Was passt in Type rein? * @param type * @return */ - public Set smArg(Type type); + public Set smArg(UnifyType type); - public Set grArg(SimpleType type); - public Set smArg(SimpleType type); + public Set grArg(SimpleType type); + public Set smArg(SimpleType type); - public Set grArg(ExtendsType type); - public Set smArg(ExtendsType type); + public Set grArg(ExtendsType type); + public Set smArg(ExtendsType type); - public Set grArg(SuperType type); - public Set smArg(SuperType type); + public Set grArg(SuperType type); + public Set smArg(SuperType type); - public Set grArg(PlaceholderType type); - public Set smArg(PlaceholderType type); + public Set grArg(PlaceholderType type); + public Set smArg(PlaceholderType type); - public Optional getGenericType(String typeName); - public Set getAllTypes(String typeName); + public Optional getGenericType(String typeName); + public Set getAllTypes(String typeName); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java index f286e3b6..ef8775b1 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java @@ -5,7 +5,7 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; -import de.dhbwstuttgart.typeinference.unify.model.Type; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.Unifier; /** @@ -14,9 +14,9 @@ import de.dhbwstuttgart.typeinference.unify.model.Unifier; */ public interface IUnify { - public Optional unify(Set terms); + public Optional unify(Set terms); - default public Optional unify(Type... terms) { + default public Optional unify(UnifyType... terms) { return unify(Arrays.stream(terms).collect(Collectors.toSet())); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java b/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java index 9fb3e454..4cf3ceef 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java @@ -7,18 +7,18 @@ import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; /** * An extends wildcard type "? extends T". */ -public final class ExtendsType extends Type { +public final class ExtendsType extends UnifyType { /** * The extended type */ - private Type extendedType; + private UnifyType extendedType; /** * Creates a new extends wildcard type. * @param extendedType The extended type e.g. Integer in "? extends Integer" */ - public ExtendsType(Type extendedType) { + public ExtendsType(UnifyType extendedType) { super("? extends " + extendedType.getName(), extendedType.getTypeParams()); this.extendedType = extendedType; } @@ -27,7 +27,7 @@ public final class ExtendsType extends Type { * Gets the type extended by this wildcard e.g. "Integer" for "? extends Integer" * @return The extended type. */ - public Type getExtendedType() { + public UnifyType getExtendedType() { return extendedType; } @@ -37,22 +37,22 @@ public final class ExtendsType extends Type { } @Override - public Type setTypeParams(TypeParams newTp) { + public UnifyType setTypeParams(TypeParams newTp) { return new ExtendsType(extendedType.setTypeParams(newTp)); } @Override - Set smArg(IFiniteClosure fc) { + Set smArg(IFiniteClosure fc) { return fc.smArg(this); } @Override - Set grArg(IFiniteClosure fc) { + Set grArg(IFiniteClosure fc) { return fc.grArg(this); } @Override - Type apply(Unifier unif) { + UnifyType apply(Unifier unif) { return new ExtendsType(extendedType.apply(unif)); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index e618482d..35fae6cb 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -11,12 +11,12 @@ import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; public class FiniteClosure implements IFiniteClosure { - private HashMap> inheritanceGraph; - private HashMap>> strInheritanceGraph; + private HashMap> inheritanceGraph; + private HashMap>> strInheritanceGraph; public FiniteClosure(Set pairs) { - inheritanceGraph = new HashMap>(); + inheritanceGraph = new HashMap>(); // Build the transitive closure of the inheritance tree for(MPair pair : pairs) { @@ -25,12 +25,12 @@ public class FiniteClosure implements IFiniteClosure { // Add nodes if not already in the graph if(!inheritanceGraph.containsKey(pair.getLhsType())) - inheritanceGraph.put(pair.getLhsType(), new Node(pair.getLhsType())); + inheritanceGraph.put(pair.getLhsType(), new Node(pair.getLhsType())); if(!inheritanceGraph.containsKey(pair.getRhsType())) - inheritanceGraph.put(pair.getRhsType(), new Node(pair.getRhsType())); + inheritanceGraph.put(pair.getRhsType(), new Node(pair.getRhsType())); - Node childNode = inheritanceGraph.get(pair.getLhsType()); - Node parentNode = inheritanceGraph.get(pair.getRhsType()); + Node childNode = inheritanceGraph.get(pair.getLhsType()); + Node parentNode = inheritanceGraph.get(pair.getRhsType()); // Add edge parentNode.AddDescendant(childNode); @@ -43,7 +43,7 @@ public class FiniteClosure implements IFiniteClosure { // Build the alternative representation with strings as keys strInheritanceGraph = new HashMap<>(); - for(Type key : inheritanceGraph.keySet()) { + for(UnifyType key : inheritanceGraph.keySet()) { if(!strInheritanceGraph.containsKey(key.getName())) strInheritanceGraph.put(key.getName(), new HashSet<>()); @@ -56,11 +56,11 @@ public class FiniteClosure implements IFiniteClosure { * @return The set of subtypes of the argument. */ @Override - public Set smaller(Type type) { + public Set smaller(UnifyType type) { if(!inheritanceGraph.containsKey(type)) return new HashSet<>(); - Set result = inheritanceGraph.get(type).getContentOfDescendants(); + Set result = inheritanceGraph.get(type).getContentOfDescendants(); result.add(type); return result; @@ -71,26 +71,26 @@ public class FiniteClosure implements IFiniteClosure { * @return The set of supertypes of the argument. */ @Override - public Set greater(Type type) { + public Set greater(UnifyType type) { if(!inheritanceGraph.containsKey(type)) return new HashSet<>(); - Set result = inheritanceGraph.get(type).getContentOfPredecessors(); + Set result = inheritanceGraph.get(type).getContentOfPredecessors(); result.add(type); return result; } @Override - public Set grArg(Type type) { + public Set grArg(UnifyType type) { return type.grArg(this); } @Override - public Set grArg(SimpleType type) { + public Set grArg(SimpleType type) { if(!inheritanceGraph.containsKey(type)) - return new HashSet(); + return new HashSet(); - Set result = new HashSet(); + Set result = new HashSet(); result.add(type); smaller(type).forEach(x -> result.add(new SuperType(x))); @@ -100,13 +100,13 @@ public class FiniteClosure implements IFiniteClosure { } @Override - public Set grArg(ExtendsType type) { + public Set grArg(ExtendsType type) { if(!inheritanceGraph.containsKey(type.getExtendedType())) - return new HashSet(); + return new HashSet(); - Set result = new HashSet(); + Set result = new HashSet(); - Type t = type.getExtendedType(); + UnifyType t = type.getExtendedType(); greater(t).forEach(x -> result.add(new ExtendsType(x))); @@ -114,13 +114,13 @@ public class FiniteClosure implements IFiniteClosure { } @Override - public Set grArg(SuperType type) { + public Set grArg(SuperType type) { if(!inheritanceGraph.containsKey(type.getSuperedType())) - return new HashSet(); + return new HashSet(); - Set result = new HashSet(); + Set result = new HashSet(); - Type t = type.getSuperedType(); + UnifyType t = type.getSuperedType(); smaller(t).forEach(x -> result.add(new SuperType(x))); @@ -128,21 +128,21 @@ public class FiniteClosure implements IFiniteClosure { } @Override - public Set grArg(PlaceholderType type) { + public Set grArg(PlaceholderType type) { return new HashSet<>(); } @Override - public Set smArg(Type type) { + public Set smArg(UnifyType type) { return type.smArg(this); } @Override - public Set smArg(SimpleType type) { + public Set smArg(SimpleType type) { if(!inheritanceGraph.containsKey(type)) - return new HashSet(); + return new HashSet(); - Set result = new HashSet(); + Set result = new HashSet(); result.add(type); smaller(type).forEach(x -> result.add(new ExtendsType(x))); @@ -150,13 +150,13 @@ public class FiniteClosure implements IFiniteClosure { return result; } - public Set smArg(ExtendsType type) { + public Set smArg(ExtendsType type) { if(!inheritanceGraph.containsKey(type.getExtendedType())) - return new HashSet(); + return new HashSet(); - Set result = new HashSet(); + Set result = new HashSet(); - Type t = type.getExtendedType(); + UnifyType t = type.getExtendedType(); result.add(t); smaller(t).forEach(x -> { @@ -169,13 +169,13 @@ public class FiniteClosure implements IFiniteClosure { @Override - public Set smArg(SuperType type) { + public Set smArg(SuperType type) { if(!inheritanceGraph.containsKey(type.getSuperedType())) - return new HashSet(); + return new HashSet(); - Set result = new HashSet(); + Set result = new HashSet(); - Type t = type.getSuperedType(); + UnifyType t = type.getSuperedType(); result.add(t); greater(t).forEach(x -> { @@ -187,19 +187,19 @@ public class FiniteClosure implements IFiniteClosure { } @Override - public Set smArg(PlaceholderType type) { + public Set smArg(PlaceholderType type) { return new HashSet<>(); } @Override - public Optional getGenericType(String typeName) { + public Optional getGenericType(String typeName) { if(!strInheritanceGraph.containsKey(typeName)) return Optional.empty(); - HashSet> candidates = strInheritanceGraph.get(typeName); + HashSet> candidates = strInheritanceGraph.get(typeName); - for(Node node : candidates) { - Type candidate = node.getContent(); + for(Node node : candidates) { + UnifyType candidate = node.getContent(); if(candidate.getTypeParams().arePlaceholders()) return Optional.of(candidate); } @@ -208,7 +208,7 @@ public class FiniteClosure implements IFiniteClosure { } @Override - public Set getAllTypes(String typeName) { + public Set getAllTypes(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/MPair.java b/src/de/dhbwstuttgart/typeinference/unify/model/MPair.java index 6b740c46..d7d17d52 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/MPair.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/MPair.java @@ -26,8 +26,8 @@ public class MPair { }; } - private Type lhs; - private Type rhs; + private UnifyType lhs; + private UnifyType rhs; private PairOperator pairOp; /*public MPair(Type t1, Type t2) { @@ -36,17 +36,17 @@ public class MPair { pairOp = PairOperator.SMALLER; }*/ - public MPair(Type t1, Type t2, PairOperator op) { + public MPair(UnifyType t1, UnifyType t2, PairOperator op) { lhs = t1; rhs = t2; pairOp = op; } - public Type getLhsType() { + public UnifyType getLhsType() { return lhs; } - public Type getRhsType() { + public UnifyType getRhsType() { return rhs; } @@ -72,11 +72,11 @@ public class MPair { * @param subst The type replacing t. * @return A pair where occurrences of t are replaced by subst. */ - public MPair substitute(Type t, Type subst) { - Type newlhs = lhs; + public MPair substitute(UnifyType t, UnifyType subst) { + UnifyType newlhs = lhs; if(lhs.equals(t)) newlhs = subst; - Type newrhs = rhs; + UnifyType newrhs = rhs; if(rhs.equals(t)) newrhs = subst; if(newlhs == lhs && newrhs == rhs) return this; diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java index 5a3d5341..f810e993 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java @@ -4,24 +4,24 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -public final class PlaceholderType extends Type{ +public final class PlaceholderType extends UnifyType{ public PlaceholderType(String name) { super(name); } @Override - Set smArg(IFiniteClosure fc) { + Set smArg(IFiniteClosure fc) { return fc.smArg(this); } @Override - Set grArg(IFiniteClosure fc) { + Set grArg(IFiniteClosure fc) { return fc.grArg(this); } @Override - public Type setTypeParams(TypeParams newTp) { + public UnifyType setTypeParams(TypeParams newTp) { return this; } @@ -31,7 +31,7 @@ public final class PlaceholderType extends Type{ } @Override - Type apply(Unifier unif) { + UnifyType apply(Unifier unif) { if(unif.hasSubstitute(this)) return unif.getSubstitute(this); return this; diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java b/src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java index ef01652a..a8997439 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java @@ -4,8 +4,8 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -public final class SimpleType extends Type { - public SimpleType(String name, Type... typeParams) { +public final class SimpleType extends UnifyType { + public SimpleType(String name, UnifyType... typeParams) { super(name, new TypeParams(typeParams)); } @@ -14,22 +14,22 @@ public final class SimpleType extends Type { } @Override - Set smArg(IFiniteClosure fc) { + Set smArg(IFiniteClosure fc) { return fc.smArg(this); } @Override - Set grArg(IFiniteClosure fc) { + Set grArg(IFiniteClosure fc) { return fc.grArg(this); } @Override - Type apply(Unifier unif) { + UnifyType apply(Unifier unif) { return new SimpleType(typeName, typeParams.apply(unif)); } @Override - public Type setTypeParams(TypeParams newTp) { + public UnifyType setTypeParams(TypeParams newTp) { return new SimpleType(new String(typeName), newTp); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java b/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java index 2503e748..8283c685 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java @@ -4,16 +4,16 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -public final class SuperType extends Type { +public final class SuperType extends UnifyType { - private Type superedType; + private UnifyType superedType; - public SuperType(Type superedType) { + public SuperType(UnifyType superedType) { super("? super " + superedType.getName(), superedType.getTypeParams()); this.superedType = superedType; } - public Type getSuperedType() { + public UnifyType getSuperedType() { return superedType; } @@ -28,22 +28,22 @@ public final class SuperType extends Type { } @Override - public Type setTypeParams(TypeParams newTp) { + public UnifyType setTypeParams(TypeParams newTp) { return new SuperType(superedType.setTypeParams(newTp)); } @Override - Set smArg(IFiniteClosure fc) { + Set smArg(IFiniteClosure fc) { return fc.smArg(this); } @Override - Set grArg(IFiniteClosure fc) { + Set grArg(IFiniteClosure fc) { return fc.grArg(this); } @Override - Type apply(Unifier unif) { + UnifyType apply(Unifier unif) { return new SuperType(superedType.apply(unif)); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java b/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java index 966a561b..a95a1b43 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java @@ -3,15 +3,15 @@ package de.dhbwstuttgart.typeinference.unify.model; import java.util.Arrays; import java.util.Iterator; -public final class TypeParams implements Iterable{ - private final Type[] typeParams; +public final class TypeParams implements Iterable{ + private final UnifyType[] typeParams; - public TypeParams(Type... types) { + public TypeParams(UnifyType... types) { typeParams = types; } public boolean arePlaceholders() { - for(Type t : typeParams) + for(UnifyType t : typeParams) if(!(t instanceof PlaceholderType)) return false; return true; @@ -20,7 +20,7 @@ public final class TypeParams implements Iterable{ @Override public String toString() { String res = ""; - for(Type t : typeParams) + for(UnifyType t : typeParams) res += t + ","; return "<" + res.substring(0, res.length()-1) + ">"; } @@ -34,14 +34,14 @@ public final class TypeParams implements Iterable{ } public TypeParams apply(Unifier unif) { - Type[] newParams = new Type[typeParams.length]; + UnifyType[] newParams = new UnifyType[typeParams.length]; for(int i = 0; i < typeParams.length; i++) newParams[i] = typeParams[i].apply(unif); return new TypeParams(newParams); } public boolean occurs(PlaceholderType t) { - for(Type p : typeParams) + for(UnifyType p : typeParams) if(p instanceof PlaceholderType) if(p.equals(t)) return true; @@ -51,26 +51,26 @@ public final class TypeParams implements Iterable{ return false; } - public boolean contains(Type t) { - for(Type t1 : typeParams) + public boolean contains(UnifyType t) { + for(UnifyType t1 : typeParams) if(t1.equals(t1)) return true; return false; } - public Type get(int i) { + public UnifyType get(int i) { return typeParams[i]; } - public TypeParams set(Type t, int idx) { - Type[] newparams = Arrays.copyOf(typeParams, typeParams.length); + public TypeParams set(UnifyType t, int idx) { + UnifyType[] newparams = Arrays.copyOf(typeParams, typeParams.length); newparams[idx] = t; return new TypeParams(newparams); } @Override - public Iterator iterator() { + public Iterator iterator() { return Arrays.stream(typeParams).iterator(); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java index 0a1fde25..c277f8fc 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java @@ -5,12 +5,12 @@ import java.util.Map.Entry; import java.util.Set; import java.util.function.Function; -public class Unifier implements Function { - private HashMap substitutions = new HashMap<>(); +public class Unifier implements Function { + private HashMap substitutions = new HashMap<>(); public static Unifier IDENTITY = new Unifier(); - public Unifier(PlaceholderType source, Type target) { + public Unifier(PlaceholderType source, UnifyType target) { substitutions.put(source, target); } @@ -21,7 +21,7 @@ public class Unifier implements Function { } - public void Add(PlaceholderType source, Type target) { + public void Add(PlaceholderType source, UnifyType target) { Unifier tempU = new Unifier(source, target); for(PlaceholderType pt : substitutions.keySet()) substitutions.put(pt, substitutions.get(pt).apply(tempU)); @@ -29,7 +29,7 @@ public class Unifier implements Function { } @Override - public Type apply(Type t) { + public UnifyType apply(UnifyType t) { return t.apply(this); } @@ -41,18 +41,18 @@ public class Unifier implements Function { return substitutions.containsKey(t); } - public Type getSubstitute(Type t) { + public UnifyType getSubstitute(UnifyType t) { return substitutions.get(t); } - public Set> getSubstitutions() { + public Set> getSubstitutions() { return substitutions.entrySet(); } @Override public String toString() { String result = "{ "; - for(Entry entry : substitutions.entrySet()) + for(Entry entry : substitutions.entrySet()) result += "(" + entry.getKey() + " -> " + entry.getValue() + "), "; if(!substitutions.isEmpty()) result = result.substring(0, result.length()-2); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/Type.java b/src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java similarity index 61% rename from src/de/dhbwstuttgart/typeinference/unify/model/Type.java rename to src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java index 3c179110..341eabd1 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/Type.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java @@ -4,17 +4,17 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -public abstract class Type { +public abstract class UnifyType { protected final String typeName; protected final TypeParams typeParams; - protected Type(String name, Type... typeParams) { + protected UnifyType(String name, UnifyType... typeParams) { typeName = name; this.typeParams = new TypeParams(typeParams); } - protected Type(String name, TypeParams p) { + protected UnifyType(String name, TypeParams p) { typeName = name; typeParams = p; } @@ -27,19 +27,19 @@ public abstract class Type { return typeParams; } - public abstract Type setTypeParams(TypeParams newTp); + public abstract UnifyType setTypeParams(TypeParams newTp); - abstract Set smArg(IFiniteClosure fc); + abstract Set smArg(IFiniteClosure fc); - abstract Set grArg(IFiniteClosure fc); + abstract Set grArg(IFiniteClosure fc); - abstract Type apply(Unifier unif); + abstract UnifyType apply(Unifier unif); @Override public String toString() { String params = ""; if(typeParams.size() != 0) { - for(Type param : typeParams) + for(UnifyType param : typeParams) params += param.toString() + ","; params = "<" + params.substring(0, params.length()-1) + ">"; } diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Mapping.java b/src/de/dhbwstuttgart/typeinference/unifynew/Mapping.java index c8996dc8..e21bb728 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Mapping.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/Mapping.java @@ -8,16 +8,16 @@ import java.util.stream.Collectors; public class Mapping { - private HashMap backwardMap = new HashMap<>(); - private HashMap forwardMap = new HashMap<>(); - private Set irreversible = new HashSet<>(); + private HashMap backwardMap = new HashMap<>(); + private HashMap forwardMap = new HashMap<>(); + private Set irreversible = new HashSet<>(); public Mapping(Set types) { for(de.dhbwstuttgart.syntaxtree.type.Type t : types) { } } - public de.dhbwstuttgart.typeinference.unify.model.Type map(de.dhbwstuttgart.syntaxtree.type.Type type) { + public de.dhbwstuttgart.typeinference.unify.model.UnifyType map(de.dhbwstuttgart.syntaxtree.type.Type type) { return forwardMap.get(type); } @@ -25,7 +25,7 @@ public class Mapping { return new de.dhbwstuttgart.typeinference.unify.model.MPair(forwardMap.get(pair.TA1), forwardMap.get(pair.TA2), mapOp(pair.GetOperator())); } - public Set mapTypeSet(Set types) { + public Set mapTypeSet(Set types) { return types.stream().map(this::map).collect(Collectors.toCollection(HashSet::new)); } @@ -33,20 +33,20 @@ public class Mapping { return pairs.stream().map(this::map).collect(Collectors.toCollection(HashSet::new)); } - public Optional unmap(de.dhbwstuttgart.typeinference.unify.model.Type type) { + public Optional unmap(de.dhbwstuttgart.typeinference.unify.model.UnifyType type) { return irreversible.contains(type) ? Optional.of(backwardMap.get(type)) : Optional.empty(); } public Optional unmap(de.dhbwstuttgart.typeinference.unify.model.MPair mpair) { - de.dhbwstuttgart.typeinference.unify.model.Type lhs = mpair.getLhsType(); - de.dhbwstuttgart.typeinference.unify.model.Type rhs = mpair.getRhsType(); + de.dhbwstuttgart.typeinference.unify.model.UnifyType lhs = mpair.getLhsType(); + de.dhbwstuttgart.typeinference.unify.model.UnifyType rhs = mpair.getRhsType(); if(irreversible.contains(lhs) || irreversible.contains(rhs)) return Optional.empty(); return Optional.of(new de.dhbwstuttgart.typeinference.Pair(backwardMap.get(lhs), backwardMap.get(rhs), unmapOp(mpair.getPairOp()))); } - public Optional> unmapTypeSet(Set types) { + public Optional> unmapTypeSet(Set types) { Set result = types.stream().map(this::unmap).filter(x -> x.isPresent()).map(x -> x.get()).collect(Collectors.toCollection(HashSet::new)); return result.size() == types.size() ? Optional.of(result) : Optional.empty(); } diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java b/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java index 6db1a512..4409ae7f 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java @@ -13,7 +13,7 @@ import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; import de.dhbwstuttgart.typeinference.unify.model.MPair; import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; -import de.dhbwstuttgart.typeinference.unify.model.Type; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.Unifier; @@ -24,15 +24,15 @@ import de.dhbwstuttgart.typeinference.unify.model.Unifier; public class MartelliMontanariUnify implements IUnify { @Override - public Optional unify(Set terms) { + public Optional unify(Set terms) { if(terms.size() < 2) return Optional.of(Unifier.IDENTITY); ArrayList termsQ = new ArrayList(); - Iterator iter = terms.iterator(); - Type prev = iter.next(); + Iterator iter = terms.iterator(); + UnifyType prev = iter.next(); while(iter.hasNext()) { - Type next = iter.next(); + UnifyType next = iter.next(); termsQ.add(new MPair(prev, next, PairOperator.EQUALS)); prev = next; } @@ -72,10 +72,10 @@ public class MartelliMontanariUnify implements IUnify { && pair.getRhsType().getTypeParams().occurs((PlaceholderType) pair.getLhsType())) return Optional.empty(); - Optional> optUni = eliminate(pair); + Optional> optUni = eliminate(pair); if(optUni.isPresent()) { - Entry substitution = optUni.get(); + Entry substitution = optUni.get(); mgu.Add(substitution.getKey(), substitution.getValue()); termsQ = termsQ.stream().map(mgu::apply).collect(Collectors.toCollection(ArrayList::new)); idx = idx+1 == termsQ.size() ? 0 : idx+1; @@ -95,8 +95,8 @@ public class MartelliMontanariUnify implements IUnify { private Optional> decompose(MPair pair) { Set result = new HashSet<>(); - Type rhs = pair.getRhsType(); - Type lhs = pair.getLhsType(); + UnifyType rhs = pair.getRhsType(); + UnifyType lhs = pair.getLhsType(); TypeParams rhsTypeParams = rhs.getTypeParams(); TypeParams lhsTypeParams = lhs.getTypeParams(); @@ -114,8 +114,8 @@ public class MartelliMontanariUnify implements IUnify { } private Optional swap(MPair pair) { - Type rhs = pair.getRhsType(); - Type lhs = pair.getLhsType(); + UnifyType rhs = pair.getRhsType(); + UnifyType lhs = pair.getLhsType(); if(!(lhs instanceof PlaceholderType) && (rhs instanceof PlaceholderType)) return Optional.of(new MPair(rhs, lhs, PairOperator.EQUALSDOT)); @@ -123,15 +123,15 @@ public class MartelliMontanariUnify implements IUnify { return Optional.empty(); } - private Optional> eliminate(MPair pair) { - Type rhs = pair.getRhsType(); - Type lhs = pair.getLhsType(); + private Optional> eliminate(MPair 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)); + return Optional.of(new AbstractMap.SimpleImmutableEntry((PlaceholderType) lhs, rhs)); } } diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java index e41525f5..fedccd86 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java @@ -18,7 +18,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.Type; +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; @@ -36,11 +36,11 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); - Type rhsType = pair.getRhsType(); + UnifyType rhsType = pair.getRhsType(); if(!(rhsType instanceof SuperType)) return Optional.empty(); - Type lhsType = pair.getLhsType(); + UnifyType lhsType = pair.getLhsType(); if(!(lhsType instanceof SimpleType) && !(lhsType instanceof PlaceholderType)) return Optional.empty(); @@ -52,11 +52,11 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); - Type lhsType = pair.getLhsType(); + UnifyType lhsType = pair.getLhsType(); if(!(lhsType instanceof ExtendsType)) return Optional.empty(); - Type rhsType = pair.getRhsType(); + UnifyType rhsType = pair.getRhsType(); if(!(rhsType instanceof SimpleType) && !(rhsType instanceof PlaceholderType)) return Optional.empty(); @@ -68,11 +68,11 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); - Type lhsType = pair.getLhsType(); + UnifyType lhsType = pair.getLhsType(); if(!(lhsType instanceof ExtendsType)) return Optional.empty(); - Type rhsType = pair.getRhsType(); + UnifyType rhsType = pair.getRhsType(); if(!(rhsType instanceof SuperType)) return Optional.empty(); @@ -84,12 +84,12 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); - Type lhsType = pair.getLhsType(); + UnifyType lhsType = pair.getLhsType(); if(!(lhsType instanceof SimpleType) && !(lhsType instanceof ExtendsType)) return Optional.empty(); - Type rhsType = pair.getRhsType(); + UnifyType rhsType = pair.getRhsType(); if(!(rhsType instanceof ExtendsType)) return Optional.empty(); @@ -117,12 +117,12 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); - Type lhsType = pair.getLhsType(); + UnifyType lhsType = pair.getLhsType(); if(!(lhsType instanceof SimpleType) && !(lhsType instanceof SuperType)) return Optional.empty(); - Type rhsType = pair.getRhsType(); + UnifyType rhsType = pair.getRhsType(); if(!(rhsType instanceof SuperType)) return Optional.empty(); @@ -150,11 +150,11 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); - Type lhsType = pair.getLhsType(); + UnifyType lhsType = pair.getLhsType(); if(lhsType instanceof PlaceholderType || lhsType.getTypeParams().empty()) return Optional.empty(); - Type rhsType = pair.getRhsType(); + UnifyType rhsType = pair.getRhsType(); if(!rhsType.getName().equals(lhsType.getName())) return Optional.empty(); @@ -181,11 +181,11 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); - Type lhsType = pair.getLhsType(); + UnifyType lhsType = pair.getLhsType(); if(!(lhsType instanceof SimpleType)) return Optional.empty(); - Type rhsType = pair.getRhsType(); + UnifyType rhsType = pair.getRhsType(); if(!(rhsType instanceof SimpleType)) return Optional.empty(); @@ -215,7 +215,7 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.EQUALSDOT) return Optional.empty(); - Type lhsType = pair.getLhsType(); + UnifyType lhsType = pair.getLhsType(); SimpleType lhsSType; if(lhsType instanceof SimpleType) @@ -230,7 +230,7 @@ public class RuleSet implements IRuleSet{ if(lhsSType.getTypeParams().empty()) return Optional.empty(); - Type rhsType = pair.getLhsType(); + UnifyType rhsType = pair.getLhsType(); SimpleType rhsSType; if(rhsType instanceof SimpleType) @@ -264,11 +264,11 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOT) return false; - Type lhsType = pair.getLhsType(); + UnifyType lhsType = pair.getLhsType(); if(!(lhsType instanceof SimpleType) && !(lhsType instanceof PlaceholderType)) return false; - Type rhsType = pair.getRhsType(); + UnifyType rhsType = pair.getRhsType(); if(!(rhsType instanceof SimpleType) && !(rhsType instanceof PlaceholderType)) return false; @@ -280,8 +280,8 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return false; - Type lhsType = pair.getLhsType(); - Type rhsType = pair.getRhsType(); + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); return finiteClosure.grArg(lhsType).contains(rhsType); } @@ -313,11 +313,11 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOT) return Optional.empty(); - Type typeD = pair.getLhsType(); + UnifyType typeD = pair.getLhsType(); if(!(typeD instanceof SimpleType)) return Optional.empty(); - Type typeDs = pair.getRhsType(); + UnifyType typeDs = pair.getRhsType(); if(!(typeDs instanceof SimpleType)) return Optional.empty(); @@ -327,22 +327,22 @@ public class RuleSet implements IRuleSet{ if(typeD.getName().equals(typeDs.getName())) return Optional.empty(); - Optional opt = finiteClosure.getGenericType(typeD.getName()); + Optional opt = finiteClosure.getGenericType(typeD.getName()); if(!opt.isPresent()) return Optional.empty(); // The generic Version of Type D (D) - Type typeDgen = opt.get(); + UnifyType typeDgen = opt.get(); // Actually greater+ because the types are ensured to have different names - Set greater = finiteClosure.greater(typeDgen); + Set greater = finiteClosure.greater(typeDgen); opt = greater.stream().filter(x -> x.getName().equals(typeDs.getName())).findAny(); if(!opt.isPresent()) return Optional.empty(); - Type newLhs = opt.get(); + UnifyType newLhs = opt.get(); TypeParams typeDParams = typeD.getTypeParams(); TypeParams typeDgenParams = typeDgen.getTypeParams(); @@ -359,36 +359,36 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); - Type typeD = pair.getLhsType(); + UnifyType typeD = pair.getLhsType(); if(!(typeD instanceof SimpleType) && !(typeD instanceof ExtendsType)) return Optional.empty(); - Type typeExtDs = pair.getRhsType(); + UnifyType typeExtDs = pair.getRhsType(); if(!(typeExtDs instanceof ExtendsType)) return Optional.empty(); if(typeD.getTypeParams().size() == 0 || typeExtDs.getTypeParams().size() == 0) return Optional.empty(); - Type typeDgen; + UnifyType typeDgen; if(typeD instanceof SimpleType) typeDgen = finiteClosure.getGenericType(typeD.getName()).orElse(null); else { - Optional opt = finiteClosure.getGenericType(((ExtendsType) typeD).getExtendedType().getName()); + Optional opt = finiteClosure.getGenericType(((ExtendsType) typeD).getExtendedType().getName()); typeDgen = opt.isPresent() ? new ExtendsType(opt.get()) : null; } if(typeDgen == null) return Optional.empty(); - Set grArg = finiteClosure.grArg(typeDgen); + Set grArg = finiteClosure.grArg(typeDgen); - Optional opt = grArg.stream().filter(x -> x.getName().equals(typeExtDs.getName())).findAny(); + Optional opt = grArg.stream().filter(x -> x.getName().equals(typeExtDs.getName())).findAny(); if(!opt.isPresent()) return Optional.empty(); - Type newLhs = ((ExtendsType) opt.get()).getExtendedType(); + UnifyType newLhs = ((ExtendsType) opt.get()).getExtendedType(); TypeParams typeDParams = typeD.getTypeParams(); TypeParams typeDgenParams = typeDgen.getTypeParams(); @@ -405,11 +405,11 @@ public class RuleSet implements IRuleSet{ if(pair.getPairOp() != PairOperator.SMALLERDOTWC) return Optional.empty(); - Type typeDs = pair.getLhsType(); + UnifyType typeDs = pair.getLhsType(); if(!(typeDs instanceof SimpleType) && !(typeDs instanceof SuperType)) return Optional.empty(); - Type typeSupD = pair.getRhsType(); + UnifyType typeSupD = pair.getRhsType(); if(!(typeSupD instanceof SuperType)) return Optional.empty(); @@ -417,31 +417,31 @@ public class RuleSet implements IRuleSet{ return Optional.empty(); - Optional opt = finiteClosure.getGenericType(((SuperType) typeSupD).getSuperedType().getName()); + Optional opt = finiteClosure.getGenericType(((SuperType) typeSupD).getSuperedType().getName()); if(!opt.isPresent()) return Optional.empty(); - Type typeDgen = opt.get(); - Type typeSupDgen = new SuperType(typeDgen); + UnifyType typeDgen = opt.get(); + UnifyType typeSupDgen = new SuperType(typeDgen); // Use of smArg instead of grArg because // a in grArg(b) => b in smArg(a) - Set smArg = finiteClosure.smArg(typeSupDgen); + Set smArg = finiteClosure.smArg(typeSupDgen); opt = smArg.stream().filter(x -> x.getName().equals(typeDs.getName())).findAny(); if(!opt.isPresent()) return Optional.empty(); // New RHS - Type newRhs = null; + UnifyType newRhs = null; if(typeDs instanceof SimpleType) newRhs = new ExtendsType(typeDs); else newRhs = new ExtendsType(((SuperType) typeDs).getSuperedType()); // New LHS - Type newLhs = opt.get(); + UnifyType newLhs = opt.get(); TypeParams typeDParams = typeSupD.getTypeParams(); TypeParams typeSupDsgenParams = typeSupDgen.getTypeParams(); @@ -458,23 +458,23 @@ 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) { - Type cFromFc = null; + private int[] pi(UnifyType C, UnifyType D) { + UnifyType cFromFc = null; if(C instanceof SimpleType) cFromFc = finiteClosure.getGenericType(C.getName()).orElse(null); else if(C instanceof ExtendsType) { - Optional opt = finiteClosure.getGenericType(((ExtendsType) C).getExtendedType().getName()); + Optional opt = finiteClosure.getGenericType(((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.getGenericType(((SuperType) C).getSuperedType().getName()); if(opt.isPresent()) cFromFc = new SuperType(opt.get()); } if(cFromFc == null) return new int[0]; - Optional opt = Optional.empty(); + Optional opt = Optional.empty(); if(D instanceof ExtendsType) { SimpleType dSType = (SimpleType) ((ExtendsType) D).getExtendedType(); opt = finiteClosure.grArg(cFromFc).stream() @@ -494,7 +494,7 @@ public class RuleSet implements IRuleSet{ if(!opt.isPresent()) return new int[0]; - Type dFromFc = opt.get(); + UnifyType dFromFc = opt.get(); Assert.assertEquals(cFromFc.getTypeParams().size(), dFromFc.getTypeParams().size()); Assert.assertTrue(dFromFc.getTypeParams().size() > 0); @@ -506,7 +506,7 @@ public class RuleSet implements IRuleSet{ boolean succ = true; for (int dArgIdx = 0; dArgIdx < dArgs.size() && succ; dArgIdx++) { - Type dArg = dArgs.get(dArgIdx); + UnifyType dArg = dArgs.get(dArgIdx); succ = false; for (int pi = 0; pi < cArgs.size(); pi++) if (cArgs.get(pi).getName().equals(dArg.getName())) { @@ -522,11 +522,11 @@ public class RuleSet implements IRuleSet{ @Override public Optional> subst(Set pairs) { - HashMap typeMap = new HashMap<>(); + HashMap typeMap = new HashMap<>(); for(MPair pair : pairs) { - Type t1 = pair.getLhsType(); - Type t2 = pair.getRhsType(); + UnifyType t1 = pair.getLhsType(); + UnifyType t2 = pair.getRhsType(); if(!typeMap.containsKey(t1)) typeMap.put(t1, 0); if(!typeMap.containsKey(t2)) @@ -542,7 +542,7 @@ public class RuleSet implements IRuleSet{ for(int i = 0; i < result.size(); i++) { MPair pair = result.get(i); PlaceholderType lhsType = null; - Type rhsType; + UnifyType rhsType; if(pair.getPairOp() == PairOperator.EQUALSDOT && pair.getLhsType() instanceof PlaceholderType) diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java index 548340b3..6fa2eda1 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java @@ -23,7 +23,7 @@ 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.Type; +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; @@ -223,46 +223,46 @@ public class Unify { for(MPair pair : eq2s) { PairOperator pairOp = pair.getPairOp(); - Type lhsType = pair.getLhsType(); - Type rhsType = pair.getRhsType(); + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); // Case 1: (a <. Theta') if(pairOp == PairOperator.SMALLERDOT && lhsType instanceof PlaceholderType) { - Type thetaPrime = pair.getRhsType(); + UnifyType thetaPrime = pair.getRhsType(); Set set = new HashSet<>(); IUnify unify = new MartelliMontanariUnify(); //Set cs = fc.getAllTypes(rhsType.getName()); - Type c = rhsType; + UnifyType c = rhsType; //Set thetaQs = cs.stream().flatMap(x -> fc.smaller(x).stream()).collect(Collectors.toCollection(HashSet::new)); - Set thetaQs = fc.smaller(c); + Set thetaQs = fc.smaller(c); - Set thetaQPrimes = new HashSet<>(); + Set thetaQPrimes = new HashSet<>(); TypeParams cParams = c.getTypeParams(); if(cParams.size() == 0) thetaQPrimes.add(c); else { - ArrayList> candidateParams = new ArrayList<>(); - for(Type param : cParams) + ArrayList> candidateParams = new ArrayList<>(); + for(UnifyType param : cParams) candidateParams.add(fc.grArg(param)); Set permutations = new HashSet(); - permuteParams(candidateParams, 0, permutations, new Type[candidateParams.size()]); + permuteParams(candidateParams, 0, permutations, new UnifyType[candidateParams.size()]); for(TypeParams tp : permutations) thetaQPrimes.add(c.setTypeParams(tp)); } - for(Type tqp : thetaQPrimes) { + for(UnifyType tqp : thetaQPrimes) { Optional opt = unify.unify(tqp, thetaPrime); if(opt.isPresent()) { Unifier unifier = opt.get(); - Set> substitutions = unifier.getSubstitutions(); - for(Entry sigma : substitutions) + 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)); + for(UnifyType tq : thetaQs) { + Set smaller = fc.smaller(unifier.apply(tq)); smaller.stream().map(x -> new MPair(lhsType, x, PairOperator.EQUALSDOT)).forEach(x -> set.add(x)); } } @@ -279,7 +279,7 @@ public class Unify { // 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)) + for(UnifyType theta : fc.smArg(rhsType)) set.add(new MPair(lhsType, theta, PairOperator.EQUALSDOT)); result.add(set); } @@ -294,7 +294,7 @@ public class Unify { // Case 5: (Theta <. a) else if(pairOp == PairOperator.SMALLERDOT && rhsType instanceof PlaceholderType) { Set set = new HashSet<>(); - for(Type thetaS : fc.greater(lhsType)) + for(UnifyType thetaS : fc.greater(lhsType)) set.add(new MPair(rhsType, thetaS, PairOperator.EQUALSDOT)); result.add(set); } @@ -302,7 +302,7 @@ public class Unify { // 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)) + for(UnifyType thetaS : fc.grArg(lhsType)) set.add(new MPair(rhsType, thetaS, PairOperator.EQUALSDOT)); result.add(set); } @@ -315,7 +315,7 @@ public class Unify { // Case 8: (Theta <.? a) else if(pairOp == PairOperator.SMALLERDOTWC && rhsType instanceof PlaceholderType) { Set set = new HashSet<>(); - for(Type thetaS : fc.grArg(lhsType)) + for(UnifyType thetaS : fc.grArg(lhsType)) set.add(new MPair(rhsType, thetaS, PairOperator.EQUALSDOT)); result.add(set); } @@ -324,22 +324,22 @@ public class Unify { return result; } - protected void permuteParams(ArrayList> candidates, int idx, Set result, Type[] current) { + protected 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); + Set localCandidates = candidates.get(idx); - for(Type t : localCandidates) { + for(UnifyType t : localCandidates) { current[idx] = t; permuteParams(candidates, idx+1, result, current); } } - private Set getAllInstantiations(Type t, IFiniteClosure fc) { - Set result = new HashSet<>(); + private Set getAllInstantiations(UnifyType t, IFiniteClosure fc) { + Set result = new HashSet<>(); result.add(t); return result; diff --git a/test/unify/FiniteClosureBuilder.java b/test/unify/FiniteClosureBuilder.java index d5b3b32b..30831a89 100644 --- a/test/unify/FiniteClosureBuilder.java +++ b/test/unify/FiniteClosureBuilder.java @@ -6,15 +6,14 @@ 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.Type; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; -import de.dhbwstuttgart.typeinference.unifynew.TypeFactory; public class FiniteClosureBuilder { private Set pairs = new HashSet<>(); - public void add(Type sub, Type sup) { + public void add(UnifyType sub, UnifyType sup) { pairs.add(new MPair(sub, sup, PairOperator.SMALLER)); } @@ -29,19 +28,19 @@ public class FiniteClosureBuilder { public IFiniteClosure getCollectionExample() { TypeFactory tf = new TypeFactory(); - Type collection = tf.getSimpleType("Collection"); - Type set = tf.getSimpleType("Set", "T"); - Type sortedSet = tf.getSimpleType("Set", "T"); - Type TreeSet = tf.getSimpleType("TreeSet", "T"); - Type hashSet = tf.getSimpleType("HashSet", "T"); - Type linkedHashSet = tf.getSimpleType("LinkedHashSet", "T"); - Type queue = tf.getSimpleType("Queue", "T"); - Type deque = tf.getSimpleType("Deque", "T"); - Type linkedList = tf.getSimpleType("LinkedList", "T"); - Type list = tf.getSimpleType("List", "T"); - Type vector = tf.getSimpleType("Vector", "T"); - Type stack = tf.getSimpleType("Stack", "T"); - Type arrayList = tf.getSimpleType("ArrayList", "T"); + UnifyType collection = tf.getSimpleType("Collection"); + UnifyType set = tf.getSimpleType("Set", "T"); + UnifyType sortedSet = tf.getSimpleType("Set", "T"); + UnifyType TreeSet = tf.getSimpleType("TreeSet", "T"); + UnifyType hashSet = tf.getSimpleType("HashSet", "T"); + UnifyType linkedHashSet = tf.getSimpleType("LinkedHashSet", "T"); + UnifyType queue = tf.getSimpleType("Queue", "T"); + UnifyType deque = tf.getSimpleType("Deque", "T"); + UnifyType linkedList = tf.getSimpleType("LinkedList", "T"); + UnifyType list = tf.getSimpleType("List", "T"); + UnifyType vector = tf.getSimpleType("Vector", "T"); + UnifyType stack = tf.getSimpleType("Stack", "T"); + UnifyType arrayList = tf.getSimpleType("ArrayList", "T"); add(set, collection); add(sortedSet, set); diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index 9b5c72e6..1b19969c 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -8,8 +8,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.unifynew.TypeFactory; -import de.dhbwstuttgart.typeinference.unify.model.Type; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public class FiniteClosureTest { diff --git a/test/unify/GenerateFiniteClosure.java b/test/unify/GenerateFiniteClosure.java new file mode 100644 index 00000000..378fb019 --- /dev/null +++ b/test/unify/GenerateFiniteClosure.java @@ -0,0 +1,47 @@ +package unify; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import de.dhbwstuttgart.syntaxtree.ImportDeclarations; +import de.dhbwstuttgart.syntaxtree.SourceFile; +import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory; +import de.dhbwstuttgart.syntaxtree.misc.UsedId; +import de.dhbwstuttgart.syntaxtree.type.RefType; +import de.dhbwstuttgart.typeinference.Menge; +import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; +import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; + +public class GenerateFiniteClosure { + + private TypeAssumptions generateAssumptionsFromImport(String importClass){ + SourceFile sf = new SourceFile(); + ImportDeclarations imports = new ImportDeclarations(); + imports.add(new UsedId(importClass,0)); + TypeAssumptions ass = sf.makeBasicAssumptionsFromJRE(imports, true); + return ass; + } + + @Test + public void generateTypeAssumptions(){ + Menge imports = new Menge<>(); + imports.add("java.util.Vector"); + imports.add("java.lang.Boolean"); + imports.add("java.util.ArrayList"); + + for(String importClass : imports){ + TypeAssumptions ass = generateAssumptionsFromImport(importClass); + assertTrue(ass.getClassAssumptionFor(new RefType(importClass,null,0))!=null); + } + } + + @Test + public void test() { + String importClass = "java.util.Vector"; + TypeAssumptions ass = generateAssumptionsFromImport(importClass); + FiniteClosure fc = UnifyTypeFactory.generateFC(ass); + System.out.println(fc); + } + +} diff --git a/test/unify/RuleSetTest.java b/test/unify/RuleSetTest.java index 1a1f55a5..1fe1359d 100644 --- a/test/unify/RuleSetTest.java +++ b/test/unify/RuleSetTest.java @@ -15,7 +15,6 @@ 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; -import de.dhbwstuttgart.typeinference.unifynew.TypeFactory; public class RuleSetTest { diff --git a/test/unify/StandardUnifyTest.java b/test/unify/StandardUnifyTest.java index 8bfc0643..e75bf38c 100644 --- a/test/unify/StandardUnifyTest.java +++ b/test/unify/StandardUnifyTest.java @@ -9,10 +9,9 @@ import org.junit.Test; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; import de.dhbwstuttgart.typeinference.unify.model.MPair; -import de.dhbwstuttgart.typeinference.unify.model.Type; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; import de.dhbwstuttgart.typeinference.unifynew.MartelliMontanariUnify; -import de.dhbwstuttgart.typeinference.unifynew.TypeFactory; public class StandardUnifyTest { @@ -25,9 +24,9 @@ public class StandardUnifyTest { * Positive Tests */ - Type x = tf.getPlaceholderType("x"); - Type y = tf.getPlaceholderType("y"); - Type f = tf.getSimpleType("f", x); + UnifyType x = tf.getPlaceholderType("x"); + UnifyType y = tf.getPlaceholderType("y"); + UnifyType f = tf.getSimpleType("f", x); // {f = y} Set terms = new HashSet(); @@ -37,10 +36,10 @@ public class StandardUnifyTest { // 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} - Type g = tf.getSimpleType("g", "x"); - Type f1 = tf.getSimpleType("f", g, x); - Type a = tf.getExtendsType(tf.getPlaceholderType("a")); - Type f2 = tf.getSimpleType("f", y, a); + UnifyType g = tf.getSimpleType("g", "x"); + UnifyType f1 = tf.getSimpleType("f", g, x); + UnifyType a = tf.getExtendsType(tf.getPlaceholderType("a")); + UnifyType f2 = tf.getSimpleType("f", y, a); terms = new HashSet<>(); diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/TypeFactory.java b/test/unify/TypeFactory.java similarity index 72% rename from src/de/dhbwstuttgart/typeinference/unifynew/TypeFactory.java rename to test/unify/TypeFactory.java index 9c18c4fc..965e324d 100644 --- a/src/de/dhbwstuttgart/typeinference/unifynew/TypeFactory.java +++ b/test/unify/TypeFactory.java @@ -1,4 +1,4 @@ -package de.dhbwstuttgart.typeinference.unifynew; +package unify; import java.util.Arrays; import java.util.stream.Collectors; @@ -7,15 +7,15 @@ 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.SuperType; -import de.dhbwstuttgart.typeinference.unify.model.Type; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public class TypeFactory { - public ExtendsType getExtendsType(Type extendedType) { + public ExtendsType getExtendsType(UnifyType extendedType) { return new ExtendsType(extendedType); } - public SuperType getSuperType(Type superedType) { + public SuperType getSuperType(UnifyType superedType) { return new SuperType(superedType); } @@ -23,12 +23,12 @@ public class TypeFactory { return new SimpleType(name); } - public SimpleType getSimpleType(String name, Type... typeParams) { + public SimpleType getSimpleType(String name, UnifyType... typeParams) { return new SimpleType(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 Type[0])); + return new SimpleType(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/UnifyOldTest.java b/test/unify/UnifyOldTest.java index 85f5ffd5..9a28e30a 100644 --- a/test/unify/UnifyOldTest.java +++ b/test/unify/UnifyOldTest.java @@ -7,8 +7,13 @@ 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.RefType; +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.Menge; import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.Pair.PairOperator; @@ -19,7 +24,6 @@ public class UnifyOldTest { @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(); @@ -29,13 +33,13 @@ public class UnifyOldTest { */ // Init Types - RefType boolT = typeFactory.GetSimpleType("java.lang.Boolean"); - TypePlaceholder aTph = typeFactory.GetTypePlaceholder("a"); + 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, typeFactory.GetExtendsType(boolT), + resultBuilder.addPair(aTph, this.GetExtendsType(boolT), PairOperator.Equal); Menge> expectedResult = resultBuilder.getNestedPairMenge(); @@ -55,17 +59,17 @@ public class UnifyOldTest { */ // Init Types - boolT = typeFactory.GetSimpleType("java.lang.Boolean"); - aTph = typeFactory.GetTypePlaceholder("a"); - TypePlaceholder bTph = typeFactory.GetTypePlaceholder("b"); + 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, typeFactory.GetExtendsType(boolT), + resultBuilder.addPair(aTph, this.GetExtendsType(boolT), PairOperator.Equal); resultBuilder.addPair(bTph, boolT, PairOperator.Equal); - resultBuilder.addPair(bTph, typeFactory.GetExtendsType(boolT), + resultBuilder.addPair(bTph, this.GetExtendsType(boolT), PairOperator.Equal); expectedResult = resultBuilder.getNestedPairMenge(); @@ -86,8 +90,8 @@ public class UnifyOldTest { * Test b <. a, a <. b */ - aTph = typeFactory.GetTypePlaceholder("a"); - bTph = typeFactory.GetTypePlaceholder("b"); + aTph = this.GetTypePlaceholder("a"); + bTph = this.GetTypePlaceholder("b"); // Expected Result resultBuilder.clear(); @@ -114,10 +118,10 @@ public class UnifyOldTest { * 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"); + 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(); @@ -141,7 +145,6 @@ public class UnifyOldTest { 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(); @@ -150,15 +153,15 @@ public class UnifyOldTest { * Test a <. MyClass */ - TypePlaceholder aTph = typeFactory.GetTypePlaceholder("a"); - RefType myType = typeFactory.GetSimpleType("MyClass", - typeFactory.GetTypePlaceholder("T"), - typeFactory.GetTypePlaceholder("F")); + 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, typeFactory.GetExtendsType(myType)); + resultBuilder.addPair(aTph, this.GetExtendsType(myType)); Menge> expectedResult = resultBuilder.getNestedPairMenge(); // Actual Result @@ -176,13 +179,13 @@ public class UnifyOldTest { * Test List> <. List */ - TypePlaceholder tTph = typeFactory.GetTypePlaceholder("T"); - RefType list = typeFactory.GetSimpleType("List", tTph); - RefType listlist = typeFactory.GetSimpleType("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(typeFactory.GetExtendsType(list), tTph, + resultBuilder.addPair(this.GetExtendsType(list), tTph, PairOperator.Equal); expectedResult = resultBuilder.getNestedPairMenge(); @@ -206,16 +209,15 @@ public class UnifyOldTest { 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"); + 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 @@ -227,10 +229,10 @@ public class UnifyOldTest { // Build expected result resultBuilder.addPair(tphA, tBool, PairOperator.Equal); - resultBuilder.addPair(tphA, typeFactory.GetExtendsType(tBool), + resultBuilder.addPair(tphA, this.GetExtendsType(tBool), PairOperator.Equal); resultBuilder.addPair(tphA, tString, PairOperator.Equal); - resultBuilder.addPair(tphA, typeFactory.GetExtendsType(tString), + resultBuilder.addPair(tphA, this.GetExtendsType(tString), PairOperator.Equal); // Assert @@ -299,5 +301,34 @@ public class UnifyOldTest { 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); + } } diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 8524c1dc..60486017 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -9,9 +9,8 @@ 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.Type; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.TypeParams; -import de.dhbwstuttgart.typeinference.unifynew.TypeFactory; import de.dhbwstuttgart.typeinference.unifynew.Unify; public class UnifyTest extends Unify { @@ -61,18 +60,18 @@ public class UnifyTest extends Unify { @Test public void permuteParamsTest() { TypeFactory tf = new TypeFactory(); - ArrayList> candidates = new ArrayList<>(); + ArrayList> candidates = new ArrayList<>(); - Set p1 = new HashSet<>(); + Set p1 = new HashSet<>(); p1.add(tf.getPlaceholderType("p11")); p1.add(tf.getExtendsType(tf.getSimpleType("p12"))); p1.add(tf.getSimpleType("p13")); - Set p2 = new HashSet<>(); + Set p2 = new HashSet<>(); p2.add(tf.getPlaceholderType("p21")); p2.add(tf.getPlaceholderType("p22")); - Set p3 = new HashSet<>(); + Set p3 = new HashSet<>(); p3.add(tf.getSimpleType("p31", "T")); p3.add(tf.getSimpleType("p32")); @@ -81,7 +80,7 @@ public class UnifyTest extends Unify { candidates.add(p3); Set result = new HashSet<>(); - permuteParams(candidates, 0, result, new Type[candidates.size()]); + permuteParams(candidates, 0, result, new UnifyType[candidates.size()]); System.out.println(result); } From c80dc162d93ab81e11198223d1d210a259f17efb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrico=20Schr=C3=B6dter?= Date: Sun, 20 Mar 2016 18:55:36 +0100 Subject: [PATCH 02/13] - Verhindern von der Generierung von doppelte Methoden --- src/de/dhbwstuttgart/syntaxtree/Class.java | 13 +- .../dhbwstuttgart/syntaxtree/Constructor.java | 2 +- src/de/dhbwstuttgart/syntaxtree/Method.java | 201 ++---------------- .../types/AutoOverloadingMultiResults.jav | 8 + .../AutoOverloadingMultiResultsTest.java | 36 ++++ .../types/AutoOverloadingVectorTest.java | 8 +- test/bytecode/types/ExtendsType.jav | 2 +- test/bytecode/types/ExtendsTypeTest.java | 2 +- .../types/ExtendsVectorStringTest.java | 11 +- 9 files changed, 85 insertions(+), 198 deletions(-) create mode 100644 test/bytecode/types/AutoOverloadingMultiResults.jav create mode 100644 test/bytecode/types/AutoOverloadingMultiResultsTest.java diff --git a/src/de/dhbwstuttgart/syntaxtree/Class.java b/src/de/dhbwstuttgart/syntaxtree/Class.java index 006e3537..a746b8c9 100755 --- a/src/de/dhbwstuttgart/syntaxtree/Class.java +++ b/src/de/dhbwstuttgart/syntaxtree/Class.java @@ -7,6 +7,8 @@ import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; import javax.lang.model.element.Modifier; @@ -72,6 +74,7 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I protected UsedId pkgName; protected Modifiers modifiers; protected String name; + private List methodSignaturesAndNames = new LinkedList<>(); /** * @@ -106,7 +109,7 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I } //Zuerst die Methoden und Felder abarbeiten: for(Method m : methods){ - m.genByteCode(_cg); + m.genByteCode(_cg, this); } InstructionList fieldInitializations = new InstructionList(); for(FieldDeclaration f : fieldDeclarations){ @@ -1039,6 +1042,14 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I public boolean isInterface(){ return false; } + + protected boolean methodExists(String nameAndSignature) { + return methodSignaturesAndNames.contains(nameAndSignature); + } + + protected void addMethod(String nameAndSignature) { + methodSignaturesAndNames.add(nameAndSignature); + } /* private Collection getGenericClasses() { diff --git a/src/de/dhbwstuttgart/syntaxtree/Constructor.java b/src/de/dhbwstuttgart/syntaxtree/Constructor.java index 65a85522..9859a734 100644 --- a/src/de/dhbwstuttgart/syntaxtree/Constructor.java +++ b/src/de/dhbwstuttgart/syntaxtree/Constructor.java @@ -98,7 +98,7 @@ public class Constructor extends Method { } @Override - public void genByteCode(ClassGenerator cg) { + public void genByteCode(ClassGenerator cg, Class classObj) { this.genByteCode(cg, new InstructionList()); } // super statement muss drin sein diff --git a/src/de/dhbwstuttgart/syntaxtree/Method.java b/src/de/dhbwstuttgart/syntaxtree/Method.java index 8977fdd8..8a3370fb 100755 --- a/src/de/dhbwstuttgart/syntaxtree/Method.java +++ b/src/de/dhbwstuttgart/syntaxtree/Method.java @@ -1,6 +1,7 @@ // ino.module.Method.8564.package package de.dhbwstuttgart.syntaxtree; +import java.util.Arrays; // ino.end // ino.module.Method.8564.import import java.util.Enumeration; @@ -465,39 +466,7 @@ public class Method extends Field implements IItemWithOffset, TypeInsertable } @Override - public void wandleRefTypeAttributes2GenericAttributes( - Menge classParalist) { - /* - * Menge paralist = new Menge();//Mit den Generischen Typen - * der Methode paralist.addAll(classParalist); - * paralist.addAll(this.genericMethodParameters); - * - * // Zuerst Returntype untersuchen Type returnType=getType(); Type - * pendantReturnType = null; if(returnType instanceof - * RefType)pendantReturnType = - * ((RefType)returnType).findGenericType(paralist, new - * Menge()); //GenericTypeVar - * pendantReturnType=ClassHelper.findGenericType(returnType, - * paralist,genericMethodParameters); if(pendantReturnType!=null){ - * //Wenn generisch, dann modifizieren setReturnType(pendantReturnType); - * } - * - * // Dann parameterlist untersuchen for(int - * par=0;par()); //GenericTypeVar - * pendantPara=ClassHelper.findGenericType - * (fpType,paralist,genericMethodParameters); if(pendantPara!=null){ - * //Wenn generisch, dann modifizieren fp.setType(pendantPara); } } - * - * // Zuletzt alle Lokalen Variablendeklarationen durchgehen - * if(block!=null){ - * block.wandleRefTypeAttributes2GenericAttributes(paralist - * ,genericMethodParameters); } - */ + public void wandleRefTypeAttributes2GenericAttributes(Menge classParalist) { } public void set_Method_Name(String string) { @@ -520,30 +489,11 @@ public class Method extends Field implements IItemWithOffset, TypeInsertable // TypeCheck, falls es sich um einen RefType handelt: this.returntype = this.returntype.checkTYPE(localAss, this); - /* - * if(this.returntype!=null && (this.returntype instanceof RefType)&& - * !(this.returntype instanceof mycompiler.mytype.Void)){//Sonderfall - * der Methode: Ihr Typ darf Void definiert werden. Type replaceType = - * null; replaceType = ass.getTypeFor((RefType)this.returntype); - * if(replaceType == null)throw new - * TypeinferenceException("Der Typ "+this - * .getType().getName()+" ist nicht korrekt",this); this.returntype = - * replaceType; } - */ // Die Parameter zu den Assumptions hinzufügen: if (this.parameterlist != null) for (FormalParameter param : this.parameterlist) { param.setType(param.getType().checkTYPE(localAss, this)); - /* - * if(param.getType() instanceof RefType) { Type replaceType = - * null; replaceType = ass.getTypeFor((RefType)param.getType()); - * if(replaceType == null) throw new - * TypeinferenceException("Der Typ " - * +param.getType().getName()+" ist nicht korrekt",param); - * param.setType(replaceType); } - */ - localAss.addAssumption(new ParameterAssumption(param)); } ret.add(this.block.TYPEStmt(localAss)); @@ -587,107 +537,15 @@ public class Method extends Field implements IItemWithOffset, TypeInsertable TypeAssumptions ret = new TypeAssumptions(); ret.addAssumption(new MethodAssumption(this, parentClass)); return ret; - /* - * TypeAssumptions assumptions = new TypeAssumptions(); this.assumedType - * = null; //if((this.get_Method_Name().equals(classmember.getName()) || - * this.get_Method_Name().equals("")) && - * ((this.getType().equals(new mycompiler.mytype.Void(0))) || - * this.getType() instanceof TypePlaceholder)){ - * if((this.get_Method_Name().equals(classmember.getName()) || - * this.get_Method_Name().equals(""))) { - * this.set_Method_Name(""); this.assumedType = new - * RefType(classmember.getName(),0); - * this.setReturnType(this.assumedType); this.assumedType = new - * RefType("void",0); //Return constructorReturnStatement = new - * Return(0,0); //constructorReturnStatement.retexpr = - * //this.block.statements.add(constructorReturnStatement); } //hoth: - * 06.04.2006 //durchlaufe Block und suche nach Objektvariablen fuer - * Offset-Markierung Iterator fieldVarIterator = - * assumptions.iterator(); while (fieldVarIterator.hasNext()) { //Wenn - * ObjektVariable CTypeAssumption dieAssum = fieldVarIterator.next(); - * if(dieAssum instanceof CInstVarTypeAssumption) { - * Class.isFirstLocalVarDecl=false; if(this.get_Block() != null) - * this.get_Block - * ().addOffsetsToAssumption(dieAssum,dieAssum.getIdentifier(),true); } - * } - * - * //methodList.addElement(method); - * - * //F�r V_fields_methods: CMethodTypeAssumption methodAssum - * = new CMethodTypeAssumption(classmember.getType(), - * this.get_Method_Name(), this.getType(), - * this.getParameterCount(),this.getLineNumber(),this.getOffset(),new - * Menge(),this.getGenericMethodParameters()); // Typannahme - * bauen... - * - * - * //Methode in V_Fields_methods ablegen //Dabei wird die - * OverloadedMethodID ermittelt !! //=> Method setzenuct - * - * - * assumptions.add(methodAssum); - * this.setOverloadedID(methodAssum.getHashSetKey - * ().getOverloadedMethodID()); - * - * - * //F�r die V_i: CTypeAssumptionSet localAssum = new - * CTypeAssumptionSet(); - * - * //Bauen... ParameterList parameterList = this.getParameterList(); - * if(parameterList!=null){ for(int i=0; - * i()); //fuege Offsets fuer Parameter hinzu, hoth: - * 06.04.2006 Class.isFirstLocalVarDecl=false; - * - * if(this.get_Block() != null) - * this.get_Block().addOffsetsToAssumption(paraAssum - * ,paraAssum.getIdentifier(),true); - * - * methodAssum.addParaAssumption(paraAssum); - * - * // F�r die V_i: CLocalVarTypeAssumption varAssum = new - * CLocalVarTypeAssumption(classmember.getName(), - * this.get_Method_Name(), this.getParameterCount(), - * this.getOverloadedID(),"1", para.get_Name(),para.getType(), - * para.getLineNumber(),para.getOffset(),new Menge()); - * localAssum.addElement(varAssum); - * //rememberLocals.addElement(varAssum); } } //...und - * hinzuf�gen: - * - * assumptions.add(localAssum);//Assumptions für lokale Variablen den - * Assumptions hinzufügen - * - * //Hier wird der Typ der als Assumption eingetragen wird in die - * Variable assumedType dieser Klasse geschrieben: if(this.assumedType - * == null) // Falls der Typ nicht schon gesetzt ist. Das ist der Fall, - * falls die Methode ein Konstruktor ist this.assumedType = - * methodAssum.getAssumedType(); - * - * return assumptions; - */ } @Override public void parserPostProcessing(SyntaxTreeNode parent) { if (this.getType() == null) this.setType(TypePlaceholder.fresh(this)); - // Bei dem Elterntyp der Methode darf es sich nur um eine Klasse - // handeln, daher Cast ohne Prüfung: - // Class parentClass = (Class)parent; if (this.returntype == null) this.returntype = TypePlaceholder.fresh(this); super.parserPostProcessing(parent); - /* - * this.returntype.parserPostProcessing(this); if(this.parameterlist != - * null){ for(FormalParameter fp : this.parameterlist){ - * fp.parserPostProcessing(this); } } for(GenericTypeVar gtv : - * this.getGenericParameter()){ gtv.parserPostProcessing(this); } - */ } @Override @@ -728,7 +586,6 @@ public class Method extends Field implements IItemWithOffset, TypeInsertable DImethod.set_Name(withSignature); ret.set_DeclId(DImethod); Block tempBlock = new Block(); - // tempBlock.setType(new RefType(parent.getName(),0)); ret.set_Block(tempBlock); ret.parserPostProcessing(parent); return ret; @@ -751,7 +608,7 @@ public class Method extends Field implements IItemWithOffset, TypeInsertable return super.equals(obj); } - public void genByteCode(ClassGenerator cg) { + public void genByteCode(ClassGenerator cg, Class classObj) { List typeInterferenceResults = cg.getTypeinferenceResults().getTypeReconstructions(this, cg); for(TypeinferenceResultSet t: typeInterferenceResults){ @@ -771,10 +628,15 @@ public class Method extends Field implements IItemWithOffset, TypeInsertable argumentNames[i] = parameter.getIdentifier(); i++; } - - if(!createdMethods.contains(argumentTypes, new ArgumentTypeEquals())){ - createdMethods.add(argumentTypes); - } + } + + String nameAndSignature = get_Method_Name()+Arrays.toString(argumentTypes); + + Logger.getLogger("nameAndSignature").error(nameAndSignature, Section.CODEGEN); + + if(classObj.methodExists(nameAndSignature)){ + Logger.getLogger("methodExists").debug(this.toString(), Section.CODEGEN); + continue; } short constants = Constants.ACC_PUBLIC; //Per Definition ist jede Methode public @@ -787,45 +649,10 @@ public class Method extends Field implements IItemWithOffset, TypeInsertable //Methode generieren und anfügen: cg.addMethod(method.createMethod(cg, getParameterList(), returnType, get_Block(), t)); + classObj.addMethod(nameAndSignature); - /* - short constants = Constants.ACC_PUBLIC; //Per Definition ist jede Methode public - if(this.modifiers != null && this.modifiers.includesModifier(new Static())) constants += Constants.ACC_STATIC; - - Type returnType = this.getType(); - - //Methode generieren: - MethodGenerator method = new MethodGenerator(constants, returnType.getBytecodeType(cg), argumentTypes , argumentNames, this.get_Method_Name(), parentClass.name, il, _cp); - - //Methode generieren und anfügen: - cg.addMethod(method.createMethod(cg, getParameterList(), returnType, get_Block())); - */ + Logger.getLogger("createMethod").debug(this.toString(), Section.CODEGEN); } } } - -class ArgumentTypeEquals implements Equal{ - - @Override - public boolean equal(org.apache.commons.bcel6.generic.Type[] a, org.apache.commons.bcel6.generic.Type[] b) { - if(a.length != b.length){ - Logger.getLogger("ArgumentTypeEquals").error("false(length)", Section.CODEGEN); - return false; - } - - for(int i = 0; i < a.length; i++){ - if(!a[i].equals(b[i])){ - String as = a[i].toString(); - String bs = b[i].toString(); - Logger.getLogger("ArgumentTypeEquals").error("false "+as+" != "+bs, Section.CODEGEN); - return false; - } - } - - Logger.getLogger("ArgumentTypeEquals").error("true", Section.CODEGEN); - - return true; - } - -} // ino.end diff --git a/test/bytecode/types/AutoOverloadingMultiResults.jav b/test/bytecode/types/AutoOverloadingMultiResults.jav new file mode 100644 index 00000000..d5c0f23f --- /dev/null +++ b/test/bytecode/types/AutoOverloadingMultiResults.jav @@ -0,0 +1,8 @@ +import java.util.Vector; + +class AutoOverloadingMultiResults{ + void method(Integer a) { + b; + b = 1; + } +} \ No newline at end of file diff --git a/test/bytecode/types/AutoOverloadingMultiResultsTest.java b/test/bytecode/types/AutoOverloadingMultiResultsTest.java new file mode 100644 index 00000000..37fa57a7 --- /dev/null +++ b/test/bytecode/types/AutoOverloadingMultiResultsTest.java @@ -0,0 +1,36 @@ +package bytecode.types; + +import static org.junit.Assert.*; + +import java.io.File; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Vector; + +import org.junit.Test; + +import org.junit.Ignore; + +import bytecode.SourceFileBytecodeTest; + + +public class AutoOverloadingMultiResultsTest extends SourceFileBytecodeTest{ + @Override + protected void init() { + testName = "AutoOverloadingMultiResults"; + rootDirectory = System.getProperty("user.dir")+"/test/bytecode/types/"; + } + + @Test + @Ignore + public void testConstruct() throws Exception{ + ClassLoader classLoader = getClassLoader(); + + Class cls = classLoader.loadClass(testName); + + Object obj = cls.newInstance(); + assertTrue(true); + } +} diff --git a/test/bytecode/types/AutoOverloadingVectorTest.java b/test/bytecode/types/AutoOverloadingVectorTest.java index aa4264b7..8dfe1d70 100644 --- a/test/bytecode/types/AutoOverloadingVectorTest.java +++ b/test/bytecode/types/AutoOverloadingVectorTest.java @@ -43,7 +43,7 @@ public class AutoOverloadingVectorTest extends SourceFileBytecodeTest{ URL url = file.toURL(); URL[] urls = new URL[]{url}; - Class string = classLoader.loadClass("java.lang.String"); + Class string = classLoader.loadClass("java%util%Vector%%java%lang%String%"); Class[] params = new Class[1]; params[0] = string; @@ -69,13 +69,13 @@ public class AutoOverloadingVectorTest extends SourceFileBytecodeTest{ URL url = file.toURL(); URL[] urls = new URL[]{url}; - Integer integer = new Integer(123); + Class integer = classLoader.loadClass("java%util%Vector%%java%lang%Integer%"); Class[] params = new Class[1]; - params[0] = integer.getClass(); + params[0] = integer; Method method = cls.getDeclaredMethod("method2", params); - method.invoke(obj, integer); + method.invoke(obj, integer.newInstance()); assertTrue(true); }catch(Exception e){ throw new RuntimeException(e); diff --git a/test/bytecode/types/ExtendsType.jav b/test/bytecode/types/ExtendsType.jav index 9b03238b..8bd50b6f 100644 --- a/test/bytecode/types/ExtendsType.jav +++ b/test/bytecode/types/ExtendsType.jav @@ -1,6 +1,6 @@ import java.util.Vector; -class SuperType{ +class ExtendsType{ Vector integerVector; void method() { diff --git a/test/bytecode/types/ExtendsTypeTest.java b/test/bytecode/types/ExtendsTypeTest.java index eb753389..a3560b9c 100644 --- a/test/bytecode/types/ExtendsTypeTest.java +++ b/test/bytecode/types/ExtendsTypeTest.java @@ -16,7 +16,7 @@ import bytecode.SourceFileBytecodeTest; public class ExtendsTypeTest extends SourceFileBytecodeTest{ @Override protected void init() { - testName = "SuperType"; + testName = "ExtendsType"; rootDirectory = System.getProperty("user.dir")+"/test/bytecode/types/"; } diff --git a/test/bytecode/types/ExtendsVectorStringTest.java b/test/bytecode/types/ExtendsVectorStringTest.java index d3ed9fb3..f92c61ad 100644 --- a/test/bytecode/types/ExtendsVectorStringTest.java +++ b/test/bytecode/types/ExtendsVectorStringTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.*; import java.lang.reflect.Constructor; import java.lang.reflect.Method; +import java.util.Vector; import org.junit.BeforeClass; import org.junit.Test; @@ -60,13 +61,13 @@ public class ExtendsVectorStringTest extends ASTBytecodeTest{ Object obj = cls.newInstance(); - Class stringClass = classLoader.loadClass("java.lang.Object"); + Class objectClass = classLoader.loadClass("java.lang.Object"); Class[] params = new Class[1]; - params[0] = stringClass; + params[0] = objectClass; Method method = cls.getDeclaredMethod("add", params); - method.invoke(obj, stringClass.newInstance()); + method.invoke(obj, objectClass.newInstance()); }catch(Exception e){ throw new RuntimeException(e); } @@ -83,5 +84,9 @@ public class ExtendsVectorStringTest extends ASTBytecodeTest{ public String getTestName() { return "ExtendsVectorString"; } + + class StringVector extends Vector{ + + } } From 47c9be54881d99c5facca963a9364aafdca79efd Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Tue, 22 Mar 2016 13:17:56 +0100 Subject: [PATCH 03/13] =?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 1e9d0517f267fcab122dbe1113f74ab77287e839 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Thu, 24 Mar 2016 11:57:17 +0100 Subject: [PATCH 04/13] 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 05/13] 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 b4d7ab02eb4e42dec409c34e30af91ff10ecee0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrico=20Schr=C3=B6dter?= Date: Mon, 28 Mar 2016 10:33:04 +0200 Subject: [PATCH 06/13] =?UTF-8?q?-=20UnitTest=20f=C3=BCr=20MultiExtends=20?= =?UTF-8?q?Problem=20-=20Verhindern=20von=20doppelten=20Methoden=20von=20C?= =?UTF-8?q?lass=20->=20ClassGen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bytecode/ClassGenerator.java | 20 +++++++++++ src/de/dhbwstuttgart/syntaxtree/Class.java | 9 ----- src/de/dhbwstuttgart/syntaxtree/Method.java | 5 --- .../AutoOverloadingMultiResultsTest.java | 1 - test/bytecode/types/MultiExtends.jav | 11 ++++++ test/bytecode/types/MultiExtendsTest.java | 35 +++++++++++++++++++ 6 files changed, 66 insertions(+), 15 deletions(-) create mode 100644 test/bytecode/types/MultiExtends.jav create mode 100644 test/bytecode/types/MultiExtendsTest.java diff --git a/src/de/dhbwstuttgart/bytecode/ClassGenerator.java b/src/de/dhbwstuttgart/bytecode/ClassGenerator.java index a13ed914..ef556c50 100644 --- a/src/de/dhbwstuttgart/bytecode/ClassGenerator.java +++ b/src/de/dhbwstuttgart/bytecode/ClassGenerator.java @@ -1,8 +1,12 @@ package de.dhbwstuttgart.bytecode; +import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; import java.util.Map; +import java.util.Vector; import org.apache.commons.bcel6.classfile.BootstrapMethod; import org.apache.commons.bcel6.classfile.BootstrapMethods; @@ -10,6 +14,7 @@ import org.apache.commons.bcel6.classfile.ConstantPool; import org.apache.commons.bcel6.classfile.InnerClass; import org.apache.commons.bcel6.classfile.InnerClasses; import org.apache.commons.bcel6.classfile.JavaClass; +import org.apache.commons.bcel6.classfile.Method; import org.apache.commons.bcel6.classfile.Signature; import org.apache.commons.bcel6.generic.ClassGen; import org.apache.commons.bcel6.generic.ConstantPoolGen; @@ -34,6 +39,7 @@ public class ClassGenerator extends ClassGen{ private Menge usedTPHs = new Menge<>(); private Map extraClasses = new HashMap<>(); + private List methodsNamesAndTypes = new LinkedList<>(); public ClassGenerator(String name, Type superClass, String string, short accessflags, String[] strings, TypeinferenceResults typeinferenceResults) { super(name,superClass.get_Name(),string,accessflags,strings, new DHBWConstantPoolGen()); @@ -162,6 +168,20 @@ public class ClassGenerator extends ClassGen{ public TypeinferenceResults getTypeinferenceResults() { return tiResult; } + + @Override + public void addMethod(Method m) { + String methodNameAndTypes = m.getName()+Arrays.toString(m.getArgumentTypes()); + + if(methodsNamesAndTypes.contains(methodNameAndTypes)){ + return; + } + + methodsNamesAndTypes.add(methodNameAndTypes); + super.addMethod(m); + } + + diff --git a/src/de/dhbwstuttgart/syntaxtree/Class.java b/src/de/dhbwstuttgart/syntaxtree/Class.java index a746b8c9..09c33f80 100755 --- a/src/de/dhbwstuttgart/syntaxtree/Class.java +++ b/src/de/dhbwstuttgart/syntaxtree/Class.java @@ -74,7 +74,6 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I protected UsedId pkgName; protected Modifiers modifiers; protected String name; - private List methodSignaturesAndNames = new LinkedList<>(); /** * @@ -1042,14 +1041,6 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I public boolean isInterface(){ return false; } - - protected boolean methodExists(String nameAndSignature) { - return methodSignaturesAndNames.contains(nameAndSignature); - } - - protected void addMethod(String nameAndSignature) { - methodSignaturesAndNames.add(nameAndSignature); - } /* private Collection getGenericClasses() { diff --git a/src/de/dhbwstuttgart/syntaxtree/Method.java b/src/de/dhbwstuttgart/syntaxtree/Method.java index 8a3370fb..ebed1381 100755 --- a/src/de/dhbwstuttgart/syntaxtree/Method.java +++ b/src/de/dhbwstuttgart/syntaxtree/Method.java @@ -634,10 +634,6 @@ public class Method extends Field implements IItemWithOffset, TypeInsertable Logger.getLogger("nameAndSignature").error(nameAndSignature, Section.CODEGEN); - if(classObj.methodExists(nameAndSignature)){ - Logger.getLogger("methodExists").debug(this.toString(), Section.CODEGEN); - continue; - } short constants = Constants.ACC_PUBLIC; //Per Definition ist jede Methode public if(this.modifiers != null && this.modifiers.includesModifier(new Static())) constants += Constants.ACC_STATIC; @@ -649,7 +645,6 @@ public class Method extends Field implements IItemWithOffset, TypeInsertable //Methode generieren und anfügen: cg.addMethod(method.createMethod(cg, getParameterList(), returnType, get_Block(), t)); - classObj.addMethod(nameAndSignature); Logger.getLogger("createMethod").debug(this.toString(), Section.CODEGEN); } diff --git a/test/bytecode/types/AutoOverloadingMultiResultsTest.java b/test/bytecode/types/AutoOverloadingMultiResultsTest.java index 37fa57a7..ce34f3f7 100644 --- a/test/bytecode/types/AutoOverloadingMultiResultsTest.java +++ b/test/bytecode/types/AutoOverloadingMultiResultsTest.java @@ -24,7 +24,6 @@ public class AutoOverloadingMultiResultsTest extends SourceFileBytecodeTest{ } @Test - @Ignore public void testConstruct() throws Exception{ ClassLoader classLoader = getClassLoader(); diff --git a/test/bytecode/types/MultiExtends.jav b/test/bytecode/types/MultiExtends.jav new file mode 100644 index 00000000..d4ada054 --- /dev/null +++ b/test/bytecode/types/MultiExtends.jav @@ -0,0 +1,11 @@ +import java.util.Vector; + +class MultiExtends{ + Integer method(Vector a){ + return method2(a); + } + + Integer method2(Vector b){ + return 1; + } +} \ No newline at end of file diff --git a/test/bytecode/types/MultiExtendsTest.java b/test/bytecode/types/MultiExtendsTest.java new file mode 100644 index 00000000..066ad1ff --- /dev/null +++ b/test/bytecode/types/MultiExtendsTest.java @@ -0,0 +1,35 @@ +package bytecode.types; + +import static org.junit.Assert.*; + +import java.io.File; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Vector; + +import org.junit.Test; + +import org.junit.Ignore; + +import bytecode.SourceFileBytecodeTest; + + +public class MultiExtendsTest extends SourceFileBytecodeTest{ + @Override + protected void init() { + testName = "MultiExtends"; + rootDirectory = System.getProperty("user.dir")+"/test/bytecode/types/"; + } + + @Test + public void testConstruct() throws Exception{ + ClassLoader classLoader = getClassLoader(); + + Class cls = classLoader.loadClass(testName); + + Object obj = cls.newInstance(); + assertTrue(true); + } +} From fa337c554612f297acfc5979c822971fdb1a828c Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Tue, 29 Mar 2016 13:23:05 +0200 Subject: [PATCH 07/13] 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 08/13] 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 b51079280e503dfdb86bdd57aa42cf383840caba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrico=20Schr=C3=B6dter?= Date: Wed, 30 Mar 2016 10:09:17 +0200 Subject: [PATCH 09/13] - New Statement, Problem Syntax des Klassennamens --- src/de/dhbwstuttgart/syntaxtree/Class.java | 2 +- src/de/dhbwstuttgart/syntaxtree/Field.java | 3 +- .../syntaxtree/FieldDeclaration.java | 6 ++-- .../syntaxtree/FormalParameter.java | 5 +-- .../syntaxtree/SyntaxTreeNode.java | 6 ++-- .../syntaxtree/statement/Block.java | 2 +- .../syntaxtree/statement/LocalVarDecl.java | 2 +- .../syntaxtree/statement/NewClass.java | 4 +-- .../syntaxtree/statement/Statement.java | 2 +- .../syntaxtree/type/RefType.java | 7 ++++ test/bytecode/Parameter.jav | 3 ++ test/bytecode/ParameterTest.java | 34 +++++++++++++++++++ test/bytecode/types/AutoOverloadingVector.jav | 2 +- 13 files changed, 63 insertions(+), 15 deletions(-) create mode 100644 test/bytecode/Parameter.jav create mode 100644 test/bytecode/ParameterTest.java diff --git a/src/de/dhbwstuttgart/syntaxtree/Class.java b/src/de/dhbwstuttgart/syntaxtree/Class.java index 09c33f80..e2d97772 100755 --- a/src/de/dhbwstuttgart/syntaxtree/Class.java +++ b/src/de/dhbwstuttgart/syntaxtree/Class.java @@ -993,7 +993,7 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I } @Override - public String getDescription(){ + public String getDescription(ClassGenerator cg, TypeinferenceResultSet rs){ return "class "+this.getName(); } @Override diff --git a/src/de/dhbwstuttgart/syntaxtree/Field.java b/src/de/dhbwstuttgart/syntaxtree/Field.java index fabc1328..25e97f78 100644 --- a/src/de/dhbwstuttgart/syntaxtree/Field.java +++ b/src/de/dhbwstuttgart/syntaxtree/Field.java @@ -16,6 +16,7 @@ import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeInsertable; import de.dhbwstuttgart.typeinference.Typeable; +import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.typedeployment.TypeInsertPoint; @@ -107,7 +108,7 @@ public abstract class Field extends GTVDeclarationContext implements TypeInserta } @Override - public String getDescription(){ + public String getDescription(ClassGenerator cg, TypeinferenceResultSet rs){ return this.getIdentifier(); } diff --git a/src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java b/src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java index 7aba86b2..08f0df8d 100644 --- a/src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java +++ b/src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java @@ -173,7 +173,7 @@ public class FieldDeclaration extends Field{ */ public InstructionList genByteCode(ClassGenerator cg, TypeinferenceResultSet rs) { //Das Feld an die Klasse anfügen: - FieldGen field = new FieldGen(0, this.getType().getBytecodeType(cg, rs), this.getDescription(), cg.getConstantPool()); + FieldGen field = new FieldGen(0, this.getType().getBytecodeType(cg, rs), this.getDescription(cg, rs), cg.getConstantPool()); field.addAttribute(cg.getInstructionFactory().createSignatureAttribute(this.getType().getBytecodeSignature(cg, rs))); cg.addField(field.getField()); @@ -183,11 +183,11 @@ public class FieldDeclaration extends Field{ il.append(this.wert.genByteCode(cg, rs)); FieldInstruction putFieldInstruction = cg.getInstructionFactory().createFieldAccess(this.getParentClass().getName().toString(), - this.getDescription(), this.getType().getBytecodeType(cg, rs), Constants.PUTFIELD); + this.getDescription(cg, rs), this.getType().getBytecodeType(cg, rs), Constants.PUTFIELD); il.append(putFieldInstruction ); return il; } - + /*@Override public void genByteCode(ClassGen cg) { // TODO Auto-generated method stub diff --git a/src/de/dhbwstuttgart/syntaxtree/FormalParameter.java b/src/de/dhbwstuttgart/syntaxtree/FormalParameter.java index d3df4039..f897ac05 100755 --- a/src/de/dhbwstuttgart/syntaxtree/FormalParameter.java +++ b/src/de/dhbwstuttgart/syntaxtree/FormalParameter.java @@ -4,7 +4,7 @@ package de.dhbwstuttgart.syntaxtree; // ino.module.FormalParameter.8561.import import de.dhbwstuttgart.typeinference.Menge; - +import de.dhbwstuttgart.bytecode.ClassGenerator; import de.dhbwstuttgart.logger.Logger; import de.dhbwstuttgart.syntaxtree.misc.DeclId; @@ -14,6 +14,7 @@ import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeInsertable; import de.dhbwstuttgart.typeinference.Typeable; +import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; import de.dhbwstuttgart.typeinference.typedeployment.TypeInsertPoint; @@ -233,7 +234,7 @@ public class FormalParameter extends SyntaxTreeNode implements Typeable, TypeIns } @Override - public String getDescription() { + public String getDescription(ClassGenerator cg, TypeinferenceResultSet rs){ String ret = ""; if(this.getType() != null && !(this.getType() instanceof TypePlaceholder)){ ret += this.getType().getBytecodeSignature(null, null); diff --git a/src/de/dhbwstuttgart/syntaxtree/SyntaxTreeNode.java b/src/de/dhbwstuttgart/syntaxtree/SyntaxTreeNode.java index f76249ba..b557ed74 100644 --- a/src/de/dhbwstuttgart/syntaxtree/SyntaxTreeNode.java +++ b/src/de/dhbwstuttgart/syntaxtree/SyntaxTreeNode.java @@ -3,6 +3,7 @@ package de.dhbwstuttgart.syntaxtree; import org.apache.commons.bcel6.generic.ClassGen; import de.dhbwstuttgart.typeinference.Menge; +import de.dhbwstuttgart.bytecode.ClassGenerator; import de.dhbwstuttgart.core.IItemWithOffset; import de.dhbwstuttgart.syntaxtree.type.GenericTypeVar; import de.dhbwstuttgart.syntaxtree.type.Type; @@ -10,6 +11,7 @@ import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeInsertable; +import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.exceptions.DebugException; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; import de.dhbwstuttgart.typeinference.typedeployment.GenericTypeInsertPoint; @@ -55,7 +57,7 @@ public abstract class SyntaxTreeNode implements IItemWithOffset{ * Eine Beschreibung/Name des SyntaxTree-Nodes * @return */ - public String getDescription(){ + public String getDescription(ClassGenerator cg, TypeinferenceResultSet rs){ return this.toString(); } @@ -64,7 +66,7 @@ public abstract class SyntaxTreeNode implements IItemWithOffset{ public boolean equals(Object object){ if(!(object instanceof SyntaxTreeNode))return false; SyntaxTreeNode equal = (SyntaxTreeNode)object; - if(!equal.getDescription().equals(this.getDescription()))return false; + if(!equal.getDescription(null, null).equals(this.getDescription(null, null)))return false; if(this.getParent()!=null) if(!this.getParent().equals(equal.getParent()))return false; //auch das Elternelement überprüfen. return true; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/Block.java b/src/de/dhbwstuttgart/syntaxtree/statement/Block.java index a149a0cf..2625da53 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/Block.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/Block.java @@ -252,7 +252,7 @@ public class Block extends Statement } @Override - public String getDescription(){ + public String getDescription(ClassGenerator cg, TypeinferenceResultSet rs){ return "Block"; } diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/LocalVarDecl.java b/src/de/dhbwstuttgart/syntaxtree/statement/LocalVarDecl.java index e03c1f81..423e143f 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/LocalVarDecl.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/LocalVarDecl.java @@ -379,7 +379,7 @@ public class LocalVarDecl extends Statement implements TypeInsertable } @Override - public String getDescription() { + public String getDescription(ClassGenerator cg, TypeinferenceResultSet rs){ if(this.getType() == null)return "no type " + declid.toString(); if(this.getType() instanceof TypePlaceholder)return declid.toString(); return this.getType().toString() + " " + declid.toString(); diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/NewClass.java b/src/de/dhbwstuttgart/syntaxtree/statement/NewClass.java index eefc048b..079f652c 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/NewClass.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/NewClass.java @@ -202,11 +202,11 @@ public class NewClass extends Expr if(arglist!=null){ il.append(arglist.generateBytecode(_cg, rs)); - il.append(_cg.getInstructionFactory().createInvoke(this.getType().getDescription(), "", + il.append(_cg.getInstructionFactory().createInvoke(this.getType().getDescription(_cg, rs), "", org.apache.commons.bcel6.generic.Type.VOID, this.arglist.getBytecodeTypeList(_cg, rs), Constants.INVOKESPECIAL)); }else{ - il.append(_cg.getInstructionFactory().createInvoke(this.getType().getDescription(), "", + il.append(_cg.getInstructionFactory().createInvoke(this.getType().getDescription(_cg, rs), "", org.apache.commons.bcel6.generic.Type.VOID, new org.apache.commons.bcel6.generic.Type[]{}, Constants.INVOKESPECIAL)); } diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/Statement.java b/src/de/dhbwstuttgart/syntaxtree/statement/Statement.java index d6e2e9f8..4e1ce702 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/Statement.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/Statement.java @@ -119,7 +119,7 @@ public abstract class Statement extends SyntaxTreeNode implements IItemWithOffse public abstract JavaCodeResult printJavaCode(ResultSet resultSet); @Override - public String getDescription(){ + public String getDescription(ClassGenerator cg, TypeinferenceResultSet rs){ return this.printJavaCode(new ResultSet(new Menge())).toString(); } diff --git a/src/de/dhbwstuttgart/syntaxtree/type/RefType.java b/src/de/dhbwstuttgart/syntaxtree/type/RefType.java index ba03d583..0e8199e7 100755 --- a/src/de/dhbwstuttgart/syntaxtree/type/RefType.java +++ b/src/de/dhbwstuttgart/syntaxtree/type/RefType.java @@ -874,6 +874,13 @@ public class RefType extends ObjectType implements IMatchable public GenericClassType getGenericClassType(){ return new GenericClassType(getName().toString(), getParaList(), parent, getOffset()); } + + @Override + public String getDescription(ClassGenerator cg, TypeinferenceResultSet rs) { + return getBytecodeSignature(cg, rs); + } + + } // ino.end diff --git a/test/bytecode/Parameter.jav b/test/bytecode/Parameter.jav new file mode 100644 index 00000000..18517679 --- /dev/null +++ b/test/bytecode/Parameter.jav @@ -0,0 +1,3 @@ +class Parameter{ + public String param; +} \ No newline at end of file diff --git a/test/bytecode/ParameterTest.java b/test/bytecode/ParameterTest.java new file mode 100644 index 00000000..cd06eeef --- /dev/null +++ b/test/bytecode/ParameterTest.java @@ -0,0 +1,34 @@ +package bytecode; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; + +import junit.framework.TestCase; + +import org.junit.Test; + +import plugindevelopment.TypeInsertTester; +import de.dhbwstuttgart.core.MyCompiler; +import de.dhbwstuttgart.core.MyCompilerAPI; +import de.dhbwstuttgart.logger.LoggerConfiguration; +import de.dhbwstuttgart.logger.Section; +import de.dhbwstuttgart.parser.JavaParser.yyException; +import de.dhbwstuttgart.typeinference.ByteCodeResult; +import de.dhbwstuttgart.typeinference.Menge; +import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; +import de.dhbwstuttgart.typeinference.typedeployment.TypeInsertSet; + +public class ParameterTest { + + public final static String rootDirectory = System.getProperty("user.dir")+"/test/bytecode/"; + public final static String testFile = "Parameter.jav"; + public final static String outputFile = "Parameter.class"; + + @Test + public void test() { + SingleClassTester.compileToBytecode(rootDirectory+testFile, rootDirectory+outputFile); + } + +} diff --git a/test/bytecode/types/AutoOverloadingVector.jav b/test/bytecode/types/AutoOverloadingVector.jav index 4a3b1197..eb65ae4c 100644 --- a/test/bytecode/types/AutoOverloadingVector.jav +++ b/test/bytecode/types/AutoOverloadingVector.jav @@ -1,6 +1,6 @@ import java.util.Vector; -class AutoOverloadingVector{ +class AutoOverloadingVector{ method2(p){ method(p); } From 5b07d580934fa934db9590d888f12ea10de36b78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrico=20Schr=C3=B6dter?= Date: Wed, 30 Mar 2016 10:14:05 +0200 Subject: [PATCH 10/13] - Klassenvariable ohne Wert --- src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java b/src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java index 08f0df8d..7cc3c54b 100644 --- a/src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java +++ b/src/de/dhbwstuttgart/syntaxtree/FieldDeclaration.java @@ -180,7 +180,13 @@ public class FieldDeclaration extends Field{ //Die Felddekleration an den Konstruktor anhängen: InstructionList il = new InstructionList(); il.append(new This(this).genByteCode(cg, rs)); - il.append(this.wert.genByteCode(cg, rs)); + + if(wert != null){ + il.append(this.wert.genByteCode(cg, rs)); + }else{ + //todo: default wert? + } + FieldInstruction putFieldInstruction = cg.getInstructionFactory().createFieldAccess(this.getParentClass().getName().toString(), this.getDescription(cg, rs), this.getType().getBytecodeType(cg, rs), Constants.PUTFIELD); From 8d8e27c84cb5643264d294fcd53d441ecfaf3259 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrico=20Schr=C3=B6dter?= Date: Thu, 31 Mar 2016 08:52:23 +0200 Subject: [PATCH 11/13] - Bugfix new Statement, Deskription darf nicht mit Semikolon enden --- src/de/dhbwstuttgart/syntaxtree/type/RefType.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/de/dhbwstuttgart/syntaxtree/type/RefType.java b/src/de/dhbwstuttgart/syntaxtree/type/RefType.java index 0e8199e7..aded666a 100755 --- a/src/de/dhbwstuttgart/syntaxtree/type/RefType.java +++ b/src/de/dhbwstuttgart/syntaxtree/type/RefType.java @@ -877,11 +877,9 @@ public class RefType extends ObjectType implements IMatchable @Override public String getDescription(ClassGenerator cg, TypeinferenceResultSet rs) { - return getBytecodeSignature(cg, rs); + String signature = getBytecodeSignature(cg, rs); + return signature.substring(1, signature.length()-1); } - - - } // ino.end From 4cdcde8fefe8f841c9a26462e6777129599175ec Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Fri, 1 Apr 2016 16:12:30 +0200 Subject: [PATCH 12/13] 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 13/13] 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));