diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs index 5c6e1080..1f0adda8 100755 --- a/.settings/org.eclipse.core.resources.prefs +++ b/.settings/org.eclipse.core.resources.prefs @@ -1,6 +1,7 @@ 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 encoding/=UTF-8 diff --git a/src/de/dhbwstuttgart/myexception/NotImplementedException.java b/src/de/dhbwstuttgart/myexception/NotImplementedException.java index bbaf52c6..d4e90ca1 100644 --- a/src/de/dhbwstuttgart/myexception/NotImplementedException.java +++ b/src/de/dhbwstuttgart/myexception/NotImplementedException.java @@ -2,6 +2,14 @@ package de.dhbwstuttgart.myexception; public class NotImplementedException extends RuntimeException { + public NotImplementedException(String message) { + super(message); + } + + public NotImplementedException() { + super("Nicht implementiert"); + } + /** * */ diff --git a/src/de/dhbwstuttgart/parser/JavaParser.jay b/src/de/dhbwstuttgart/parser/JavaParser.jay index 553ad069..b4f760e7 100755 --- a/src/de/dhbwstuttgart/parser/JavaParser.jay +++ b/src/de/dhbwstuttgart/parser/JavaParser.jay @@ -1693,7 +1693,7 @@ assignment :lefthandside assignmentoperator assignmentexpr { de.dhbwstuttgart.logger.Logger.getLogger("parser").debug("\nParser --> Zuweisung1!\n", Section.PARSER); Assign Ass = new Assign($1.getOffset(),$1.getVariableLength()); - LocalOrFieldVar LOFV = new LocalOrFieldVar($1.getOffset(),$1.getVariableLength()); + LocalOrFieldVarOrClassname LOFV = new LocalOrFieldVarOrClassname($1.getOffset(),$1.getVariableLength()); LOFV.set_UsedId($1); //auskommentiert von Andreas Stadelmeier (a10023) LOFV.setType(TypePlaceholder.fresh()); //auskommentiert von Andreas Stadelmeier (a10023) Ass.setType(TypePlaceholder.fresh()); @@ -1717,7 +1717,7 @@ assignment :lefthandside assignmentoperator assignmentexpr | lefthandside assignmentoperator classinstancecreationexpression { Assign Ass =new Assign($1.getOffset(),$1.getVariableLength()); - LocalOrFieldVar LOFV = new LocalOrFieldVar($1.getOffset(),$1.getVariableLength()); + LocalOrFieldVarOrClassname LOFV = new LocalOrFieldVarOrClassname($1.getOffset(),$1.getVariableLength()); LOFV.set_UsedId($1); //auskommentiert von Andreas Stadelmeier (a10023) LOFV.setType(TypePlaceholder.fresh()); //auskommentiert von Andreas Stadelmeier (a10023) Ass.setType(TypePlaceholder.fresh()); @@ -1939,7 +1939,7 @@ methodinvocation: rec = new Receiver(INSTVA); } else if ($1.get_Name().size() == 2) { - LocalOrFieldVar LOFV = new LocalOrFieldVar($1.getOffset(),$1.getVariableLength()); + LocalOrFieldVarOrClassname LOFV = new LocalOrFieldVarOrClassname($1.getOffset(),$1.getVariableLength()); $1.removeLast(); LOFV.set_UsedId($1); //auskommentiert von Andreas Stadelmeier (a10023) LOFV.setType(TypePlaceholder.fresh()); @@ -1969,7 +1969,7 @@ methodinvocation: rec = new Receiver(INSTVA); } else if ($1.get_Name().size() == 2) { - LocalOrFieldVar LOFV = new LocalOrFieldVar($1.getOffset(),$1.getVariableLength()); + LocalOrFieldVarOrClassname LOFV = new LocalOrFieldVarOrClassname($1.getOffset(),$1.getVariableLength()); $1.removeLast(); LOFV.set_UsedId($1); //auskommentiert von Andreas Stadelmeier (a10023) LOFV.setType(TypePlaceholder.fresh()); @@ -2105,7 +2105,7 @@ postfixexpression :primary $$ = INSTVA; } else { - LocalOrFieldVar Postincexpr = new LocalOrFieldVar($1.getOffset(),$1.getVariableLength()); + LocalOrFieldVarOrClassname Postincexpr = new LocalOrFieldVarOrClassname($1.getOffset(),$1.getVariableLength()); Postincexpr.set_UsedId($1); //auskommentiert von Andreas Stadelmeier (a10023) Postincexpr.setType(TypePlaceholder.fresh()); $$=Postincexpr; diff --git a/src/de/dhbwstuttgart/syntaxtree/Class.java b/src/de/dhbwstuttgart/syntaxtree/Class.java index 09c33f80..10ea63f1 100755 --- a/src/de/dhbwstuttgart/syntaxtree/Class.java +++ b/src/de/dhbwstuttgart/syntaxtree/Class.java @@ -49,7 +49,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.*; @@ -170,59 +169,30 @@ public class Class extends GTVDeclarationContext implements AClassOrInterface, I { this.superif = superif; } - - // ino.attribute.superclassid.23014.decldescription type=line - // private Status status; - // ino.end - // ino.attribute.superclassid.23014.declaration - public UsedId superclassid = (SourceFile.READ_OBJECT_SUPERCLASSES_FROM_JRE?UsedId.createFromQualifiedName("Object",-1):null); - // ino.end - // ino.attribute.class_block.23020.decldescription type=line - // private Class java; - // ino.end - // ino.attribute.class_block.23020.declaration - private Block class_block; - // ino.end - // ino.attribute.paralist.23023.declaration - //private Menge paralist = new Menge(); // Parameterliste 'class xy{}' wird gespeichert - // ino.end - // ino.attribute.parahash.23026.declaration - private Hashtable parahash = new Hashtable(); // parametrisierten Attrib. werden mit den Paramet.aus paralist verk. - // ino.end - // ino.attribute.isFirstLocalVarDecl.23029.declaration - public static boolean isFirstLocalVarDecl; //Hilfsvariable fuer Offsets, hoth - // ino.end - //private Menge genericClassParameters=new Menge(); - - // ino.attribute.containedTypes.23032.decldescription type=line + public UsedId superclassid = (SourceFile.READ_OBJECT_SUPERCLASSES_FROM_JRE?UsedId.createFromQualifiedName("Object",-1):null); + + private Block class_block; + + private Hashtable parahash = new Hashtable(); // parametrisierten Attrib. werden mit den Paramet.aus paralist verk. + + public static boolean isFirstLocalVarDecl; //Hilfsvariable fuer Offsets, hoth // PL 05-07-30 eingefuegt. Vektor aller Typdeklarationen, die in der Klasse // vorkommen. Wird in der Studienarbeit von Andreas Stadelmeier nur für Verifizierung der Tests eingesetzt. - // ino.end - // ino.attribute.containedTypes.23032.declaration private Menge containedTypes = new Menge(); - // ino.end - // ino.attribute.usedIdsToCheck.23035.declaration private Menge usedIdsToCheck = new Menge(); - // ino.end private TypeAssumptions typeAssumptions = null;//muss mit null Initialisiert werden. Darf nur über getTypeAssumptions abgerufen werden. - // ino.attribute.parserlog.23038.declaration - //protected Logger parselog = Logger.getLogger("parser"); - // ino.end protected Logger typinferenzLog = Logger.getLogger(Class.class.getName()); private SyntaxTreeNode parent; private Menge fielddecl = new Menge(); private GenericDeclarationList genericClassParameters; private int offset; - private Type superClass; + private RefType superClass; - // ino.method.Class.23041.definition public Class(String name, int offset) - // ino.end - // ino.method.Class.23041.body { this.name = name; if(name.equals("java.lang.Object")){ @@ -242,7 +212,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<>(); @@ -263,7 +233,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; @@ -295,14 +265,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; @@ -316,7 +286,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 { @@ -627,7 +597,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 { @@ -639,8 +609,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: ////////////////////////////// @@ -673,7 +642,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)); @@ -1030,7 +1000,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/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 f4fa56e7..dce25711 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/SourceFile.java b/src/de/dhbwstuttgart/syntaxtree/SourceFile.java index cea600d1..bc4c39ef 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,29 +40,27 @@ 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; 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; 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.UnifyPair; - -// 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 +171,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 +186,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 +200,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,63 +238,66 @@ 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: + //Typen in UnifyTypen umwandeln: //////////////// + UnifyConstraintsSet unifyConstraints = UnifyTypeFactory.convert(oderConstraints); //Unmögliche ConstraintsSets aussortieren durch Unifizierung - Unifier unifier = (pairs)->{ - Menge> retValue = new Menge<>(); - retValue = Unify.unify(pairs, 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); + + typinferenzLog.debug("Übriggebliebene Konvertierte Konstraints:\n"+unifyConstraints+"\n", Section.TYPEINFERENCE); + + //////////////// + //Karthesisches Produkt bilden: + //////////////// + Set> xConstraints = unifyConstraints.cartesianProduct(); + - typinferenzLog.debug("Übriggebliebene Konstraints:\n"+oderConstraints+"\n", Section.TYPEINFERENCE); - //Die Constraints in Pair's umwandeln (Karthesisches Produkt bilden): - Menge> xConstraints = oderConstraints.cartesianProduct(); - + + typinferenzLog.debug("Finite Closure: "+finiteClosure, Section.TYPEINFERENCE); 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>(); - - //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(); + //Menge> result = new Menge>(); //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;} @@ -762,17 +312,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 +335,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); @@ -808,10 +358,23 @@ public class SourceFile return new Menge<>(); //kein unifiziertes Ergebnis, damit wird das Geseamtergebnis [] return cardprodret; }); - + */ + typinferenzLog.debug("\nUnifiziere Constraints:\n"+constraints, Section.TYPEINFERENCE); + Set> unifyResult = new Unify().unify(constraints, finiteClosure); + + Menge> convertedResult = unifyResult.parallelStream().>map((Set resultSet)->{ + Menge innerConvert = resultSet.stream().map((UnifyPair mp)->UnifyTypeFactory.convert(mp)) + .collect(Menge::new, Menge::add, Menge::addAll); + return innerConvert; + }).collect(Menge::new, Menge::add, Menge::addAll); + + Menge convertedConstraints = constraints.stream().map( + (UnifyPair mp)->{return UnifyTypeFactory.convert(mp);} + ).collect(Menge::new, Menge::add, Menge::addAll); + //Dann den Ergebnissen anfügen typinferenzLog.debug("\nErgebnis der Unifizierung:\n"+unifyResult, Section.TYPEINFERENCE); - result.addAll(unifyResult); + //result.addAll(convertedResult); typinferenzLog.debug("\nJavaFiles:\n", Section.TYPEINFERENCE); @@ -821,10 +384,10 @@ public class SourceFile //Für jede Klasse in diesem SourceFile gilt das selbe ResultSet: for(Class klasse : this.KlassenVektor){ //Der Unifikationsalgorithmus kann wiederum auch mehrere Lösungen errechnen, diese werden im folgenden durchlaufen: - for(Menge resultSet : result){ + for(Menge resultSet : convertedResult){ unifyFail = false; //Ein Unifiziertes Ergebnis ist entstanden (es kann auch leer sein, das bedeutet nur, dass die Constraints mindestens in einem Fall Sinn ergaben) //Add Result set as a new ReconstructionResult to ret: - TypeinferenceResultSet reconstructionResult = new TypeinferenceResultSet(klasse, constraints, new ResultSet(resultSet)); + TypeinferenceResultSet reconstructionResult = new TypeinferenceResultSet(klasse, convertedConstraints, new ResultSet(resultSet)); ret.add(reconstructionResult); //ResultSet res = new ResultSet(resultSet); 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 c718a7bf..1f14bb34 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -1,8 +1,10 @@ package de.dhbwstuttgart.syntaxtree.factory; 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; @@ -11,43 +13,66 @@ 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; import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; -import de.dhbwstuttgart.typeinference.unify.model.SimpleType; +import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; +import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; -public class UnifyTypeFactory { +public class UnifyTypeFactory { + + private final static NullSyntaxTreeNode NULL_NODE = new NullSyntaxTreeNode(); + public static FiniteClosure generateFC(TypeAssumptions fromAss){ - HashSet pairs = new HashSet<>(); + HashSet pairs = new HashSet<>(); for(ClassAssumption cAss : fromAss.getClassAssumptions()){ UnifyType tl = UnifyTypeFactory.convert(cAss.getAssumedClass().getType()); - Type superClass = cAss.getAssumedClass().getSuperClass(); + RefType superClass = cAss.getAssumedClass().getSuperClass(); if(superClass != null){ UnifyType tr = UnifyTypeFactory.convert(superClass); - pairs.add(smaller(tl, tr)); + pairs.add(generateSmallerPair(tl, tr)); } } return new FiniteClosure(pairs); } - public static MPair smaller(UnifyType tl, UnifyType tr){ - return new MPair(tl, tr,MPair.PairOperator.SMALLER); + public static UnifyPair generateSmallerPair(UnifyType tl, UnifyType tr){ + return new UnifyPair(tl, tr, PairOperator.SMALLER); } 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); + }else if(t instanceof RefType){ + 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); } - System.out.println("Der Typ "+t+" kann nicht umgewandelt werden"); - throw new NotImplementedException(); + throw new NotImplementedException("Der Typ "+t+" kann nicht umgewandelt werden"); } public static UnifyType convert(RefType t){ @@ -57,9 +82,9 @@ public class UnifyTypeFactory { for(Type pT : t.getParaList()){ params.add(UnifyTypeFactory.convert(pT)); } - ret = new SimpleType(t.get_Name(),params.toArray()); + ret = new ReferenceType(t.get_Name(),new TypeParams(params)); }else{ - ret = new SimpleType(t.get_Name()); + ret = new ReferenceType(t.get_Name()); } return ret; } @@ -77,6 +102,73 @@ public class UnifyTypeFactory { } public static UnifyType convert(GenericTypeVar t){ - return new SimpleType(t.get_Name()); + return new ReferenceType(t.get_Name()); + } + + public static UnifyConstraintsSet convert(ConstraintsSet constraints) { + UnifyConstraintsSet ret = new UnifyConstraintsSet(); + for(OderConstraint oC : constraints.getOderConstraints()){ + ret.add(UnifyTypeFactory.convert(oC)); + } + return ret; + } + + public static UnifyOderConstraint convert(OderConstraint set) { + UnifyOderConstraint ret = new UnifyOderConstraint(); + for(UndConstraint oC : set.getUndConstraints()){ + ret.addConstraint(UnifyTypeFactory.convert(oC)); + } + return ret; + } + + public static UnifyUndConstraint convert(UndConstraint set) { + UnifyUndConstraint ret = new UnifyUndConstraint(); + for(EinzelElement oC : set.getPairs()){ + ret.add(UnifyTypeFactory.convert(oC)); + } + return ret; + } + + public static UnifyPair convert(EinzelElement p) { + return convert(p.getItem()); + } + + public static UnifyPair convert(Pair p) { + if(!p.OperatorSmaller())throw new NotImplementedException(); + UnifyPair ret = generateSmallerPair(UnifyTypeFactory.convert(p.TA1) + , UnifyTypeFactory.convert(p.TA2)); + return ret; + } + + public static Pair convert(UnifyPair mp) { + Type tl = UnifyTypeFactory.convert(mp.getLhsType()); + Type tr = UnifyTypeFactory.convert(mp.getRhsType()); + return new Pair(tl, tr, mp.getPairOp()); + } + + public static Type convert(ReferenceType t) { + return new RefType(t.getName(),null,0); + } + + public static Type convert(SuperType t) { + 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_NODE,0); + return new ExtendsWildcardType(innerType); + } + + public static Type convert(PlaceholderType t) { + return TypePlaceholder.getInstance(t.getName()); + } + + public static Type convert(UnifyType t) { + if(t instanceof ReferenceType)return convert((ReferenceType) t); + if(t instanceof SuperType)return convert((SuperType) t); + if(t instanceof ExtendsType)return convert((ExtendsType) t); + if(t instanceof PlaceholderType)return convert((PlaceholderType) t); + 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 524e729e..1ea4403f 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; @@ -14,18 +13,16 @@ public class Unify_FC_TTO_Builder { public void AddInheritance(Type t1, Type t2) { if(t1 instanceof RefType) - classes.add(new Class(t1.get_Name(), t1.getOffset())); + if(!classes.stream().anyMatch(x -> x.getName().equals(t1.getName()))) + classes.add(new Class(t1.get_Name(), t1.getOffset())); if(t2 instanceof RefType) - classes.add(new Class(t2.get_Name(), t2.getOffset())); - + if(!classes.stream().anyMatch(x -> x.getName().equals(t2.getName()))) + classes.add(new Class(t2.get_Name(), t2.getOffset())); + fc.add(new Pair(t1, t2)); } - 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/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 9e863d01..19132759 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/Assign.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/Assign.java @@ -34,7 +34,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; @@ -108,8 +107,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 035d4c0a..44fc3cc8 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/Binary.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/Binary.java @@ -38,12 +38,10 @@ 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; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/Block.java b/src/de/dhbwstuttgart/syntaxtree/statement/Block.java index a149a0cf..5ac5dc0a 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/Block.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/Block.java @@ -32,12 +32,10 @@ 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; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; @@ -188,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/BoolLiteral.java b/src/de/dhbwstuttgart/syntaxtree/statement/BoolLiteral.java index 87be3f47..c04a8c68 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/BoolLiteral.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/BoolLiteral.java @@ -24,7 +24,6 @@ import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/CastExpr.java b/src/de/dhbwstuttgart/syntaxtree/statement/CastExpr.java index 0cc93bfe..db1f3fb7 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/CastExpr.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/CastExpr.java @@ -25,7 +25,6 @@ import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/CharLiteral.java b/src/de/dhbwstuttgart/syntaxtree/statement/CharLiteral.java index 717b7d2a..c5398b08 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/CharLiteral.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/CharLiteral.java @@ -24,7 +24,6 @@ import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/DoubleLiteral.java b/src/de/dhbwstuttgart/syntaxtree/statement/DoubleLiteral.java index 7661bf86..dc8b83d3 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/DoubleLiteral.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/DoubleLiteral.java @@ -27,7 +27,6 @@ import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/EmptyStmt.java b/src/de/dhbwstuttgart/syntaxtree/statement/EmptyStmt.java index c80d67f3..2786749e 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/EmptyStmt.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/EmptyStmt.java @@ -22,7 +22,6 @@ import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; 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 fb7ca5ce..23131b42 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/IfStmt.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/IfStmt.java @@ -44,11 +44,9 @@ 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; -import de.dhbwstuttgart.typeinference.unify.MUB; import de.dhbwstuttgart.typeinference.unify.Unify; @@ -142,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/IntLiteral.java b/src/de/dhbwstuttgart/syntaxtree/statement/IntLiteral.java index e593d448..725225c1 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/IntLiteral.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/IntLiteral.java @@ -28,7 +28,6 @@ import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/LambdaExpression.java b/src/de/dhbwstuttgart/syntaxtree/statement/LambdaExpression.java index edf8eb33..4acaa018 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/LambdaExpression.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/LambdaExpression.java @@ -41,13 +41,11 @@ 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; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; /** * @author A10023 - Andreas Stadelmeier @@ -199,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/Literal.java b/src/de/dhbwstuttgart/syntaxtree/statement/Literal.java index bee299fe..21aa9f17 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/Literal.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/Literal.java @@ -3,7 +3,6 @@ package de.dhbwstuttgart.syntaxtree.statement; // ino.end import de.dhbwstuttgart.myexception.JVMCodeException; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; // ino.class.Literal.25490.declaration public abstract class Literal extends Expr diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/LocalOrFieldVarOrClassname.java b/src/de/dhbwstuttgart/syntaxtree/statement/LocalOrFieldVarOrClassname.java index c35bd139..2c632bb9 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/LocalOrFieldVarOrClassname.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/LocalOrFieldVarOrClassname.java @@ -28,13 +28,11 @@ 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.ClassAssumption; import de.dhbwstuttgart.typeinference.assumptions.FieldAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/LocalVarDecl.java b/src/de/dhbwstuttgart/syntaxtree/statement/LocalVarDecl.java index a5a319b0..5fb393db 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; @@ -35,7 +34,6 @@ import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.DebugException; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; import de.dhbwstuttgart.typeinference.typedeployment.TypeInsertPoint; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; @@ -372,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/LongLiteral.java b/src/de/dhbwstuttgart/syntaxtree/statement/LongLiteral.java index a127eb4b..fa402791 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/LongLiteral.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/LongLiteral.java @@ -24,7 +24,6 @@ import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/NegativeExpr.java b/src/de/dhbwstuttgart/syntaxtree/statement/NegativeExpr.java index fd5676fa..82a0cfec 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/NegativeExpr.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/NegativeExpr.java @@ -28,7 +28,6 @@ import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; import de.dhbwstuttgart.typeinference.unify.Unify; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/NewArray.java b/src/de/dhbwstuttgart/syntaxtree/statement/NewArray.java index a42de638..953535bf 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/NewArray.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/NewArray.java @@ -22,7 +22,6 @@ import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/NewClass.java b/src/de/dhbwstuttgart/syntaxtree/statement/NewClass.java index eb1405b2..41f8fb0d 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/NewClass.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/NewClass.java @@ -34,13 +34,11 @@ 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; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/NotExpr.java b/src/de/dhbwstuttgart/syntaxtree/statement/NotExpr.java index c7b6dd99..8cf996db 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/NotExpr.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/NotExpr.java @@ -28,7 +28,6 @@ import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; import de.dhbwstuttgart.typeinference.unify.Unify; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/Null.java b/src/de/dhbwstuttgart/syntaxtree/statement/Null.java index aa70e5d1..537aaad7 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/Null.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/Null.java @@ -24,7 +24,6 @@ import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/PositivExpr.java b/src/de/dhbwstuttgart/syntaxtree/statement/PositivExpr.java index 04cef0d5..10cd52f9 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/PositivExpr.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/PositivExpr.java @@ -22,7 +22,6 @@ import de.dhbwstuttgart.typeinference.JavaCodeResult; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/PostDecExpr.java b/src/de/dhbwstuttgart/syntaxtree/statement/PostDecExpr.java index 9b80a94a..0893b076 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/PostDecExpr.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/PostDecExpr.java @@ -28,7 +28,6 @@ import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; import de.dhbwstuttgart.typeinference.unify.Unify; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/PostIncExpr.java b/src/de/dhbwstuttgart/syntaxtree/statement/PostIncExpr.java index 036a5b55..672e5cde 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/PostIncExpr.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/PostIncExpr.java @@ -33,7 +33,6 @@ import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.UndConstraint; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; import de.dhbwstuttgart.typeinference.unify.Unify; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/PreDecExpr.java b/src/de/dhbwstuttgart/syntaxtree/statement/PreDecExpr.java index d8c3ecea..bce1dc97 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/PreDecExpr.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/PreDecExpr.java @@ -28,7 +28,6 @@ import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; import de.dhbwstuttgart.typeinference.unify.Unify; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/PreIncExpr.java b/src/de/dhbwstuttgart/syntaxtree/statement/PreIncExpr.java index 16ff6864..8ef55b9a 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/PreIncExpr.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/PreIncExpr.java @@ -28,7 +28,6 @@ import de.dhbwstuttgart.typeinference.Pair; import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; import de.dhbwstuttgart.typeinference.unify.Unify; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/Return.java b/src/de/dhbwstuttgart/syntaxtree/statement/Return.java index d39204c8..dce35395 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/Return.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/Return.java @@ -24,10 +24,8 @@ 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; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; @@ -96,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/SuperCall.java b/src/de/dhbwstuttgart/syntaxtree/statement/SuperCall.java index ef90282b..cc4d1c01 100644 --- a/src/de/dhbwstuttgart/syntaxtree/statement/SuperCall.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/SuperCall.java @@ -32,7 +32,6 @@ import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.ConstructorAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/This.java b/src/de/dhbwstuttgart/syntaxtree/statement/This.java index dc9b142b..0474e7ae 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/This.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/This.java @@ -32,7 +32,6 @@ import de.dhbwstuttgart.typeinference.TypeinferenceResultSet; import de.dhbwstuttgart.typeinference.assumptions.ConstructorAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/ThisCall.java b/src/de/dhbwstuttgart/syntaxtree/statement/ThisCall.java index 2bc329bf..e248583d 100644 --- a/src/de/dhbwstuttgart/syntaxtree/statement/ThisCall.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/ThisCall.java @@ -24,7 +24,6 @@ import de.dhbwstuttgart.typeinference.ResultSet; import de.dhbwstuttgart.typeinference.assumptions.ConstructorAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.exceptions.TypeinferenceException; -import de.dhbwstuttgart.typeinference.unify.CSubstitutionSet; diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/WhileStmt.java b/src/de/dhbwstuttgart/syntaxtree/statement/WhileStmt.java index dd95b912..35a18dc7 100755 --- a/src/de/dhbwstuttgart/syntaxtree/statement/WhileStmt.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/WhileStmt.java @@ -28,11 +28,10 @@ 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.CSubstitutionSet; import de.dhbwstuttgart.typeinference.unify.Unify; @@ -113,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 0c7a4468..26b0c2cf 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/RefType.java b/src/de/dhbwstuttgart/syntaxtree/type/RefType.java index 80534098..d0033d32 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/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/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/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 5c8524a8..e9f9918d 100755 --- a/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java +++ b/src/de/dhbwstuttgart/typeinference/ConstraintsSet.java @@ -1,10 +1,12 @@ package de.dhbwstuttgart.typeinference; 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; +import de.dhbwstuttgart.typeinference.unify.Unifikationsalgorithmus; public class ConstraintsSet extends UndMenge implements Iterable{ private static final Logger log = Logger.getLogger(ConstraintsSet.class.getName()); @@ -35,20 +37,22 @@ public class ConstraintsSet extends UndMenge implements Iterable uCons = this.filterUndConstraints(); Vector alleUndConstraints = new Vector<>(); @@ -57,16 +61,16 @@ 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; }); } - + */ /** * Aus dem ConstraintsSet [ u1, u2, ... (OderConstraint), ... uN ] werden alle * UndConstraints, welche sich nicht innerhalb eines OderConstraints befinden, herausgefiltert @@ -89,6 +93,20 @@ public class ConstraintsSet extends UndMenge implements Iterable> getSet() { + return this.getOderConstraints(); + } + + public Menge 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/EinzelElement.java b/src/de/dhbwstuttgart/typeinference/EinzelElement.java index 58f4970d..d33396b9 100644 --- a/src/de/dhbwstuttgart/typeinference/EinzelElement.java +++ b/src/de/dhbwstuttgart/typeinference/EinzelElement.java @@ -1,5 +1,7 @@ package de.dhbwstuttgart.typeinference; +import java.util.Set; + import com.rits.cloning.Cloner; public class EinzelElement implements KomplexeMenge{ @@ -16,9 +18,9 @@ public class EinzelElement implements KomplexeMenge{ } @Override - public Menge> cartesianProduct() { + public Set> cartesianProduct() { Cloner cloner = new Cloner(); - Menge> ret = new Menge<>(); + Set> ret = new Menge<>(); Menge i = new Menge(); i.add(cloner.deepClone(item)); ret.add(i); @@ -30,4 +32,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/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..9c741ec8 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; @@ -7,10 +8,10 @@ import de.dhbwstuttgart.logger.Section; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.unify.Unifier; +import de.dhbwstuttgart.typeinference.unify.Unifikationsalgorithmus; public class OderConstraint extends OderMenge{ - private 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(); @@ -89,11 +90,11 @@ public class OderConstraint extends OderMenge{ * 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) { - 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{ @@ -102,7 +103,6 @@ public class OderConstraint extends OderMenge{ } this.oderConstraintPairs = filteredConstraints; } - UndConstraint filterUndConstraints() { if(this.oderConstraintPairs.size()==1){ return this.oderConstraintPairs.firstElement(); @@ -110,8 +110,9 @@ public class OderConstraint extends OderMenge{ return null; } + */ @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..d6083480 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; @@ -9,15 +10,15 @@ import de.dhbwstuttgart.logger.Section; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.Type; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.unify.Unifier; +import de.dhbwstuttgart.typeinference.unify.Unifikationsalgorithmus; public abstract class OderMenge implements KomplexeMenge{ - 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/Pair.java b/src/de/dhbwstuttgart/typeinference/Pair.java index dcb13958..c31fc695 100755 --- a/src/de/dhbwstuttgart/typeinference/Pair.java +++ b/src/de/dhbwstuttgart/typeinference/Pair.java @@ -11,10 +11,8 @@ import java.io.Serializable; import java.util.Hashtable; import de.dhbwstuttgart.typeinference.Menge; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; // ino.end - - - import de.dhbwstuttgart.parser.JavaClassName; import de.dhbwstuttgart.syntaxtree.type.FreshWildcardType; import de.dhbwstuttgart.syntaxtree.type.GenericTypeVar; @@ -43,9 +41,8 @@ public class Pair implements Serializable, DeepCloneable // ino.end // ino.attribute.bEqual.26549.declaration - private PairOperator eOperator = PairOperator.Smaller; + private PairOperator eOperator = PairOperator.SMALLER; - public enum PairOperator { Smaller, SmallerExtends, Equal }; // ino.end // ino.attribute.bSubst.26552.decldescription type=line // false <--> vorinitialisierter Wert @@ -79,7 +76,7 @@ public class Pair implements Serializable, DeepCloneable this.TA1 = TA1; this.TA2 = TA2; bSubst = false; - eOperator = PairOperator.Smaller; + eOperator = PairOperator.SMALLER; } // ino.end @@ -342,7 +339,7 @@ public class Pair implements Serializable, DeepCloneable */ public boolean OperatorEqual() { - return eOperator == PairOperator.Equal; + return eOperator == PairOperator.EQUALSDOT; } /** @@ -351,7 +348,7 @@ public class Pair implements Serializable, DeepCloneable */ public boolean OperatorSmaller() { - return eOperator == PairOperator.Smaller; + return eOperator == PairOperator.SMALLER; } /** @@ -360,7 +357,7 @@ public class Pair implements Serializable, DeepCloneable */ public boolean OperatorSmallerExtends() { - return eOperator == PairOperator.SmallerExtends; + return eOperator == PairOperator.SMALLERDOTWC; } /** 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/UndConstraint.java b/src/de/dhbwstuttgart/typeinference/UndConstraint.java index a30e4127..a53f0998 100755 --- a/src/de/dhbwstuttgart/typeinference/UndConstraint.java +++ b/src/de/dhbwstuttgart/typeinference/UndConstraint.java @@ -1,11 +1,12 @@ 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.Unifikationsalgorithmus; /** * Stellt ein Constraint dar, welches aus mehreren Constraint-Paaren besteht. Diese gelten alle stets gleichzeitig / sind per "Und" miteinander verknüpft. @@ -21,13 +22,13 @@ public class UndConstraint extends UndMenge { return set; } - public Menge getConstraintPairs() { - Menge> ret = this.cartesianProduct(); + public Set getConstraintPairs() { + Set> ret = this.cartesianProduct(); if(ret.size() != 1){ //UndConstraints enthalten nur SingleConstraints, wodurch das Karthesische Produkt nur aus einem Element bestehen kann. throw new DebugException("Fehler in ConstraintPairs-Bildung"); } - return ret.firstElement(); + return ret.iterator().next(); } public void addConstraint(Type type, Type rT) { @@ -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/UndMenge.java b/src/de/dhbwstuttgart/typeinference/UndMenge.java index 6771bf18..fa300765 100644 --- a/src/de/dhbwstuttgart/typeinference/UndMenge.java +++ b/src/de/dhbwstuttgart/typeinference/UndMenge.java @@ -3,32 +3,32 @@ 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; - //Cloner cloner = new Cloner(); + public Set> cartesianProduct() { + Set> ret = null; 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(); - undElement.addAll(Unify.deepClone(r)); + 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(r); undElement.addAll(m); cartesianProduct.add(undElement); } ret = cartesianProduct; } } - if(ret == null)return new Menge>(); + if(ret == null)return new Menge<>(); return ret; } diff --git a/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java b/src/de/dhbwstuttgart/typeinference/UnifyConstraintsSet.java new file mode 100644 index 00000000..b19a0197 --- /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.Unifikationsalgorithmus; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; + +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(Unifikationsalgorithmus 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(Unifikationsalgorithmus 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..4955ea93 --- /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.Unifikationsalgorithmus; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; + +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(UnifyPair 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(Unifikationsalgorithmus 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..2860d32f --- /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.UnifyPair; + + +public class UnifySingleConstraint extends UnifyUndConstraint{ + + private UnifyPair constraintPair; //entspricht θ condition θ' + + @Override + public Menge> getSet() { + Menge> ret = new Menge<>(); + ret.add(new EinzelElement<>(constraintPair)); + return ret; + } + + public UnifySingleConstraint(UnifyPair toAdd) { + this.addConstraint(toAdd); + } + + public UnifyPair getPair(){ + return constraintPair; + } + + @Override //Methode überschreiben, damit immer nur ein Vector mit nur einem Element zurückgeliefert wird. + public Menge getConstraintPairs(){ + Menge ret = new Menge<>(); + ret.add(constraintPair); + return ret; + } + + public void addConstraint(UnifyPair toAdd){ + if(constraintPair != null)throw new DebugException("Ein Constraint darf nur aus einem ConstraintPair bestehen. Das hinzufügen von "+ toAdd + " ist nicht möglich."); + + constraintPair = toAdd; + } + + @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..f1ed0548 --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/UnifyUndConstraint.java @@ -0,0 +1,45 @@ +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.Unifikationsalgorithmus; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; + +/** + * Stellt ein Constraint dar, welches aus mehreren Constraint-Paaren besteht. Diese gelten alle stets gleichzeitig / sind per "Und" miteinander verknüpft. + * @author janulrich + * + */ +public class UnifyUndConstraint extends UndMenge { + + 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(UnifyPair pair){ + set.add(new EinzelElement<>(pair)); + } + +} 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 66% rename from src/de/dhbwstuttgart/typeinference/unifynew/GuavaSetOperations.java rename to src/de/dhbwstuttgart/typeinference/unify/GuavaSetOperations.java index cc4e907c..b51fb648 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; @@ -7,10 +7,16 @@ import com.google.common.collect.Sets; import de.dhbwstuttgart.typeinference.unify.interfaces.ISetOperations; +/** + * Implements set operations using google guava. + * @author DH10STF + * + */ public class GuavaSetOperations implements ISetOperations { @Override public Set> cartesianProduct(List> sets) { + // Wraps the call to google guava return Sets.cartesianProduct(sets); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/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 54% rename from src/de/dhbwstuttgart/typeinference/unifynew/Mapping.java rename to src/de/dhbwstuttgart/typeinference/unify/Mapping.java index e21bb728..b6ec1e34 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; @@ -6,6 +6,9 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import de.dhbwstuttgart.typeinference.Pair; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; + public class Mapping { private HashMap backwardMap = new HashMap<>(); @@ -21,15 +24,15 @@ public class Mapping { return forwardMap.get(type); } - public de.dhbwstuttgart.typeinference.unify.model.MPair map(de.dhbwstuttgart.typeinference.Pair pair) { - return new de.dhbwstuttgart.typeinference.unify.model.MPair(forwardMap.get(pair.TA1), forwardMap.get(pair.TA2), mapOp(pair.GetOperator())); + public de.dhbwstuttgart.typeinference.unify.model.UnifyPair map(de.dhbwstuttgart.typeinference.Pair pair) { + return new de.dhbwstuttgart.typeinference.unify.model.UnifyPair(forwardMap.get(pair.TA1), forwardMap.get(pair.TA2), mapOp(pair.GetOperator())); } public Set mapTypeSet(Set types) { return types.stream().map(this::map).collect(Collectors.toCollection(HashSet::new)); } - public Set mapPairSet(Set pairs) { + public Set mapPairSet(Set pairs) { return pairs.stream().map(this::map).collect(Collectors.toCollection(HashSet::new)); } @@ -37,13 +40,13 @@ public class Mapping { return irreversible.contains(type) ? Optional.of(backwardMap.get(type)) : Optional.empty(); } - public Optional unmap(de.dhbwstuttgart.typeinference.unify.model.MPair mpair) { + public Optional unmap(de.dhbwstuttgart.typeinference.unify.model.UnifyPair mpair) { de.dhbwstuttgart.typeinference.unify.model.UnifyType lhs = mpair.getLhsType(); de.dhbwstuttgart.typeinference.unify.model.UnifyType rhs = mpair.getRhsType(); 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()))); + return Optional.of(new Pair(backwardMap.get(lhs), backwardMap.get(rhs), unmapOp(mpair.getPairOp()))); } public Optional> unmapTypeSet(Set types) { @@ -51,40 +54,19 @@ public class Mapping { return result.size() == types.size() ? Optional.of(result) : Optional.empty(); } - public Optional> unmapPairSet(Set pairs) { + public Optional> unmapPairSet(Set pairs) { Set result = pairs.stream().map(this::unmap).filter(x -> x.isPresent()).map(x -> x.get()).collect(Collectors.toCollection(HashSet::new)); return result.size() == pairs.size() ? Optional.of(result) : Optional.empty(); } - - 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/MartelliMontanariUnify.java b/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java new file mode 100644 index 00000000..ae017235 --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/unify/MartelliMontanariUnify.java @@ -0,0 +1,105 @@ +package de.dhbwstuttgart.typeinference.unify; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; +import de.dhbwstuttgart.typeinference.unify.model.TypeParams; +import de.dhbwstuttgart.typeinference.unify.model.Unifier; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; + +/** + * Implementation of the Martelli-Montanari unification algorithm. + * @author Florian Steurer + */ +public class MartelliMontanariUnify implements IUnify { + + @Override + public Optional unify(Set terms) { + // Sets with less than 2 terms are trivially unified + if(terms.size() < 2) + return Optional.of(Unifier.Identity()); + + // For the the set of terms {t1,...,tn}, + // build a list of equations {(t1 = t2), (t2 = t3), (t3 = t4), ....} + ArrayList termsList = new ArrayList(); + Iterator iter = terms.iterator(); + UnifyType prev = iter.next(); + while(iter.hasNext()) { + UnifyType next = iter.next(); + termsList.add(new UnifyPair(prev, next, PairOperator.EQUALSDOT)); + prev = next; + } + + // Start with the identity unifier. Substitutions will be added later. + Unifier mgu = Unifier.Identity(); + + // Apply rules while possible + int idx = 0; + while(idx < termsList.size()) { + UnifyPair pair = termsList.get(idx); + UnifyType rhsType = pair.getRhsType(); + UnifyType lhsType = pair.getLhsType(); + TypeParams rhsTypeParams = rhsType.getTypeParams(); + TypeParams lhsTypeParams = lhsType.getTypeParams(); + + // DELETE - Rule + if(pair.getRhsType().equals(pair.getLhsType())) { + termsList.remove(idx); + continue; + } + + // REDUCE - Rule + if(!(rhsType instanceof PlaceholderType) && !(lhsType instanceof PlaceholderType) + && (rhsTypeParams.size() != 0 || lhsTypeParams.size() != 0)) { + Set result = new HashSet<>(); + + // f<...> = g<...> with f != g are not unifiable + if(!rhsType.getName().equals(lhsType.getName())) + return Optional.empty(); // conflict + // f = f are not unifiable + if(rhsTypeParams.size() != lhsTypeParams.size()) + return Optional.empty(); // conflict + + // Unpack the arguments + for(int i = 0; i < rhsTypeParams.size(); i++) + result.add(new UnifyPair(rhsTypeParams.get(i), lhsTypeParams.get(i), PairOperator.EQUALSDOT)); + + termsList.remove(idx); + termsList.addAll(result); + continue; + } + + // SWAP - Rule + if(!(lhsType instanceof PlaceholderType) && (rhsType instanceof PlaceholderType)) { + termsList.remove(idx); + termsList.add(new UnifyPair(rhsType, lhsType, PairOperator.EQUALSDOT)); + continue; + } + + // OCCURS-CHECK + if(pair.getLhsType() instanceof PlaceholderType + && pair.getRhsType().getTypeParams().occurs((PlaceholderType) pair.getLhsType())) + return Optional.empty(); + + // SUBST - Rule + if(lhsType instanceof PlaceholderType) { + mgu.Add((PlaceholderType) lhsType, rhsType); + termsList = termsList.stream().map(mgu::apply).collect(Collectors.toCollection(ArrayList::new)); + idx = idx+1 == termsList.size() ? 0 : idx+1; + continue; + } + + idx++; + } + + return Optional.of(mgu); + } +} 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/unify/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java new file mode 100644 index 00000000..82ee9683 --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -0,0 +1,778 @@ +package de.dhbwstuttgart.typeinference.unify; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Optional; +import java.util.Queue; +import java.util.Set; +import java.util.Stack; +import java.util.stream.Collectors; + +import junit.framework.Assert; +import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; +import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; +import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; +import de.dhbwstuttgart.typeinference.unify.model.FunNType; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; +import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; +import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; +import de.dhbwstuttgart.typeinference.unify.model.SuperType; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; +import de.dhbwstuttgart.typeinference.unify.model.WildcardType; +import de.dhbwstuttgart.typeinference.unify.model.TypeParams; +import de.dhbwstuttgart.typeinference.unify.model.Unifier; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; + +/** + * Implementation of the type inference rules. + * @author Florian Steurer + * + */ +public class RuleSet implements IRuleSet{ + + protected IFiniteClosure finiteClosure; + + /** + * Creates a new instance that uses the specified FC for greater, grArg, etc. + * @param fc The FC that is used for greater, grArg, etc. + */ + public RuleSet(IFiniteClosure fc) { + finiteClosure = fc; + } + + @Override + public Optional reduceUp(UnifyPair pair) { + // Check if reduce up is applicable + if(pair.getPairOp() != PairOperator.SMALLERDOT) + return Optional.empty(); + + UnifyType rhsType = pair.getRhsType(); + if(!(rhsType instanceof SuperType)) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + if(!(lhsType instanceof ReferenceType) && !(lhsType instanceof PlaceholderType)) + return Optional.empty(); + + // Rule is applicable, unpack the SuperType + return Optional.of(new UnifyPair(lhsType, ((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT)); + } + + @Override + public Optional reduceLow(UnifyPair pair) { + // Check if rule is applicable + if(pair.getPairOp() != PairOperator.SMALLERDOT) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + if(!(lhsType instanceof ExtendsType)) + return Optional.empty(); + + UnifyType rhsType = pair.getRhsType(); + if(!(rhsType instanceof ReferenceType) && !(rhsType instanceof PlaceholderType)) + return Optional.empty(); + + // Rule is applicable, unpack the ExtendsType + return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(), rhsType, PairOperator.SMALLERDOT)); + } + + @Override + public Optional reduceUpLow(UnifyPair pair) { + // Check if rule is applicable + if(pair.getPairOp() != PairOperator.SMALLERDOT) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + if(!(lhsType instanceof ExtendsType)) + return Optional.empty(); + + UnifyType rhsType = pair.getRhsType(); + if(!(rhsType instanceof SuperType)) + return Optional.empty(); + + // Rule is applicable, unpack both sides + return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(),((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT)); + } + + @Override + public Optional> reduceExt(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + UnifyType x = pair.getLhsType(); + UnifyType sTypeX; + + if(x instanceof ReferenceType) + sTypeX = x; + else if(x instanceof ExtendsType) + sTypeX = ((ExtendsType) x).getExtendedType(); + else + return Optional.empty(); + + UnifyType extY = pair.getRhsType(); + + if(!(extY instanceof ExtendsType)) + return Optional.empty(); + + if(x.getTypeParams().empty() || extY.getTypeParams().size() != x.getTypeParams().size()) + return Optional.empty(); + + UnifyType xFromFc = finiteClosure.getLeftHandedType(sTypeX.getName()).orElse(null); + + if(xFromFc == null || !xFromFc.getTypeParams().arePlaceholders()) + return Optional.empty(); + + if(x instanceof ExtendsType) + xFromFc = new ExtendsType(xFromFc); + + UnifyType extYFromFc = finiteClosure.grArg(xFromFc).stream().filter(t -> t.getName().equals(extY.getName())).filter(t -> t.getTypeParams().arePlaceholders()).findAny().orElse(null); + + if(extYFromFc == null || extYFromFc.getTypeParams() != xFromFc.getTypeParams()) + return Optional.empty(); + + TypeParams extYParams = extY.getTypeParams(); + TypeParams xParams = x.getTypeParams(); + + int[] pi = pi(xParams, extYParams); + + if(pi.length == 0) + return Optional.empty(); + + Set result = new HashSet<>(); + + for(int rhsIdx = 0; rhsIdx < extYParams.size(); rhsIdx++) + result.add(new UnifyPair(xParams.get(pi[rhsIdx]), extYParams.get(rhsIdx), PairOperator.SMALLERDOTWC)); + + return Optional.of(result); + } + + @Override + public Optional> reduceSup(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + UnifyType x = pair.getLhsType(); + UnifyType sTypeX; + + if(x instanceof ReferenceType) + sTypeX = x; + else if(x instanceof SuperType) + sTypeX = ((SuperType) x).getSuperedType(); + else + return Optional.empty(); + + UnifyType supY = pair.getRhsType(); + + if(!(supY instanceof SuperType)) + return Optional.empty(); + + if(x.getTypeParams().empty() || supY.getTypeParams().size() != x.getTypeParams().size()) + return Optional.empty(); + + UnifyType xFromFc = finiteClosure.getLeftHandedType(sTypeX.getName()).orElse(null); + + if(xFromFc == null || !xFromFc.getTypeParams().arePlaceholders()) + return Optional.empty(); + + if(x instanceof SuperType) + xFromFc = new SuperType(xFromFc); + + UnifyType supYFromFc = finiteClosure.grArg(xFromFc).stream().filter(t -> t.getName().equals(supY.getName())).filter(t -> t.getTypeParams().arePlaceholders()).findAny().orElse(null); + + if(supYFromFc == null || supYFromFc.getTypeParams() != xFromFc.getTypeParams()) + return Optional.empty(); + + TypeParams supYParams = supY.getTypeParams(); + TypeParams xParams = x.getTypeParams(); + Set result = new HashSet<>(); + + int[] pi = pi(xParams, supYParams); + + if(pi.length == 0) + return Optional.empty(); + + for(int rhsIdx = 0; rhsIdx < supYParams.size(); rhsIdx++) + result.add(new UnifyPair(supYParams.get(rhsIdx), xParams.get(pi[rhsIdx]), PairOperator.SMALLERDOTWC)); + + return Optional.of(result); + } + + @Override + public Optional> reduceEq(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + if(lhsType instanceof PlaceholderType || lhsType.getTypeParams().empty()) + return Optional.empty(); + + UnifyType rhsType = pair.getRhsType(); + + if(!rhsType.getName().equals(lhsType.getName())) + return Optional.empty(); + + if(rhsType instanceof PlaceholderType || lhsType instanceof PlaceholderType || rhsType.getTypeParams().empty()) + return Optional.empty(); + + if(rhsType.getTypeParams().size() != lhsType.getTypeParams().size()) + return Optional.empty(); + + // Keine Permutation wie im Paper nötig + Set result = new HashSet<>(); + TypeParams lhsTypeParams = lhsType.getTypeParams(); + TypeParams rhsTypeParams = rhsType.getTypeParams(); + + for(int i = 0; i < lhsTypeParams.size(); i++) + result.add(new UnifyPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT)); + + return Optional.of(result); + } + + @Override + public Optional> reduce1(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOT) + return Optional.empty(); + + UnifyType c = pair.getLhsType(); + if(!(c instanceof ReferenceType)) + return Optional.empty(); + + UnifyType d = pair.getRhsType(); + if(!(d instanceof ReferenceType)) + return Optional.empty(); + + ReferenceType lhsSType = (ReferenceType) c; + ReferenceType rhsSType = (ReferenceType) d; + + if(lhsSType.getTypeParams().empty() || lhsSType.getTypeParams().size() != rhsSType.getTypeParams().size()) + return Optional.empty(); + + UnifyType cFromFc = finiteClosure.getLeftHandedType(c.getName()).orElse(null); + + if(cFromFc == null || !cFromFc.getTypeParams().arePlaceholders()) + return Optional.empty(); + + UnifyType dFromFc = finiteClosure.getAncestors(cFromFc).stream().filter(x -> x.getName().equals(d.getName())).findAny().orElse(null); + + if(dFromFc == null || !dFromFc.getTypeParams().arePlaceholders() || dFromFc.getTypeParams().size() != cFromFc.getTypeParams().size()) + return Optional.empty(); + + int[] pi = pi(cFromFc.getTypeParams(), dFromFc.getTypeParams()); + + if(pi.length == 0) + return Optional.empty(); + + TypeParams rhsTypeParams = d.getTypeParams(); + TypeParams lhsTypeParams = c.getTypeParams(); + Set result = new HashSet<>(); + + for(int rhsIdx = 0; rhsIdx < rhsTypeParams.size(); rhsIdx++) + result.add(new UnifyPair(lhsTypeParams.get(pi[rhsIdx]), rhsTypeParams.get(rhsIdx), PairOperator.SMALLERDOTWC)); + + return Optional.of(result); + } + + @Override + public Optional> reduce2(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.EQUALSDOT) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + ReferenceType lhsSType; + + if(lhsType instanceof ReferenceType) + lhsSType = (ReferenceType) lhsType; + else if(lhsType instanceof WildcardType) { + UnifyType lhsSTypeRaw = ((WildcardType) lhsType).getWildcardedType(); + if(lhsSTypeRaw instanceof ReferenceType) + lhsSType = (ReferenceType) lhsSTypeRaw; + else + return Optional.empty(); + } + else + return Optional.empty(); + + if(lhsSType.getTypeParams().empty()) + return Optional.empty(); + + UnifyType rhsType = pair.getLhsType(); + ReferenceType rhsSType; + + if(rhsType instanceof ReferenceType) + rhsSType = (ReferenceType) rhsType; + else if(rhsType instanceof WildcardType) { + UnifyType rhsSTypeRaw = ((WildcardType) rhsType).getWildcardedType(); + if(rhsSTypeRaw instanceof ReferenceType) + rhsSType = (ReferenceType) rhsSTypeRaw; + else + return Optional.empty(); + } + else + return Optional.empty(); + + if(!rhsSType.getName().equals(lhsSType.getName())) + return Optional.empty(); + + Assert.assertEquals(lhsSType.getTypeParams().size(), rhsSType.getTypeParams().size()); + //if(rhsSType.getTypeParams().size() != lhsSType.getTypeParams().size()) + // return Optional.empty(); + + Set result = new HashSet<>(); + + TypeParams rhsTypeParams = rhsSType.getTypeParams(); + TypeParams lhsTypeParams = lhsSType.getTypeParams(); + for(int i = 0; i < rhsTypeParams.size(); i++) + result.add(new UnifyPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT)); + + return Optional.of(result); + } + + @Override + public boolean erase1(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOT) + return false; + + UnifyType lhsType = pair.getLhsType(); + if(!(lhsType instanceof ReferenceType) && !(lhsType instanceof PlaceholderType)) + return false; + + UnifyType rhsType = pair.getRhsType(); + if(!(rhsType instanceof ReferenceType) && !(rhsType instanceof PlaceholderType)) + return false; + + return finiteClosure.greater(lhsType).contains(rhsType); + } + + @Override + public boolean erase2(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return false; + + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + + return finiteClosure.grArg(lhsType).contains(rhsType); + } + + @Override + public boolean erase3(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.EQUALSDOT) + return false; + + return pair.getLhsType().equals(pair.getRhsType()); + } + + @Override + public Optional swap(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.EQUALSDOT) + return Optional.empty(); + + if(pair.getLhsType() instanceof PlaceholderType) + return Optional.empty(); + + if(!(pair.getRhsType() instanceof PlaceholderType)) + return Optional.empty(); + + return Optional.of(new UnifyPair(pair.getRhsType(), pair.getLhsType(), PairOperator.EQUALSDOT)); + } + + @Override + public Optional adapt(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOT) + return Optional.empty(); + + UnifyType typeD = pair.getLhsType(); + if(!(typeD instanceof ReferenceType)) + return Optional.empty(); + + UnifyType typeDs = pair.getRhsType(); + if(!(typeDs instanceof ReferenceType)) + return Optional.empty(); + + /*if(typeD.getTypeParams().size() == 0 || typeDs.getTypeParams().size() == 0) + return Optional.empty();*/ + + if(typeD.getName().equals(typeDs.getName())) + return Optional.empty(); + + + Optional opt = finiteClosure.getLeftHandedType(typeD.getName()); + if(!opt.isPresent()) + return Optional.empty(); + + // The generic Version of Type D (D) + UnifyType typeDgen = opt.get(); + + // Actually greater+ because the types are ensured to have different names + Set greater = finiteClosure.getAncestors(typeDgen); + opt = greater.stream().filter(x -> x.getName().equals(typeDs.getName())).findAny(); + + if(!opt.isPresent()) + return Optional.empty(); + + UnifyType newLhs = opt.get(); + + TypeParams typeDParams = typeD.getTypeParams(); + TypeParams typeDgenParams = typeDgen.getTypeParams(); + + Unifier unif = Unifier.Identity(); + for(int i = 0; i < typeDParams.size(); i++) + unif.Add((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i)); + + return Optional.of(new UnifyPair(unif.apply(newLhs), typeDs, PairOperator.SMALLERDOT)); + } + + @Override + public Optional adaptExt(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + UnifyType typeD = pair.getLhsType(); + if(!(typeD instanceof ReferenceType) && !(typeD instanceof ExtendsType)) + return Optional.empty(); + + UnifyType typeExtDs = pair.getRhsType(); + if(!(typeExtDs instanceof ExtendsType)) + return Optional.empty(); + + if(typeD.getTypeParams().size() == 0 || typeExtDs.getTypeParams().size() == 0) + return Optional.empty(); + + UnifyType typeDgen; + if(typeD instanceof ReferenceType) + typeDgen = finiteClosure.getLeftHandedType(typeD.getName()).orElse(null); + else { + Optional opt = finiteClosure.getLeftHandedType(((ExtendsType) typeD).getExtendedType().getName()); + typeDgen = opt.isPresent() ? new ExtendsType(opt.get()) : null; + } + + if(typeDgen == null) + return Optional.empty(); + + Set grArg = finiteClosure.grArg(typeDgen); + + Optional opt = grArg.stream().filter(x -> x.getName().equals(typeExtDs.getName())).findAny(); + + if(!opt.isPresent()) + return Optional.empty(); + + UnifyType newLhs = ((ExtendsType) opt.get()).getExtendedType(); + + TypeParams typeDParams = typeD.getTypeParams(); + TypeParams typeDgenParams = typeDgen.getTypeParams(); + + Unifier unif = new Unifier((PlaceholderType) typeDgenParams.get(0), typeDParams.get(0)); + for(int i = 1; i < typeDParams.size(); i++) + unif.Add((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i)); + + return Optional.of(new UnifyPair(unif.apply(newLhs), typeExtDs, PairOperator.SMALLERDOTWC)); + } + + @Override + public Optional adaptSup(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + UnifyType typeDs = pair.getLhsType(); + if(!(typeDs instanceof ReferenceType) && !(typeDs instanceof SuperType)) + return Optional.empty(); + + UnifyType typeSupD = pair.getRhsType(); + if(!(typeSupD instanceof SuperType)) + return Optional.empty(); + + if(typeDs.getTypeParams().size() == 0 || typeSupD.getTypeParams().size() == 0) + return Optional.empty(); + + + Optional opt = finiteClosure.getLeftHandedType(((SuperType) typeSupD).getSuperedType().getName()); + + if(!opt.isPresent()) + return Optional.empty(); + + 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); + opt = smArg.stream().filter(x -> x.getName().equals(typeDs.getName())).findAny(); + + if(!opt.isPresent()) + return Optional.empty(); + + // New RHS + UnifyType newRhs = null; + if(typeDs instanceof ReferenceType) + newRhs = new ExtendsType(typeDs); + else + newRhs = new ExtendsType(((SuperType) typeDs).getSuperedType()); + + // New LHS + UnifyType newLhs = opt.get(); + TypeParams typeDParams = typeSupD.getTypeParams(); + TypeParams typeSupDsgenParams = typeSupDgen.getTypeParams(); + + Unifier unif = new Unifier((PlaceholderType) typeSupDsgenParams.get(0), typeDParams.get(0)); + for(int i = 1; i < typeDParams.size(); i++) + unif.Add((PlaceholderType) typeSupDsgenParams.get(i), typeDParams.get(i)); + + return Optional.of(new UnifyPair(unif.apply(newLhs), newRhs, PairOperator.SMALLERDOTWC)); + } + + /** + * Finds the permutation pi of the type arguments of two types based on the finite closure + * @param C The type which arguments are permuted + * @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(TypeParams cArgs, TypeParams dArgs) { + Assert.assertEquals(cArgs.size(), dArgs.size()); + + int[] permutation = new int[dArgs.size()]; + + boolean succ = true; + for (int dArgIdx = 0; dArgIdx < dArgs.size() && succ; dArgIdx++) { + UnifyType dArg = dArgs.get(dArgIdx); + succ = false; + for (int pi = 0; pi < cArgs.size(); pi++) + if (cArgs.get(pi).getName().equals(dArg.getName())) { + permutation[dArgIdx] = pi; + succ = true; + break; + } + } + + return succ ? permutation : new int[0]; + } + + @Override + public Optional> subst(Set pairs) { + HashMap typeMap = new HashMap<>(); + + Stack occuringTypes = new Stack<>(); + + for(UnifyPair pair : pairs) { + occuringTypes.push(pair.getLhsType()); + occuringTypes.push(pair.getRhsType()); + } + + while(!occuringTypes.isEmpty()) { + UnifyType t1 = occuringTypes.pop(); + if(!typeMap.containsKey(t1)) + typeMap.put(t1, 0); + typeMap.put(t1, typeMap.get(t1)+1); + + if(t1 instanceof ExtendsType) + occuringTypes.push(((ExtendsType) t1).getExtendedType()); + if(t1 instanceof SuperType) + occuringTypes.push(((SuperType) t1).getSuperedType()); + else + t1.getTypeParams().forEach(x -> occuringTypes.push(x)); + } + + Queue result1 = new LinkedList(pairs); + ArrayList result = new ArrayList(); + boolean applied = false; + + while(!result1.isEmpty()) { + UnifyPair pair = result1.poll(); + PlaceholderType lhsType = null; + UnifyType rhsType; + + if(pair.getPairOp() == PairOperator.EQUALSDOT + && pair.getLhsType() instanceof PlaceholderType) + lhsType = (PlaceholderType) pair.getLhsType(); + if(lhsType != null + && !((rhsType = pair.getRhsType()) instanceof PlaceholderType) + && typeMap.get(lhsType) > 1 // The type occurs in more pairs in the set than just the recent pair. + && !rhsType.getTypeParams().occurs(lhsType)) { + Unifier uni = new Unifier(lhsType, rhsType); + result = result.stream().map(uni::apply).collect(Collectors.toCollection(ArrayList::new)); + result1 = result1.stream().map(uni::apply).collect(Collectors.toCollection(LinkedList::new)); + applied = true; + } + + result.add(pair); + } + + return applied ? Optional.of(new HashSet<>(result)) : Optional.empty(); + } + + @Override + public Optional reduceWildcardLow(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + if(!(lhsType instanceof ExtendsType) || !(rhsType instanceof ExtendsType)) + return Optional.empty(); + + return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(), ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT)); + } + + @Override + public Optional reduceWildcardLowRight(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + if(!(lhsType instanceof ReferenceType) || !(rhsType instanceof ExtendsType)) + return Optional.empty(); + + return Optional.of(new UnifyPair(lhsType, ((ExtendsType) rhsType).getExtendedType(), PairOperator.SMALLERDOT)); + } + + @Override + public Optional reduceWildcardUp(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + if(!(lhsType instanceof SuperType) || !(rhsType instanceof SuperType)) + return Optional.empty(); + + return Optional.of(new UnifyPair(((SuperType) rhsType).getSuperedType(), ((SuperType) lhsType).getSuperedType(), PairOperator.SMALLERDOT)); + } + + @Override + public Optional reduceWildcardUpRight(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + if(!(lhsType instanceof ReferenceType) || !(rhsType instanceof SuperType)) + return Optional.empty(); + + return Optional.of(new UnifyPair(((SuperType) rhsType).getSuperedType(), lhsType, PairOperator.SMALLERDOTWC)); + } + + @Override + public Optional reduceWildcardLowUp(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + if(!(lhsType instanceof ExtendsType) || !(rhsType instanceof SuperType)) + return Optional.empty(); + + return Optional.of(new UnifyPair(((ExtendsType) lhsType).getExtendedType(), ((SuperType) rhsType).getSuperedType(), PairOperator.EQUALSDOT)); + } + + @Override + public Optional reduceWildcardUpLow(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + if(!(lhsType instanceof SuperType) || !(rhsType instanceof ExtendsType)) + return Optional.empty(); + + return Optional.of(new UnifyPair(((SuperType) lhsType).getSuperedType(), ((ExtendsType) rhsType).getExtendedType(), PairOperator.EQUALSDOT)); + } + + @Override + public Optional reduceWildcardLeft(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOTWC) + return Optional.empty(); + + UnifyType rhsType = pair.getRhsType(); + if(!(rhsType instanceof ReferenceType)) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + + if(lhsType instanceof WildcardType) + return Optional.of(new UnifyPair(((WildcardType) lhsType).getWildcardedType(), rhsType, PairOperator.EQUALSDOT)); + + return Optional.empty(); + } + + @Override + public Optional> reduceFunN(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOT) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + + if(!(lhsType instanceof FunNType) || !(rhsType instanceof FunNType)) + return Optional.empty(); + + FunNType funNLhsType = (FunNType) lhsType; + FunNType funNRhsType = (FunNType) rhsType; + + if(funNLhsType.getN() != funNRhsType.getN()) + return Optional.empty(); + + Set result = new HashSet(); + + result.add(new UnifyPair(funNLhsType.getTypeParams().get(0), funNRhsType.getTypeParams().get(0), PairOperator.SMALLERDOT)); + for(int i = 1; i < funNLhsType.getTypeParams().size(); i++) + result.add(new UnifyPair(funNRhsType.getTypeParams().get(i), funNLhsType.getTypeParams().get(i), PairOperator.SMALLERDOT)); + + return Optional.of(result); + } + + @Override + public Optional> greaterFunN(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOT) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + + if(!(lhsType instanceof FunNType) || !(rhsType instanceof PlaceholderType)) + return Optional.empty(); + + FunNType funNLhsType = (FunNType) lhsType; + + Set result = new HashSet(); + + UnifyType[] freshPlaceholders = new UnifyType[funNLhsType.getTypeParams().size()]; + for(int i = 0; i < freshPlaceholders.length; i++) + freshPlaceholders[i] = PlaceholderType.freshPlaceholder(); + + result.add(new UnifyPair(funNLhsType.getTypeParams().get(0), freshPlaceholders[0], PairOperator.SMALLERDOT)); + for(int i = 1; i < funNLhsType.getTypeParams().size(); i++) + result.add(new UnifyPair(freshPlaceholders[i], funNLhsType.getTypeParams().get(i), PairOperator.SMALLERDOT)); + result.add(new UnifyPair(rhsType, funNLhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT)); + + return Optional.of(result); + } + + @Override + public Optional> smallerFunN(UnifyPair pair) { + if(pair.getPairOp() != PairOperator.SMALLERDOT) + return Optional.empty(); + + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + + if(!(lhsType instanceof PlaceholderType) || !(rhsType instanceof FunNType)) + return Optional.empty(); + + FunNType funNRhsType = (FunNType) rhsType; + + Set result = new HashSet(); + + UnifyType[] freshPlaceholders = new UnifyType[funNRhsType.getTypeParams().size()]; + for(int i = 0; i < freshPlaceholders.length; i++) + freshPlaceholders[i] = PlaceholderType.freshPlaceholder(); + + result.add(new UnifyPair(freshPlaceholders[0], funNRhsType.getTypeParams().get(0), PairOperator.SMALLERDOT)); + for(int i = 1; i < funNRhsType.getTypeParams().size(); i++) + result.add(new UnifyPair(funNRhsType.getTypeParams().get(i), freshPlaceholders[i], PairOperator.SMALLERDOT)); + result.add(new UnifyPair(lhsType, funNRhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT)); + + return Optional.of(result); + } +} diff --git a/src/de/dhbwstuttgart/typeinference/unify/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/Unifier.java 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/Unifikationsalgorithmus.java b/src/de/dhbwstuttgart/typeinference/unify/Unifikationsalgorithmus.java new file mode 100644 index 00000000..39c25e57 --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/unify/Unifikationsalgorithmus.java @@ -0,0 +1,11 @@ +package de.dhbwstuttgart.typeinference.unify; + +import java.util.Set; + +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; + +public interface Unifikationsalgorithmus { + + public Set> apply (Set 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..0d2014b9 --- a/src/de/dhbwstuttgart/typeinference/unify/Unify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/Unify.java @@ -1,3563 +1,652 @@ -//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; - - } - - // 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 +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.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.UnifyPair; +import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; +import de.dhbwstuttgart.typeinference.unify.model.SuperType; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.TypeParams; +import de.dhbwstuttgart.typeinference.unify.model.Unifier; + + +/** + * Implementation of the type unification algorithm + * @author Florian Steurer + */ +public class Unify { + + protected ISetOperations setOps = new GuavaSetOperations(); + + 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); + eq2s.removeAll(bufferSet); + } + + // Sets that originate from pair pattern matching + // Sets of the "second level" + Set undefinedPairs = new HashSet<>(); + Set>>> secondLevelSets = calculatePairSets(eq2s, fc, undefinedPairs); + + // If pairs occured that did not match one of the cartesian product cases, + // those pairs are contradictory and the unification is impossible. + if(!undefinedPairs.isEmpty()) + return new HashSet<>(); + + /* Up to here, no cartesian products are calculated. + * filters for pairs and sets can be applied here */ + + // Sub cartesian products of the second level (pattern matched) sets + for(Set>> secondLevelSet : secondLevelSets) { + List>> secondLevelSetList = new ArrayList<>(secondLevelSet); + Set>> cartResult = setOps.cartesianProduct(secondLevelSetList); + + Set> flat = new HashSet<>(); + cartResult.stream().forEach(x -> flat.addAll(x)); + topLevelSets.add(flat); + } + + // Cartesian product over all (up to 10) top level sets + Set>> eqPrimeSet = setOps.cartesianProduct(topLevelSets) + .stream().map(x -> new HashSet<>(x)) + .collect(Collectors.toCollection(HashSet::new)); + //System.out.println(result); + + /* + * Step 5: Substitution + */ + + 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> restartSet = new HashSet<>(); + Set> eqPrimePrimeSet = new HashSet<>(); + + for(Set eqPrime : eqPrimeSetFlat) { + Optional> eqPrimePrime = rules.subst(eqPrime); + + /*if (eqPrime.equals(eq)) + eqPrimePrimeSet.add(eqPrime); + else if(eqPrimePrime.isPresent()) { + Set> subUnifyResult = unify(eqPrimePrime.get(), fc); + eqPrimePrimeSet.addAll(subUnifyResult); + } + else + eqPrimePrimeSet.addAll(this.unify(eqPrime, fc));*/ + if(eqPrimePrime.isPresent()) + restartSet.add(eqPrimePrime.get()); + else if(!isSolvedForm(eqPrime)) + restartSet.add(eqPrime); + else + eqPrimePrimeSet.add(eqPrime); + } + + /* + * Step 6 a) Restart for pairs where subst was applied + * b) Build the union over everything + */ + + for(Set eqss : restartSet) + eqPrimePrimeSet.addAll(this.unify(eqss, fc)); + + /* + * Step 7: Filter empty sets; + */ + return eqPrimePrimeSet.stream().filter(x -> isSolvedForm(x)).collect(Collectors.toCollection(HashSet::new)); + + } + + protected boolean isSolvedForm(Set eqPrimePrime) { + for(UnifyPair pair : eqPrimePrime) { + UnifyType lhsType = pair.getLhsType(); + UnifyType rhsType = pair.getRhsType(); + + if(!(lhsType instanceof PlaceholderType)) + return false; + + if(pair.getPairOp() != PairOperator.EQUALSDOT && !(rhsType instanceof PlaceholderType)) + return false; + } + + return true; + } + + protected Set applyTypeUnificationRules(Set eq, IFiniteClosure fc) { + + /* + * Rule Application Strategy: + * + * 1. Swap all pairs and erase all erasable pairs + * 2. Apply all possible rules to a single pair, then move it to the result set. + * Iterating over pairs first, then iterating over rules prevents the application + * of rules to a "finished" pair over and over. + * 2.1 Apply all rules repeatedly except for erase rules. If + * the application of a rule creates new pairs, check immediately + * against the erase rules. + */ + + + LinkedHashSet targetSet = new LinkedHashSet(); + LinkedList eqQueue = new LinkedList<>(); + IRuleSet rules = new RuleSet(fc); + + /* + * Swap all pairs and erase all erasable pairs + */ + eq.forEach(x -> swapAddOrErase(x, rules, eqQueue)); + + /* + * Apply rules until the queue is empty + */ + while(!eqQueue.isEmpty()) { + UnifyPair pair = eqQueue.pollFirst(); + + // ReduceUp, ReduceLow, ReduceUpLow + Optional opt = rules.reduceUpLow(pair); + opt = opt.isPresent() ? opt : rules.reduceLow(pair); + opt = opt.isPresent() ? opt : rules.reduceUp(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardLow(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardLowRight(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardUp(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardUpRight(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardLowUp(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardUpLow(pair); + opt = opt.isPresent() ? opt : rules.reduceWildcardLeft(pair); + + // One of the rules has been applied + if(opt.isPresent()) { + swapAddOrErase(opt.get(), rules, eqQueue); + continue; + } + + // Reduce1, Reduce2, ReduceExt, ReduceSup, ReduceEq + Optional> optSet = rules.reduce1(pair); + optSet = optSet.isPresent() ? optSet : rules.reduce2(pair); + optSet = optSet.isPresent() ? optSet : rules.reduceExt(pair); + optSet = optSet.isPresent() ? optSet : rules.reduceSup(pair); + optSet = optSet.isPresent() ? optSet : rules.reduceEq(pair); + + // One of the rules has been applied + if(optSet.isPresent()) { + optSet.get().forEach(x -> swapAddOrErase(x, rules, eqQueue)); + continue; + } + + // Adapt, AdaptExt, AdaptSup + opt = rules.adapt(pair); + opt = opt.isPresent() ? opt : rules.adaptExt(pair); + opt = opt.isPresent() ? opt : rules.adaptSup(pair); + + // One of the rules has been applied + if(opt.isPresent()) { + swapAddOrErase(opt.get(), rules, eqQueue); + continue; + } + + // None of the rules has been applied + targetSet.add(pair); + } + + return targetSet; + } + + protected void swapAddOrErase(UnifyPair pair, IRuleSet rules, Collection collection) { + Optional opt = rules.swap(pair); + UnifyPair pair2 = opt.isPresent() ? opt.get() : pair; + + if(rules.erase1(pair2) || rules.erase3(pair2) || rules.erase2(pair2)) + return; + + collection.add(pair2); + } + + protected void splitEq(Set eq, Set eq1s, Set eq2s) { + for(UnifyPair pair : eq) + if(pair.getLhsType() instanceof PlaceholderType && pair.getRhsType() instanceof PlaceholderType) + eq1s.add(pair); + else + eq2s.add(pair); + } + + + protected Set>>> calculatePairSets(Set eq2s, IFiniteClosure fc, Set undefined) { + List>>> result = new ArrayList<>(); + + // Init all 8 cases + for(int i = 0; i < 8; i++) + result.add(new HashSet<>()); + + for(UnifyPair 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)); + // Case unknown: If a pair fits no other case, then the type unification has failed. + // Through application of the rules, every pair should have one of the above forms. + // Pairs that do not have one of the aboves form are contradictory. + else + undefined.add(pair); + + } + + return result.stream().map(x -> x.stream().filter(y -> y.size() > 0).collect(Collectors.toCollection(HashSet::new))) + .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()); + cs.add(thetaPrime); + + for(UnifyType c : cs) { + Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); + thetaQs.add(thetaPrime); + + Set thetaQPrimes = new HashSet<>(); + TypeParams cParams = c.getTypeParams(); + if(cParams.size() == 0) + thetaQPrimes.add(c); + else { + ArrayList> candidateParams = new ArrayList<>(); + + /* + * TODO Optimierungsmöglichkeit: + * + * An dieser Stelle gibt es Raum für Optimierung. + * Z.B. resultiert (a <. C) durch Permutation der Parameter mit grArg und smaller in: + * (a = C, b' <.? ? extends Number) + * (a = C, b' <.? ? extends Integer) + * (a = C, b' <.? Integer) + * usw... + * + * Der erste Fall ist am allgemeinsten und schließt alle anderen Fälle mit ein. Jeder Fall resultiert in einem + * rekursiven Aufruf des Unify. Es würde reichen nur den allgemeinsten Fall zu betrachten da dieser den Lösungraum + * der anderen Fälle miteinschließt. + * + * Prüfen: + * Gibt es einen einzigen maximalen Fall? + * Wahrscheinlich gibt es 2: ? super x (x möglichst klein) und ? ext y (y möglichst groß)) + */ + + for(UnifyType param : cParams) + 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(); + unifier.swapPlaceholderSubstitutions(thetaPrime.getTypeParams().toArray()); + Set substitutionSet = new HashSet<>(); + for (Entry sigma : unifier.getSubstitutions()) + substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); + + List freshTphs = new ArrayList<>(); + for (UnifyType tq : thetaQs) { + Set smaller = fc.smaller(unifier.apply(tq)); + for(UnifyType theta : smaller) { + Set resultPrime = new HashSet<>(); + + //UnifyType[] freshTphs = new UnifyType[theta.getTypeParams().size()]; + for(int i = 0; i < theta.getTypeParams().size(); i++) { + if(freshTphs.size()-1 < i) + freshTphs.add(PlaceholderType.freshPlaceholder()); + resultPrime.add(new UnifyPair(freshTphs.get(i), theta.getTypeParams().get(i), PairOperator.SMALLERDOTWC)); + } + + UnifyType freshTheta = theta.setTypeParams(new TypeParams(freshTphs.toArray(new UnifyType[0]))); + resultPrime.add(new UnifyPair(a, freshTheta, PairOperator.EQUALSDOT)); + resultPrime.addAll(substitutionSet); + result.add(resultPrime); + } + } + + } + } + + return result; + } + + protected Set> unifyCase2(PlaceholderType a, ExtendsType extThetaPrime, IFiniteClosure fc) { + Set> result = new HashSet<>(); + + UnifyType aPrime = PlaceholderType.freshPlaceholder(); + UnifyType extAPrime = new ExtendsType(aPrime); + UnifyType thetaPrime = extThetaPrime.getExtendedType(); + //for(UnifyType theta : fc.smArg(subThetaPrime)) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, aPrime, PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(aPrime, thetaPrime, PairOperator.SMALLERDOT)); + result.add(resultPrime); + + resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, extAPrime, PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(aPrime, thetaPrime, PairOperator.SMALLERDOT)); + result.add(resultPrime); + //} + + return result; + +// Set> result = new HashSet<>(); +// IUnify unify = new MartelliMontanariUnify(); +// +// UnifyType thetaPrime = extThetaPrime.getExtendedType(); +// Set cs = fc.getAllTypesByName(thetaPrime.getName()); +// cs.add(thetaPrime); +// +// for(UnifyType c : cs) { +// Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); +// thetaQs.add(thetaPrime); +// +// Set thetaQPrimes = new HashSet<>(); +// TypeParams cParams = c.getTypeParams(); +// if(cParams.size() == 0) +// thetaQPrimes.add(c); +// else { +// ArrayList> candidateParams = new ArrayList<>(); +// for(UnifyType param : cParams) +// candidateParams.add(fc.grArg(param)); +// +// for(TypeParams tp : permuteParams(candidateParams)) +// thetaQPrimes.add(c.setTypeParams(tp)); +// } +// +// for(UnifyType tqp : thetaQPrimes) { +// Optional opt = unify.unify(tqp, thetaPrime); +// if (!opt.isPresent()) +// continue; +// +// Unifier unifier = opt.get(); +// +// Set substitutionSet = new HashSet<>(); +// for (Entry sigma : unifier.getSubstitutions()) +// substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); +// +// for (UnifyType tq : thetaQs) { +// ExtendsType extTq = new ExtendsType(tq); +// Set smArg = fc.smArg(unifier.apply(extTq)); +// for(UnifyType theta : smArg) { +// Set resultPrime = new HashSet<>(); +// resultPrime.add(new UnifyPair(a, theta, PairOperator.EQUALSDOT)); +// resultPrime.addAll(substitutionSet); +// result.add(resultPrime); +// } +// } +// +// } +// } +// +// return result; + } + + protected Set> unifyCase3(PlaceholderType a, SuperType subThetaPrime, IFiniteClosure fc) { + Set> result = new HashSet<>(); + + UnifyType aPrime = PlaceholderType.freshPlaceholder(); + UnifyType supAPrime = new SuperType(aPrime); + UnifyType thetaPrime = subThetaPrime.getSuperedType(); + //for(UnifyType theta : fc.smArg(subThetaPrime)) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, aPrime, PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(thetaPrime, aPrime, PairOperator.SMALLERDOT)); + result.add(resultPrime); + + resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, supAPrime, PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(thetaPrime, aPrime, PairOperator.SMALLERDOT)); + result.add(resultPrime); + //} + + return result; + } + + protected Set> unifyCase4(PlaceholderType a, UnifyType thetaPrime, IFiniteClosure fc) { + Set> result = new HashSet<>(); + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, thetaPrime, PairOperator.EQUALSDOT)); + result.add(resultPrime); + + return result; + } + + protected Set> unifyCase5(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { + Set> result = new HashSet<>(); + for(UnifyType thetaS : fc.greater(theta)) { + Set resultPrime = new HashSet<>(); + + UnifyType[] freshTphs = new UnifyType[thetaS.getTypeParams().size()]; + for(int i = 0; i < freshTphs.length; i++) { + freshTphs[i] = PlaceholderType.freshPlaceholder(); + resultPrime.add(new UnifyPair(thetaS.getTypeParams().get(i), freshTphs[i], PairOperator.SMALLERDOTWC)); + } + + resultPrime.add(new UnifyPair(a, thetaS.setTypeParams(new TypeParams(freshTphs)), PairOperator.EQUALSDOT)); + result.add(resultPrime); + } + + return result; + } + + protected Set> unifyCase6(ExtendsType extTheta, PlaceholderType a, IFiniteClosure fc) { + Set> result = new HashSet<>(); + //for(UnifyType thetaS : fc.smaller(extTheta.getExtendedType())) { + UnifyType freshTph = PlaceholderType.freshPlaceholder(); + UnifyType extFreshTph = new ExtendsType(freshTph); + + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, extFreshTph, PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(extTheta.getExtendedType(), freshTph, PairOperator.SMALLERDOT)); + result.add(resultPrime); + //} + + return result; + } + + protected Set> unifyCase7(SuperType supTheta, PlaceholderType a, IFiniteClosure fc) { + Set> result = new HashSet<>(); + + UnifyType aPrime = PlaceholderType.freshPlaceholder(); + UnifyType supAPrime = new SuperType(aPrime); + UnifyType theta = supTheta.getSuperedType(); + //for(UnifyType theta : fc.smArg(subThetaPrime)) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, supAPrime, PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(aPrime, theta, PairOperator.SMALLERDOT)); + result.add(resultPrime); + //} + + return result; + +// Set> result = new HashSet<>(); +// IUnify unify = new MartelliMontanariUnify(); +// +// UnifyType theta = supTheta.getSuperedType(); +// Set cs = fc.getAllTypesByName(theta.getName()); +// cs.add(theta); +// +// for(UnifyType c : cs) { +// Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); +// thetaQs.add(theta); +// +// Set thetaQPrimes = new HashSet<>(); +// TypeParams cParams = c.getTypeParams(); +// if(cParams.size() == 0) +// thetaQPrimes.add(c); +// else { +// ArrayList> candidateParams = new ArrayList<>(); +// for(UnifyType param : cParams) +// candidateParams.add(fc.grArg(param)); +// +// for(TypeParams tp : permuteParams(candidateParams)) +// thetaQPrimes.add(c.setTypeParams(tp)); +// } +// +// for(UnifyType tqp : thetaQPrimes) { +// Optional opt = unify.unify(tqp, theta); +// if (!opt.isPresent()) +// continue; +// +// Unifier unifier = opt.get(); +// +// Set substitutionSet = new HashSet<>(); +// for (Entry sigma : unifier.getSubstitutions()) +// substitutionSet.add(new UnifyPair(sigma.getKey(), sigma.getValue(), PairOperator.EQUALSDOT)); +// +// for (UnifyType tq : thetaQs) { +// Set smaller = fc.smaller(unifier.apply(tq)); +// +// for(UnifyType thetaPrime : smaller) { +// Set resultPrime = new HashSet<>(); +// resultPrime.add(new UnifyPair(a, new SuperType(thetaPrime), PairOperator.EQUALSDOT)); +// resultPrime.addAll(substitutionSet); +// result.add(resultPrime); +// } +// } +// +// } +// } +// +// return result; + } + + protected Set> unifyCase8(UnifyType theta, PlaceholderType a, IFiniteClosure fc) { + Set> result = new HashSet<>(); + //for(UnifyType thetaS : fc.grArg(theta)) { + Set resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, theta, PairOperator.EQUALSDOT)); + result.add(resultPrime); + + UnifyType freshTph = PlaceholderType.freshPlaceholder(); + resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, new ExtendsType(freshTph), PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(theta, freshTph, PairOperator.SMALLERDOT)); + result.add(resultPrime); + + resultPrime = new HashSet<>(); + resultPrime.add(new UnifyPair(a, new SuperType(freshTph), PairOperator.EQUALSDOT)); + resultPrime.add(new UnifyPair(freshTph, theta, PairOperator.SMALLERDOT)); + result.add(resultPrime); + //} + + return result; + } + + 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/interfaces/IFiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java index fa640eb8..dcb6c4d1 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IFiniteClosure.java @@ -4,11 +4,16 @@ import java.util.Optional; import java.util.Set; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; +import de.dhbwstuttgart.typeinference.unify.model.FunNType; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; -import de.dhbwstuttgart.typeinference.unify.model.SimpleType; +import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; +/** + * + * @author Florian Steurer + */ public interface IFiniteClosure { /** @@ -37,18 +42,23 @@ public interface IFiniteClosure { */ public Set smArg(UnifyType type); - public Set grArg(SimpleType type); - public Set smArg(SimpleType type); + public Set grArg(ReferenceType type); + public Set smArg(ReferenceType type); public Set grArg(ExtendsType type); public Set smArg(ExtendsType type); public Set grArg(SuperType type); public Set smArg(SuperType type); - + public Set grArg(PlaceholderType type); public Set smArg(PlaceholderType type); + + public Set grArg(FunNType type); + public Set smArg(FunNType type); - public Optional getGenericType(String typeName); - public Set getAllTypes(String typeName); + public Optional getLeftHandedType(String typeName); + public Set getAncestors(UnifyType t); + public Set getChildren(UnifyType t); + public Set getAllTypesByName(String typeName); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java index 840d7259..26ea0dce 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java @@ -3,28 +3,69 @@ package de.dhbwstuttgart.typeinference.unify.interfaces; import java.util.Optional; import java.util.Set; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; +/** + * Contains the inference rules that are applied to the set Eq. + * @author Florian Steurer + */ public interface IRuleSet { - public Optional reduceUp(MPair pair); - public Optional reduceLow(MPair pair); - public Optional reduceUpLow(MPair pair); - public Optional> reduceExt(MPair pair); - public Optional> reduceSup(MPair pair); - public Optional> reduceEq(MPair pair); - public Optional> reduce1(MPair pair); - public Optional> reduce2(MPair pair); + public Optional reduceUp(UnifyPair pair); + public Optional reduceLow(UnifyPair pair); + public Optional reduceUpLow(UnifyPair pair); + public Optional> reduceExt(UnifyPair pair); + public Optional> reduceSup(UnifyPair pair); + public Optional> reduceEq(UnifyPair pair); + public Optional> reduce1(UnifyPair pair); + public Optional> reduce2(UnifyPair pair); - public boolean erase1(MPair pair); - public boolean erase2(MPair pair); - public boolean erase3(MPair pair); + /* + * Missing Reduce-Rules for Wildcards + */ + public Optional reduceWildcardLow(UnifyPair pair); + public Optional reduceWildcardLowRight(UnifyPair pair); + public Optional reduceWildcardUp(UnifyPair pair); + public Optional reduceWildcardUpRight(UnifyPair pair); + public Optional reduceWildcardLowUp(UnifyPair pair); + public Optional reduceWildcardUpLow(UnifyPair pair); + public Optional reduceWildcardLeft(UnifyPair pair); - public Optional swap(MPair pair); + /* + * FunN Rules + */ + public Optional> reduceFunN(UnifyPair pair); + public Optional> greaterFunN(UnifyPair pair); + public Optional> smallerFunN(UnifyPair pair); - public Optional adapt(MPair pair); - public Optional adaptExt(MPair pair); - public Optional adaptSup(MPair pair); + /** + * Checks whether the erase1-Rule applies to the pair. + * @return True if the pair is erasable, false otherwise. + */ + public boolean erase1(UnifyPair pair); - public Optional> subst(Set pair); + /** + * Checks whether the erase2-Rule applies to the pair. + * @return True if the pair is erasable, false otherwise. + */ + public boolean erase2(UnifyPair pair); + + /** + * Checks whether the erase3-Rule applies to the pair. + * @return True if the pair is erasable, false otherwise. + */ + public boolean erase3(UnifyPair pair); + + public Optional swap(UnifyPair pair); + + public Optional adapt(UnifyPair pair); + public Optional adaptExt(UnifyPair pair); + public Optional adaptSup(UnifyPair pair); + + /** + * Applies the subst-Rule to a set of pairs (usually Eq'). + * @param pairs The set of pairs where the subst rule should apply. + * @return An optional of the modified set, if there were any substitutions. An empty optional if there were no substitutions. + */ + public Optional> subst(Set pairs); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/ISetOperations.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/ISetOperations.java index caed79e4..4a98aaba 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/ISetOperations.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/ISetOperations.java @@ -3,6 +3,14 @@ package de.dhbwstuttgart.typeinference.unify.interfaces; import java.util.List; import java.util.Set; +/** + * Contains operations on sets. + * @author Florian Steurer + */ public interface ISetOperations { + /** + * Calculates the cartesian product of the sets. + * @return The cartesian product + */ Set> cartesianProduct(List> sets); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java index ef8775b1..524608f5 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java +++ b/src/de/dhbwstuttgart/typeinference/unify/interfaces/IUnify.java @@ -14,8 +14,20 @@ import de.dhbwstuttgart.typeinference.unify.model.Unifier; */ public interface IUnify { + /** + * Finds the most general unifier sigma of the set {t1,...,tn} so that + * sigma(t1) = sigma(t2) = ... = sigma(tn). + * @param terms The set of terms to be unified + * @return An optional of the most general unifier if it exists or an empty optional if there is no unifier. + */ public Optional unify(Set terms); + /** + * Finds the most general unifier sigma of the set {t1,...,tn} so that + * sigma(t1) = sigma(t2) = ... = sigma(tn). + * @param terms The set of terms to be unified + * @return An optional of the most general unifier if it exists or an empty optional if there is no unifier. + */ default public Optional unify(UnifyType... terms) { return unify(Arrays.stream(terms).collect(Collectors.toSet())); } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java b/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java index 4cf3ceef..9416d786 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/ExtendsType.java @@ -7,38 +7,28 @@ import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; /** * An extends wildcard type "? extends T". */ -public final class ExtendsType extends UnifyType { - - /** - * The extended type - */ - private UnifyType extendedType; +public final class ExtendsType extends WildcardType { /** * Creates a new extends wildcard type. * @param extendedType The extended type e.g. Integer in "? extends Integer" */ public ExtendsType(UnifyType extendedType) { - super("? extends " + extendedType.getName(), extendedType.getTypeParams()); - this.extendedType = extendedType; + super("? extends " + extendedType.getName(), extendedType); } - - /** - * Gets the type extended by this wildcard e.g. "Integer" for "? extends Integer" - * @return The extended type. - */ + public UnifyType getExtendedType() { - return extendedType; + return wildcardedType; } @Override public TypeParams getTypeParams() { - return extendedType.getTypeParams(); + return wildcardedType.getTypeParams(); } @Override public UnifyType setTypeParams(TypeParams newTp) { - return new ExtendsType(extendedType.setTypeParams(newTp)); + return new ExtendsType(wildcardedType.setTypeParams(newTp)); } @Override @@ -53,12 +43,16 @@ public final class ExtendsType extends UnifyType { @Override UnifyType apply(Unifier unif) { - return new ExtendsType(extendedType.apply(unif)); + return new ExtendsType(wildcardedType.apply(unif)); } @Override public int hashCode() { - return extendedType.hashCode() + 17; + /* + * It is important that the prime that is added is different to the prime added in hashCode() of SuperType. + * Otherwise ? extends T and ? super T have the same hashCode() for every Type T. + */ + return wildcardedType.hashCode() + 229; } @Override @@ -67,11 +61,12 @@ public final class ExtendsType extends UnifyType { return false; ExtendsType other = (ExtendsType) obj; - return other.getExtendedType().equals(extendedType); + return other.getWildcardedType().equals(wildcardedType); } @Override public String toString() { - return "? extends " + extendedType; + return "? extends " + wildcardedType; } + } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 35fae6cb..aae6d7e6 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -1,25 +1,33 @@ package de.dhbwstuttgart.typeinference.unify.model; +import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import de.dhbwstuttgart.typeinference.exceptions.NotImplementedException; +import de.dhbwstuttgart.typeinference.unify.MartelliMontanariUnify; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; +import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; public class FiniteClosure implements IFiniteClosure { - + private HashMap> inheritanceGraph; private HashMap>> strInheritanceGraph; + private Set pairs; + //private Set basicTypes; + //TODO im konstruktor mitgeben um typenabzuhandeln die keine extends beziehung haben. (Damit die FC diese Typen auch kennt) + //(ALternative: immer die extends zu object beziehung einfügen) - public FiniteClosure(Set pairs) { - - inheritanceGraph = new HashMap>(); + public FiniteClosure(Set pairs) { + this.pairs = new HashSet<>(pairs); + inheritanceGraph = new HashMap>(); // Build the transitive closure of the inheritance tree - for(MPair pair : pairs) { + for(UnifyPair pair : pairs) { if(pair.getPairOp() != PairOperator.SMALLER) continue; @@ -50,47 +58,216 @@ public class FiniteClosure implements IFiniteClosure { strInheritanceGraph.get(key.getName()).add(inheritanceGraph.get(key)); } } - + /** * Returns all types of the finite closure that are subtypes of the argument. * @return The set of subtypes of the argument. - */ + */ @Override public Set smaller(UnifyType type) { - if(!inheritanceGraph.containsKey(type)) - return new HashSet<>(); + if(type instanceof FunNType) + return computeSmallerFunN((FunNType) type); - Set result = inheritanceGraph.get(type).getContentOfDescendants(); - result.add(type); + return computeSmaller(type); + } + + private Set computeSmaller(UnifyType type) { + if(inheritanceGraph.containsKey(type)) { + Set result = new HashSet<>(); + result.add(type); + result.addAll(inheritanceGraph.get(type).getContentOfDescendants()); + return result; + } + + IUnify unify = new MartelliMontanariUnify(); + Set result1 = new HashSet<>(); + + // if T = T' then T <=* T' + result1.add(type); + + {ArrayList> paramCandidates = new ArrayList<>(); + for (UnifyType param : type.getTypeParams()) + paramCandidates.add(smArg(param)); + + Set permResult = permuteParams(paramCandidates); + + for (TypeParams newParams : permResult) + result1.add(type.setTypeParams(newParams));} + + Set result2 = new HashSet<>(); + if (strInheritanceGraph.containsKey(type.getName())) { + HashSet candidates = new HashSet<>(); + strInheritanceGraph.get(type.getName()).forEach(x -> candidates.add(x.getContent())); + + for(UnifyType typePrime : result1) { + for (UnifyType theta2 : candidates) { + Optional sigma2Opt = unify.unify(typePrime, theta2); + if (!sigma2Opt.isPresent()) + continue; + Unifier sigma2 = sigma2Opt.get(); + sigma2.swapPlaceholderSubstitutions(typePrime.getTypeParams().toArray()); + if(type.equals(theta2)) + continue; + Set theta1s = smaller(theta2); + for (UnifyType theta1 : theta1s) { + // Because only the most general type is calculated, sigma1 = sigma2 + UnifyType sigma1Theta1 = sigma2.apply(theta1); + result2.add(sigma1Theta1); + } + } + } + } + else + result2 = result1; + + Set result3 = new HashSet<>(); + for(UnifyType t : result2) { + ArrayList> paramCandidates = new ArrayList<>(); + for (UnifyType param : t.getTypeParams()) + paramCandidates.add(smArg(param)); + + Set permResult = permuteParams(paramCandidates); + + for (TypeParams newParams : permResult) { + UnifyType tPrime = t.setTypeParams(newParams); + if(tPrime.equals(t)) + result3.add(t); + else + result3.addAll(smaller(tPrime)); + } + + } + + return result3; + } + + private Set computeSmallerFunN(FunNType type) { + Set result = new HashSet<>(); + + // if T = T' then T <=* T' + result.add(type); + + ArrayList> paramCandidates = new ArrayList<>(); + paramCandidates.add(smaller(type.getTypeParams().get(0))); + for (int i = 1; i < type.getTypeParams().size(); i++) + paramCandidates.add(greater(type.getTypeParams().get(i))); + + Set permResult = permuteParams(paramCandidates); + + for (TypeParams newParams : permResult) + result.add(type.setTypeParams(newParams)); return result; } - + /** * Returns all types of the finite closure that are supertypes of the argument. * @return The set of supertypes of the argument. - */ + */ @Override public Set greater(UnifyType type) { - if(!inheritanceGraph.containsKey(type)) - return new HashSet<>(); + if(type instanceof FunNType) + return computeGreaterFunN((FunNType) type); + return computeGreater(type); + } + + protected Set computeGreater(UnifyType type) { + IUnify unify = new MartelliMontanariUnify(); + Set result1 = new HashSet<>(); + + if(inheritanceGraph.containsKey(type)) + result1.addAll(inheritanceGraph.get(type).getContentOfPredecessors()); + + // if T = T' then T <=* T' + result1.add(type); + + {ArrayList> paramCandidates = new ArrayList<>(); + for (UnifyType param : type.getTypeParams()) + paramCandidates.add(grArg(param)); + + Set permResult = new HashSet<>(); + permuteParams(paramCandidates, 0, permResult, new UnifyType[paramCandidates.size()]); + + for (TypeParams newParams : permResult) + result1.add(type.setTypeParams(newParams));} + + Set result2 = new HashSet<>(); + if (strInheritanceGraph.containsKey(type.getName()) && !inheritanceGraph.containsKey(type)) { + HashSet candidates = new HashSet<>(); + strInheritanceGraph.get(type.getName()).forEach(x -> candidates.add(x.getContent())); + + for(UnifyType typePrime : result1) { + for (UnifyType theta2 : candidates) { + Optional sigma2Opt = unify.unify(typePrime, theta2); + if (!sigma2Opt.isPresent()) + continue; + if(type.equals(theta2)) + continue; + + Unifier sigma2 = sigma2Opt.get(); + sigma2.swapPlaceholderSubstitutions(typePrime.getTypeParams().toArray()); + Set theta1s = greater(theta2); + for (UnifyType theta1 : theta1s) { + // Because only the most general type is calculated, sigma1 = sigma2 + UnifyType sigma1Theta1 = sigma2.apply(theta1); + result2.add(sigma1Theta1); + } + } + } + } + + result2.addAll(result1); + + Set result3 = new HashSet<>(); + for(UnifyType t : result2) { + ArrayList> paramCandidates = new ArrayList<>(); + for (UnifyType param : t.getTypeParams()) + paramCandidates.add(grArg(param)); + + Set permResult = new HashSet<>(); + permuteParams(paramCandidates, 0, permResult, new UnifyType[paramCandidates.size()]); + + for (TypeParams newParams : permResult) { + UnifyType tPrime = t.setTypeParams(newParams); + if(tPrime.equals(t)) + result3.add(t); + else + result3.addAll(greater(tPrime)); + } + + } + + return result3; + } + + protected Set computeGreaterFunN(FunNType type) { + Set result = new HashSet<>(); + + // if T = T' then T <=* T' + result.add(type); + + ArrayList> paramCandidates = new ArrayList<>(); + paramCandidates.add(greater(type.getTypeParams().get(0))); + for (int i = 1; i < type.getTypeParams().size(); i++) + paramCandidates.add(smaller(type.getTypeParams().get(i))); + + Set permResult = permuteParams(paramCandidates); + + for (TypeParams newParams : permResult) + result.add(type.setTypeParams(newParams)); - Set result = inheritanceGraph.get(type).getContentOfPredecessors(); - result.add(type); return result; } + @Override public Set grArg(UnifyType type) { return type.grArg(this); } - @Override - public Set grArg(SimpleType type) { - if(!inheritanceGraph.containsKey(type)) - return new HashSet(); - - Set result = new HashSet(); + @Override + public Set grArg(ReferenceType type) { + Set result = new HashSet(); result.add(type); smaller(type).forEach(x -> result.add(new SuperType(x))); @@ -99,12 +276,15 @@ public class FiniteClosure implements IFiniteClosure { return result; } + @Override + public Set grArg(FunNType type) { + throw new NotImplementedException(); + } + @Override public Set grArg(ExtendsType type) { - if(!inheritanceGraph.containsKey(type.getExtendedType())) - return new HashSet(); - Set result = new HashSet(); + result.add(type); UnifyType t = type.getExtendedType(); @@ -113,23 +293,25 @@ public class FiniteClosure implements IFiniteClosure { return result; } - @Override + @Override public Set grArg(SuperType type) { - if(!inheritanceGraph.containsKey(type.getSuperedType())) - return new HashSet(); - Set result = new HashSet(); + result.add(type); - UnifyType t = type.getSuperedType(); + UnifyType t = type.getSuperedType(); smaller(t).forEach(x -> result.add(new SuperType(x))); return result; } - @Override + @Override public Set grArg(PlaceholderType type) { - return new HashSet<>(); + HashSet result = new HashSet<>(); + result.add(type); + //result.add(new SuperType(type)); + //result.add(new ExtendsType(type)); + return result; } @Override @@ -137,24 +319,23 @@ public class FiniteClosure implements IFiniteClosure { return type.smArg(this); } - @Override - public Set smArg(SimpleType type) { - if(!inheritanceGraph.containsKey(type)) - return new HashSet(); - - Set result = new HashSet(); + @Override + public Set smArg(ReferenceType type) { + Set result = new HashSet(); result.add(type); - smaller(type).forEach(x -> result.add(new ExtendsType(x))); - return result; + } + + @Override + public Set smArg(FunNType type) { + throw new NotImplementedException(); } - + + @Override public Set smArg(ExtendsType type) { - if(!inheritanceGraph.containsKey(type.getExtendedType())) - return new HashSet(); - Set result = new HashSet(); + result.add(type); UnifyType t = type.getExtendedType(); @@ -168,12 +349,10 @@ public class FiniteClosure implements IFiniteClosure { } - @Override + @Override public Set smArg(SuperType type) { - if(!inheritanceGraph.containsKey(type.getSuperedType())) - return new HashSet(); - Set result = new HashSet(); + result.add(type); UnifyType t = type.getSuperedType(); @@ -186,31 +365,87 @@ public class FiniteClosure implements IFiniteClosure { return result; } - @Override + @Override public Set smArg(PlaceholderType type) { - return new HashSet<>(); + HashSet result = new HashSet<>(); + result.add(type); + return result; } + + public boolean isGenericType(UnifyType t) { + if(t.getTypeParams().size() == 0) + return true; + + if(!strInheritanceGraph.containsKey(t.getName())) + return false; + + for(UnifyPair pair : pairs) + if(pair.getLhsType().equals(t)) + return true; + + return false; + } + + @Override + public Set getAllTypesByName(String typeName) { + if(!strInheritanceGraph.containsKey(typeName)) + return new HashSet<>(); + return strInheritanceGraph.get(typeName).stream().map(x -> x.getContent()).collect(Collectors.toCollection(HashSet::new)); + } + @Override - public Optional getGenericType(String typeName) { + public Optional getLeftHandedType(String typeName) { if(!strInheritanceGraph.containsKey(typeName)) return Optional.empty(); - HashSet> candidates = strInheritanceGraph.get(typeName); - - for(Node node : candidates) { - UnifyType candidate = node.getContent(); - if(candidate.getTypeParams().arePlaceholders()) - return Optional.of(candidate); - } + for(UnifyPair pair : pairs) + if(pair.getLhsType().getName().equals(typeName)) + return Optional.of(pair.getLhsType()); return Optional.empty(); } @Override - public Set getAllTypes(String typeName) { - if(!strInheritanceGraph.containsKey(typeName)) + public Set getAncestors(UnifyType t) { + if(!inheritanceGraph.containsKey(t)) return new HashSet<>(); - return strInheritanceGraph.get(typeName).stream().map(x -> x.getContent()).collect(Collectors.toCollection(HashSet::new)); + Set result = inheritanceGraph.get(t).getContentOfPredecessors(); + result.add(t); + return result; + } + + @Override + public Set getChildren(UnifyType t) { + if(!inheritanceGraph.containsKey(t)) + return new HashSet<>(); + Set result = inheritanceGraph.get(t).getContentOfDescendants(); + result.add(t); + return result; + } + + protected Set permuteParams(ArrayList> candidates) { + Set result = new HashSet<>(); + permuteParams(candidates, 0, result, new UnifyType[candidates.size()]); + return result; + } + + protected void permuteParams(ArrayList> candidates, int idx, Set result, UnifyType[] current) { + if(candidates.size() == idx) { + result.add(new TypeParams(Arrays.copyOf(current, current.length))); + return; + } + + Set localCandidates = candidates.get(idx); + + for(UnifyType t : localCandidates) { + current[idx] = t; + permuteParams(candidates, idx+1, result, current); + } + } + + @Override + public String toString(){ + return this.inheritanceGraph.toString(); } } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java b/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java new file mode 100644 index 00000000..3363be75 --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/unify/model/FunNType.java @@ -0,0 +1,68 @@ +package de.dhbwstuttgart.typeinference.unify.model; + +import java.util.Set; + +import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; + +public class FunNType extends UnifyType { + + protected FunNType(TypeParams p) { + super("FuN", p); + } + + public static FunNType getFunNType(TypeParams tp) { + if(!validateTypeParams(tp)) + throw new IllegalArgumentException("Invalid TypeParams for a FunNType: " + tp); + return new FunNType(tp); + } + + private static boolean validateTypeParams(TypeParams tp) { + if(tp.size() == 0) + return false; + for(UnifyType t : tp) + if(t instanceof WildcardType) + return false; + return true; + } + + @Override + public UnifyType setTypeParams(TypeParams newTp) { + return getFunNType(newTp); + } + + public int getN() { + return typeParams.size()-1; + } + + @Override + Set smArg(IFiniteClosure fc) { + return fc.smArg(this); + } + + @Override + Set grArg(IFiniteClosure fc) { + return fc.grArg(this); + } + + @Override + UnifyType apply(Unifier unif) { + // TODO Auto-generated method stub + return null; + } + + @Override + public int hashCode() { + return 31 + typeParams.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if(!(obj instanceof FunNType)) + return false; + + FunNType other = (FunNType) obj; + + return other.getTypeParams().equals(typeParams); + } + +} diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/MPair.java b/src/de/dhbwstuttgart/typeinference/unify/model/MPair.java deleted file mode 100644 index d7d17d52..00000000 --- a/src/de/dhbwstuttgart/typeinference/unify/model/MPair.java +++ /dev/null @@ -1,97 +0,0 @@ -package de.dhbwstuttgart.typeinference.unify.model; - -public class MPair { - - public enum PairOperator { - SMALLER, - SMALLERDOT, - SMALLERDOTWC, - EQUALS, - EQUALSDOT; - - @Override - public String toString() { - switch (this) { - case SMALLER: - return "<"; - case SMALLERDOT: - return "<."; - case SMALLERDOTWC: - return "<.?"; - case EQUALS: - return "="; - default: - return "=."; - } - }; - } - - private UnifyType lhs; - private UnifyType rhs; - private PairOperator pairOp; - - /*public MPair(Type t1, Type t2) { - lhs = t1; - rhs = t2; - pairOp = PairOperator.SMALLER; - }*/ - - public MPair(UnifyType t1, UnifyType t2, PairOperator op) { - lhs = t1; - rhs = t2; - pairOp = op; - } - - public UnifyType getLhsType() { - return lhs; - } - - public UnifyType getRhsType() { - return rhs; - } - - public PairOperator getPairOp() { - return pairOp; - } - - @Override - public boolean equals(Object obj) { - if(!(obj instanceof MPair)) - return false; - - MPair other = (MPair) obj; - - return other.getPairOp() == pairOp - && other.getLhsType().equals(lhs) - && other.getRhsType().equals(rhs); - } - - /** - * Substitutes the occurrences of Type t on the left or right side of the pair with the Type subst. - * @param t Type to be replaced. - * @param subst The type replacing t. - * @return A pair where occurrences of t are replaced by subst. - */ - public MPair substitute(UnifyType t, UnifyType subst) { - UnifyType newlhs = lhs; - if(lhs.equals(t)) newlhs = subst; - - UnifyType newrhs = rhs; - if(rhs.equals(t)) newrhs = subst; - - if(newlhs == lhs && newrhs == rhs) return this; - return new MPair(newlhs, newrhs, pairOp); - } - - @Override - public int hashCode() { - return 17 + 31 * lhs.hashCode() + 31 * rhs.hashCode() + 31 * pairOp.hashCode(); - } - - @Override - public String toString() { - return "(" + lhs + " " + pairOp + " " + rhs + ")"; - } -} - - diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/Node.java b/src/de/dhbwstuttgart/typeinference/unify/model/Node.java index 7010ec32..d338d16b 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/Node.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/Node.java @@ -4,7 +4,7 @@ import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; -public class Node { +class Node { private T content; private HashSet> predecessors = new HashSet<>(); diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/PairOperator.java b/src/de/dhbwstuttgart/typeinference/unify/model/PairOperator.java new file mode 100644 index 00000000..7b8258bd --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/unify/model/PairOperator.java @@ -0,0 +1,22 @@ +package de.dhbwstuttgart.typeinference.unify.model; + +public enum PairOperator { + SMALLER, + SMALLERDOT, + SMALLERDOTWC, + EQUALSDOT; + + @Override + public String toString() { + switch (this) { + case SMALLER: + return "<"; + case SMALLERDOT: + return "<."; + case SMALLERDOTWC: + return "<.?"; + default: + return "=."; + } + }; +} \ No newline at end of file diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java index f810e993..ddb7d273 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/PlaceholderType.java @@ -1,13 +1,50 @@ package de.dhbwstuttgart.typeinference.unify.model; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Random; import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; public final class PlaceholderType extends UnifyType{ + protected static final HashSet EXISTING_PLACEHOLDERS = new HashSet(); + protected static String nextName = "gen_"; + protected static Random rnd = new Random(43558747548978L); + + private final boolean IsGenerated; + public PlaceholderType(String name) { - super(name); + super(name, new TypeParams()); + EXISTING_PLACEHOLDERS.add(name); + IsGenerated = false; + } + + protected PlaceholderType(String name, boolean isGenerated) { + super(name, new TypeParams()); + EXISTING_PLACEHOLDERS.add(name); + IsGenerated = isGenerated; + } + + public static PlaceholderType freshPlaceholder() { + String name = nextName + randomChar(); + + while(EXISTING_PLACEHOLDERS.contains(name)); + name += randomChar(); + + return new PlaceholderType(name, true); + } + + /** + * Returns random char between 'a' and 'z' + */ + private static char randomChar() { + return (char) (rnd.nextInt(22) + 97); + } + + public boolean isGenerated() { + return IsGenerated; } @Override diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java b/src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java similarity index 59% rename from src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java rename to src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java index a8997439..4f557b53 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/SimpleType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/ReferenceType.java @@ -4,12 +4,12 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -public final class SimpleType extends UnifyType { - public SimpleType(String name, UnifyType... typeParams) { +public final class ReferenceType extends UnifyType { + public ReferenceType(String name, UnifyType... typeParams) { super(name, new TypeParams(typeParams)); } - private SimpleType(String name, TypeParams params) { + public ReferenceType(String name, TypeParams params) { super(name, params); } @@ -22,28 +22,28 @@ public final class SimpleType extends UnifyType { Set grArg(IFiniteClosure fc) { return fc.grArg(this); } - + @Override UnifyType apply(Unifier unif) { - return new SimpleType(typeName, typeParams.apply(unif)); + return new ReferenceType(typeName, typeParams.apply(unif)); } @Override public UnifyType setTypeParams(TypeParams newTp) { - return new SimpleType(new String(typeName), newTp); + return new ReferenceType(new String(typeName), newTp); } @Override public int hashCode() { - return typeName.hashCode(); + return 31 + 17 * typeName.hashCode() + 17 * typeParams.hashCode(); } @Override public boolean equals(Object obj) { - if(!(obj instanceof SimpleType)) + if(!(obj instanceof ReferenceType)) return false; - SimpleType other = (SimpleType) obj; + ReferenceType other = (ReferenceType) obj; if(!other.getName().equals(typeName)) return false; diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java b/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java index 8283c685..7c557ade 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/SuperType.java @@ -4,32 +4,28 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -public final class SuperType extends UnifyType { - - private UnifyType superedType; - +public final class SuperType extends WildcardType { public SuperType(UnifyType superedType) { - super("? super " + superedType.getName(), superedType.getTypeParams()); - this.superedType = superedType; + super("? super " + superedType.getName(), superedType); } public UnifyType getSuperedType() { - return superedType; + return wildcardedType; } @Override public String toString() { - return "? super " + superedType; + return "? super " + wildcardedType; } @Override public TypeParams getTypeParams() { - return superedType.getTypeParams(); + return wildcardedType.getTypeParams(); } @Override public UnifyType setTypeParams(TypeParams newTp) { - return new SuperType(superedType.setTypeParams(newTp)); + return new SuperType(wildcardedType.setTypeParams(newTp)); } @Override @@ -44,12 +40,16 @@ public final class SuperType extends UnifyType { @Override UnifyType apply(Unifier unif) { - return new SuperType(superedType.apply(unif)); + return new SuperType(wildcardedType.apply(unif)); } @Override public int hashCode() { - return superedType.hashCode() + 17; + /* + * It is important that the prime that is added is different to the prime added in hashCode() of ExtendsType. + * Otherwise ? extends T and ? super T have the same hashCode() for every Type T. + */ + return wildcardedType.hashCode() + 3917; } @Override @@ -58,6 +58,6 @@ public final class SuperType extends UnifyType { return false; SuperType other = (SuperType) obj; - return other.getSuperedType().equals(superedType); + return other.getSuperedType().equals(wildcardedType); } } diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java b/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java index a95a1b43..f5b7686b 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/TypeParams.java @@ -2,11 +2,20 @@ 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(UnifyType... types) { + public TypeParams(Menge types){ + typeParams = new UnifyType[types.size()]; + for(int i=0;i{ return new TypeParams(newparams); } + public UnifyType[] toArray() { + return Arrays.copyOf(typeParams, typeParams.length); + } @Override public Iterator iterator() { diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java index c277f8fc..f5af52d0 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/Unifier.java @@ -5,23 +5,27 @@ import java.util.Map.Entry; import java.util.Set; import java.util.function.Function; -public class Unifier implements Function { + +public class Unifier implements Function /*, Set*/ { // TODO set implementieren private HashMap substitutions = new HashMap<>(); - - public static Unifier IDENTITY = new Unifier(); - - public Unifier(PlaceholderType source, UnifyType target) { + + + public Unifier(PlaceholderType source, UnifyType target) { substitutions.put(source, target); } /** * Identity function as an "unifier". */ - public Unifier() { + protected Unifier() { } + + public static Unifier Identity() { + return new Unifier(); + } - public void Add(PlaceholderType source, UnifyType 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)); @@ -33,21 +37,33 @@ public class Unifier implements Function { return t.apply(this); } - public MPair apply(MPair p) { - return new MPair(this.apply(p.getLhsType()), this.apply(p.getRhsType()), p.getPairOp()); + public UnifyPair apply(UnifyPair p) { + return new UnifyPair(this.apply(p.getLhsType()), this.apply(p.getRhsType()), p.getPairOp()); } public boolean hasSubstitute(PlaceholderType t) { return substitutions.containsKey(t); } - public UnifyType getSubstitute(UnifyType t) { + public UnifyType getSubstitute(PlaceholderType t) { return substitutions.get(t); } public Set> getSubstitutions() { return substitutions.entrySet(); } + + public void swapPlaceholderSubstitutions(UnifyType... targetParams) { + for(UnifyType tph : targetParams) { + if(!(tph instanceof PlaceholderType)) + continue; + if(substitutions.containsKey(tph) && substitutions.get(tph) instanceof PlaceholderType) { + PlaceholderType newLhs = (PlaceholderType) substitutions.get(tph); + substitutions.remove(tph); + substitutions.put(newLhs, tph); + } + } + } @Override public String toString() { diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java b/src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java new file mode 100644 index 00000000..ed2c95ef --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java @@ -0,0 +1,80 @@ +package de.dhbwstuttgart.typeinference.unify.model; + +/** + * A pair which contains two types and an operator, e.q. (Integer <. a). + * @author Florian Steurer + */ +public class UnifyPair { + + /** + * The type on the left hand side of the pair. + */ + private UnifyType lhs; + + /** + * The type on the right hand side of the pair. + */ + private UnifyType rhs; + + /** + * The operator that determines the relation between the left and right hand side type. + */ + private PairOperator pairOp; + + /** + * Creates a new instance of the pair. + * @param lhs The type on the left hand side of the pair. + * @param rhs The type on the right hand side of the pair. + * @param op The operator that determines the relation between the left and right hand side type. + */ + public UnifyPair(UnifyType lhs, UnifyType rhs, PairOperator op) { + this.lhs = lhs; + this.rhs = rhs; + pairOp = op; + } + + /** + * Returns the type on the left hand side of the pair. + */ + public UnifyType getLhsType() { + return lhs; + } + + /** + * Returns the type on the right hand side of the pair. + */ + public UnifyType getRhsType() { + return rhs; + } + + /** + * Returns the operator that determines the relation between the left and right hand side type. + */ + public PairOperator getPairOp() { + return pairOp; + } + + @Override + public boolean equals(Object obj) { + if(!(obj instanceof UnifyPair)) + return false; + + UnifyPair other = (UnifyPair) obj; + + return other.getPairOp() == pairOp + && other.getLhsType().equals(lhs) + && other.getRhsType().equals(rhs); + } + + @Override + public int hashCode() { + return 17 + 31 * lhs.hashCode() + 31 * rhs.hashCode() + 31 * pairOp.hashCode(); + } + + @Override + public String toString() { + return "(" + lhs + " " + pairOp + " " + rhs + ")"; + } +} + + diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java b/src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java index 341eabd1..4f1965eb 100644 --- a/src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java +++ b/src/de/dhbwstuttgart/typeinference/unify/model/UnifyType.java @@ -4,35 +4,76 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; +/** + * Represents a java type. + * @author Florian Steurer + */ public abstract class UnifyType { + /** + * The name of the type e.q. "Integer", "? extends Integer" or "List" for (List) + */ protected final String typeName; + + /** + * The type parameters of the type. + */ protected final TypeParams typeParams; - protected UnifyType(String name, UnifyType... typeParams) { - typeName = name; - this.typeParams = new TypeParams(typeParams); - } - + /** + * Creates a new instance + * @param name Name of the type (e.q. List for List, Integer or ? extends Integer) + * @param typeParams Parameters of the type (e.q. for List) + */ protected UnifyType(String name, TypeParams p) { typeName = name; typeParams = p; } + /** + * Returns the name of the type. + * @return The name e.q. List for List, Integer or ? extends Integer + */ public String getName() { return typeName; } + /** + * The parameters of the type. + * @return Parameters of the type, e.q. for List. + */ public TypeParams getTypeParams() { return typeParams; } + /** + * Returns a new type that equals this type except for the type parameters. + * @param newTp The type params of the new type. + * @return A new type object. + */ public abstract UnifyType setTypeParams(TypeParams newTp); + /** + * Implementation of the visitor-pattern. Returns the set of smArg + * by calling the most specific overload in the FC. + * @param fc The FC that is called. + * @return The set that is smArg(this) + */ abstract Set smArg(IFiniteClosure fc); + /** + * Implementation of the visitor-pattern. Returns the set of grArg + * by calling the most specific overload in the FC. + * @param fc The FC that is called. + * @return The set that is grArg(this) + */ abstract Set grArg(IFiniteClosure fc); + /** + * Applies a unifier to this object. + * @param unif The unifier + * @return A UnifyType, that may or may not be a new object, that has its subtypes substituted. + */ abstract UnifyType apply(Unifier unif); @Override diff --git a/src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java b/src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java new file mode 100644 index 00000000..9db59498 --- /dev/null +++ b/src/de/dhbwstuttgart/typeinference/unify/model/WildcardType.java @@ -0,0 +1,45 @@ +package de.dhbwstuttgart.typeinference.unify.model; + +/** + * A wildcard type that is either a ExtendsType or a SuperType. + * @author Florian Steurer + */ +public abstract class WildcardType extends UnifyType { + + /** + * The wildcarded type, e.q. Integer for ? extends Integer. Never a wildcard type itself. + */ + protected UnifyType wildcardedType; + + /** + * Creates a new instance. + * @param name The name of the type, e.q. ? extends Integer + * @param wildcardedType The wildcarded type, e.q. Integer for ? extends Integer. Never a wildcard type itself. + */ + protected WildcardType(String name, UnifyType wildcardedType) { + super(name, wildcardedType.getTypeParams()); + this.wildcardedType = wildcardedType; + } + + /** + * Returns the wildcarded type, e.q. Integer for ? extends Integer. + * @return The wildcarded type. Never a wildcard type itself. + */ + public UnifyType getWildcardedType() { + return wildcardedType; + } + + @Override + public int hashCode() { + return wildcardedType.hashCode() + getName().hashCode() + 17; + } + + @Override + public boolean equals(Object obj) { + if(!(obj instanceof WildcardType)) + return false; + + WildcardType other = (WildcardType) obj; + return other.getWildcardedType().equals(wildcardedType); + } +} diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java b/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java deleted file mode 100644 index 4409ae7f..00000000 --- a/src/de/dhbwstuttgart/typeinference/unifynew/MartelliMontanariUnify.java +++ /dev/null @@ -1,137 +0,0 @@ -package de.dhbwstuttgart.typeinference.unifynew; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; -import de.dhbwstuttgart.typeinference.unify.model.MPair; -import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; -import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; -import de.dhbwstuttgart.typeinference.unify.model.UnifyType; -import de.dhbwstuttgart.typeinference.unify.model.TypeParams; -import de.dhbwstuttgart.typeinference.unify.model.Unifier; - -/** - * Implementation of the Martelli-Montanari unification algorithm. - * @author Florian Steurer - */ -public class MartelliMontanariUnify implements IUnify { - - @Override - public Optional unify(Set terms) { - if(terms.size() < 2) - return Optional.of(Unifier.IDENTITY); - - ArrayList termsQ = new ArrayList(); - Iterator iter = terms.iterator(); - UnifyType prev = iter.next(); - while(iter.hasNext()) { - UnifyType next = iter.next(); - termsQ.add(new MPair(prev, next, PairOperator.EQUALS)); - prev = next; - } - - Unifier mgu = Unifier.IDENTITY; - - int idx = 0; - while(idx < termsQ.size()) { - MPair pair = termsQ.get(idx); - - if(delete(pair)) { - termsQ.remove(idx); - continue; - } - - Optional> optSet = decompose(pair); - - if(optSet == null) - return Optional.empty(); // Unification failed - - if(optSet.isPresent()) { - termsQ.addAll(optSet.get()); - idx = idx+1 == termsQ.size() ? 0 : idx+1; - continue; - } - - Optional optPair = swap(pair); - - if(optPair.isPresent()) { - termsQ.add(optPair.get()); - idx = idx+1 == termsQ.size() ? 0 : idx+1; - continue; - } - - // Occurs-Check - if(pair.getLhsType() instanceof PlaceholderType - && pair.getRhsType().getTypeParams().occurs((PlaceholderType) pair.getLhsType())) - return Optional.empty(); - - Optional> optUni = eliminate(pair); - - if(optUni.isPresent()) { - Entry substitution = optUni.get(); - mgu.Add(substitution.getKey(), substitution.getValue()); - termsQ = termsQ.stream().map(mgu::apply).collect(Collectors.toCollection(ArrayList::new)); - idx = idx+1 == termsQ.size() ? 0 : idx+1; - continue; - } - - idx++; - } - - return Optional.of(mgu); - } - - private boolean delete(MPair pair) { - return pair.getRhsType().equals(pair.getLhsType()); - } - - private Optional> decompose(MPair pair) { - Set result = new HashSet<>(); - - UnifyType rhs = pair.getRhsType(); - UnifyType lhs = pair.getLhsType(); - - TypeParams rhsTypeParams = rhs.getTypeParams(); - TypeParams lhsTypeParams = lhs.getTypeParams(); - - if(rhsTypeParams.size() == 0 || lhsTypeParams.size() == 0) - return Optional.empty(); - - if(!rhs.getName().equals(lhs.getName()) || rhsTypeParams.size() != lhsTypeParams.size()) - return null; // conflict - - for(int i = 0; i < rhsTypeParams.size(); i++) - result.add(new MPair(rhsTypeParams.get(i), lhsTypeParams.get(i), PairOperator.EQUALSDOT)); - - return Optional.of(result); - } - - private Optional swap(MPair pair) { - UnifyType rhs = pair.getRhsType(); - UnifyType lhs = pair.getLhsType(); - - if(!(lhs instanceof PlaceholderType) && (rhs instanceof PlaceholderType)) - return Optional.of(new MPair(rhs, lhs, PairOperator.EQUALSDOT)); - - return Optional.empty(); - } - - 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)); - } -} diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java b/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java deleted file mode 100644 index fedccd86..00000000 --- a/src/de/dhbwstuttgart/typeinference/unifynew/RuleSet.java +++ /dev/null @@ -1,562 +0,0 @@ -package de.dhbwstuttgart.typeinference.unifynew; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; -import java.util.Queue; -import java.util.Set; -import java.util.stream.Collectors; - -import junit.framework.Assert; -import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; -import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; -import de.dhbwstuttgart.typeinference.unify.model.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; -import de.dhbwstuttgart.typeinference.unify.model.TypeParams; -import de.dhbwstuttgart.typeinference.unify.model.Unifier; -import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; - -public class RuleSet implements IRuleSet{ - - protected IFiniteClosure finiteClosure; - - public RuleSet(IFiniteClosure fc) { - finiteClosure = fc; - } - - @Override - public Optional reduceUp(MPair pair) { - if(pair.getPairOp() != PairOperator.SMALLERDOT) - return Optional.empty(); - - UnifyType rhsType = pair.getRhsType(); - if(!(rhsType instanceof SuperType)) - return Optional.empty(); - - UnifyType lhsType = pair.getLhsType(); - if(!(lhsType instanceof SimpleType) && !(lhsType instanceof PlaceholderType)) - return Optional.empty(); - - return Optional.of(new MPair(lhsType, ((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT)); - } - - @Override - public Optional reduceLow(MPair pair) { - if(pair.getPairOp() != PairOperator.SMALLERDOT) - return Optional.empty(); - - UnifyType lhsType = pair.getLhsType(); - if(!(lhsType instanceof ExtendsType)) - return Optional.empty(); - - UnifyType rhsType = pair.getRhsType(); - if(!(rhsType instanceof SimpleType) && !(rhsType instanceof PlaceholderType)) - return Optional.empty(); - - return Optional.of(new MPair(((ExtendsType) lhsType).getExtendedType(), rhsType, PairOperator.SMALLERDOT)); - } - - @Override - public Optional reduceUpLow(MPair pair) { - if(pair.getPairOp() != PairOperator.SMALLERDOT) - return Optional.empty(); - - UnifyType lhsType = pair.getLhsType(); - if(!(lhsType instanceof ExtendsType)) - return Optional.empty(); - - UnifyType rhsType = pair.getRhsType(); - if(!(rhsType instanceof SuperType)) - return Optional.empty(); - - return Optional.of(new MPair(((ExtendsType) lhsType).getExtendedType(),((SuperType) rhsType).getSuperedType(), PairOperator.SMALLERDOT)); - } - - @Override - public Optional> reduceExt(MPair pair) { - if(pair.getPairOp() != PairOperator.SMALLERDOTWC) - return Optional.empty(); - - UnifyType lhsType = pair.getLhsType(); - - if(!(lhsType instanceof SimpleType) && !(lhsType instanceof ExtendsType)) - return Optional.empty(); - - UnifyType rhsType = pair.getRhsType(); - - if(!(rhsType instanceof ExtendsType)) - return Optional.empty(); - - if(lhsType.getTypeParams().empty() || rhsType.getTypeParams().size() != lhsType.getTypeParams().size()) - return Optional.empty(); - - int[] pi = pi(lhsType, rhsType); - - if(pi.length == 0) - return Optional.empty(); - - TypeParams rhsTypeParams = rhsType.getTypeParams(); - TypeParams lhsTypeParams = lhsType.getTypeParams(); - Set result = new HashSet<>(); - - for(int rhsIdx = 0; rhsIdx < rhsTypeParams.size(); rhsIdx++) - result.add(new MPair(lhsTypeParams.get(pi[rhsIdx]), rhsTypeParams.get(rhsIdx), PairOperator.SMALLERDOTWC)); - - return Optional.of(result); - } - - @Override - public Optional> reduceSup(MPair pair) { - if(pair.getPairOp() != PairOperator.SMALLERDOTWC) - return Optional.empty(); - - UnifyType lhsType = pair.getLhsType(); - - if(!(lhsType instanceof SimpleType) && !(lhsType instanceof SuperType)) - return Optional.empty(); - - UnifyType rhsType = pair.getRhsType(); - - if(!(rhsType instanceof SuperType)) - return Optional.empty(); - - if(lhsType.getTypeParams().empty() || rhsType.getTypeParams().size() != lhsType.getTypeParams().size()) - return Optional.empty(); - - int[] pi = pi(lhsType, rhsType); - - if(pi.length == 0) - return Optional.empty(); - - TypeParams rhsTypeParams = rhsType.getTypeParams(); - TypeParams lhsTypeParams = lhsType.getTypeParams(); - Set result = new HashSet<>(); - - for(int rhsIdx = 0; rhsIdx < rhsTypeParams.size(); rhsIdx++) - result.add(new MPair(lhsTypeParams.get(pi[rhsIdx]), rhsTypeParams.get(rhsIdx), PairOperator.SMALLERDOTWC)); - - return Optional.of(result); - } - - @Override - public Optional> reduceEq(MPair pair) { - if(pair.getPairOp() != PairOperator.SMALLERDOTWC) - return Optional.empty(); - - UnifyType lhsType = pair.getLhsType(); - if(lhsType instanceof PlaceholderType || lhsType.getTypeParams().empty()) - return Optional.empty(); - - UnifyType rhsType = pair.getRhsType(); - - if(!rhsType.getName().equals(lhsType.getName())) - return Optional.empty(); - - if(rhsType instanceof PlaceholderType || rhsType.getTypeParams().empty()) - return Optional.empty(); - - if(rhsType.getTypeParams().size() != lhsType.getTypeParams().size()) - return Optional.empty(); - - // TODO Permutation? - Set result = new HashSet<>(); - TypeParams lhsTypeParams = lhsType.getTypeParams(); - TypeParams rhsTypeParams = rhsType.getTypeParams(); - - for(int i = 0; i < lhsTypeParams.size(); i++) - result.add(new MPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT)); - - return Optional.of(result); - } - - @Override - public Optional> reduce1(MPair pair) { - if(pair.getPairOp() != PairOperator.SMALLERDOT) - return Optional.empty(); - - UnifyType lhsType = pair.getLhsType(); - if(!(lhsType instanceof SimpleType)) - return Optional.empty(); - - UnifyType rhsType = pair.getRhsType(); - if(!(rhsType instanceof SimpleType)) - return Optional.empty(); - - SimpleType lhsSType = (SimpleType) lhsType; - SimpleType rhsSType = (SimpleType) rhsType; - - if(lhsSType.getTypeParams().empty() || lhsSType.getTypeParams().size() != rhsSType.getTypeParams().size()) - return Optional.empty(); - - int[] pi = pi(lhsSType, rhsSType); - - if(pi.length == 0) - return Optional.empty(); - - TypeParams rhsTypeParams = rhsType.getTypeParams(); - TypeParams lhsTypeParams = lhsType.getTypeParams(); - Set result = new HashSet<>(); - - for(int rhsIdx = 0; rhsIdx < rhsTypeParams.size(); rhsIdx++) - result.add(new MPair(lhsTypeParams.get(pi[rhsIdx]), rhsTypeParams.get(rhsIdx), PairOperator.SMALLERDOTWC)); - - return Optional.of(result); - } - - @Override - public Optional> reduce2(MPair pair) { - if(pair.getPairOp() != PairOperator.EQUALSDOT) - return Optional.empty(); - - UnifyType lhsType = pair.getLhsType(); - SimpleType lhsSType; - - if(lhsType instanceof SimpleType) - lhsSType = (SimpleType) lhsType; - else if(lhsType instanceof ExtendsType) - lhsSType = (SimpleType) ((ExtendsType) lhsType).getExtendedType(); - else if(lhsType instanceof SuperType) - lhsSType = (SimpleType) ((SuperType) lhsType).getSuperedType(); - else - return Optional.empty(); - - if(lhsSType.getTypeParams().empty()) - return Optional.empty(); - - UnifyType rhsType = pair.getLhsType(); - SimpleType rhsSType; - - if(rhsType instanceof SimpleType) - rhsSType = (SimpleType) rhsType; - else if(rhsType instanceof ExtendsType) - rhsSType = (SimpleType) ((ExtendsType) rhsType).getExtendedType(); - else if(rhsType instanceof SuperType) - rhsSType = (SimpleType) ((SuperType) rhsType).getSuperedType(); - else - return Optional.empty(); - - if(!rhsSType.getName().equals(lhsSType.getName())) - return Optional.empty(); - - Assert.assertEquals(lhsSType.getTypeParams().size(), rhsSType.getTypeParams().size()); - //if(rhsSType.getTypeParams().size() != lhsSType.getTypeParams().size()) - // return Optional.empty(); - - Set result = new HashSet<>(); - - TypeParams rhsTypeParams = rhsSType.getTypeParams(); - TypeParams lhsTypeParams = lhsSType.getTypeParams(); - for(int i = 0; i < rhsTypeParams.size(); i++) - result.add(new MPair(lhsTypeParams.get(i), rhsTypeParams.get(i), PairOperator.EQUALSDOT)); - - return Optional.of(result); - } - - @Override - public boolean erase1(MPair pair) { - if(pair.getPairOp() != PairOperator.SMALLERDOT) - return false; - - UnifyType lhsType = pair.getLhsType(); - if(!(lhsType instanceof SimpleType) && !(lhsType instanceof PlaceholderType)) - return false; - - UnifyType rhsType = pair.getRhsType(); - if(!(rhsType instanceof SimpleType) && !(rhsType instanceof PlaceholderType)) - return false; - - return finiteClosure.greater(lhsType).contains(rhsType); - } - - @Override - public boolean erase2(MPair pair) { - if(pair.getPairOp() != PairOperator.SMALLERDOTWC) - return false; - - UnifyType lhsType = pair.getLhsType(); - UnifyType rhsType = pair.getRhsType(); - - return finiteClosure.grArg(lhsType).contains(rhsType); - } - - @Override - public boolean erase3(MPair pair) { - if(pair.getPairOp() != PairOperator.EQUALSDOT) - return false; - - return pair.getLhsType().equals(pair.getRhsType()); - } - - @Override - public Optional swap(MPair pair) { - if(pair.getPairOp() != PairOperator.EQUALSDOT) - return Optional.empty(); - - if(pair.getLhsType() instanceof PlaceholderType) - return Optional.empty(); - - if(!(pair.getRhsType() instanceof PlaceholderType)) - return Optional.empty(); - - return Optional.of(new MPair(pair.getRhsType(), pair.getLhsType(), PairOperator.EQUALSDOT)); - } - - @Override - public Optional adapt(MPair pair) { - if(pair.getPairOp() != PairOperator.SMALLERDOT) - return Optional.empty(); - - UnifyType typeD = pair.getLhsType(); - if(!(typeD instanceof SimpleType)) - return Optional.empty(); - - UnifyType typeDs = pair.getRhsType(); - if(!(typeDs instanceof SimpleType)) - return Optional.empty(); - - if(typeD.getTypeParams().size() == 0 || typeDs.getTypeParams().size() == 0) - return Optional.empty(); - - if(typeD.getName().equals(typeDs.getName())) - return Optional.empty(); - - Optional opt = finiteClosure.getGenericType(typeD.getName()); - - if(!opt.isPresent()) - return Optional.empty(); - - // The generic Version of Type D (D) - UnifyType typeDgen = opt.get(); - - // Actually greater+ because the types are ensured to have different names - Set greater = finiteClosure.greater(typeDgen); - opt = greater.stream().filter(x -> x.getName().equals(typeDs.getName())).findAny(); - - if(!opt.isPresent()) - return Optional.empty(); - - UnifyType newLhs = opt.get(); - - TypeParams typeDParams = typeD.getTypeParams(); - TypeParams typeDgenParams = typeDgen.getTypeParams(); - - Unifier unif = new Unifier((PlaceholderType) typeDgenParams.get(0), typeDParams.get(0)); - for(int i = 1; i < typeDParams.size(); i++) - unif.andThen(new Unifier((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i))); - - return Optional.of(new MPair(unif.apply(newLhs), typeDs, PairOperator.SMALLERDOT)); - } - - @Override - public Optional adaptExt(MPair pair) { - if(pair.getPairOp() != PairOperator.SMALLERDOTWC) - return Optional.empty(); - - UnifyType typeD = pair.getLhsType(); - if(!(typeD instanceof SimpleType) && !(typeD instanceof ExtendsType)) - return Optional.empty(); - - UnifyType typeExtDs = pair.getRhsType(); - if(!(typeExtDs instanceof ExtendsType)) - return Optional.empty(); - - if(typeD.getTypeParams().size() == 0 || typeExtDs.getTypeParams().size() == 0) - return Optional.empty(); - - UnifyType typeDgen; - if(typeD instanceof SimpleType) - typeDgen = finiteClosure.getGenericType(typeD.getName()).orElse(null); - else { - 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); - - Optional opt = grArg.stream().filter(x -> x.getName().equals(typeExtDs.getName())).findAny(); - - if(!opt.isPresent()) - return Optional.empty(); - - UnifyType newLhs = ((ExtendsType) opt.get()).getExtendedType(); - - TypeParams typeDParams = typeD.getTypeParams(); - TypeParams typeDgenParams = typeDgen.getTypeParams(); - - Unifier unif = new Unifier((PlaceholderType) typeDgenParams.get(0), typeDParams.get(0)); - for(int i = 1; i < typeDParams.size(); i++) - unif.andThen(new Unifier((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i))); - - return Optional.of(new MPair(unif.apply(newLhs), typeExtDs, PairOperator.SMALLERDOTWC)); - } - - @Override - public Optional adaptSup(MPair pair) { - if(pair.getPairOp() != PairOperator.SMALLERDOTWC) - return Optional.empty(); - - UnifyType typeDs = pair.getLhsType(); - if(!(typeDs instanceof SimpleType) && !(typeDs instanceof SuperType)) - return Optional.empty(); - - UnifyType typeSupD = pair.getRhsType(); - if(!(typeSupD instanceof SuperType)) - return Optional.empty(); - - if(typeDs.getTypeParams().size() == 0 || typeSupD.getTypeParams().size() == 0) - return Optional.empty(); - - - Optional opt = finiteClosure.getGenericType(((SuperType) typeSupD).getSuperedType().getName()); - - if(!opt.isPresent()) - return Optional.empty(); - - 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); - opt = smArg.stream().filter(x -> x.getName().equals(typeDs.getName())).findAny(); - - if(!opt.isPresent()) - return Optional.empty(); - - // New RHS - UnifyType newRhs = null; - if(typeDs instanceof SimpleType) - newRhs = new ExtendsType(typeDs); - else - newRhs = new ExtendsType(((SuperType) typeDs).getSuperedType()); - - // New LHS - UnifyType newLhs = opt.get(); - TypeParams typeDParams = typeSupD.getTypeParams(); - TypeParams typeSupDsgenParams = typeSupDgen.getTypeParams(); - - Unifier unif = new Unifier((PlaceholderType) typeSupDsgenParams.get(0), typeDParams.get(0)); - for(int i = 1; i < typeDParams.size(); i++) - unif.andThen(new Unifier((PlaceholderType) typeSupDsgenParams.get(i), typeDParams.get(i))); - - return Optional.of(new MPair(unif.apply(newLhs), newRhs, PairOperator.SMALLERDOTWC)); - } - - /** - * Finds the permutation pi of the type arguments of two types based on the finite closure - * @param C The type which arguments are permuted - * @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(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()); - if(opt.isPresent()) cFromFc = new ExtendsType(opt.get()); - } - else if(C instanceof SuperType) { - 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(); - if(D instanceof ExtendsType) { - SimpleType dSType = (SimpleType) ((ExtendsType) D).getExtendedType(); - opt = finiteClosure.grArg(cFromFc).stream() - .filter(x -> x instanceof ExtendsType) - .filter(x -> ((ExtendsType) x).getExtendedType().getName().equals(dSType.getName())).findAny(); - } - else if(D instanceof SuperType) { - SimpleType dSType = (SimpleType) ((SuperType) D).getSuperedType(); - opt = finiteClosure.grArg(cFromFc).stream() - .filter(x -> x instanceof SuperType) - .filter(x -> ((SuperType) x).getSuperedType().getName().equals(dSType.getName())).findAny(); - } - else if (D instanceof SimpleType) - opt = finiteClosure.greater(cFromFc).stream() - .filter(x -> x.getName().equals(D.getName())).findAny(); - - if(!opt.isPresent()) - return new int[0]; - - UnifyType dFromFc = opt.get(); - - Assert.assertEquals(cFromFc.getTypeParams().size(), dFromFc.getTypeParams().size()); - Assert.assertTrue(dFromFc.getTypeParams().size() > 0); - - TypeParams cArgs = cFromFc.getTypeParams(); - TypeParams dArgs = dFromFc.getTypeParams(); - - int[] permutation = new int[dArgs.size()]; - - boolean succ = true; - for (int dArgIdx = 0; dArgIdx < dArgs.size() && succ; dArgIdx++) { - UnifyType dArg = dArgs.get(dArgIdx); - succ = false; - for (int pi = 0; pi < cArgs.size(); pi++) - if (cArgs.get(pi).getName().equals(dArg.getName())) { - permutation[dArgIdx] = pi; - succ = true; - break; - } - } - - if(succ) return permutation; - return new int[0]; - } - - @Override - public Optional> subst(Set pairs) { - HashMap typeMap = new HashMap<>(); - - for(MPair pair : pairs) { - UnifyType t1 = pair.getLhsType(); - UnifyType t2 = pair.getRhsType(); - if(!typeMap.containsKey(t1)) - typeMap.put(t1, 0); - if(!typeMap.containsKey(t2)) - typeMap.put(t2, 0); - typeMap.put(t1, typeMap.get(t1)+1); - typeMap.put(t2, typeMap.get(t2)+1); - } - - ArrayList result = new ArrayList(pairs); - - boolean applied = false; - - for(int i = 0; i < result.size(); i++) { - MPair pair = result.get(i); - PlaceholderType lhsType = null; - UnifyType rhsType; - - if(pair.getPairOp() == PairOperator.EQUALSDOT - && pair.getLhsType() instanceof PlaceholderType) - lhsType = (PlaceholderType) pair.getLhsType(); - if(lhsType != null - && !((rhsType = pair.getRhsType()) instanceof PlaceholderType) - && typeMap.get(lhsType) > 1 // The type occurs in more pairs in the set than just the recent pair. - && !rhsType.getTypeParams().occurs(lhsType)) { - Unifier uni = new Unifier(lhsType, rhsType); - result = result.stream().map(uni::apply).collect(Collectors.toCollection(ArrayList::new)); - applied = true; - } - } - - return applied ? Optional.of(new HashSet<>(result)) : Optional.empty(); - } -} diff --git a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java b/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java deleted file mode 100644 index 6fa2eda1..00000000 --- a/src/de/dhbwstuttgart/typeinference/unifynew/Unify.java +++ /dev/null @@ -1,349 +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 - */ - - // All Sets - List> sets = new ArrayList>(); - - if(eq1s.size() != 0) - sets.add(eq1s); // Add Eq1' - - // Add the set of [a =. Theta | (a=. Theta) in Eq2'] - Set bufferSet = eq2s.stream() - .filter(x -> x.getPairOp() == PairOperator.EQUALSDOT && x.getLhsType() instanceof PlaceholderType) - .collect(Collectors.toSet()); - - if(bufferSet.size() != 0) - sets.add(bufferSet); - - // Sets that originate from pair pattern matching - // Sets of the "second level" - - sets.addAll(calculatePairSets(eq2s, fc)); - - /* Up to here, no cartesian products are calculated. - * Around here, filters for pairs and sets can be applied */ - - ISetOperations setOps = new GuavaSetOperations(); - - // Calculate the cartesian products - Set> result = setOps.cartesianProduct(sets).stream() - .map(x -> new HashSet(x)).collect(Collectors.toCollection(HashSet::new)); - //System.out.println(result); - - /* - * Step 5: Substitution - */ - - /* - * TODO - * Im Paper wird Eq'' genannt, es wird also von einer Menge in einer Menge in einer Menge ausgegangen. - * Durch das flache Kartesische Produkt gibt es hier aber nur Mengen in Mengen. - * Richtig so? - */ - - IRuleSet rules = new RuleSet(fc); - Set> changed = new HashSet<>(); - Set> unchanged = new HashSet<>(); - - for(Set eqss : result) { - Optional> newEqss = rules.subst(eqss); - if(newEqss.isPresent()) - changed.add(newEqss.get()); - else - unchanged.add(eqss); - } - - - /* - * Step 6 a) Restart for pairs where subst was applied - * b) Build the union over everything - */ - - for(Set eqss : changed) - unchanged.addAll(this.unify(eqss, fc)); - - /* - * Step 7: Filter result for solved pairs TODO wie? - */ - - return unchanged; - - } - - 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 List> calculatePairSets(Set eq2s, IFiniteClosure fc) { - List> result = new ArrayList>(); - - 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) { - UnifyType thetaPrime = pair.getRhsType(); - Set set = new HashSet<>(); - IUnify unify = new MartelliMontanariUnify(); - - //Set cs = fc.getAllTypes(rhsType.getName()); - UnifyType c = rhsType; - - //Set thetaQs = cs.stream().flatMap(x -> fc.smaller(x).stream()).collect(Collectors.toCollection(HashSet::new)); - Set thetaQs = fc.smaller(c); - - Set thetaQPrimes = new HashSet<>(); - - TypeParams cParams = c.getTypeParams(); - if(cParams.size() == 0) - thetaQPrimes.add(c); - else { - ArrayList> candidateParams = new ArrayList<>(); - for(UnifyType param : cParams) - candidateParams.add(fc.grArg(param)); - Set permutations = new HashSet(); - permuteParams(candidateParams, 0, permutations, new UnifyType[candidateParams.size()]); - - for(TypeParams tp : permutations) - thetaQPrimes.add(c.setTypeParams(tp)); - } - - 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.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(lhsType, x, PairOperator.EQUALSDOT)).forEach(x -> set.add(x)); - } - } - } - - result.add(set); - } - - // Case 2: (a <.? ? ext Theta') - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof ExtendsType){ - throw new NotImplementedException(); // TODO - } - - // Case 3: (a <.? ? sup Theta') - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType && rhsType instanceof SuperType) { - Set set = new HashSet<>(); - for(UnifyType theta : fc.smArg(rhsType)) - set.add(new MPair(lhsType, theta, PairOperator.EQUALSDOT)); - result.add(set); - } - - // Case 4: (a <.? Theta') - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof PlaceholderType) { - Set set = new HashSet<>(); - set.add(new MPair(lhsType, rhsType, PairOperator.EQUALSDOT)); - result.add(set); - } - - // Case 5: (Theta <. a) - else if(pairOp == PairOperator.SMALLERDOT && rhsType instanceof PlaceholderType) { - Set set = new HashSet<>(); - for(UnifyType thetaS : fc.greater(lhsType)) - set.add(new MPair(rhsType, thetaS, PairOperator.EQUALSDOT)); - result.add(set); - } - - // Case 6: (? ext Theta <.? a) - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof ExtendsType && rhsType instanceof PlaceholderType) { - Set set = new HashSet<>(); - for(UnifyType thetaS : fc.grArg(lhsType)) - set.add(new MPair(rhsType, thetaS, PairOperator.EQUALSDOT)); - result.add(set); - } - - // Case 7: (? sup Theta <.? a) - else if(pairOp == PairOperator.SMALLERDOTWC && lhsType instanceof SuperType && rhsType instanceof PlaceholderType) { - throw new NotImplementedException(); // TODO - } - - // Case 8: (Theta <.? a) - else if(pairOp == PairOperator.SMALLERDOTWC && rhsType instanceof PlaceholderType) { - Set set = new HashSet<>(); - for(UnifyType thetaS : fc.grArg(lhsType)) - set.add(new MPair(rhsType, thetaS, PairOperator.EQUALSDOT)); - result.add(set); - } - } - - return result; - } - - protected void permuteParams(ArrayList> candidates, int idx, Set result, UnifyType[] current) { - if(candidates.size() == idx) { - result.add(new TypeParams(Arrays.copyOf(current, current.length))); - return; - } - - Set localCandidates = candidates.get(idx); - - for(UnifyType t : localCandidates) { - current[idx] = t; - permuteParams(candidates, idx+1, result, current); - } - } - - private Set getAllInstantiations(UnifyType t, IFiniteClosure fc) { - Set result = new HashSet<>(); - result.add(t); - return result; - - // TODO - } - -} diff --git a/test/bytecode/types/AutoOverloading.jav b/test/bytecode/types/AutoOverloading.jav index 314a7f48..8d97f705 100644 --- a/test/bytecode/types/AutoOverloading.jav +++ b/test/bytecode/types/AutoOverloading.jav @@ -1,15 +1,20 @@ class AutoOverloading{ method2(String p){ - + return p; } method2(Integer p){ - + return p; } method(p){ - method2(p); + return method2(p); + } + + public static void main(String[] args){ + System.out.println(methode("hallo")); + System.out.println(methode(2)); } } \ No newline at end of file diff --git a/test/bytecode/types/Overloading2.jav b/test/bytecode/types/Overloading2.jav new file mode 100644 index 00000000..86961c95 --- /dev/null +++ b/test/bytecode/types/Overloading2.jav @@ -0,0 +1,18 @@ +import java.util.Vector; + +class Overloading2{ + + String method(Vector v) { + return v; + } + + Integer method(Vector v) { + return v; + } + + public static void main(String[] args){ + Overloading2 t; + t = new Overloading2(); + t.method(new Vector()); + } +} \ No newline at end of file diff --git a/test/bytecode/types/Overloading2Test.java b/test/bytecode/types/Overloading2Test.java new file mode 100644 index 00000000..aed1c45d --- /dev/null +++ b/test/bytecode/types/Overloading2Test.java @@ -0,0 +1,71 @@ +package bytecode.types; + +import static org.junit.Assert.*; + +import java.io.File; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Vector; + +import org.junit.Test; + +import bytecode.SourceFileBytecodeTest; + +public class Overloading2Test extends SourceFileBytecodeTest{ + @Override + protected void init() { + testName = "Overloading2"; + rootDirectory = System.getProperty("user.dir")+"/test/bytecode/types/"; + } + + + @Test + public void testString() { + try{ + ClassLoader classLoader = getClassLoader(); + + Class cls = classLoader.loadClass(testName); + + Object obj = cls.newInstance(); + + File file = new File(rootDirectory); + URL url = file.toURL(); + URL[] urls = new URL[]{url}; + + Class stringVector = classLoader.loadClass("java%util%Vector%%java%lang%String%"); + + Class[] params = new Class[1]; + params[0] = stringVector; + + Method method = cls.getDeclaredMethod("method", params); + method.invoke(obj, stringVector.newInstance()); + assertTrue(true); + }catch(Exception e){ + throw new RuntimeException(e); + } + } + + @Test + public void testInteger() { + try{ + ClassLoader classLoader = getClassLoader(); + + Class cls = classLoader.loadClass(testName); + + Object obj = cls.newInstance(); + + Class integerVector = classLoader.loadClass("java%util%Vector%%java%lang%Integer%"); + + Class[] params = new Class[1]; + params[0] = integerVector; + + Method method = cls.getDeclaredMethod("method", params); + method.invoke(obj, integerVector.newInstance()); + assertTrue(true); + }catch(Exception e){ + throw new RuntimeException(e); + } + } + +} diff --git a/test/bytecode/types/SuperType.java b/test/bytecode/types/SuperType.java index 5b2e2e12..42a8d77b 100644 --- a/test/bytecode/types/SuperType.java +++ b/test/bytecode/types/SuperType.java @@ -17,6 +17,7 @@ import bytecode.SourceFileBytecodeTest; public class SuperType extends SourceFileBytecodeTest{ + @Override protected void init() { testName = "ExtendsType"; diff --git a/test/plugindevelopment/TypeInsertTests/MultipleTypesInsertTester.java b/test/plugindevelopment/TypeInsertTests/MultipleTypesInsertTester.java index db3346a1..4542f9f0 100755 --- a/test/plugindevelopment/TypeInsertTests/MultipleTypesInsertTester.java +++ b/test/plugindevelopment/TypeInsertTests/MultipleTypesInsertTester.java @@ -102,12 +102,13 @@ public class MultipleTypesInsertTester extends TypeInsertTester{ } catch (IOException | yyException e) { e.printStackTrace(); TestCase.fail(); + }finally{ + writeLog(sourceFileToInfere+".log"); } for(String containString : mustContain){ TestCase.assertTrue("\""+containString+"\" muss in den inferierten Lösungen vorkommen",gesamterSrc.contains(containString)); } - writeLog(sourceFileToInfere+".log"); } private static void writeLog(String toFile){ diff --git a/test/unify/FiniteClosureBuilder.java b/test/unify/FiniteClosureBuilder.java index 30831a89..8b8b5f73 100644 --- a/test/unify/FiniteClosureBuilder.java +++ b/test/unify/FiniteClosureBuilder.java @@ -5,16 +5,16 @@ import java.util.Set; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; -import de.dhbwstuttgart.typeinference.unify.model.MPair; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; -import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; public class FiniteClosureBuilder { - private Set pairs = new HashSet<>(); + private Set pairs = new HashSet<>(); public void add(UnifyType sub, UnifyType sup) { - pairs.add(new MPair(sub, sup, PairOperator.SMALLER)); + pairs.add(new UnifyPair(sub, sup, PairOperator.SMALLER)); } public IFiniteClosure getFiniteClosure() { @@ -27,10 +27,13 @@ public class FiniteClosureBuilder { public IFiniteClosure getCollectionExample() { TypeFactory tf = new TypeFactory(); + + /* Collection */ UnifyType collection = tf.getSimpleType("Collection"); UnifyType set = tf.getSimpleType("Set", "T"); - UnifyType sortedSet = tf.getSimpleType("Set", "T"); + //Type sortedSet = tf.getSimpleType("SortedSet", "T"); Sorted set bei den Unit-Tests vergessen + // nachträgliches einfügen zu aufwendig UnifyType TreeSet = tf.getSimpleType("TreeSet", "T"); UnifyType hashSet = tf.getSimpleType("HashSet", "T"); UnifyType linkedHashSet = tf.getSimpleType("LinkedHashSet", "T"); @@ -40,11 +43,11 @@ public class FiniteClosureBuilder { UnifyType list = tf.getSimpleType("List", "T"); UnifyType vector = tf.getSimpleType("Vector", "T"); UnifyType stack = tf.getSimpleType("Stack", "T"); - UnifyType arrayList = tf.getSimpleType("ArrayList", "T"); + UnifyType arrayList = tf.getSimpleType("ArrayList", "T"); add(set, collection); - add(sortedSet, set); - add(TreeSet, sortedSet); + //add(sortedSet, set); + add(TreeSet, set); add(hashSet, set); add(linkedHashSet, set); @@ -57,6 +60,22 @@ public class FiniteClosureBuilder { add(arrayList, list); add(stack, vector); + /* Map */ + UnifyType map = tf.getSimpleType("Map", "K", "V"); + UnifyType sortedMap = tf.getSimpleType("SortedMap", "K", "V"); + UnifyType navigableMap = tf.getSimpleType("NavigableMap", "K", "V"); + UnifyType treeMap = tf.getSimpleType("TreeMap", "K", "V"); + UnifyType hashMap = tf.getSimpleType("HashMap", "K", "V"); + UnifyType hashtable = tf.getSimpleType("Hashtable", "K", "V"); + UnifyType linkedHashMap = tf.getSimpleType("LinkedHashMap", "K", "V"); + + add(sortedMap, map); + add(hashMap, map); + add(hashtable, map); + add(navigableMap, sortedMap); + add(treeMap, navigableMap); + add(linkedHashMap, hashMap); + IFiniteClosure fc = getFiniteClosure(); clear(); return fc; diff --git a/test/unify/FiniteClosureTest.java b/test/unify/FiniteClosureTest.java index 1b19969c..b58b9298 100644 --- a/test/unify/FiniteClosureTest.java +++ b/test/unify/FiniteClosureTest.java @@ -1,64 +1,692 @@ package unify; +import java.util.Arrays; import java.util.HashSet; import java.util.Set; +import java.util.stream.Collectors; +import org.junit.Assert; import org.junit.Test; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -import de.dhbwstuttgart.typeinference.unify.model.MPair; -import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; -import de.dhbwstuttgart.typeinference.unify.model.UnifyType; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public class FiniteClosureTest { - @Test - public void testGreater() { - IFiniteClosure fc = new FiniteClosureBuilder().getCollectionExample(); - TypeFactory tf = new TypeFactory(); - - System.out.println("\n\n----- Greater Test -----"); - System.out.println("Greater(LinkedList) = " + fc.greater(tf.getSimpleType("LinkedList", "T"))); - System.out.println("Greater(TreeSet) = " + fc.greater(tf.getSimpleType("TreeSet", "T"))); - System.out.println("Greater(Collection) = " + fc.greater(tf.getSimpleType("Collection"))); - } - - @Test - public void testGrArg() { - IFiniteClosure fc = new FiniteClosureBuilder().getCollectionExample(); - TypeFactory tf = new TypeFactory(); - - System.out.println("\n\n----- GrArg Test -----"); - System.out.println("GrArg(List) = " + fc.grArg(tf.getSimpleType("List", "T"))); - System.out.println("GrArg(? extends List) = " + fc.grArg(tf.getExtendsType(tf.getSimpleType("List", "T")))); - System.out.println("GrArg(? super List) = " + fc.grArg(tf.getSuperType(tf.getSimpleType("List", "T")))); - } - @Test public void testSmaller() { - IFiniteClosure fc = new FiniteClosureBuilder().getCollectionExample(); TypeFactory tf = new TypeFactory(); + + UnifyType integer = tf.getSimpleType("Integer"); + UnifyType number = tf.getSimpleType("Number"); - System.out.println("\n\n----- Smaller Test -----"); - System.out.println("Smaller(List) = " + fc.smaller(tf.getSimpleType("List", "T"))); - System.out.println("Smaller(TreeSet) = " + fc.smaller(tf.getSimpleType("TreeSet", "T"))); - System.out.println("Smaller(Collection) = " + fc.smaller(tf.getSimpleType("Collection"))); + FiniteClosureBuilder fcb = new FiniteClosureBuilder(); + fcb.add(integer, number); + fcb.add(tf.getSimpleType("MyMap", "T"), tf.getSimpleType("HashMap", tf.getSimpleType("Integer"))); + fcb.add(tf.getSimpleType("HashMap", "T"), tf.getSimpleType("Collection")); + IFiniteClosure fc = fcb.getCollectionExample(); + + /* + * Test Case 1: + * + * smaller(Set) = { HashSet, Set, LinkedHashSet } + */ + + UnifyType setInt = tf.getSimpleType("Set", integer); + UnifyType hashSetInt = tf.getSimpleType("HashSet", integer); + UnifyType treeSetInt = tf.getSimpleType("TreeSet", integer); + UnifyType linkedHashSetInt = tf.getSimpleType("LinkedHashSet", integer); + + Set expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + setInt, hashSetInt, linkedHashSetInt, treeSetInt, + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setInt)); + + /* + * Test Case 2: + * + * smaller(Set) = + * { HashSet, Set, TreeSet, LinkedHashSet, + * HashSet, Set, TreeSet, LinkedHashSet } + */ + + UnifyType extInt = tf.getExtendsType(integer); + UnifyType hashSetExtInt = tf.getSimpleType("HashSet", extInt); + UnifyType treeSetExtInt = tf.getSimpleType("TreeSet", extInt); + UnifyType linkedHashSetExtInt = tf.getSimpleType("LinkedHashSet", extInt); + UnifyType setExtInt = tf.getSimpleType("Set", extInt); + + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + setInt, hashSetInt, linkedHashSetInt, treeSetInt, + hashSetExtInt, treeSetExtInt, linkedHashSetExtInt, setExtInt, + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setExtInt)); + + /* + * Test Case 3: + * + * smaller(Set) = + * { HashSet, Set, TreeSet, LinkedHashSet, + * HashSet, Set, TreeSet, LinkedHashSet, + * HashSet, Set, TreeSet, LinkedHashSet + * HashSet } + */ + + UnifyType hashSetNum = tf.getSimpleType("HashSet", number); + UnifyType treeSetNum = tf.getSimpleType("TreeSet", number); + UnifyType linkedHashSetNum = tf.getSimpleType("LinkedHashSet", number); + UnifyType setNum = tf.getSimpleType("Set", number); + + UnifyType extNum = tf.getExtendsType(number); + UnifyType hashSetExtNum = tf.getSimpleType("HashSet", extNum); + UnifyType treeSetExtNum = tf.getSimpleType("TreeSet", extNum); + UnifyType linkedHashSetExtNum = tf.getSimpleType("LinkedHashSet", extNum); + UnifyType setExtNum = tf.getSimpleType("Set", extNum); + + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + setInt, hashSetInt, linkedHashSetInt, treeSetInt, + setNum, hashSetNum, linkedHashSetNum, treeSetNum, + setExtInt, hashSetExtInt, linkedHashSetExtInt, treeSetExtInt, + setExtNum, hashSetExtNum, linkedHashSetExtNum, treeSetExtNum + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setExtNum)); + + /* + * Test Case 4: + * smaller(Set) = + * { HashSet, Set, TreeSet, LinkedHashSet } + */ + + 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); + + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + setT, hashSetT, treeSetT, linkedHashSetT + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setT)); + + /* + * Test Case 5 + * + * smaller(Set = + * { Set, HashSet, TreeSet, LinkedHashSet, + * Set, HashSet, TreeSet, LinkedHashSet, + * Set, HashSet, TreeSet, LinkedHashSet } + */ + + UnifyType superNum = tf.getSuperType(number); + UnifyType superInt = tf.getSuperType(integer); + + UnifyType setSupInt = tf.getSimpleType("Set", superInt); + UnifyType hashSetSupInt = tf.getSimpleType("HashSet", superInt); + UnifyType linkedHashSetSupInt = tf.getSimpleType("LinkedHashSet", superInt); + UnifyType treeSetSupInt = tf.getSimpleType("TreeSet", superInt); + UnifyType setSupNum = tf.getSimpleType("Set", superNum); + UnifyType hashSetSupNum = tf.getSimpleType("HashSet", superNum); + UnifyType linkedHashSetSupNum = tf.getSimpleType("LinkedHashSet", superNum); + UnifyType treeSetSupNum = tf.getSimpleType("TreeSet", superNum); + + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + setSupInt, hashSetSupInt, linkedHashSetSupInt, treeSetSupInt, + setSupNum, hashSetSupNum, linkedHashSetSupNum, treeSetSupNum, + setInt, hashSetInt, linkedHashSetInt, treeSetInt, + setNum, hashSetNum, linkedHashSetNum, treeSetNum + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setSupInt)); + + /* + * Test Case 6: + * TODO probleme wenn Set weil T auch in der Klassendeklaration class Set verwendet wird. + * smaller(Set, Set, TreeSet, LinkedHashSet, + * HashSet, Set, TreeSet, LinkedHashSet } + * + */ + 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[] { + setT1, hashSetT1, treeSetT1, linkedHashSetT1, + setExtT1, hashSetExtT1, treeSetExtT1, linkedHashSetExtT1 + }).collect(Collectors.toSet())); + + //System.out.println(fc.smaller(setExtT1)); + Assert.assertEquals(expectedResult, fc.smaller(setExtT1)); + + /* + * Test Case 7: + * + * smaller(Set) = + * { HashSet, Set, TreeSet, LinkedHashSet, + * HashSet, Set, TreeSet, LinkedHashSet } + */ + + UnifyType notInFc = tf.getSimpleType("notInFC"); + UnifyType setNotInFc = tf.getSimpleType("Set", notInFc); + UnifyType hashSetNotInFc = tf.getSimpleType("HashSet", notInFc); + UnifyType treeSetNotInFc = tf.getSimpleType("TreeSet", notInFc); + UnifyType linkedHashSetNotInFc = tf.getSimpleType("LinkedHashSet", notInFc); + UnifyType hashSetExtNotInFc = tf.getSimpleType("HashSet", notInFc); + UnifyType treeSetExtNotInFc = tf.getSimpleType("TreeSet", notInFc); + UnifyType linkedHashSetExtNotInFc = tf.getSimpleType("LinkedHashSet", notInFc); + UnifyType setExtNotInFc = tf.getSimpleType("Set", notInFc); + + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + setNotInFc, hashSetNotInFc, treeSetNotInFc, linkedHashSetNotInFc, + setExtNotInFc, hashSetExtNotInFc, treeSetExtNotInFc, linkedHashSetExtNotInFc + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setNotInFc)); + + /* + * Test Case 8: + * + * smaller(Set) = + * { Set, HashSet, LinkedHashSet, TreeSet, + * Set, HashSet, LinkedHashSet, TreeSet } + */ + + UnifyType superNotInFc = tf.getSuperType(notInFc); + UnifyType setSuperNotInFc = tf.getSimpleType("Set", superNotInFc); + UnifyType hashSetSuperNotInFc = tf.getSimpleType("HashSet", superNotInFc); + UnifyType treeSetSuperNotInFc = tf.getSimpleType("TreeSet", superNotInFc); + UnifyType linkedHashSetSuperNotInFc = tf.getSimpleType("LinkedHashSet", superNotInFc); + + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + setNotInFc, hashSetNotInFc, treeSetNotInFc, linkedHashSetNotInFc, + setSuperNotInFc, hashSetSuperNotInFc, treeSetSuperNotInFc, linkedHashSetSuperNotInFc + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(setSuperNotInFc)); + + /* + * Test Case 8: + * + * smaller(NotInFc) = + * { NotInFc, NotInFc, NotInFc, NotInFc } + */ + + UnifyType notInFcExtNumber = tf.getSimpleType("NotInFc", extNum); + UnifyType notInFcInteger = tf.getSimpleType("NotInFc", integer); + UnifyType notInFcNumber = tf.getSimpleType("NotInFc", number); + UnifyType notInFcExtInt = tf.getSimpleType("NotInFc", extInt); + + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + notInFcExtNumber, notInFcInteger, notInFcNumber, notInFcExtInt + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, fc.smaller(notInFcExtNumber)); + + /* + * Test Case 9: + * + * smaller(NotInFc = + * { NotInFc, NotInFc } + */ + + UnifyType alsoNotInFc = tf.getSimpleType("AlsoNotInFc"); + UnifyType notInFcAlsoNotInFc = tf.getSimpleType("NotInFc", alsoNotInFc); + UnifyType notInFcSupAlsoNotInFc = tf.getSimpleType("NotInFc", tf.getSuperType(alsoNotInFc)); + + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + notInFcAlsoNotInFc, notInFcSupAlsoNotInFc + }).collect(Collectors.toSet())); + + Set actual = fc.smaller(notInFcSupAlsoNotInFc); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 10: + * + * smaller(TreeMap) = + * { TreeMap, TreeMap, TreeMap, TreeMap + * TreeMap, TreeMap, TreeMap, TreeMap, + * TreeMap, TreeMap, TreeMap + * TreeMap, TreeMap, TreeMap, TreeMap } + */ + + UnifyType treeMapExtNumSupInt = tf.getSimpleType("TreeMap", extNum, superInt); + + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + treeMapExtNumSupInt, tf.getSimpleType("TreeMap", extNum, superNum), tf.getSimpleType("TreeMap", extNum, integer), tf.getSimpleType("TreeMap", extNum, number), + tf.getSimpleType("TreeMap", number, superInt), tf.getSimpleType("TreeMap", number, superNum), tf.getSimpleType("TreeMap", number, integer), tf.getSimpleType("TreeMap", number, number), + tf.getSimpleType("TreeMap", integer, superInt), tf.getSimpleType("TreeMap", integer, superNum), tf.getSimpleType("TreeMap", integer, integer), tf.getSimpleType("TreeMap", integer, number), + tf.getSimpleType("TreeMap", extInt, superInt), tf.getSimpleType("TreeMap", extInt, superNum), tf.getSimpleType("TreeMap", extInt, integer), tf.getSimpleType("TreeMap", extInt, number) + }).collect(Collectors.toSet())); + + actual = fc.smaller(treeMapExtNumSupInt); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 11: + * + * smaller(SortedMap) = { SortedMap, NavigableMap, TreeMap } + */ + + UnifyType sortedMapNumberT = tf.getSimpleType("SortedMap", number, t); + UnifyType navigableMapNumberT = tf.getSimpleType("NavigableMap", number, t); + UnifyType treeMapNumberT = tf.getSimpleType("TreeMap", number, t); + + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + sortedMapNumberT, navigableMapNumberT, treeMapNumberT + }).collect(Collectors.toSet())); + + actual = fc.smaller(sortedMapNumberT); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 12: + * + * MyMap <* TreeMap> + * + * smaller(TreeMap) = { TreeMap>, MyMap } + */ + + fcb = new FiniteClosureBuilder(); + UnifyType k = tf.getPlaceholderType("K"); + UnifyType myMap = tf.getSimpleType("MyMap", k); + fcb.add(myMap, tf.getSimpleType("TreeMap", k, tf.getSimpleType("List", k))); + fcb.add(integer, number); + fc = fcb.getCollectionExample(); + + UnifyType treeMapNumberListNumber = tf.getSimpleType("TreeMap", number, tf.getSimpleType("List", number)); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + treeMapNumberListNumber, + tf.getSimpleType("MyMap", number) + }).collect(Collectors.toSet())); + + actual = fc.smaller(treeMapNumberListNumber); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 13: + * + * MyMap <* TreeMap> + * + * smaller(TreeMap) = + * { TreeMap, List>, + * TreeMap>, + * TreeMap>, + * TreeMap>, + * MyMap } + */ + + UnifyType listInteger = tf.getSimpleType("List", integer); + UnifyType treeMapExtNumberListInteger = tf.getSimpleType("TreeMap", extNum, listInteger); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + treeMapExtNumberListInteger, + tf.getSimpleType("TreeMap", extInt, listInteger), + tf.getSimpleType("TreeMap", number, listInteger), + tf.getSimpleType("TreeMap", integer, listInteger), + tf.getSimpleType("MyMap", integer) + }).collect(Collectors.toSet())); + + actual = fc.smaller(treeMapExtNumberListInteger); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 14 + * + * MyMap <* TreeMap> + * + * smaller(TreeMap) = + * { TreeMap, List>, + * TreeMap>, + * TreeMap>, + * TreeMap>, + * MyMap + * MyMap + * MyMap + * MyMap + */ + + UnifyType listExtNum = tf.getSimpleType("List", extNum); + UnifyType treeMapExtNumListExtNum = tf.getSimpleType("TreeMap", extNum, listExtNum); + UnifyType myMapInt = tf.getSimpleType("MyMap", integer); + UnifyType myMapNumber = tf.getSimpleType("MyMap", number); + UnifyType myMapExtInt = tf.getSimpleType("MyMap", extInt); + UnifyType myMapExtNum = tf.getSimpleType("MyMap", extNum); + + actual = fc.smaller(treeMapExtNumListExtNum); + + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + tf.getSimpleType("TreeMap", extNum, listExtNum), + tf.getSimpleType("TreeMap", extInt, listExtNum), + tf.getSimpleType("TreeMap", number, listExtNum), + tf.getSimpleType("TreeMap", integer, listExtNum), + myMapInt, myMapNumber, myMapExtInt, myMapExtNum + }).collect(Collectors.toSet())); + + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 15: + * + * MyMap <* TreeMap> + * + * smaller(NavigableSet>) = + * { Permutationen der List, + * Permutationen der List in TreeSets, + * MyMap und MyMap + * } + */ + + UnifyType navSet = tf.getSimpleType("NavigableMap", extInt, tf.getExtendsType(tf.getSimpleType("List", extInt))); + + actual = fc.smaller(navSet); + + Assert.assertEquals(82, actual.size()); + Assert.assertTrue(actual.contains(myMapExtInt)); + Assert.assertTrue(actual.contains(myMapInt)); + + /* + * Test Case 16: + * + * smaller(FunN) = + * { FunN, FunN, + * FunN, FunN, + * FunN, FunN, + * FunN, FunN } + */ + + UnifyType object = tf.getSimpleType("Object"); + + fcb = new FiniteClosureBuilder(); + fcb.add(integer, number); + fcb.add(number, object); + fc = fcb.getCollectionExample(); + + UnifyType funNNumber = tf.getFunNType(number, number, number); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + tf.getFunNType(number, number, number), tf.getFunNType(number, object, number), + tf.getFunNType(number, number, object), tf.getFunNType(number, object, object), + tf.getFunNType(integer, number, number), tf.getFunNType(integer, object, number), + tf.getFunNType(integer, number, object), tf.getFunNType(integer, object, object), + }).collect(Collectors.toSet())); + + actual = fc.smaller(funNNumber); + //System.out.println(actual); + Assert.assertEquals(expectedResult, actual); + } @Test - public void testSmArg() { - IFiniteClosure fc = new FiniteClosureBuilder().getCollectionExample(); + public void testGreater() { TypeFactory tf = new TypeFactory(); + FiniteClosureBuilder fcb = new FiniteClosureBuilder(); + UnifyType k = tf.getPlaceholderType("K"); + UnifyType integer = tf.getSimpleType("Integer"); + UnifyType number = tf.getSimpleType("Number"); + UnifyType myMap = tf.getSimpleType("MyMap", k); + UnifyType myIntMap = tf.getSimpleType("MyIntMap"); + UnifyType collection = tf.getSimpleType("Collection"); + UnifyType sortedSet =tf.getSimpleType("SortedSet", "T"); + UnifyType extInt = tf.getExtendsType(integer); + UnifyType extNum = tf.getExtendsType(number); + UnifyType supInt = tf.getSuperType(integer); + UnifyType supNum = tf.getSuperType(number); + fcb.add(myMap, tf.getSimpleType("Map", k, tf.getSimpleType("List", k))); + fcb.add(myIntMap, tf.getSimpleType("MyMap", integer)); + fcb.add(sortedSet, tf.getSimpleType("Set", "T")); // sortedSet < Set missing in collection example + fcb.add(integer, number); + IFiniteClosure fc = fcb.getCollectionExample(); - System.out.println("\n\n----- SmArg Test -----"); - System.out.println("SmArg(List) = " + fc.smArg(tf.getSimpleType("List", "T"))); - System.out.println("SmArg(? extends List) = " + fc.smArg(tf.getExtendsType(tf.getSimpleType("List", "T")))); - System.out.println("SmArg(? super List) = " + fc.smArg(tf.getSuperType(tf.getSimpleType("List", "T")))); - } - - @Test - public void testGetGenericType() { + /* + * Test Case 1: + * + * greater(SortedSet) = + * { SortedSet, Set, Collection + * SortedSet, SortedSet, SortedSet, + * Set, Set, Set } + */ + + UnifyType sortedSetInteger = tf.getSimpleType("SortedSet", integer); + Set expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + sortedSetInteger, tf.getSimpleType("Set", integer), collection, + tf.getSimpleType("SortedSet", extInt), tf.getSimpleType("SortedSet", supInt), + tf.getSimpleType("SortedSet", extNum), tf.getSimpleType("Set", extInt), + tf.getSimpleType("Set", supInt), tf.getSimpleType("Set", extNum) + }).collect(Collectors.toSet())); - // TODO + Set actual = fc.greater(sortedSetInteger); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 2: + * + * greater(SortedSet) = + * { SortedSet, SortedSet, + * Set, Set, Collection } + */ + + UnifyType sortedSetExtInt = tf.getSimpleType("SortedSet", extInt); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + sortedSetExtInt, tf.getSimpleType("SortedSet", extNum), collection, + tf.getSimpleType("Set", extInt), tf.getSimpleType("Set", extNum) + }).collect(Collectors.toSet())); + + actual = fc.greater(sortedSetExtInt); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 3: + * + * TODO hier extends und super? (siehe test case 4 bei smaller) + * greater(SortedSet) = + * { SortedSet, SortedSet, SortedSet, + * Set, Set, Set, Collection } + */ + + /* + * Test Case 4: + * + * greater(SortedSet) = + * { SortedSet, SortedSet + * Set, Set, Collection } + */ + + UnifyType sortedSetSupNum = tf.getSimpleType("SortedSet", supNum); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + sortedSetSupNum, tf.getSimpleType("SortedSet", supInt), collection, + tf.getSimpleType("Set", supNum), tf.getSimpleType("Set", supInt) + }).collect(Collectors.toSet())); + + actual = fc.greater(sortedSetSupNum); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 5: + * + * TODO nicht unifizierbar bei T wenn Set deklariert wurde. Können die beiden T's verschieden sein? + * greater(SortedSet) = + * { SortedSet, Set, Collection } + */ + + UnifyType extT = tf.getExtendsType(tf.getPlaceholderType("T1")); + UnifyType sortedSetExtT = tf.getSimpleType("SortedSet", extT); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + sortedSetExtT, tf.getSimpleType("Set", extT), collection, + }).collect(Collectors.toSet())); + + actual = fc.greater(sortedSetExtT); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 6: + * + * greater(SortedSet) = + * { SortedSet, SortedSet, SortedSet, + * Set, Set, Set, Collection } + */ + + UnifyType notInFc = tf.getSimpleType("NotInFc"); + UnifyType extNotInFc = tf.getExtendsType(notInFc); + UnifyType supNotInFc = tf.getSuperType(notInFc); + UnifyType sortedSetNotInFc= tf.getSimpleType("SortedSet", notInFc); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + sortedSetNotInFc, tf.getSimpleType("SortedSet", extNotInFc), tf.getSimpleType("SortedSet", supNotInFc), + tf.getSimpleType("Set", notInFc), tf.getSimpleType("Set", extNotInFc), tf.getSimpleType("Set", supNotInFc), + collection + }).collect(Collectors.toSet())); + + actual = fc.greater(sortedSetNotInFc); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 7: + * + * greater(SortedSet, Set, Collection } + */ + + UnifyType sortedSetSupNotInFc= tf.getSimpleType("SortedSet", supNotInFc); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + sortedSetSupNotInFc, tf.getSimpleType("Set", supNotInFc), collection + }).collect(Collectors.toSet())); + + actual = fc.greater(sortedSetSupNotInFc); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 8: + * + * greater(NotInFc) = + * { NotInFc, NotInFc, NotInFC, + * NotInFc } + */ + + UnifyType notInFcInteger = tf.getSimpleType("NotInFc", integer); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + notInFcInteger, tf.getSimpleType("NotInFc", supInt), + tf.getSimpleType("NotInFc", extInt), tf.getSimpleType("NotInFc", extNum) + }).collect(Collectors.toSet())); + + actual = fc.greater(notInFcInteger); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 9: + * greater(NotInFc) = + * { NotInFc, NotInFc } + */ + + UnifyType notInFcAlsoNotInFc = tf.getSimpleType("NotInFc", tf.getSimpleType("AlsoNotInFc")); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + notInFcAlsoNotInFc, tf.getSimpleType("NotInFc", tf.getExtendsType(tf.getSimpleType("AlsoNotInFc"))), + tf.getSimpleType("NotInFc", tf.getSuperType(tf.getSimpleType("AlsoNotInFc"))) + }).collect(Collectors.toSet())); + + actual = fc.greater(notInFcAlsoNotInFc); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 10: + * greater(Map) = + * { Map, Map, + * Map, Map, + * Map, Map, + * Map, Map } + */ + + UnifyType mapExtIntInt = tf.getSimpleType("Map", extInt, integer); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + mapExtIntInt, tf.getSimpleType("Map", extInt, extInt), + tf.getSimpleType("Map", extInt, supInt), tf.getSimpleType("Map", extInt, extNum), + tf.getSimpleType("Map", extNum, integer), tf.getSimpleType("Map", extNum, extInt), + tf.getSimpleType("Map", extNum, supInt), tf.getSimpleType("Map", extNum, extNum) + }).collect(Collectors.toSet())); + + actual = fc.greater(mapExtIntInt); + Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 11: + * + * MyIntMap < MyMap + * MyMap < Map> + * + * greater(MyIntMap) = + * { MyMap, MyMap, MyMap, MyMap, + * Map, Map, List, + * Map, List, Map, MyIntMap } + */ + + UnifyType listInteger = tf.getSimpleType("List", integer); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + myIntMap, tf.getSimpleType("MyMap", integer), tf.getSimpleType("MyMap", extInt), + tf.getSimpleType("MyMap", extNum), tf.getSimpleType("MyMap", supInt), + tf.getSimpleType("Map", integer, listInteger), tf.getSimpleType("Map", extInt, listInteger), + tf.getSimpleType("MyMap", extNum, listInteger), tf.getSimpleType("MyMap", supInt, listInteger) + }).collect(Collectors.toSet())); + + actual = fc.greater(myIntMap); + //Assert.assertEquals(expectedResult, actual); + + /* + * Test Case 12: + * + * MyIntMap < MyMap + * MyMap < Map> + * + * TODO + * D d = null; + * A> a = null; + * a = d; ist nicht möglich! + * + * greater(MyMap) = + * { MyMap, MyMap, + * Map>, + * Map, List> } + */ + + /* + * Test Case 13: + * + * greater(SortedMap, ? super List>) = + * + */ + + /* + * Test Case 14: + * + * greater(FunN) = + * { FunN, FunN, + * FunN, FunN, + * FunN, FunN, + * FunN, FunN } + */ + + UnifyType object = tf.getSimpleType("Object"); + + fcb = new FiniteClosureBuilder(); + fcb.add(integer, number); + fcb.add(number, object); + fc = fcb.getCollectionExample(); + + UnifyType funNNumber = tf.getFunNType(number, number, number); + expectedResult = new HashSet<>(Arrays.stream(new UnifyType[] { + tf.getFunNType(number, number, number), tf.getFunNType(number, integer, number), + tf.getFunNType(number, number, integer), tf.getFunNType(number, integer, integer), + tf.getFunNType(object, number, number), tf.getFunNType(object, integer, number), + tf.getFunNType(object, number, integer), tf.getFunNType(object, integer, integer) + }).collect(Collectors.toSet())); + + actual = fc.greater(funNNumber); + Assert.assertEquals(expectedResult, actual); } } diff --git a/test/unify/GenerateFiniteClosure.java b/test/unify/GenerateFiniteClosure.java index 378fb019..42a5e862 100644 --- a/test/unify/GenerateFiniteClosure.java +++ b/test/unify/GenerateFiniteClosure.java @@ -2,6 +2,8 @@ package unify; import static org.junit.Assert.*; +import java.util.Set; + import org.junit.Test; import de.dhbwstuttgart.syntaxtree.ImportDeclarations; @@ -12,8 +14,9 @@ import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.typeinference.Menge; import de.dhbwstuttgart.typeinference.assumptions.TypeAssumptions; import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; -public class GenerateFiniteClosure { +public class GenerateFiniteClosure{ private TypeAssumptions generateAssumptionsFromImport(String importClass){ SourceFile sf = new SourceFile(); @@ -41,7 +44,8 @@ public class GenerateFiniteClosure { String importClass = "java.util.Vector"; TypeAssumptions ass = generateAssumptionsFromImport(importClass); FiniteClosure fc = UnifyTypeFactory.generateFC(ass); - System.out.println(fc); + Set test = fc.getAllTypesByName(importClass); + assertTrue(test.size()>0); } } diff --git a/test/unify/RuleSetTest.java b/test/unify/RuleSetTest.java index 1fe1359d..0dc9f319 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.UnifyPair; +import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; 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.unify.model.PairOperator; public class RuleSetTest { @@ -28,14 +28,14 @@ public class RuleSetTest { * Positive Tests */ - MPair reduce1 = new MPair(tf.getSimpleType("type"), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair reduce2 = new MPair(tf.getPlaceholderType("T"), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair reduce1 = new UnifyPair(tf.getSimpleType("type"), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair reduce2 = new UnifyPair(tf.getPlaceholderType("T"), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair expected1 = new MPair(tf.getSimpleType("type"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair expected2 = new MPair(tf.getPlaceholderType("T"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair expected1 = new UnifyPair(tf.getSimpleType("type"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair expected2 = new UnifyPair(tf.getPlaceholderType("T"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - Optional opt1 = rules.reduceUp(reduce1); - Optional opt2 = rules.reduceUp(reduce2); + Optional opt1 = rules.reduceUp(reduce1); + Optional opt2 = rules.reduceUp(reduce2); Assert.assertTrue(opt1.isPresent()); Assert.assertTrue(opt2.isPresent()); @@ -46,10 +46,10 @@ public class RuleSetTest { * Negative Tests */ - MPair noreduce1 = new MPair(tf.getSuperType(tf.getSimpleType("type")), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair noreduce2 = new MPair(tf.getPlaceholderType("T"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair noreduce3 = new MPair(tf.getPlaceholderType("T"), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair noreduce4 = new MPair(tf.getPlaceholderType("T"), tf.getSuperType(tf.getSimpleType("type")), PairOperator.EQUALSDOT); + UnifyPair noreduce1 = new UnifyPair(tf.getSuperType(tf.getSimpleType("type")), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair noreduce2 = new UnifyPair(tf.getPlaceholderType("T"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair noreduce3 = new UnifyPair(tf.getPlaceholderType("T"), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair noreduce4 = new UnifyPair(tf.getPlaceholderType("T"), tf.getSuperType(tf.getSimpleType("type")), PairOperator.EQUALSDOT); Assert.assertFalse(rules.reduceUp(noreduce1).isPresent()); Assert.assertFalse(rules.reduceUp(noreduce2).isPresent()); @@ -65,14 +65,14 @@ public class RuleSetTest { /* * Positive Tests */ - MPair reduce1 = new MPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair reduce2 = new MPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getPlaceholderType("T"), PairOperator.SMALLERDOT); + UnifyPair reduce1 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair reduce2 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getPlaceholderType("T"), PairOperator.SMALLERDOT); - MPair expected1 = new MPair(tf.getSimpleType("type"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair expected2 = new MPair(tf.getSimpleType("type"), tf.getPlaceholderType("T"), PairOperator.SMALLERDOT); + UnifyPair expected1 = new UnifyPair(tf.getSimpleType("type"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair expected2 = new UnifyPair(tf.getSimpleType("type"), tf.getPlaceholderType("T"), PairOperator.SMALLERDOT); - Optional opt1 = rules.reduceLow(reduce1); - Optional opt2 = rules.reduceLow(reduce2); + Optional opt1 = rules.reduceLow(reduce1); + Optional opt2 = rules.reduceLow(reduce2); Assert.assertTrue(opt1.isPresent()); Assert.assertTrue(opt2.isPresent()); @@ -82,10 +82,10 @@ public class RuleSetTest { /* * Negative Tests */ - MPair noreduce1 = new MPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair noreduce2 = new MPair(tf.getPlaceholderType("T"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair noreduce3 = new MPair(tf.getSuperType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair noreduce4 = new MPair(tf.getExtendsType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.EQUALSDOT); + UnifyPair noreduce1 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair noreduce2 = new UnifyPair(tf.getPlaceholderType("T"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair noreduce3 = new UnifyPair(tf.getSuperType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair noreduce4 = new UnifyPair(tf.getExtendsType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.EQUALSDOT); Assert.assertFalse(rules.reduceLow(noreduce1).isPresent()); Assert.assertFalse(rules.reduceLow(noreduce2).isPresent()); @@ -101,14 +101,14 @@ public class RuleSetTest { /* * Positive Tests */ - MPair reduce1 = new MPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair reduce2 = new MPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getSuperType(tf.getPlaceholderType("T")), PairOperator.SMALLERDOT); + UnifyPair reduce1 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getSuperType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair reduce2 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getSuperType(tf.getPlaceholderType("T")), PairOperator.SMALLERDOT); - MPair expected1 = new MPair(tf.getSimpleType("type"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair expected2 = new MPair(tf.getSimpleType("type"), tf.getPlaceholderType("T"), PairOperator.SMALLERDOT); + UnifyPair expected1 = new UnifyPair(tf.getSimpleType("type"), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair expected2 = new UnifyPair(tf.getSimpleType("type"), tf.getPlaceholderType("T"), PairOperator.SMALLERDOT); - Optional opt1 = rules.reduceUpLow(reduce1); - Optional opt2 = rules.reduceUpLow(reduce2); + Optional opt1 = rules.reduceUpLow(reduce1); + Optional opt2 = rules.reduceUpLow(reduce2); Assert.assertTrue(opt1.isPresent()); Assert.assertTrue(opt2.isPresent()); @@ -118,10 +118,10 @@ public class RuleSetTest { /* * Negative Tests */ - MPair noreduce1 = new MPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair noreduce2 = new MPair(tf.getSuperType(tf.getPlaceholderType("T")), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); - MPair noreduce3 = new MPair(tf.getSuperType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.SMALLERDOT); - MPair noreduce4 = new MPair(tf.getExtendsType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.EQUALSDOT); + UnifyPair noreduce1 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("type")), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair noreduce2 = new UnifyPair(tf.getSuperType(tf.getPlaceholderType("T")), tf.getExtendsType(tf.getSimpleType("type")), PairOperator.SMALLERDOT); + UnifyPair noreduce3 = new UnifyPair(tf.getSuperType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.SMALLERDOT); + UnifyPair noreduce4 = new UnifyPair(tf.getExtendsType(tf.getPlaceholderType("T")), tf.getSimpleType("type"), PairOperator.EQUALSDOT); Assert.assertFalse(rules.reduceUpLow(noreduce1).isPresent()); Assert.assertFalse(rules.reduceUpLow(noreduce2).isPresent()); @@ -139,28 +139,28 @@ public class RuleSetTest { */ // C - SimpleType c1 = tf.getSimpleType("C", "T1", "T2", "T3", "T4"); + ReferenceType c1 = tf.getSimpleType("C", "T1", "T2", "T3", "T4"); // D - SimpleType d1 = tf.getSimpleType("D", "T4", "T1", "T2", "T3"); - SimpleType buffer = tf.getSimpleType("Buffer"); + ReferenceType d1 = tf.getSimpleType("D", "T4", "T1", "T2", "T3"); + ReferenceType buffer = tf.getSimpleType("Buffer"); //C - SimpleType c2 = tf.getSimpleType("C", tf.getSimpleType("Int"), tf.getExtendsType(tf.getSimpleType("Double")), tf.getPlaceholderType("M"), tf.getPlaceholderType("N")); + ReferenceType c2 = tf.getSimpleType("C", tf.getSimpleType("Int"), tf.getExtendsType(tf.getSimpleType("Double")), tf.getPlaceholderType("M"), tf.getPlaceholderType("N")); //D, Number, Double, N> - SimpleType d2 = tf.getSimpleType("D", tf.getSuperType(tf.getSimpleType("HashSet", "Int")), tf.getSimpleType("Number"), tf.getSimpleType("Double"), tf.getPlaceholderType("N")); + ReferenceType d2 = tf.getSimpleType("D", tf.getSuperType(tf.getSimpleType("HashSet", "Int")), tf.getSimpleType("Number"), tf.getSimpleType("Double"), tf.getPlaceholderType("N")); // C<...> < buffer < D<...> fcb.add(c1, buffer); fcb.add(buffer, d1); IRuleSet rules = new RuleSet(fcb.getFiniteClosure()); - MPair pair = new MPair(c2, d2, PairOperator.SMALLERDOT); + UnifyPair pair = new UnifyPair(c2, d2, PairOperator.SMALLERDOT); System.out.println("------ Reduce1 ------"); - Optional> res = rules.reduce1(pair); + Optional> res = rules.reduce1(pair); System.out.println(res); - pair = new MPair(c2, c2, PairOperator.SMALLERDOT); + pair = new UnifyPair(c2, c2, PairOperator.SMALLERDOT); res = rules.reduce1(pair); System.out.println(res); @@ -169,17 +169,17 @@ public class RuleSetTest { */ // Case 1: D <. C and C <* D - pair = new MPair(d2, c2, PairOperator.SMALLERDOT); + pair = new UnifyPair(d2, c2, PairOperator.SMALLERDOT); Assert.assertFalse(rules.reduce1(pair).isPresent()); // Case 2: D =. C - pair = new MPair(c2, d2, PairOperator.EQUALSDOT); + pair = new UnifyPair(c2, d2, PairOperator.EQUALSDOT); Assert.assertFalse(rules.reduce1(pair).isPresent()); // Case 3: C <. D and !(C <* D) fcb.clear(); rules = new RuleSet(fcb.getFiniteClosure()); - pair = new MPair(c1, d1, PairOperator.SMALLERDOT); + pair = new UnifyPair(c1, d1, PairOperator.SMALLERDOT); Assert.assertFalse(rules.reduce1(pair).isPresent()); } @@ -195,21 +195,21 @@ public class RuleSetTest { System.out.println("----- Reduce2 ------"); // C - SimpleType c1 = tf.getSimpleType("C", tf.getPlaceholderType("T1"), tf.getSimpleType("SType1"), tf.getExtendsType(tf.getSimpleType("SType1"))); + ReferenceType c1 = tf.getSimpleType("C", tf.getPlaceholderType("T1"), tf.getSimpleType("SType1"), tf.getExtendsType(tf.getSimpleType("SType1"))); // C - SimpleType c2 = tf.getSimpleType("C", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); + ReferenceType c2 = tf.getSimpleType("C", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); - MPair pair1 = new MPair(c1, c2, PairOperator.EQUALSDOT); - MPair pair2 = new MPair(tf.getExtendsType(c1), tf.getExtendsType(c2), PairOperator.EQUALSDOT); - MPair pair3 = new MPair(tf.getSuperType(c1), tf.getSuperType(c2), PairOperator.EQUALSDOT); + UnifyPair pair1 = new UnifyPair(c1, c2, PairOperator.EQUALSDOT); + UnifyPair pair2 = new UnifyPair(tf.getExtendsType(c1), tf.getExtendsType(c2), PairOperator.EQUALSDOT); + UnifyPair pair3 = new UnifyPair(tf.getSuperType(c1), tf.getSuperType(c2), PairOperator.EQUALSDOT); - Optional> opt1 = rules.reduce2(pair1); + Optional> opt1 = rules.reduce2(pair1); System.out.println(opt1); - Optional> opt2 = rules.reduce2(pair2); + Optional> opt2 = rules.reduce2(pair2); System.out.println(opt2); - Optional> opt3 = rules.reduce2(pair3); + Optional> opt3 = rules.reduce2(pair3); System.out.println(opt3); @@ -217,11 +217,11 @@ public class RuleSetTest { * Negative Tests */ - SimpleType d1 = tf.getSimpleType("D", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); - pair1 = new MPair(d1, c1, PairOperator.EQUALSDOT); // Case 1: D =. C - pair2 = new MPair(tf.getExtendsType(c1), c2, PairOperator.EQUALSDOT); // Case 2: ? extends C =. C - pair3 = new MPair(tf.getExtendsType(c1), tf.getSuperType(c2), PairOperator.EQUALSDOT); // Case 3: ? extends C =. ? super C - MPair pair4 = new MPair(c1, c2, PairOperator.SMALLERDOT); // Case 4: C <. C + ReferenceType d1 = tf.getSimpleType("D", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); + pair1 = new UnifyPair(d1, c1, PairOperator.EQUALSDOT); // Case 1: D =. C + pair2 = new UnifyPair(tf.getExtendsType(c1), c2, PairOperator.EQUALSDOT); // Case 2: ? extends C =. C + pair3 = new UnifyPair(tf.getExtendsType(c1), tf.getSuperType(c2), PairOperator.EQUALSDOT); // Case 3: ? extends C =. ? super C + UnifyPair pair4 = new UnifyPair(c1, c2, PairOperator.SMALLERDOT); // Case 4: C <. C Assert.assertFalse(rules.reduceEq(pair1).isPresent()); Assert.assertFalse(rules.reduceEq(pair2).isPresent()); @@ -239,13 +239,13 @@ public class RuleSetTest { */ // X - SimpleType x1 = tf.getSimpleType("X", "T1", "T2", "T3", "T4"); + ReferenceType x1 = tf.getSimpleType("X", "T1", "T2", "T3", "T4"); // Y - SimpleType y1 = tf.getSimpleType("Y", "T4", "T1", "T2", "T3"); - SimpleType buffer = tf.getSimpleType("Buffer"); + ReferenceType y1 = tf.getSimpleType("Y", "T4", "T1", "T2", "T3"); + ReferenceType buffer = tf.getSimpleType("Buffer"); //X - SimpleType x2 = tf.getSimpleType("X", tf.getSimpleType("Int"), tf.getExtendsType(tf.getSimpleType("Double")), tf.getPlaceholderType("M"), tf.getPlaceholderType("N")); + ReferenceType x2 = tf.getSimpleType("X", tf.getSimpleType("Int"), tf.getExtendsType(tf.getSimpleType("Double")), tf.getPlaceholderType("M"), tf.getPlaceholderType("N")); //? extends Y, Number, Double, N> ExtendsType extY1 = tf.getExtendsType(tf.getSimpleType("Y", tf.getSuperType(tf.getSimpleType("HashSet", "Int")), tf.getSimpleType("Number"), tf.getSimpleType("Double"), tf.getPlaceholderType("N"))); @@ -254,18 +254,18 @@ public class RuleSetTest { fcb.add(buffer, y1); IRuleSet rules = new RuleSet(fcb.getFiniteClosure()); - MPair pair1 = new MPair(x2, extY1, PairOperator.SMALLERDOTWC); - MPair pair2 = new MPair(tf.getExtendsType(x2), extY1, PairOperator.SMALLERDOTWC); - MPair pair3 = new MPair(extY1, extY1, PairOperator.SMALLERDOTWC); + UnifyPair pair1 = new UnifyPair(x2, extY1, PairOperator.SMALLERDOTWC); + UnifyPair pair2 = new UnifyPair(tf.getExtendsType(x2), extY1, PairOperator.SMALLERDOTWC); + UnifyPair pair3 = new UnifyPair(extY1, extY1, PairOperator.SMALLERDOTWC); System.out.println("------ ReduceExt ------"); - Optional> opt1 = rules.reduceExt(pair1); + Optional> opt1 = rules.reduceExt(pair1); System.out.println(opt1); - Optional> opt2 = rules.reduceExt(pair2); + Optional> opt2 = rules.reduceExt(pair2); System.out.println(opt2); - Optional> opt3 = rules.reduceExt(pair3); + Optional> opt3 = rules.reduceExt(pair3); System.out.println(opt3); /* @@ -273,21 +273,21 @@ public class RuleSetTest { */ // Case 1: X <.? Y - pair1 = new MPair(x2, extY1.getExtendedType(), PairOperator.SMALLERDOTWC); + pair1 = new UnifyPair(x2, extY1.getExtendedType(), PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceExt(pair1).isPresent()); // Case 2: X =. ? super Y - pair2 = new MPair(x2, extY1, PairOperator.EQUALSDOT); + pair2 = new UnifyPair(x2, extY1, PairOperator.EQUALSDOT); Assert.assertFalse(rules.reduceExt(pair2).isPresent()); // Case 3: ? extends Y <.? ? extends X - pair3 = new MPair(extY1, tf.getExtendsType(x2), PairOperator.SMALLERDOTWC); + pair3 = new UnifyPair(extY1, tf.getExtendsType(x2), PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceExt(pair3).isPresent()); // Case 4: X <. ? extends Y and ? extends Y not in grArg(X) fcb.clear(); rules = new RuleSet(fcb.getFiniteClosure()); - pair1 = new MPair(x2, extY1, PairOperator.SMALLERDOTWC); + pair1 = new UnifyPair(x2, extY1, PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceExt(pair1).isPresent()); } @@ -301,13 +301,13 @@ public class RuleSetTest { */ // X - SimpleType x1 = tf.getSimpleType("X", "T1", "T2", "T3", "T4"); + ReferenceType x1 = tf.getSimpleType("X", "T1", "T2", "T3", "T4"); // Y - SimpleType y1 = tf.getSimpleType("Y", "T4", "T1", "T2", "T3"); - SimpleType buffer = tf.getSimpleType("Buffer"); + ReferenceType y1 = tf.getSimpleType("Y", "T4", "T1", "T2", "T3"); + ReferenceType buffer = tf.getSimpleType("Buffer"); //X - SimpleType x2 = tf.getSimpleType("X", tf.getSimpleType("Int"), tf.getExtendsType(tf.getSimpleType("Double")), tf.getPlaceholderType("M"), tf.getPlaceholderType("N")); + ReferenceType x2 = tf.getSimpleType("X", tf.getSimpleType("Int"), tf.getExtendsType(tf.getSimpleType("Double")), tf.getPlaceholderType("M"), tf.getPlaceholderType("N")); //? super Y, Number, Double, N> SuperType supY1 = tf.getSuperType(tf.getSimpleType("Y", tf.getSuperType(tf.getSimpleType("HashSet", "Int")), tf.getSimpleType("Number"), tf.getSimpleType("Double"), tf.getPlaceholderType("N"))); @@ -316,18 +316,18 @@ public class RuleSetTest { fcb.add(buffer, x1); IRuleSet rules = new RuleSet(fcb.getFiniteClosure()); - MPair pair1 = new MPair(x2, supY1, PairOperator.SMALLERDOTWC); - MPair pair2 = new MPair(tf.getSuperType(x2), supY1, PairOperator.SMALLERDOTWC); - MPair pair3 = new MPair(supY1, supY1, PairOperator.SMALLERDOTWC); + UnifyPair pair1 = new UnifyPair(x2, supY1, PairOperator.SMALLERDOTWC); + UnifyPair pair2 = new UnifyPair(tf.getSuperType(x2), supY1, PairOperator.SMALLERDOTWC); + UnifyPair pair3 = new UnifyPair(supY1, supY1, PairOperator.SMALLERDOTWC); System.out.println("------ ReduceSup ------"); - Optional> opt1 = rules.reduceSup(pair1); + Optional> opt1 = rules.reduceSup(pair1); System.out.println(opt1); - Optional> opt2 = rules.reduceSup(pair2); + Optional> opt2 = rules.reduceSup(pair2); System.out.println(opt2); - Optional> opt3 = rules.reduceSup(pair3); + Optional> opt3 = rules.reduceSup(pair3); System.out.println(opt3); /* @@ -335,21 +335,21 @@ public class RuleSetTest { */ // Case 1: X <.? Y - pair1 = new MPair(x2, supY1.getSuperedType(), PairOperator.SMALLERDOTWC); + pair1 = new UnifyPair(x2, supY1.getSuperedType(), PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceSup(pair1).isPresent()); // Case 2: X =. ? super Y - pair2 = new MPair(x2, supY1, PairOperator.EQUALSDOT); + pair2 = new UnifyPair(x2, supY1, PairOperator.EQUALSDOT); Assert.assertFalse(rules.reduceSup(pair2).isPresent()); // Case 3: ? super Y <.? ? super X - pair3 = new MPair(supY1, tf.getSuperType(x2), PairOperator.SMALLERDOTWC); + pair3 = new UnifyPair(supY1, tf.getSuperType(x2), PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceSup(pair3).isPresent()); // Case 4: X <. ? super Y and ? super Y not in grArg(X) fcb.clear(); rules = new RuleSet(fcb.getFiniteClosure()); - pair1 = new MPair(x2, supY1, PairOperator.SMALLERDOTWC); + pair1 = new UnifyPair(x2, supY1, PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceSup(pair1).isPresent()); } @@ -365,12 +365,12 @@ public class RuleSetTest { System.out.println("----- ReduceEq ------"); // C - SimpleType c1 = tf.getSimpleType("C", tf.getPlaceholderType("T1"), tf.getSimpleType("SType1"), tf.getExtendsType(tf.getSimpleType("SType1"))); + ReferenceType c1 = tf.getSimpleType("C", tf.getPlaceholderType("T1"), tf.getSimpleType("SType1"), tf.getExtendsType(tf.getSimpleType("SType1"))); // C - SimpleType c2 = tf.getSimpleType("C", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); + ReferenceType c2 = tf.getSimpleType("C", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); - MPair pair = new MPair(c1, c2, PairOperator.SMALLERDOTWC); - Optional> res = rules.reduceEq(pair); + UnifyPair pair = new UnifyPair(c1, c2, PairOperator.SMALLERDOTWC); + Optional> res = rules.reduceEq(pair); System.out.println(res); /* @@ -378,12 +378,12 @@ public class RuleSetTest { */ // Case 1: D <.? C - SimpleType d1 = tf.getSimpleType("D", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); - pair = new MPair(d1, c1, PairOperator.SMALLERDOTWC); + ReferenceType d1 = tf.getSimpleType("D", tf.getPlaceholderType("T2"), tf.getSimpleType("SType2"), tf.getExtendsType(tf.getSimpleType("SType2"))); + pair = new UnifyPair(d1, c1, PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.reduceEq(pair).isPresent()); // Case 2: C <. C - pair = new MPair(c1, c2, PairOperator.SMALLERDOT); + pair = new UnifyPair(c1, c2, PairOperator.SMALLERDOT); Assert.assertFalse(rules.reduceEq(pair).isPresent()); } @@ -395,9 +395,9 @@ public class RuleSetTest { /* * Positive Tests */ - MPair erase1 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("Collection"), PairOperator.SMALLERDOT); - MPair erase2 = new MPair(tf.getSimpleType("HashSet", "T"), tf.getSimpleType("Collection"), PairOperator.SMALLERDOT); - MPair erase3 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); + UnifyPair erase1 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("Collection"), PairOperator.SMALLERDOT); + UnifyPair erase2 = new UnifyPair(tf.getSimpleType("HashSet", "T"), tf.getSimpleType("Collection"), PairOperator.SMALLERDOT); + UnifyPair erase3 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); Assert.assertTrue(rules.erase1(erase1)); Assert.assertTrue(rules.erase1(erase2)); @@ -406,9 +406,9 @@ public class RuleSetTest { /* * Negative Tests */ - MPair noerase1 = new MPair(tf.getSimpleType("Collection"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); - MPair noerase2 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("Collection"), PairOperator.EQUALSDOT); - MPair noerase3 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("Collection"), PairOperator.SMALLERDOTWC); + UnifyPair noerase1 = new UnifyPair(tf.getSimpleType("Collection"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); + UnifyPair noerase2 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("Collection"), PairOperator.EQUALSDOT); + UnifyPair noerase3 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("Collection"), PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.erase1(noerase1)); Assert.assertFalse(rules.erase1(noerase2)); @@ -423,11 +423,11 @@ public class RuleSetTest { /* * Positive Tests */ - MPair erase1 = new MPair(tf.getSimpleType("List", "T"), tf.getExtendsType(tf.getSimpleType("Collection")), PairOperator.SMALLERDOTWC); - MPair erase2 = new MPair(tf.getSimpleType("Collection"), tf.getSuperType(tf.getSimpleType("HashSet", "T")), PairOperator.SMALLERDOTWC); - MPair erase3 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOTWC); - MPair erase4 = new MPair(tf.getExtendsType(tf.getSimpleType("LinkedList", "T")), tf.getExtendsType(tf.getSimpleType("List", "T")), PairOperator.SMALLERDOTWC); - MPair erase5 = new MPair(tf.getSuperType(tf.getSimpleType("List", "T")), tf.getSuperType(tf.getSimpleType("Stack", "T")), PairOperator.SMALLERDOTWC); + UnifyPair erase1 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getExtendsType(tf.getSimpleType("Collection")), PairOperator.SMALLERDOTWC); + UnifyPair erase2 = new UnifyPair(tf.getSimpleType("Collection"), tf.getSuperType(tf.getSimpleType("HashSet", "T")), PairOperator.SMALLERDOTWC); + UnifyPair erase3 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOTWC); + UnifyPair erase4 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("LinkedList", "T")), tf.getExtendsType(tf.getSimpleType("List", "T")), PairOperator.SMALLERDOTWC); + UnifyPair erase5 = new UnifyPair(tf.getSuperType(tf.getSimpleType("List", "T")), tf.getSuperType(tf.getSimpleType("Stack", "T")), PairOperator.SMALLERDOTWC); Assert.assertTrue(rules.erase2(erase1)); @@ -439,10 +439,10 @@ public class RuleSetTest { /* * Negative Tests */ - MPair noerase1 = new MPair(tf.getSimpleType("Collection"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOTWC); - MPair noerase2 = new MPair(tf.getSuperType(tf.getSimpleType("List", "T")), tf.getSimpleType("ArrayList", "T"), PairOperator.SMALLERDOTWC); - MPair noerase3 = new MPair(tf.getExtendsType(tf.getSimpleType("List", "T")), tf.getSuperType(tf.getSimpleType("List", "T")), PairOperator.SMALLERDOTWC); - MPair noerase4 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); + UnifyPair noerase1 = new UnifyPair(tf.getSimpleType("Collection"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOTWC); + UnifyPair noerase2 = new UnifyPair(tf.getSuperType(tf.getSimpleType("List", "T")), tf.getSimpleType("ArrayList", "T"), PairOperator.SMALLERDOTWC); + UnifyPair noerase3 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("List", "T")), tf.getSuperType(tf.getSimpleType("List", "T")), PairOperator.SMALLERDOTWC); + UnifyPair noerase4 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); Assert.assertFalse(rules.erase2(noerase1)); Assert.assertFalse(rules.erase2(noerase2)); @@ -458,8 +458,8 @@ public class RuleSetTest { /* * Positive Tests */ - MPair erase1 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.EQUALSDOT); - MPair erase2 = new MPair(tf.getPlaceholderType("W"), tf.getPlaceholderType("W"), PairOperator.EQUALSDOT); + UnifyPair erase1 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.EQUALSDOT); + UnifyPair erase2 = new UnifyPair(tf.getPlaceholderType("W"), tf.getPlaceholderType("W"), PairOperator.EQUALSDOT); Assert.assertTrue(rules.erase3(erase1)); Assert.assertTrue(rules.erase3(erase2)); @@ -467,8 +467,8 @@ public class RuleSetTest { /* * Negative Tests */ - MPair noerase1 = new MPair(tf.getSimpleType("Collection"), tf.getSimpleType("List", "T"), PairOperator.EQUALSDOT); - MPair noerase2 = new MPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); + UnifyPair noerase1 = new UnifyPair(tf.getSimpleType("Collection"), tf.getSimpleType("List", "T"), PairOperator.EQUALSDOT); + UnifyPair noerase2 = new UnifyPair(tf.getSimpleType("List", "T"), tf.getSimpleType("List", "T"), PairOperator.SMALLERDOT); Assert.assertFalse(rules.erase3(noerase1)); Assert.assertFalse(rules.erase3(noerase2)); @@ -482,14 +482,14 @@ public class RuleSetTest { /* * Positive Tests */ - MPair swap1 = new MPair(tf.getExtendsType(tf.getSimpleType("MyClass")), tf.getPlaceholderType("P"), PairOperator.EQUALSDOT); - MPair swap2 = new MPair(tf.getSimpleType("MyClass"), tf.getPlaceholderType("X"), PairOperator.EQUALSDOT); + UnifyPair swap1 = new UnifyPair(tf.getExtendsType(tf.getSimpleType("MyClass")), tf.getPlaceholderType("P"), PairOperator.EQUALSDOT); + UnifyPair swap2 = new UnifyPair(tf.getSimpleType("MyClass"), tf.getPlaceholderType("X"), PairOperator.EQUALSDOT); - MPair expected1 = new MPair(tf.getPlaceholderType("P"), tf.getExtendsType(tf.getSimpleType("MyClass")), PairOperator.EQUALSDOT); - MPair expected2 = new MPair(tf.getPlaceholderType("X"), tf.getSimpleType("MyClass"), PairOperator.EQUALSDOT); + UnifyPair expected1 = new UnifyPair(tf.getPlaceholderType("P"), tf.getExtendsType(tf.getSimpleType("MyClass")), PairOperator.EQUALSDOT); + UnifyPair expected2 = new UnifyPair(tf.getPlaceholderType("X"), tf.getSimpleType("MyClass"), PairOperator.EQUALSDOT); - Optional opt1 = rules.swap(swap1); - Optional opt2 = rules.swap(swap2); + Optional opt1 = rules.swap(swap1); + Optional opt2 = rules.swap(swap2); // swap((? extends MyClass =. P)) = (P =. MyClass) Assert.assertEquals(opt1.get(), expected1); @@ -500,15 +500,15 @@ public class RuleSetTest { /* * Negative Tests */ - MPair noswap1 = new MPair(tf.getPlaceholderType("Z"), tf.getPlaceholderType("X"), PairOperator.EQUALSDOT); - MPair noswap2 = new MPair(tf.getSimpleType("MyClass"), tf.getExtendsType(tf.getPlaceholderType("X")), PairOperator.EQUALSDOT); - MPair noswap3 = new MPair( tf.getPlaceholderType("X"), tf.getSimpleType("MyClass"), PairOperator.EQUALSDOT); - MPair noswap4 = new MPair(tf.getSimpleType("MyClass"), tf.getPlaceholderType("X"), PairOperator.SMALLERDOT); + UnifyPair noswap1 = new UnifyPair(tf.getPlaceholderType("Z"), tf.getPlaceholderType("X"), PairOperator.EQUALSDOT); + UnifyPair noswap2 = new UnifyPair(tf.getSimpleType("MyClass"), tf.getExtendsType(tf.getPlaceholderType("X")), PairOperator.EQUALSDOT); + UnifyPair noswap3 = new UnifyPair( tf.getPlaceholderType("X"), tf.getSimpleType("MyClass"), PairOperator.EQUALSDOT); + UnifyPair noswap4 = new UnifyPair(tf.getSimpleType("MyClass"), tf.getPlaceholderType("X"), PairOperator.SMALLERDOT); opt1 = rules.swap(noswap1); opt2 = rules.swap(noswap2); - Optional opt3 = rules.swap(noswap3); - Optional opt4 = rules.swap(noswap4); + Optional opt3 = rules.swap(noswap3); + Optional opt4 = rules.swap(noswap4); Assert.assertFalse(opt1.isPresent()); Assert.assertFalse(opt2.isPresent()); @@ -521,9 +521,9 @@ public class RuleSetTest { TypeFactory tf = new TypeFactory(); FiniteClosureBuilder fcb = new FiniteClosureBuilder(); - SimpleType t1 = tf.getSimpleType("Type1", "T", "U"); - SimpleType t2 = tf.getSimpleType("Type2", "T"); - SimpleType t3 = tf.getSimpleType("Type3", tf.getPlaceholderType("T"), tf.getSimpleType("Integer")); + ReferenceType t1 = tf.getSimpleType("Type1", "T", "U"); + ReferenceType t2 = tf.getSimpleType("Type2", "T"); + ReferenceType t3 = tf.getSimpleType("Type3", tf.getPlaceholderType("T"), tf.getSimpleType("Integer")); fcb.add(t1, t2); fcb.add(t2, t3); @@ -534,13 +534,13 @@ public class RuleSetTest { * Positive Tests */ - SimpleType c1 = tf.getSimpleType("Type1", "String", "Double"); - SimpleType c2 = tf.getSimpleType("Type2", "Object"); - SimpleType c3 = tf.getSimpleType("Type3", "Object", "Number"); + ReferenceType c1 = tf.getSimpleType("Type1", "String", "Double"); + ReferenceType c2 = tf.getSimpleType("Type2", "Object"); + ReferenceType c3 = tf.getSimpleType("Type3", "Object", "Number"); - MPair pair1 = new MPair(c1, c2, PairOperator.SMALLERDOT); - MPair pair2 = new MPair(c2, c3, PairOperator.SMALLERDOT); - MPair pair3 = new MPair(c1, c3, PairOperator.SMALLERDOT); + UnifyPair pair1 = new UnifyPair(c1, c2, PairOperator.SMALLERDOT); + UnifyPair pair2 = new UnifyPair(c2, c3, PairOperator.SMALLERDOT); + UnifyPair pair3 = new UnifyPair(c1, c3, PairOperator.SMALLERDOT); System.out.println("------ Adapt ------"); System.out.println(rules.adapt(pair1)); @@ -551,9 +551,9 @@ public class RuleSetTest { * Negative Tests */ - MPair noAdapt1 = new MPair(c2, c1, PairOperator.SMALLERDOT); - MPair noAdapt2 = new MPair(c1, c1, PairOperator.SMALLERDOT); - MPair noAdapt3 = new MPair(c1, c2, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt1 = new UnifyPair(c2, c1, PairOperator.SMALLERDOT); + UnifyPair noAdapt2 = new UnifyPair(c1, c1, PairOperator.SMALLERDOT); + UnifyPair noAdapt3 = new UnifyPair(c1, c2, PairOperator.SMALLERDOTWC); Assert.assertFalse(rules.adapt(noAdapt1).isPresent()); Assert.assertFalse(rules.adapt(noAdapt2).isPresent()); @@ -565,11 +565,11 @@ public class RuleSetTest { TypeFactory tf = new TypeFactory(); FiniteClosureBuilder fcb = new FiniteClosureBuilder(); - SimpleType t1 = tf.getSimpleType("Type1", "T", "U"); - SimpleType t2 = tf.getSimpleType("Type2", "T"); - SimpleType t3 = tf.getSimpleType("Type3", tf.getPlaceholderType("T"), tf.getSimpleType("Integer")); - SimpleType t32 = tf.getSimpleType("Type3", "T", "U"); - SimpleType t4 = tf.getSimpleType("Object"); + ReferenceType t1 = tf.getSimpleType("Type1", "T", "U"); + ReferenceType t2 = tf.getSimpleType("Type2", "T"); + ReferenceType t3 = tf.getSimpleType("Type3", tf.getPlaceholderType("T"), tf.getSimpleType("Integer")); + ReferenceType t32 = tf.getSimpleType("Type3", "T", "U"); + ReferenceType t4 = tf.getSimpleType("Object"); fcb.add(t1, t2); fcb.add(t2, t3); @@ -581,20 +581,20 @@ public class RuleSetTest { * Positive Tests */ - SimpleType c1 = tf.getSimpleType("Type1", "String", "Double"); - SimpleType c2 = tf.getSimpleType("Type2", "Object"); - SimpleType c3 = tf.getSimpleType("Type3", "Object", "Number"); + ReferenceType c1 = tf.getSimpleType("Type1", "String", "Double"); + ReferenceType c2 = tf.getSimpleType("Type2", "Object"); + ReferenceType c3 = tf.getSimpleType("Type3", "Object", "Number"); ExtendsType extc1 = new ExtendsType(c1); ExtendsType extc2 = new ExtendsType(c2); ExtendsType extc3 = new ExtendsType(c3); - MPair pair1 = new MPair(c1, extc2, PairOperator.SMALLERDOTWC); - MPair pair2 = new MPair(c2, extc3, PairOperator.SMALLERDOTWC); - MPair pair3 = new MPair(c1, extc3, PairOperator.SMALLERDOTWC); - MPair pair4 = new MPair(extc1, extc2, PairOperator.SMALLERDOTWC); - MPair pair5 = new MPair(extc2, extc3, PairOperator.SMALLERDOTWC); - MPair pair6 = new MPair(extc1, extc3, PairOperator.SMALLERDOTWC); - MPair pair7 = new MPair(extc1, extc1, PairOperator.SMALLERDOTWC); + UnifyPair pair1 = new UnifyPair(c1, extc2, PairOperator.SMALLERDOTWC); + UnifyPair pair2 = new UnifyPair(c2, extc3, PairOperator.SMALLERDOTWC); + UnifyPair pair3 = new UnifyPair(c1, extc3, PairOperator.SMALLERDOTWC); + UnifyPair pair4 = new UnifyPair(extc1, extc2, PairOperator.SMALLERDOTWC); + UnifyPair pair5 = new UnifyPair(extc2, extc3, PairOperator.SMALLERDOTWC); + UnifyPair pair6 = new UnifyPair(extc1, extc3, PairOperator.SMALLERDOTWC); + UnifyPair pair7 = new UnifyPair(extc1, extc1, PairOperator.SMALLERDOTWC); System.out.println("------ AdaptExt ------"); System.out.println(rules.adaptExt(pair1)); @@ -609,11 +609,11 @@ public class RuleSetTest { * Negative Tests */ - MPair noAdapt1 = new MPair(extc2, extc1, PairOperator.SMALLERDOTWC); - MPair noAdapt2 = new MPair(extc1, c2, PairOperator.SMALLERDOTWC); - MPair noAdapt3 = new MPair(tf.getSuperType(c1), extc2, PairOperator.SMALLERDOTWC); - MPair noAdapt4 = new MPair(extc3, extc1, PairOperator.SMALLERDOTWC); - MPair noAdapt5 = new MPair(c1, extc2, PairOperator.SMALLERDOT); + UnifyPair noAdapt1 = new UnifyPair(extc2, extc1, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt2 = new UnifyPair(extc1, c2, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt3 = new UnifyPair(tf.getSuperType(c1), extc2, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt4 = new UnifyPair(extc3, extc1, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt5 = new UnifyPair(c1, extc2, PairOperator.SMALLERDOT); Assert.assertFalse(rules.adaptExt(noAdapt1).isPresent()); Assert.assertFalse(rules.adaptExt(noAdapt2).isPresent()); @@ -627,11 +627,11 @@ public class RuleSetTest { TypeFactory tf = new TypeFactory(); FiniteClosureBuilder fcb = new FiniteClosureBuilder(); - SimpleType t1 = tf.getSimpleType("Type1", "T", "U"); - SimpleType t2 = tf.getSimpleType("Type2", "T"); - SimpleType t3 = tf.getSimpleType("Type3", tf.getPlaceholderType("T"), tf.getSimpleType("Integer")); - SimpleType t32 = tf.getSimpleType("Type3", "T", "U"); - SimpleType t4 = tf.getSimpleType("Object"); + ReferenceType t1 = tf.getSimpleType("Type1", "T", "U"); + ReferenceType t2 = tf.getSimpleType("Type2", "T"); + ReferenceType t3 = tf.getSimpleType("Type3", tf.getPlaceholderType("T"), tf.getSimpleType("Integer")); + ReferenceType t32 = tf.getSimpleType("Type3", "T", "U"); + ReferenceType t4 = tf.getSimpleType("Object"); fcb.add(t1, t2); fcb.add(t2, t3); @@ -643,20 +643,20 @@ public class RuleSetTest { * Positive Tests */ - SimpleType c1 = tf.getSimpleType("Type1", "String", "Double"); - SimpleType c2 = tf.getSimpleType("Type2", "Object"); - SimpleType c3 = tf.getSimpleType("Type3", "Object", "Number"); + ReferenceType c1 = tf.getSimpleType("Type1", "String", "Double"); + ReferenceType c2 = tf.getSimpleType("Type2", "Object"); + ReferenceType c3 = tf.getSimpleType("Type3", "Object", "Number"); SuperType supc1 = new SuperType(c1); SuperType supc2 = new SuperType(c2); SuperType supc3 = new SuperType(c3); - MPair pair1 = new MPair(c2, supc1, PairOperator.SMALLERDOTWC); - MPair pair2 = new MPair(c3, supc2, PairOperator.SMALLERDOTWC); - MPair pair3 = new MPair(c3, supc1, PairOperator.SMALLERDOTWC); - MPair pair4 = new MPair(supc2, supc1, PairOperator.SMALLERDOTWC); - MPair pair5 = new MPair(supc3, supc2, PairOperator.SMALLERDOTWC); - MPair pair6 = new MPair(supc3, supc1, PairOperator.SMALLERDOTWC); - MPair pair7 = new MPair(supc1, supc1, PairOperator.SMALLERDOTWC); + UnifyPair pair1 = new UnifyPair(c2, supc1, PairOperator.SMALLERDOTWC); + UnifyPair pair2 = new UnifyPair(c3, supc2, PairOperator.SMALLERDOTWC); + UnifyPair pair3 = new UnifyPair(c3, supc1, PairOperator.SMALLERDOTWC); + UnifyPair pair4 = new UnifyPair(supc2, supc1, PairOperator.SMALLERDOTWC); + UnifyPair pair5 = new UnifyPair(supc3, supc2, PairOperator.SMALLERDOTWC); + UnifyPair pair6 = new UnifyPair(supc3, supc1, PairOperator.SMALLERDOTWC); + UnifyPair pair7 = new UnifyPair(supc1, supc1, PairOperator.SMALLERDOTWC); System.out.println("------ AdaptSup ------"); System.out.println(rules.adaptSup(pair1)); @@ -671,11 +671,11 @@ public class RuleSetTest { * Negative Tests */ - MPair noAdapt1 = new MPair(supc2, supc1, PairOperator.SMALLERDOTWC); - MPair noAdapt2 = new MPair(supc1, c2, PairOperator.SMALLERDOTWC); - MPair noAdapt3 = new MPair(tf.getExtendsType(c1), supc2, PairOperator.SMALLERDOTWC); - MPair noAdapt4 = new MPair(supc3, supc1, PairOperator.SMALLERDOTWC); - MPair noAdapt5 = new MPair(c1, supc2, PairOperator.SMALLERDOT); + UnifyPair noAdapt1 = new UnifyPair(supc2, supc1, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt2 = new UnifyPair(supc1, c2, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt3 = new UnifyPair(tf.getExtendsType(c1), supc2, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt4 = new UnifyPair(supc3, supc1, PairOperator.SMALLERDOTWC); + UnifyPair noAdapt5 = new UnifyPair(c1, supc2, PairOperator.SMALLERDOT); Assert.assertFalse(rules.adaptExt(noAdapt1).isPresent()); Assert.assertFalse(rules.adaptExt(noAdapt2).isPresent()); diff --git a/test/unify/StandardUnifyTest.java b/test/unify/StandardUnifyTest.java index e75bf38c..83f8abe1 100644 --- a/test/unify/StandardUnifyTest.java +++ b/test/unify/StandardUnifyTest.java @@ -7,11 +7,10 @@ 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.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; -import de.dhbwstuttgart.typeinference.unify.model.MPair.PairOperator; -import de.dhbwstuttgart.typeinference.unifynew.MartelliMontanariUnify; public class StandardUnifyTest { @@ -29,12 +28,10 @@ public class StandardUnifyTest { UnifyType f = tf.getSimpleType("f", x); // {f = y} - Set terms = new HashSet(); + Set terms = new HashSet(); System.out.println(unify.unify(f, y).get()); - // TODO ist das ergebnis { (x -> ? extends a), (y -> g) } in der richtigen form oder - // muss es { (x -> ? extends a), (y -> g) } sein? // {f,x> = f} UnifyType g = tf.getSimpleType("g", "x"); UnifyType f1 = tf.getSimpleType("f", g, x); diff --git a/test/unify/TypeFactory.java b/test/unify/TypeFactory.java index 965e324d..881222c8 100644 --- a/test/unify/TypeFactory.java +++ b/test/unify/TypeFactory.java @@ -4,9 +4,11 @@ import java.util.Arrays; import java.util.stream.Collectors; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; +import de.dhbwstuttgart.typeinference.unify.model.FunNType; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; -import de.dhbwstuttgart.typeinference.unify.model.SimpleType; +import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; import de.dhbwstuttgart.typeinference.unify.model.SuperType; +import de.dhbwstuttgart.typeinference.unify.model.TypeParams; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public class TypeFactory { @@ -19,19 +21,24 @@ public class TypeFactory { return new SuperType(superedType); } - public SimpleType getSimpleType(String name) { - return new SimpleType(name); + public ReferenceType getSimpleType(String name) { + return new ReferenceType(name); } - public SimpleType getSimpleType(String name, UnifyType... typeParams) { - return new SimpleType(name, typeParams); + public ReferenceType getSimpleType(String name, UnifyType... typeParams) { + return new ReferenceType(name, typeParams); } - public SimpleType getSimpleType(String name, String... typeParams) { - return new SimpleType(name, Arrays.stream(typeParams).map(x -> getPlaceholderType(x)).collect(Collectors.toList()).toArray(new UnifyType[0])); + public ReferenceType getSimpleType(String name, String... typeParams) { + return new ReferenceType(name, Arrays.stream(typeParams).map(x -> getPlaceholderType(x)).collect(Collectors.toList()).toArray(new UnifyType[0])); } public PlaceholderType getPlaceholderType(String name) { return new PlaceholderType(name); } + + public FunNType getFunNType(UnifyType... typeParams) { + return FunNType.getFunNType(new TypeParams(typeParams)); + } + } diff --git a/test/unify/UnifyOldTest.java b/test/unify/UnifyOldTest.java deleted file mode 100644 index 9a28e30a..00000000 --- a/test/unify/UnifyOldTest.java +++ /dev/null @@ -1,334 +0,0 @@ -package unify; - -import junit.framework.Assert; - -import org.junit.Test; - -import de.dhbwstuttgart.syntaxtree.factory.UnifyPairMengenBuilder; -import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory; -import de.dhbwstuttgart.syntaxtree.factory.Unify_FC_TTO_Builder; -import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; -import de.dhbwstuttgart.syntaxtree.type.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; -import de.dhbwstuttgart.typeinference.unify.Unify; - -public class UnifyOldTest { - - @Test - public void unifyTestSimpleTypes() { - // Init Factories and Builders - Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); - UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); - UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); - - /* - * Test a <. Boolean - */ - - // Init Types - RefType boolT = this.GetSimpleType("java.lang.Boolean"); - TypePlaceholder aTph = this.GetTypePlaceholder("a"); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(aTph, boolT, PairOperator.Equal); - resultBuilder.addPair(aTph, this.GetExtendsType(boolT), - PairOperator.Equal); - Menge> expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(aTph, boolT); - Menge> actualResult = Unify.unify( - assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test b <. a, a <. Boolean - */ - - // Init Types - boolT = this.GetSimpleType("java.lang.Boolean"); - aTph = this.GetTypePlaceholder("a"); - TypePlaceholder bTph = this.GetTypePlaceholder("b"); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(aTph, boolT, PairOperator.Equal); - resultBuilder.addPair(aTph, this.GetExtendsType(boolT), - PairOperator.Equal); - resultBuilder.addPair(bTph, boolT, PairOperator.Equal); - resultBuilder.addPair(bTph, this.GetExtendsType(boolT), - PairOperator.Equal); - expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(bTph, aTph); - assumptionBuilder.addPair(aTph, boolT); - actualResult = Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - // NOTE: Elemente im actualResult sind nicht unique - // Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test b <. a, a <. b - */ - - aTph = this.GetTypePlaceholder("a"); - bTph = this.GetTypePlaceholder("b"); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(bTph, aTph); - resultBuilder.addPair(aTph, bTph); - - Menge buffer = resultBuilder.getPairMenge(); - expectedResult = new Menge>(); - expectedResult.add(buffer); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(bTph, aTph); - assumptionBuilder.addPair(aTph, bTph); - actualResult = Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test Integer <. a, a <. Boolean - */ - - RefType intT = this.GetSimpleType("java.lang.Integer"); - boolT = this.GetSimpleType("java.lang.Boolean"); - aTph = this.GetTypePlaceholder("a"); - bTph = this.GetTypePlaceholder("b"); - - // Expected Result - resultBuilder.clear(); - expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(intT, aTph); - assumptionBuilder.addPair(aTph, boolT); - actualResult = Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - } - - @Test - public void unifyTestGenerics() { - - // Init Factories and Builders - Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); - UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); - UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); - - /* - * Test a <. MyClass - */ - - TypePlaceholder aTph = this.GetTypePlaceholder("a"); - RefType myType = this.GetSimpleType("MyClass", - this.GetTypePlaceholder("T"), - this.GetTypePlaceholder("F")); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(aTph, myType, PairOperator.Equal); - resultBuilder.addPair(aTph, this.GetExtendsType(myType)); - Menge> expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(aTph, myType); - Menge> actualResult = Unify.unify( - assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); - - // System.out.println(expectedResult); - // System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test List> <. List - */ - - TypePlaceholder tTph = this.GetTypePlaceholder("T"); - RefType list = this.GetSimpleType("List", tTph); - RefType listlist = this.GetSimpleType("List", list); - - // Expected Result - resultBuilder.clear(); - resultBuilder.addPair(this.GetExtendsType(list), tTph, - PairOperator.Equal); - expectedResult = resultBuilder.getNestedPairMenge(); - - // Actual Result - assumptionBuilder.clear(); - assumptionBuilder.addPair(listlist, list); - actualResult = Unify.unify(assumptionBuilder.getPairMenge(), - fcBuilder.Get_FC_TTO()); - - System.out.println(expectedResult); - System.out.println(actualResult); - - Assert.assertTrue(mengeEquals(expectedResult, actualResult)); - - /* - * Test List <. List> - */ - } - - @Test - public void unifyTestInheritance() { - - // Init Factories and Builders - Unify_FC_TTO_Builder fcBuilder = new Unify_FC_TTO_Builder(); - UnifyPairMengenBuilder assumptionBuilder = new UnifyPairMengenBuilder(); - UnifyPairMengenBuilder resultBuilder = new UnifyPairMengenBuilder(); - - // Init Types - RefType tBool = this.GetSimpleType("java.lang.Boolean"); - RefType tString = this.GetSimpleType("java.lang.String"); - RefType tInt = this.GetSimpleType("java.lang.Integer"); - TypePlaceholder tphA = this.GetTypePlaceholder("a"); - - // Build inheritance hierachy - // Bool <. String <. Int - fcBuilder.AddInheritance(tBool, tString); - fcBuilder.AddInheritance(tString, tInt); - - // Build Assumptions - assumptionBuilder.addPair(tphA, tString); - - // Build expected result - resultBuilder.addPair(tphA, tBool, PairOperator.Equal); - resultBuilder.addPair(tphA, this.GetExtendsType(tBool), - PairOperator.Equal); - resultBuilder.addPair(tphA, tString, PairOperator.Equal); - resultBuilder.addPair(tphA, this.GetExtendsType(tString), - PairOperator.Equal); - - // Assert - Menge> actualResult = Unify.unify( - assumptionBuilder.getPairMenge(), fcBuilder.Get_FC_TTO()); - - // System.out.println(actualResult); - // System.out.println("-------------------"); - // System.out.println(resultBuilder.getNestedPairMenge()); - - Assert.assertTrue(mengeEquals(resultBuilder.getNestedPairMenge(), - actualResult)); - } - - @Test - public void unifyTestWildcards() { - - } - - private static boolean mengeEquals(Menge> m1, - Menge> m2) { - if (m1.size() != m2.size()) - return false; - - return containsAll(m1, m2) && containsAll(m2, m1); - } - - private static boolean containsAll(Menge> m1, - Menge> m2) { - for (Menge elem : m2) - if (!contains(m1, elem)) - return false; - return true; - } - - private static boolean contains(Menge> m1, Menge m2) { - for (Menge elem : m1) - if (mengePairEquals(elem, m2)) - return true; - return false; - } - - private static boolean mengePairEquals(Menge m1, Menge m2) { - if (m1.size() != m2.size()) - return false; - - return containsAllPair(m1, m2) && containsAllPair(m2, m1); - } - - private static boolean containsAllPair(Menge m1, Menge m2) { - for (Pair elem : m1) - if (contains(m2, elem)) - return true; - return false; - } - - private static boolean contains(Menge m, Pair p) { - for (Pair elem : m) - if (pairEquals(elem, p)) - return true; - return false; - - } - - private static boolean pairEquals(Pair p1, Pair p2) { - return (p1.TA1.equals(p2.TA1) && p1.TA2.equals(p2.TA2)) - || (p1.TA1.equals(p2.TA2) && p1.TA2.equals(p2.TA1)); - } - - - private RefType GetSimpleType(String name, Type... parameters) { - if(parameters.length == 0) - return new RefType(name, null, 0); - - Menge typeParams = new Menge(); - - for(Type t : parameters) - typeParams.add(t); - - return new RefType(name, typeParams, null, 0); - } - - private ExtendsWildcardType GetExtendsType(ObjectType extendedType) { - return new ExtendsWildcardType(extendedType); - } - - private SuperWildcardType GetSuperType(ObjectType superedType) { - return new SuperWildcardType(superedType); - } - - private WildcardType GetWildcardType() { - return new WildcardType(null, null, 0); - } - - private TypePlaceholder GetTypePlaceholder(String name) { - return TypePlaceholder.backdoorCreate(name); - } - -} diff --git a/test/unify/UnifyTest.java b/test/unify/UnifyTest.java index 60486017..666731b8 100644 --- a/test/unify/UnifyTest.java +++ b/test/unify/UnifyTest.java @@ -1,50 +1,595 @@ package unify; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashSet; import java.util.Set; +import java.util.stream.Collectors; 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.UnifyPair; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.TypeParams; -import de.dhbwstuttgart.typeinference.unifynew.Unify; +import junit.framework.Assert; public class UnifyTest extends Unify { + /** + * Testing the unification for cases with (n)one pair and without generics. + */ @Test - public void unifyTest() { + public void unifyTestTrivial() { + /* + * INIT + */ + TypeFactory tf = new TypeFactory(); FiniteClosureBuilder fcb = new FiniteClosureBuilder(); - Set eq = new HashSet(); - - //fcb.add(tf.getSimpleType("Number"), tf.getSimpleType("Object")); - fcb.add(tf.getSimpleType("Integer"), tf.getSimpleType("Number")); - fcb.add(tf.getSimpleType("Double"), tf.getSimpleType("Number")); - //fcb.add(tf.getSimpleType("List", "T")); + + UnifyType number = tf.getSimpleType("Number"); + UnifyType object = tf.getSimpleType("Object"); + UnifyType integer = tf.getSimpleType("Integer"); + UnifyType doubl = tf.getSimpleType("Double"); + fcb.add(number, object); + fcb.add(integer, number); + fcb.add(doubl, number); + IFiniteClosure fc = fcb.getCollectionExample(); - // Vector <. Vector - // Vector - // A <. Integer - // Number <. A - // Double <. B - // B <. Object - eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Integer")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Number")), tf.getSimpleType("Vector", "A"), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getSimpleType("Vector", tf.getSimpleType("Integer")), tf.getSimpleType("Vector", "C"), PairOperator.SMALLERDOT)); - eq.add(new MPair(tf.getPlaceholderType("A"), tf.getSimpleType("List", tf.getSimpleType("Number")), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getSimpleType("Number"), tf.getPlaceholderType("A"), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getPlaceholderType("A"), tf.getPlaceholderType("C"), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getSimpleType("Double"), tf.getPlaceholderType("B"), PairOperator.SMALLERDOT)); - //eq.add(new MPair(tf.getPlaceholderType("B"), tf.getSimpleType("Object"), PairOperator.EQUALSDOT)); + /* + * Test 1: + * + * unify({ }) = { } + */ - System.out.println(this.unify(eq, fc)); + Set eq = new HashSet(); + Set> expected = new HashSet<>(); + expected.add(new HashSet<>()); + Set> actual = unify(eq, fc); + Assert.assertEquals(expected, actual); + /* + * Test 2: + * + * (a <. Number) + */ + + UnifyType tphA = tf.getPlaceholderType("a"); + eq = new HashSet<>(); + eq.add(new UnifyPair(tphA, number, PairOperator.SMALLERDOT)); + + expected = new HashSet<>(); + addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, integer, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, doubl, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + /* + * Test 3: + * + * (Integer <. a) + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(integer, tphA, PairOperator.SMALLERDOT)); + + expected = new HashSet<>(); + addAsSet(expected, new UnifyPair(tphA, integer, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, object, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + + /* + * Test 4: + * + * (a <.? Number) + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(tphA, number, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + /* + * Test 5: + * + * (a <.? ? super Integer) + */ + + UnifyType supInteger = tf.getSuperType(integer); + UnifyType supNumber = tf.getSuperType(number); + UnifyType supObject = tf.getSuperType(object); + eq = new HashSet<>(); + eq.add(new UnifyPair(tphA, supInteger, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new UnifyPair(tphA, integer, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, object, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, supInteger, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, supNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, supObject, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + System.out.println("? super Integer"); + System.out.println(actual); + actual = filterGeneratedTPHsMultiple(actual); + + Assert.assertEquals(expected, actual); + + /* + * Test 6: + * + * (Number <.? a) + * + */ + + eq = new HashSet<>(); + UnifyType extNumber = tf.getExtendsType(number); + UnifyType extObject = tf.getExtendsType(object); + UnifyType supDouble = tf.getSuperType(doubl); + eq.add(new UnifyPair(number, tphA, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, extNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, extObject, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, supInteger, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, supDouble, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, supNumber, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + actual = filterGeneratedTPHsMultiple(actual); + + Assert.assertEquals(expected, actual); + + /* + * Test 7: + * + * (? extends Number <.? a) + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(extNumber, tphA, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new UnifyPair(tphA, extNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, extObject, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + actual = filterGeneratedTPHsMultiple(actual); + Assert.assertEquals(expected, actual); + + + /* + * Test 8: + * + * (a <.? ? extends Number) + */ + + UnifyType extInteger = tf.getExtendsType(integer); + UnifyType extDouble = tf.getExtendsType(doubl); + + eq = new HashSet<>(); + eq.add(new UnifyPair(tphA, extNumber, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new UnifyPair(tphA, extNumber, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, extInteger, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, extDouble, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, doubl, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, integer, PairOperator.EQUALSDOT)); + addAsSet(expected, new UnifyPair(tphA, number, PairOperator.EQUALSDOT)); + + actual = unify(eq, fc); + actual = filterGeneratedTPHsMultiple(actual); + + Assert.assertEquals(expected, actual); + + /* + * Test 8: + * + * (Integer <. Number) + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(integer, number, PairOperator.SMALLERDOT)); + + expected = new HashSet<>(); + expected.add(new HashSet<>()); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + /* + * Test 9: + * + * (Integer <.? Number) + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(integer, number, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + /* + * Test 10: + * + * (a <. b) + */ + + UnifyType tphB = tf.getPlaceholderType("b"); + eq = new HashSet<>(); + eq.add(new UnifyPair(tphA, tphB, PairOperator.SMALLERDOT)); + + expected = new HashSet<>(); + addAsSet(expected, new UnifyPair(tphA, tphB, PairOperator.SMALLERDOT)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + + /* + * Test 11: + * + * (a <.? b) + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(tphA, tphB, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + addAsSet(expected, new UnifyPair(tphA, tphB, PairOperator.SMALLERDOTWC)); + + actual = unify(eq, fc); + + Assert.assertEquals(expected, actual); + } + + @Test + public void unifyTestSimple() { + /* + * INIT + */ + TypeFactory tf = new TypeFactory(); + FiniteClosureBuilder fcb = new FiniteClosureBuilder(); + + UnifyType number = tf.getSimpleType("Number"); + UnifyType object = tf.getSimpleType("Object"); + UnifyType integer = tf.getSimpleType("Integer"); + UnifyType doubl = tf.getSimpleType("Double"); + + //fcb.add(number, object); + fcb.add(integer, number); + //fcb.add(doubl, number); + + IFiniteClosure fc = fcb.getCollectionExample(); + + /* + * Test 1: + * + * (Vector <. Vector) + * (List <. List) + * + * Expected: + * {(b = Number), (a = Number)}, {(b = Number), (a = Integer)}, {(b = Number), (a = Integer)} + * (b = Integer), + */ + + UnifyType tphA = tf.getPlaceholderType("a"); + UnifyType tphB = tf.getPlaceholderType("b"); + UnifyType extB = tf.getExtendsType(tphB); + UnifyType extNum = tf.getExtendsType(number); + + Set eq = new HashSet(); + eq.add(new UnifyPair(tf.getSimpleType("Vector", tphA), tf.getSimpleType("Vector", extB), PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(tf.getSimpleType("List", tphB), tf.getSimpleType("List", extNum), PairOperator.SMALLERDOT)); + + Set> expected = new HashSet<>(); + Set> actual = unify(eq, fc); + + //System.out.println(actual); + //Assert.assertEquals(actual, expected); + + + /* + * Test 2: + * + * Vector <. List + * + */ + + UnifyType extA = tf.getExtendsType(tphA); + + eq = new HashSet(); + eq.add(new UnifyPair(tf.getSimpleType("Vector", extA), tf.getSimpleType("Vector", extNum), PairOperator.SMALLERDOT)); + + expected = new HashSet<>(); + actual = unify(eq, fc); + + //System.out.println(actual); + //Assert.assertEquals(actual, expected); + + /* + * Test 3: + * + * Vector <. List + * + */ + + eq = new HashSet(); + eq.add(new UnifyPair(tf.getSimpleType("Vector", extNum), tf.getSimpleType("Vector", extA), PairOperator.SMALLERDOT)); + + expected = new HashSet<>(); + actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(actual, expected); + + /* + * Test 4: + * + * LinkedList <. Deque <. Queue <. Collection + * + * Vector <. List + * List <. AbstractList + * ? extends Number <.? b + */ + + eq = new HashSet(); + eq.add(new UnifyPair(tf.getSimpleType("LinkedList", number), tf.getSimpleType("Deque", tphA), PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(tf.getSimpleType("Deque", tphA), tf.getSimpleType("Queue", tphB), PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(extNum, tphB, PairOperator.SMALLERDOTWC)); + + expected = new HashSet<>(); + actual = unify(eq, fc); + + //System.out.println(actual); + //Assert.assertEquals(actual, expected); + } + + /** + * These are tests that specifically test cases where the old unify algorithm was incomplete. + */ + @Test + public void unifyTestExtension() { + /* + * INIT + */ + TypeFactory tf = new TypeFactory(); + FiniteClosureBuilder fcb = new FiniteClosureBuilder(); + + UnifyType number = tf.getSimpleType("Number"); + UnifyType object = tf.getSimpleType("Object"); + UnifyType integer = tf.getSimpleType("Integer"); + UnifyType doubl = tf.getSimpleType("Double"); + UnifyType mygeneric = tf.getSimpleType("MyGeneric", "T"); + + + fcb.add(mygeneric, object); + fcb.add(integer, number); + //fcb.add(doubl, number); + + IFiniteClosure fc = fcb.getCollectionExample(); + + + /* + * Test 1: + * This is a Test for the extension of case 1 in the cartesian product of step 4. + * + * (a <. Vector) + * (List <. List) + * + * Expected: + * (b = Integer), (a = Vector) + * (b = ? extends Integer), (a = Vector), + * (b = ? extends Integer), (a = Vector), + * (b = ? super Integer), (a = Vector) + * (b = ? super Integer), (a = Vector) + * (b = ? super Integer), (a = Vector) + * (b = ? super Integer), (a = Vector) + * (b = ? extends Number), (a = Vector) + * (b = ? extends Number), (a = Vector) + * (b = ? extends Number), (a = Vector) + * (b = ? extends Number), (a = Vector) + */ + + UnifyType tphA = tf.getPlaceholderType("a"); + UnifyType tphB = tf.getPlaceholderType("b"); + UnifyType extB = tf.getExtendsType(tphB); + UnifyType extNum = tf.getExtendsType(number); + + Set eq = new HashSet(); + eq.add(new UnifyPair(tphA, tf.getSimpleType("Stack", tphB), PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(tf.getSimpleType("List", integer), tf.getSimpleType("List", tphB), PairOperator.SMALLERDOT)); + + Set> expected = new HashSet<>(); + Set> actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(actual, expected); + + /* + * Test 2: + * + * This is a test for th extension of case 2 of the cartesian product of step 4. + * + * (a <.? ? ext b) + * (b =. Number) + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(tphA, extB, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphB, number, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + System.out.println("Case 2"); + System.out.println(actual); + + /* + * Test 3: + * This is a test for the extension of case 3 of the cartesian product of step 4. + * + * (a <.? ? sup b) + * (b = Number) + */ + + UnifyType supB = tf.getSuperType(tphB); + eq = new HashSet<>(); + eq.add(new UnifyPair(tphA, supB, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphB, number, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + + System.out.println("Case 3"); + System.out.println(actual); + //Assert.assertEquals(expected, actual); + + /* + * Case 4 has no extension + */ + + /* + * Test 5: + * This is a test for the extension of case 5 of the cartesian product of step 4. + * + * Vector <. a + * b =. Number + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(tf.getSimpleType("HashSet", tphB), tphA, PairOperator.SMALLERDOT)); + eq.add(new UnifyPair(tphB, number, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(expected, actual); + + /* + * Test 6: + * This is a test for the extension of case 6 of the cartesian product of step 4. + * + * ? extends b <.? a + * b =. Integer + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(extB, tphA, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphB, integer, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + System.out.println(actual); + //Assert.assertEquals(expected, actual); + + /* + * Test 7: + * This is a test for the extension of case 7 of the cartesian product of step 4. + * + * ? sup b <.? a + * b =. Number + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(supB, tphA, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphB, number, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + System.out.println("Case 7"); + System.out.println(actual); + //Assert.assertEquals(expected, actual); + + + /* + * Test 8: + * This is a test for the extension of case 8 of the cartesian product of step 4. + * + * MyGeneric <.? a + * b =. Integer + */ + + eq = new HashSet<>(); + eq.add(new UnifyPair(tf.getSimpleType("MyGeneric", extB), tphA, PairOperator.SMALLERDOTWC)); + eq.add(new UnifyPair(tphB, number, PairOperator.EQUALSDOT)); + + expected = new HashSet<>(); + + actual = unify(eq, fc); + + System.out.println("Case 8:"); + System.out.println(actual); + //Assert.assertEquals(expected, actual); + + } + + @Test + public void unifyTestComplex() { + /* + * INIT + */ + TypeFactory tf = new TypeFactory(); + FiniteClosureBuilder fcb = new FiniteClosureBuilder(); + + UnifyType tphT = tf.getPlaceholderType("T"); + UnifyType vector = tf.getSimpleType("Vector", tphT); + UnifyType number = tf.getSimpleType("Number"); + UnifyType integer = tf.getSimpleType("Integer"); + UnifyType object = tf.getSimpleType("Object"); + UnifyType matrix = tf.getSimpleType("Matrix"); + UnifyType vectorvectorint = tf.getSimpleType("Vector", tf.getSimpleType("Vector", integer)); + + + fcb.add(integer, number); + fcb.add(matrix, vectorvectorint); + fcb.add(vector, object); + + IFiniteClosure fc = fcb.getFiniteClosure(); + + Set eq = new HashSet(); + eq.add(new UnifyPair(tf.getSimpleType("Matrix"), tf.getSimpleType("Vector", tf.getPlaceholderType("a")), PairOperator.SMALLERDOT)); + + Set> expected = new HashSet<>(); + Set> actual = unify(eq, fc); + + System.out.println("Test Matrix:"); + System.out.println(actual); } @Test @@ -62,27 +607,58 @@ public class UnifyTest extends Unify { TypeFactory tf = new TypeFactory(); ArrayList> candidates = new ArrayList<>(); + UnifyType p11 = tf.getPlaceholderType("p11"); + UnifyType p12 = tf.getExtendsType(tf.getSimpleType("p12")); + UnifyType p13 = tf.getSimpleType("p13"); + UnifyType p21 = tf.getPlaceholderType("p21"); + UnifyType p22 = tf.getPlaceholderType("p22"); + UnifyType p31 = tf.getSimpleType("p31", "T"); + Set p1 = new HashSet<>(); - p1.add(tf.getPlaceholderType("p11")); - p1.add(tf.getExtendsType(tf.getSimpleType("p12"))); - p1.add(tf.getSimpleType("p13")); + p1.add(p11); + p1.add(p12); + p1.add(p13); Set p2 = new HashSet<>(); - p2.add(tf.getPlaceholderType("p21")); - p2.add(tf.getPlaceholderType("p22")); + p2.add(p21); + p2.add(p22); Set p3 = new HashSet<>(); - p3.add(tf.getSimpleType("p31", "T")); - p3.add(tf.getSimpleType("p32")); + p3.add(p31); candidates.add(p1); candidates.add(p2); candidates.add(p3); - Set result = new HashSet<>(); - permuteParams(candidates, 0, result, new UnifyType[candidates.size()]); - System.out.println(result); + /* + * Expected Result: + * { | x in { p11, p12, p13}, y in { p21, p22 }, z in { p31 }} + */ + Set expected = Arrays.stream(new TypeParams[] { + new TypeParams(p11, p21, p31), + new TypeParams(p11, p22, p31), + new TypeParams(p12, p21, p31), + new TypeParams(p12, p22, p31), + new TypeParams(p13, p21, p31), + new TypeParams(p13, p22, p31) + }).collect(Collectors.toSet()); + + Set actual = permuteParams(candidates); + + Assert.assertEquals(expected, actual); } + private Set> filterGeneratedTPHsMultiple(Set> set) { + return set.stream().map(x -> filterGeneratedTPHs(x)).collect(Collectors.toSet()); + } + + private Set filterGeneratedTPHs(Set set) { + return set.stream().filter(x -> !((x.getRhsType() instanceof PlaceholderType) && ((PlaceholderType) x.getRhsType()).isGenerated())). + filter(x -> !((x.getLhsType() instanceof PlaceholderType) && ((PlaceholderType) x.getLhsType()).isGenerated())).collect(Collectors.toSet()); + } + + private void addAsSet(Set> addTo, UnifyPair... mPairs) { + addTo.add(new HashSet<>(Arrays.stream(mPairs).collect(Collectors.toSet()))); + } } diff --git a/test/unify/UnifyTypeFactoryTest.java b/test/unify/UnifyTypeFactoryTest.java new file mode 100644 index 00000000..2cf5bc53 --- /dev/null +++ b/test/unify/UnifyTypeFactoryTest.java @@ -0,0 +1,157 @@ +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.UnifyPair; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; +import de.dhbwstuttgart.typeinference.unify.model.UnifyType; + + +public class UnifyTypeFactoryTest { + private static TypeFactory tf = new TypeFactory(); + + @Test + public void convertUnifyTypes(){ + //UnifyType ut = + } + + @Test + public void convertConstraintSet(){ + ConstraintsSet cons = new ConstraintsSet(); + 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() { + UnifyPair mp1 = getSimpleMPair(); + checkConvertMPair(mp1); + + TypePlaceholder tph1 = TypePlaceholder.fresh(new NullSyntaxTreeNode()); + TypePlaceholder tph2 = TypePlaceholder.fresh(new NullSyntaxTreeNode()); + + UnifyPair mp2 = new UnifyPair(getSimpleType(), tf.getPlaceholderType(tph1.getName().toString()), PairOperator.SMALLERDOT); + checkConvertMPair(mp2); + + UnifyPair mp3 = new UnifyPair(tf.getSuperType(getSimpleType()), getSimpleType(), PairOperator.SMALLERDOT); + checkConvertMPair(mp3); + + UnifyPair mp4 = new UnifyPair(tf.getPlaceholderType(tph2.getName().toString()), tf.getPlaceholderType(tph1.getName().toString()), PairOperator.SMALLERDOT); + checkConvertMPair(mp4); + + ReferenceType typeWithParams = tf.getSimpleType("Test", getSimpleType()); + ReferenceType typeWithTPHParams = tf.getSimpleType("Test", tf.getPlaceholderType("Test")); + UnifyPair mp5 = new UnifyPair(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(UnifyPair mp : pairs){ + Pair p = checkConvertMPair(mp); + tmpSet.add(p); + } + controlSet.add(tmpSet); + } + assertTrue(controlSet.equals(check)); + } + + private static UnifyPair checkConvertPair(Pair p){ + System.out.println("Checking Pair: "+p); + UnifyPair mp = UnifyTypeFactory.convert(p); + assertTrue(p.TA1.get_Name().equals(mp.getLhsType().getName())); + assertTrue(p.TA2.get_Name().equals(mp.getRhsType().getName())); + return mp; + } + + private static Pair checkConvertMPair(UnifyPair 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 ReferenceType getSimpleType(){ + return tf.getSimpleType("String"); + } + + private static UnifyPair getSimpleMPair(){ + UnifyType lt = tf.getSimpleType("String"); + UnifyType rt = tf.getSimpleType("String"); + UnifyPair ret = new UnifyPair(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()); + } +}