2
0

Compare commits

..

5 Commits

155 changed files with 2513 additions and 5338 deletions
README_aktuelle_Branchespom.xml
src
main
antlr4
java
de
dhbwstuttgart
bytecode
core
parser
SyntaxTreeGenerator
syntaxtree
target
typeinference
test
java
resources

@ -1,10 +0,0 @@
Stand: 24.5.21
bigRefactoring: Master-Brach
bigRefactoringUnifyComment: Dokumentation Unify, Martin
bytecodeGenericsSecond: Generated Generics, Ali, Martin
inferWildcards, Wildcards, Till
master, derzeit nicht genutzt
plugin, eigemntlicher Branch fuer Plugin-Basis, derzeit nicht aktuelle (aktuelle Version in simplifyRes
simplifyRes, Basis fuer Plugin, sollte auf Plugin gemerged werden, noch keine Packages, Michael
strucTypesNew, Struturelle Typen, alte Basis, arbeite derzeit niemand

16
pom.xml

@ -118,15 +118,6 @@ http://maven.apache.org/maven-v4_0_0.xsd">
</descriptorRefs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>17</source>
<target>17</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
@ -138,11 +129,8 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<compilerArgs>
--enable-preview
</compilerArgs>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<tycho.version>0.23.0</tycho.version>
<mainClass>de.dhbwstuttgart.core.ConsoleInterface</mainClass>
</properties>

@ -0,0 +1,37 @@
grammar UnifyResult;
answer : 'ANSWER' (resultSetRule '.')*;
resultSetRule :
parameter
| equals
| smaller
| typeVar
| type
| otherRule
;
parameterList : '(' value (',' value)* ')';
value : NAME
| resultSetRule ;
parameter : PARAMLIST_NAME parameterList;
equals : EQUALS_NAME parameterList;
smaller : SMALLER_NAME parameterList;
typeVar : TYPEVAR_NAME parameterList;
type : TYPE_NAME parameterList;
otherRule : NAME parameterList;
//TODO: Es sollte Regeln für das Result set geben, welche sich nicht mit den anderen überdecken, dann auch nur diese im Result ausgeben
PARAMLIST_NAME : 'param';
EQUALS_NAME : 'equals';
SMALLER_NAME : 'smaller';
TYPEVAR_NAME : 'typeVar';
TYPE_NAME : 'type';
NAME : [a-zA-Z0-9_]+;
WS : [ \t\r\n\u000C]+ -> skip
;
LINE_COMMENT
: '%' ~[\r\n]* -> skip
;

@ -0,0 +1,23 @@
T__0=1
T__1=2
T__2=3
T__3=4
T__4=5
PARAMLIST_NAME=6
EQUALS_NAME=7
SMALLER_NAME=8
TYPEVAR_NAME=9
TYPE_NAME=10
NAME=11
WS=12
LINE_COMMENT=13
'ANSWER'=1
'.'=2
'('=3
','=4
')'=5
'param'=6
'equals'=7
'smaller'=8
'typeVar'=9
'type'=10

@ -0,0 +1,23 @@
T__0=1
T__1=2
T__2=3
T__3=4
T__4=5
PARAMLIST_NAME=6
EQUALS_NAME=7
SMALLER_NAME=8
TYPEVAR_NAME=9
TYPE_NAME=10
NAME=11
WS=12
LINE_COMMENT=13
'ANSWER'=1
'.'=2
'('=3
','=4
')'=5
'param'=6
'equals'=7
'smaller'=8
'typeVar'=9
'type'=10

@ -13,10 +13,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import de.dhbwstuttgart.bytecode.funN.FunNGenerator;
import de.dhbwstuttgart.bytecode.funN.FunNUtilities;
import de.dhbwstuttgart.bytecode.utilities.*;
import de.dhbwstuttgart.environment.DirectoryClassLoader;
import de.dhbwstuttgart.exceptions.NotImplementedException;
@ -592,21 +589,10 @@ public class BytecodeGenMethod implements StatementVisitor {
this.lamCounter++;
String typeErasure = createDescriptorWithTypeErasure(lambdaExpression);
//ToDo Etienne: Double Check
RefTypeOrTPHOrWildcardOrGeneric returnType = resolver.resolve(lambdaExpression.getReturnType());
List<RefTypeOrTPHOrWildcardOrGeneric> argumentTypes = lambdaExpression
.params
.getFormalparalist()
.stream()
.map(FormalParameter::getType)
.map(resolver::resolve)
.collect(Collectors.toList());
FunNUtilities funNUtilities = FunNGenerator.getInstance();
FunNUtilities.writeClassFile(funNUtilities.getSuperClassName(argumentTypes.size()),
funNUtilities.generateSuperBytecode(argumentTypes.size()), path);
FunNUtilities.writeClassFile(funNUtilities.getSpecializedClassName(argumentTypes, returnType),
funNUtilities.generateSpecializedBytecode(argumentTypes, returnType), path);
ByteCodeForFunNGenerator.generateBCForFunN(lambdaExpression, typeErasure,path);
Lambda lam = new Lambda(lambdaExpression);
String lamDesc = lam.accept(new DescriptorToString(resultSet));
// Call site, which, when invoked, returns an instance of the functional
@ -828,20 +814,8 @@ public class BytecodeGenMethod implements StatementVisitor {
} else if(!helper.isInCurrPkg(clazz)){
if(clazz.contains(CONSTANTS.$$)) {
mDesc = helper.getDescriptorOfApplyMethod(methCallType);
//ToDo Etienne: Double Check
RefTypeOrTPHOrWildcardOrGeneric returnType = resolver.resolve(methodCall.getType());
List<RefTypeOrTPHOrWildcardOrGeneric> argumentTypes = methodCall
.arglist
.getArguments()
.stream()
.map(TypableStatement::getType)
.map(resolver::resolve)
.collect(Collectors.toList());
FunNUtilities funNUtilities = FunNGenerator.getInstance();
FunNUtilities.writeClassFile(funNUtilities.getSuperClassName(argumentTypes.size()),
funNUtilities.generateSuperBytecode(argumentTypes.size()), path);
FunNUtilities.writeClassFile(funNUtilities.getSpecializedClassName(argumentTypes, returnType),
funNUtilities.generateSpecializedBytecode(argumentTypes, returnType), path);
helper.generateBCForFunN(mDesc);
// mDesc = helper.generateBCForFunN(methCallType,typesOfParams);
}else {
try {
cLoader2 = new DirectoryClassLoader(path, classLoader);

@ -10,9 +10,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
@ -33,9 +30,6 @@ import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.result.GenericInsertPair;
import de.dhbwstuttgart.typeinference.result.ResultPair;
import de.dhbwstuttgart.typeinference.result.ResultSet;
@ -55,10 +49,6 @@ public class TPHExtractor extends AbstractASTWalker {
boolean inLocalOrParamOrReturn = false;
public final ArrayList<MethodAndTPH> ListOfMethodsAndTph = new ArrayList<>();
// Alle Constraints in einer Menge (Und- & Oder-Constraints)
public Set<Pair> oldConstraints = new HashSet<>();
final ArrayList<ResultPair<TypePlaceholder, TypePlaceholder>> allPairs = new ArrayList<>();
public final ArrayList<TPHConstraint> allCons = new ArrayList<>();
private ResultSet resultSet;
@ -88,25 +78,15 @@ public class TPHExtractor extends AbstractASTWalker {
public void visit(TypePlaceholder tph) {
if (resultSet.resolveType(tph).resolvedType instanceof TypePlaceholder) {
TypePlaceholder resolvedTPH = (TypePlaceholder) resultSet.resolveType(tph).resolvedType;
String tphName = resolvedTPH.getName();
if (inMethod && !tphsClass.contains(tphName)) {
ArrayList<String> tphs = null;
if (!(tphs = methodAndTph.getTphs()).contains(tphName)) {
methodAndTph.addTph(tphName);
}
if (inLocalOrParamOrReturn) {
if (!(tphs = methodAndTph.getLocalTphs()).contains(tphName)) {
tphs.add(tphName);
}
}
} else {
if (!tphsClass.contains(tphName)) {
tphsClass.add(tphName);
}
}
if (!allTPHS.containsKey(tphName)) {
allTPHS.put(tphName, inMethod);
if (inMethod) {
methodAndTph.getTphs().add(resolvedTPH.getName());
if (inLocalOrParamOrReturn)
methodAndTph.getLocalTphs().add(resolvedTPH.getName());
}else {
tphsClass.add(resolvedTPH.getName());
}
allTPHS.put(resolvedTPH.getName(), inMethod);
// final List<TPHConstraint> cons = new ArrayList<>();
// resultSet.resolveType(tph).additionalGenerics.forEach(ag -> {
// TPHConstraint con = new ExtendsConstraint(ag.TA1.getName(), ag.TA2.getName(), Relation.EXTENDS);
@ -173,7 +153,7 @@ public class TPHExtractor extends AbstractASTWalker {
public void visit(GenericRefType genericRefType) {
String name = genericRefType.getParsedName();
if (inMethod) {
methodAndTph.addTph(name);
methodAndTph.getTphs().add(name);
if (inLocalOrParamOrReturn)
methodAndTph.getLocalTphs().add(name);
}else {
@ -195,33 +175,7 @@ public class TPHExtractor extends AbstractASTWalker {
public void visit(Method method) {
inMethod = true;
String id = MethodUtility.createID(resolver,method);
Predicate<Pair> filterUndConstraints = cs -> ((cs.TA1 instanceof TypePlaceholder) && (cs.TA2 instanceof TypePlaceholder) &&
(resultSet.resolveType((TypePlaceholder)(cs.TA1)).resolvedType instanceof TypePlaceholder) &&
(resultSet.resolveType((TypePlaceholder)(cs.TA2)).resolvedType instanceof TypePlaceholder));
Function<ConstraintSet<Pair>, ConstraintSet<Pair>> filterConstrRemainingTVar =
csS -> {
ConstraintSet<Pair> ret = new ConstraintSet<>();
ret.addAllUndConstraint(
csS.getUndConstraints()
.stream().filter(filterUndConstraints)
.collect(Collectors.toCollection(Constraint<Pair>::new)));
csS.getOderConstraints()
.forEach(oConSSet -> { Set<Constraint<Pair>> setCons = new HashSet<>();
oConSSet.forEach(OConS -> { Constraint<Pair> newConsPair = new Constraint<Pair>();
newConsPair.isStatement = OConS.isStatement;
setCons.add(
OConS.stream()
.filter(filterUndConstraints)
.collect(Collectors.toCollection(() -> newConsPair)) );
} );
ret.addOderConstraint(setCons);} );
return ret;
};
ConstraintSet<Pair> filteredConstraints = filterConstrRemainingTVar.apply(method.getConstraints());
methodAndTph = new MethodAndTPH(id, filteredConstraints);
oldConstraints.addAll(filteredConstraints.getAll());
methodAndTph = new MethodAndTPH(id);
inLocalOrParamOrReturn = true;
method.getReturnType().accept(this);
@ -230,7 +184,7 @@ public class TPHExtractor extends AbstractASTWalker {
if(method.block != null)
method.block.accept(this);
inMethod = false;
ListOfMethodsAndTph.add(methodAndTph);
}

@ -1,25 +1,13 @@
package de.dhbwstuttgart.bytecode.constraint;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
public class TPHConstraint {
protected String left;
protected String right;
protected Relation rel;
protected int variance; //noch nicht benutzt
public enum Relation{
EXTENDS, EQUAL
}
public TPHConstraint(Pair p) {
this.left = ((TypePlaceholder)p.TA1).getName();
this.right = ((TypePlaceholder)p.TA2).getName();
this.rel = p.GetOperator().equals(PairOperator.SMALLERDOT) ? Relation.EXTENDS : Relation.EQUAL;
}
public TPHConstraint(String left, String right, Relation rel) {
this.left = left;
this.right = right;
@ -60,25 +48,6 @@ public class TPHConstraint {
return rel == constraint.getRel() && left.equals(constraint.getLeft()) && right.equals(constraint.getRight());
}
@Override
public int hashCode() {
return (left+right).hashCode();
}
@Override
public boolean equals (Object o) {
if (o instanceof TPHConstraint) {
TPHConstraint o_tphcons = (TPHConstraint)o;
return (this.left.equals(o_tphcons.getLeft())
&& this.right.equals(o_tphcons.getRight())
&& this.rel.equals(o_tphcons.rel));
}
else {
return false;
}
}
@Override
public String toString() {
if(rel == Relation.EXTENDS) {

@ -153,7 +153,6 @@ public class DescriptorToString implements DescriptorVisitor, CONSTANTS {
return desc;
}
//ToDo Etienne: ändern
@Override
public String visit(Lambda lambdaExpression) {
String desc = "(";

@ -1,24 +1,17 @@
package de.dhbwstuttgart.bytecode.descriptor;
import de.dhbwstuttgart.bytecode.funN.FunNGenerator;
import de.dhbwstuttgart.bytecode.funN.FunNUtilities;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.syntaxtree.type.TypeVisitor;
public class TypeToDescriptor implements TypeVisitor<String>{
private final boolean specializedFunN;
public TypeToDescriptor(){ this(true); }
public TypeToDescriptor(boolean specializedFunN) { this.specializedFunN = specializedFunN; }
@Override
public String visit(RefType refType) {
if (refType.getName().toString().matches("Fun\\d+\\$\\$") && specializedFunN) {
FunNUtilities funNUtilities = FunNGenerator.getInstance();
return funNUtilities.getSpecializedDescriptor(funNUtilities.getArguments(refType.getParaList()), funNUtilities.getReturnType(refType.getParaList()));
}
return refType.getName().toString().replace(".", "/");
// String t = refType.getName().toString().replace(".", "/");
// return t.equals("Fun1")?(t+"$$"):t;
@ -45,8 +38,6 @@ public class TypeToDescriptor implements TypeVisitor<String>{
//throw new NotImplementedException();
}
//ToDo Etienne: bin der Meinung hier müsste immer der Descriptor der extends-Schranke sein, z.b. <T> => Ljava/lang/Object; oder <T extends String> => Ljava/lang/String;
//Tests sind aber damit grün?! => Fehler in Tests schon vorher aufgefallen und gut möglich!
@Override
public String visit(GenericRefType genericRefType) {
return genericRefType.getParsedName().replace(".", "/");

@ -1,181 +0,0 @@
package de.dhbwstuttgart.bytecode.funN;
import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor;
import de.dhbwstuttgart.bytecode.signature.TypeToSignature;
import de.dhbwstuttgart.bytecode.utilities.CONSTANTS;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.objectweb.asm.Opcodes.*;
/**
* Represents a Singleton-Service implementation for the {@link FunNUtilities} interface.
*
* @since Studienarbeit Type Erasure
* @author etiennezink
*/
public final class FunNGenerator implements FunNUtilities{
private static final FunNGenerator funNGenerator = new FunNGenerator();
/**
* @return the Singleton instance for {@link FunNGenerator}
*/
public static FunNUtilities getInstance(){ return funNGenerator; }
private final String argumentGenericBase = "T";
private final String returnGeneric = "R";
private final String methodName = "apply";
private final int bytecodeVersion = V1_8;
private final String objectSuperType = Type.getInternalName(Object.class).replace('.','/');
private final RefType objectRefType = new RefType(new JavaClassName(objectSuperType), null);
private final String objectSignature = applySignature(objectRefType);
private FunNGenerator(){}
@Override
public byte[] generateSuperBytecode(int numberArguments) {
StringBuilder superFunNClassSignature = new StringBuilder("<");
StringBuilder superFunNMethodSignature = new StringBuilder("(");
StringBuilder superFunNMethodDescriptor = new StringBuilder("(");
for (int currentParameter = 1; currentParameter <= numberArguments; currentParameter++){
superFunNClassSignature.append(String.format("%s%d:%s",argumentGenericBase, currentParameter, objectSignature));
superFunNMethodSignature.append(applySignature( new GenericRefType(argumentGenericBase + currentParameter, null)));
superFunNMethodDescriptor.append(objectSignature);
}
superFunNClassSignature.append(String.format("%s:%s>%s", returnGeneric, objectSignature, objectSignature));
superFunNMethodSignature.append(String.format(")%s", applySignature(new GenericRefType(returnGeneric, null))));
superFunNMethodDescriptor.append(String.format(")%s", objectSignature));
ClassWriter classWriter = new ClassWriter(0);
MethodVisitor methodVisitor;
classWriter.visit(bytecodeVersion, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, getSuperClassName(numberArguments), superFunNClassSignature.toString(), objectSuperType, null);
methodVisitor = classWriter.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, methodName, superFunNMethodDescriptor.toString(), superFunNMethodSignature.toString(), null);
methodVisitor.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
@Override
public String getSuperClassName(int numberArguments) {
return String.format("Fun%d$$", numberArguments);
}
@Override
public byte[] generateSpecializedBytecode(List<RefTypeOrTPHOrWildcardOrGeneric> argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType) {
Objects.requireNonNull(argumentTypes);
Objects.requireNonNull(returnType);
//generates a list of all params and substitutes the TPH
List<RefTypeOrTPHOrWildcardOrGeneric> parameters = Stream
.concat(argumentTypes.stream(), Stream.of(returnType))
.map(this::substituteTPH)
.collect(Collectors.toList());
RefType superFunN = new RefType(new JavaClassName(getSuperClassName(argumentTypes.size())), parameters , null);
StringBuilder funNClassSignature = new StringBuilder(objectSignature + (superFunN.acceptTV(new TypeToSignature(false))));
boolean containsGeneric = false;
String genericSignature = "<";
for (RefTypeOrTPHOrWildcardOrGeneric typeArgument : parameters) {
if (typeArgument instanceof GenericRefType){
GenericRefType generic = (GenericRefType) typeArgument;
String signatureOfArgument = generic.getParsedName();
if(genericSignature.contains(signatureOfArgument)) continue;
genericSignature += String.format("%s:%s", signatureOfArgument, objectSignature);
containsGeneric = true;
}
}
genericSignature += ">";
if (containsGeneric) funNClassSignature.insert(0, genericSignature);
ClassWriter classWriter = new ClassWriter(0);
classWriter.visit(bytecodeVersion, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, getSpecializedClassName(argumentTypes, returnType), funNClassSignature.toString(), objectSuperType, new String[]{getSuperClassName(argumentTypes.size())});
classWriter.visitEnd();
return classWriter.toByteArray();
}
@Override
public String getSpecializedClassName(List<RefTypeOrTPHOrWildcardOrGeneric> argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType) {
Objects.requireNonNull(argumentTypes);
Objects.requireNonNull(returnType);
return String.format("Fun%d$$%s%s",
argumentTypes.size(),
argumentTypes
.stream()
.map(this::applyNameDescriptor)
.collect(Collectors.joining()),
applyNameDescriptor(returnType))
.replace('/', '$')
.replace(";", "$_$");
}
@Override
public String getSpecializedDescriptor(List<RefTypeOrTPHOrWildcardOrGeneric> argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType) {
Objects.requireNonNull(argumentTypes);
Objects.requireNonNull(returnType);
return applyDescriptor(getSpecializedFunNRefType(argumentTypes, returnType));
}
@Override
public String getSpecializedSignature(List<RefTypeOrTPHOrWildcardOrGeneric> argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType) {
Objects.requireNonNull(argumentTypes);
Objects.requireNonNull(returnType);
return applySignature(getSpecializedFunNRefType(argumentTypes, returnType));
}
@Override
public List<RefTypeOrTPHOrWildcardOrGeneric> getArguments(List<RefTypeOrTPHOrWildcardOrGeneric> list) {
Objects.requireNonNull(list);
return list
.stream()
.limit(Math.max(0, list.size() - 1))
.collect(Collectors.toList());
}
@Override
public RefTypeOrTPHOrWildcardOrGeneric getReturnType(List<RefTypeOrTPHOrWildcardOrGeneric> list) {
Objects.requireNonNull(list);
if(list.size() == 0) return null;
return list.get(list.size() - 1);
}
private String applyDescriptor(RefTypeOrTPHOrWildcardOrGeneric a) { return a.acceptTV(new TypeToDescriptor(true)); }
private String applySignature(RefTypeOrTPHOrWildcardOrGeneric a) { return a.acceptTV(new TypeToSignature(true)); }
/**
* @param a
* @return the name for the type {@code a} which should be used in the specialized name for FunN.
*/
private String applyNameDescriptor(RefTypeOrTPHOrWildcardOrGeneric a){ return a instanceof TypePlaceholder ? "LTPH;" : String.format("L%s;", applyDescriptor(a)); }
private RefTypeOrTPHOrWildcardOrGeneric substituteTPH(RefTypeOrTPHOrWildcardOrGeneric t) {
if (t instanceof TypePlaceholder) {
TypePlaceholder tph = (TypePlaceholder) t;
return new GenericRefType(tph.getName()+"$", t.getOffset());
}
return t;
}
private RefType getSpecializedFunNRefType(List<RefTypeOrTPHOrWildcardOrGeneric> argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType){
return new RefType(new JavaClassName(getSpecializedClassName(argumentTypes, returnType)),
Stream
.concat(argumentTypes.stream(), Stream.of(returnType))
.filter(t -> t instanceof GenericRefType ||
t instanceof TypePlaceholder)
.collect(Collectors.toList()),null);
}
}

@ -1,90 +0,0 @@
package de.dhbwstuttgart.bytecode.funN;
import de.dhbwstuttgart.bytecode.utilities.CONSTANTS;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
/**
* Interface which represents the functionality for specifying and generating the specified functional types (FunN).
*
* @since Studienarbeit Type Erasure
* @author etiennezink
*/
public interface FunNUtilities {
/**
* @param numberArguments (excluding the return type!)
* @return the bytecode for the super FunN-interface
*/
byte[] generateSuperBytecode(int numberArguments);
/**
* @param numberArguments (excluding the return type!)
* @return the name for the super FunN-interface
*/
String getSuperClassName(int numberArguments);
/**
* @param argumentTypes (excluding the return type!)
* @param returnType
* @return the bytecode for the specialized FunN-interface
*/
byte[] generateSpecializedBytecode(List<RefTypeOrTPHOrWildcardOrGeneric> argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType);
/**
* @param argumentTypes (excluding the return type!)
* @param returnType
* @return the name for the specialized FunN-interface
*/
String getSpecializedClassName(List<RefTypeOrTPHOrWildcardOrGeneric> argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType);
/**
* @param argumentTypes (excluding the return type!)
* @param returnType
* @return the descriptor for a specialized FunN-interface.
*/
String getSpecializedDescriptor(List<RefTypeOrTPHOrWildcardOrGeneric> argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType);
/**
* @param argumentTypes (excluding the return type!)
* @param returnType
* @return the signature for a specialized FunN-interface.
*/
String getSpecializedSignature(List<RefTypeOrTPHOrWildcardOrGeneric> argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType);
/**
* @param list containing type arguments and the return type.
* @return a {@link List} containing only the arguments of the specialized FunN-interface.
*/
List<RefTypeOrTPHOrWildcardOrGeneric> getArguments(List<RefTypeOrTPHOrWildcardOrGeneric> list);
/**
* @param list containing type arguments and the return type.
* @return the return type of the {@code list} (last member)
*/
RefTypeOrTPHOrWildcardOrGeneric getReturnType(List<RefTypeOrTPHOrWildcardOrGeneric> list);
/**
* Should be refactored into a central API.
*
* @param className
* @param bytecode
* @param directory
* @return {@code true} iff the file could be generated and {@code false} if not
*/
@Deprecated
static boolean writeClassFile(String className, byte[] bytecode, File directory) {
try (FileOutputStream output = new FileOutputStream(new File(directory , className + CONSTANTS.EXTENSIONCLASS))){
output.write(bytecode);
output.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}

@ -3,14 +3,16 @@
*/
package de.dhbwstuttgart.bytecode.genericsGenerator;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import de.dhbwstuttgart.bytecode.TPHExtractor;
import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.*;
import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint;
import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResultForClass;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.MethodAndConstraints;
import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH;
import de.dhbwstuttgart.bytecode.utilities.MethodUtility;
import de.dhbwstuttgart.bytecode.utilities.Resolver;
@ -79,7 +81,6 @@ public class GeneratedGenericsFinder implements ASTVisitor {
private JavaClassName className;
private Resolver resolver;
/**
* @param sf
* @param listOfResultSets
@ -94,14 +95,6 @@ public class GeneratedGenericsFinder implements ASTVisitor {
return generatedGenericsForSF;
}
/**
* returns the family of Generated Generics
* insbesondere fuer Testzwecke
*/
public FamilyOfGeneratedGenerics getFogg() {
return fogg;
}
/*
* (non-Javadoc)
*
@ -134,7 +127,6 @@ public class GeneratedGenericsFinder implements ASTVisitor {
ConstraintsSimplierResult simplifiedConstraints = null;
GenericsGeneratorResultForClass ggResult = null;
GenericsGeneratorResultForClass ggResultAlternative = null;
for (int i = 0; i < listOfResultSetsList.size(); i++) {
resultSet = listOfResultSetsList.get(i);
@ -143,19 +135,9 @@ public class GeneratedGenericsFinder implements ASTVisitor {
classOrInterface.accept(tphExtractor);
//PL 2020-10-16: Ab hier GGenerics implementieren durch Ali
//Rueckgabe an generatedGenericsForSF
fogg = new FamilyOfGeneratedGenerics(tphExtractor, resultSet);
System.out.println("fogg.allConstraints: "+ fogg.allConstraints);
System.out.println("fogg.posOfTPHs: "+ fogg.posOfTPHs);
System.out.println("fogg.classConstraints: "+ fogg.classConstraints);
System.out.println("fogg.methodConstraintsWithPosition: "+ fogg.methodConstraintsWithPosition);
System.out.println(fogg);
///*
//Fayez Ansatz Anfang
fogg = new FamilyOfGeneratedGenerics(tphExtractor);
tphsClass = tphExtractor.tphsClass;
//PL 2020-01-15
//Es muss ggResult aus fogg gebildet werden
simplifiedConstraints = GenericsGenerator.simplifyConstraints(tphExtractor, tphsClass);
if(!isVisited) {
ggResult = GenericsGenerator.generateConstraints(className, tphExtractor, tphsClass,simplifiedConstraints);
@ -164,45 +146,12 @@ public class GeneratedGenericsFinder implements ASTVisitor {
for(Method m : classOrInterface.getMethods()) {
addMethodConstraints(simplifiedConstraints, ggResult, m);
}
if(ggResult != null) { //Hinzufuegen von Fayez ggResult
if(ggResult != null)
generatedGenericsForSF.addGenericGeneratorResultClass(ggResult);
}
// Fayez Ansatz Ende
//*/
//Ali Ansatz Anfang
List<GenericsGeneratorResult> listOfClassCons = new ArrayList<>();
for(TPHConstraint clCons: fogg.classConstraints) {
// ExtendsConstraint ec = new ExtendsConstraint(clCons.getLeft(), clCons.getRight());
GenericsGeneratorResult ggR = new GenericsGeneratorResult(clCons, new HashSet<>());
listOfClassCons.add(ggR);
}
GenericGeneratorResultsForAllMethods ggRfaM = null;
List<MethodAndConstraints> listOfMethAndCons = new ArrayList<>();
for(String methID: fogg.methodConstraintsWithPosition.keySet()) {
List<GenericsGeneratorResult> listOfGGR = new ArrayList<>();
for(TPHConstraint methCons: fogg.methodConstraintsWithPosition.get(methID)) {
// ExtendsConstraint ec = new ExtendsConstraint(methCons.getLeft(),methCons.getRight());
GenericsGeneratorResult ggR = new GenericsGeneratorResult(methCons, new HashSet<>());
listOfGGR.add(ggR);
}
MethodAndConstraints mac = new MethodAndConstraints(methID, listOfGGR);
listOfMethAndCons.add(mac);
}
ggRfaM = new GenericGeneratorResultsForAllMethods(listOfMethAndCons);
ggResultAlternative = new GenericsGeneratorResultForClass(className, listOfClassCons, ggRfaM);
if(ggResultAlternative != null) {//hinzufuegen von Alis ggResult
//generatedGenericsForSF.addGenericGeneratorResultClass(ggResultAlternative);
System.out.println(generatedGenericsForSF);
}
System.out.println(ggResultAlternative);
//Ali Ansatz Ende
System.out.println("ddd");
}

@ -29,13 +29,5 @@ public class GenericGeneratorResultsForAllMethods {
public List<MethodAndConstraints> getMethodsAndConstraints() {
return methodsAndConstraints;
}
@Override
public String toString() {
String ret = "";
ret = ret + methodsAndConstraints.stream().reduce("", (x,y) -> x + y.toString(), (x,y) -> x + y);
//ret = ret + "\n";
return ret;
}
}

@ -52,8 +52,4 @@ public class GenericsGeneratorResult {
this.equalsTPHs = equalsTPHs;
}
@Override
public String toString() {
return constraint.toString() + " EqualsTPS: " + equalsTPHs.toString();
}
}

@ -73,12 +73,4 @@ public class GenericsGeneratorResultForClass {
return Collections.emptyList();
}
}
@Override
public String toString() {
String ret = "Classconstraints: ";
ret = ret + classConstraints.stream().reduce("", (x,y) -> x + y.toString(), (x,y) -> x + y);
ret = ret + "\n" + methodsAndTheirConstraints.toString();
return ret;
}
}

@ -33,14 +33,4 @@ public class MethodAndConstraints {
return constraints;
}
@Override
public String toString() {
String ret = methodID + ": ";
ret = ret + constraints.stream().reduce("",
(x,y) -> x + y.toString(),
(x,y) -> x + y);
ret = ret + "\n";
return ret;
}
}

@ -1,7 +1,6 @@
package de.dhbwstuttgart.bytecode.insertGenerics;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
public class ClassConstraint extends TPHConstraint {
//private TPHConstraint constraint;

@ -3,45 +3,28 @@ package de.dhbwstuttgart.bytecode.insertGenerics;
import de.dhbwstuttgart.bytecode.TPHExtractor;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult;
import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH;
import java.util.*;
import java.util.function.Predicate;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.result.ResultPair;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import org.objectweb.asm.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class FamilyOfGeneratedGenerics {
public List<TPHConstraint> allConstraints = new ArrayList<>();
// HashMap speichert ob TPH in einer Methode oder in der Klasse ist; und wenn es in der Methode ist, in welcher Methode
public HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTPHs = new HashMap<>();
public HashMap<String, PairTphMethod<PositionFinder.Position, String>> posOfTPHs = new HashMap<>();
public List<ClassConstraint> classConstraints = new ArrayList<>();
private HashMap<String, MethodAndTPH> mapMethodsAndTph = new HashMap<>();
public List<MethodConstraint> methodConstraints = new ArrayList<>();
public HashMap<String, List<MethodConstraint>> methodConstraintsWithPosition = new HashMap<>();
public ResultSet resSet;
public Set<Pair> oldCons = new HashSet<>();
private static final String objectType = Type.getInternalName(Object.class);
public FamilyOfGeneratedGenerics(TPHExtractor tphExtractor, ResultSet resultSet) {
this.resSet = resultSet;
this.oldCons = tphExtractor.oldConstraints;
public FamilyOfGeneratedGenerics(TPHExtractor tphExtractor) {
this.allConstraints = tphExtractor.allCons;
this.posOfTPHs = positionConverter(tphExtractor.allTPHS, tphExtractor.ListOfMethodsAndTph);
this.classConstraints = getClassConstraints(allConstraints,posOfTPHs);
tphExtractor.ListOfMethodsAndTph.forEach(matph -> this.mapMethodsAndTph.put(matph.getId(), matph));
this.methodConstraints = getMethodConstraints(allConstraints,classConstraints,posOfTPHs, tphExtractor.ListOfMethodsAndTph);
this.methodConstraintsWithPosition = getMethodConstraintsWithPositionNew(allConstraints,classConstraints,posOfTPHs, tphExtractor.ListOfMethodsAndTph, resSet, oldCons);
// this.methodConstraints =
}
public static List<ClassConstraint> getClassConstraints(List<TPHConstraint> cs, HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTphs) { //Inputparameter List<TPHConstraint> constraintsSet weg
public static List<ClassConstraint> getClassConstraints(List<TPHConstraint> cs, HashMap<String, PairTphMethod<PositionFinder.Position, String>> posOfTphs) { //Inputparameter List<TPHConstraint> constraintsSet weg
List<ClassConstraint> cs_cl = new ArrayList<>();
List<ClassConstraint> classConstraints1 = typeOfANodeOfAField(cs, posOfTphs);
for (ClassConstraint cons: classConstraints1) {
@ -49,21 +32,13 @@ public class FamilyOfGeneratedGenerics {
cs_cl.add(cons);
}
}
// if sth new is added to cs_cl, then do same step again
boolean addedToConstraintsListForCC2 = false;
do {
addedToConstraintsListForCC2 = false;
List<ClassConstraint> classConstraints2 = transitiveSubtypeForClassTypes(cs, cs_cl); // in Klammer classConstraints1 oder constraintsSet? beides eher
for (ClassConstraint cons: classConstraints2) {
if (!checkForDuplicates(cons, cs_cl)) {
cs_cl.add(cons);
addedToConstraintsListForCC2 = true;
}
List<ClassConstraint> classConstraints2 = transitiveSubtypeForClassTypes(cs, cs_cl); // in Klammer classConstraints1 oder constraintsSet? beides eher
for (ClassConstraint cons: classConstraints2) {
if (!checkForDuplicates(cons, cs_cl)) {
cs_cl.add(cons);
}
} while (addedToConstraintsListForCC2);
List<ClassConstraint> classConstraints3 = hasNoSupertypeForClassTypes(cs_cl, posOfTphs);
}
List<ClassConstraint> classConstraints3 = hasNoSupertypeForClassTypes(cs, cs_cl, posOfTphs);
for (ClassConstraint cons: classConstraints3) {
if (!checkForDuplicates(cons, cs_cl)) {
cs_cl.add(cons);
@ -72,123 +47,33 @@ public class FamilyOfGeneratedGenerics {
return cs_cl;
}
public List<MethodConstraint> getMethodConstraints(List<TPHConstraint> cs, List<ClassConstraint> cs_cl, HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTphs, List<MethodAndTPH> listOfMethodsAndTph) {
public static List<MethodConstraint> getMethodConstraints(List<TPHConstraint> cs, HashMap<String, PairTphMethod<PositionFinder.Position, String>> posOfTphs) {
//TODO: Regeln
List<MethodConstraint> cs_m = new ArrayList<>();
List<MethodConstraint> methodConstraints1 = typeOfTheMethodInClSigma(cs, posOfTphs);
List<MethodConstraint> methodConstraints1 = typeOfTheMethodInClSigma(cs, cs_m, posOfTphs);
for (MethodConstraint cons: methodConstraints1) {
if (!checkForDuplicates(cons, cs_m)) {
cs_m.add(cons);
}
}
// if sth new is added to cs_cl, then do same step again
boolean addedToConstraintsListForMC2 = false;
do {
addedToConstraintsListForMC2 = false;
List<MethodConstraint> methodConstraints2 = firstTransitiveSubtypeForMethodTypes(cs, cs_m);
for (MethodConstraint cons : methodConstraints2) {
if (!checkForDuplicates(cons, cs_m)) {
cs_m.add(cons);
addedToConstraintsListForMC2 = true;
}
}
} while (addedToConstraintsListForMC2);
// if sth new is added to cs_cl, then do same step again
boolean addedToConstraintsListForMC3 = false;
do {
addedToConstraintsListForMC3 = false;
List<MethodConstraint> methodConstraints3 = secondTransitiveSubtypeForMethodTypes(cs, cs_cl, cs_m);
for (MethodConstraint cons : methodConstraints3) {
if (!checkForDuplicates(cons, cs_m)) {
cs_m.add(cons);
addedToConstraintsListForMC3 = true;
}
}
} while (addedToConstraintsListForMC3);
List<MethodConstraint> methodConstraints4 = hasNoSupertypeForMethodTypes(cs, cs_m, posOfTphs, listOfMethodsAndTph);
for (MethodConstraint cons: methodConstraints4) {
if (!checkForDuplicates(cons, cs_m)) {
cs_m.add(cons);
}
}
List<MethodConstraint> methodConstraints5 = methodTypesWithoutClassTypes(cs_cl, cs_m);
cs_m = methodConstraints5;
//List<MethodConstraint> methodConstraints2 = firstTransitiveSubtypeForMethodTypes();
return cs_m;
}
public HashMap<String, List<MethodConstraint>> getMethodConstraintsWithPosition(List<TPHConstraint> cs, List<ClassConstraint> cs_cl, HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTphs, List<MethodAndTPH> listOfMethodsAndTph, ResultSet resSet, Set<Pair> oldCons) {
HashMap<String, List<MethodConstraint>> tempMethodConstraintsWithPosition = new HashMap<>();
for(MethodAndTPH method: listOfMethodsAndTph){
List<String> methodsAddedToHashMap = new ArrayList<>();
String currentMethod = method.getId();
boolean containsCurrentMethod = false;
if(!containsCurrentMethod) {
methodsAddedToHashMap.add(currentMethod);
containsCurrentMethod = true;
List<MethodConstraint> listOfThisMethod = new ArrayList<>();
HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTPHsForThisMethod = new HashMap<>();
for(String s: posOfTphs.keySet()) {
for(PairTphMethod pair: posOfTphs.get(s)) {
if(pair.snd == currentMethod && pair.snd != null) {
posOfTPHsForThisMethod.put(s,posOfTphs.get(s));
}
}
}
listOfThisMethod = getMethodConstraints(cs,cs_cl,posOfTPHsForThisMethod,listOfMethodsAndTph);
tempMethodConstraintsWithPosition.put(currentMethod, listOfThisMethod);
List<MethodConstraint> newMCList = firstLineMethodDefinition(cs, posOfTphs, method, resSet);
List<MethodConstraint> newMCList2 = secondLineMethodDefinition(cs, posOfTphs, method, resSet, oldCons);
System.out.println(newMCList);
System.out.println(newMCList2);
}
}
for(String curMeth: tempMethodConstraintsWithPosition.keySet()){
for(int i=0; i<tempMethodConstraintsWithPosition.get(curMeth).size(); i++) {
MethodConstraint currentMC = tempMethodConstraintsWithPosition.get(curMeth).get(i);
if(currentMC.getRight()!= objectType && !compareTphsOfConstraints(currentMC.getRight(), cs_cl) && !compareTphsOfConstraints(currentMC.getRight(), tempMethodConstraintsWithPosition.get(curMeth))) {
MethodConstraint mc = new MethodConstraint(currentMC.getRight(), objectType, Relation.EXTENDS);
tempMethodConstraintsWithPosition.get(curMeth).add(mc);
}
}
}
return tempMethodConstraintsWithPosition;
}
// Hilfsmethode um TPHs in den Methoden zu finden, die <. Object sein müssen
private static boolean compareTphsOfConstraints(String tph, List list) {
List<TPHConstraint> tempList = new ArrayList<>(list);
for(TPHConstraint tphC: tempList) {
if(tph == tphC.getLeft()) {
return true;
}
}
return false;
}
/**
* Def. FGG: erste Zeile von cs_cl
* {T < .T' | T is a type variable in a type of a node of a field}
*/
public static List<ClassConstraint> typeOfANodeOfAField(List<TPHConstraint> allConstraints, HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTphs) {
public static List<ClassConstraint> typeOfANodeOfAField(List<TPHConstraint> allConstraints, HashMap<String, PairTphMethod<PositionFinder.Position, String>> posOfTphs) {
//RuntimeException re = new RuntimeException("enthält EQUALS-Relation");
List<ClassConstraint> tempCC = new ArrayList<>();
List<ClassConstraint> tempCC= new ArrayList<>();
for(TPHConstraint allCons: allConstraints){
if(posOfTphs.containsKey(allCons.getLeft()) && allCons.getRight()!=null && allCons.getRel()==Relation.EXTENDS) {
for(String tph: posOfTphs.keySet()) {
for(PairTphMethod pair: posOfTphs.get(tph)) {
if(tph == allCons.getLeft() && pair.fst == PositionFinder.Position.FIELD) {
ClassConstraint consToAdd = new ClassConstraint(tph, allCons.getRight(), allCons.getRel());
if (!checkForDuplicates(consToAdd, tempCC)) {
tempCC.add(consToAdd);
}
/*}else if(pair.fst == PositionFinder.Position.FIELD){
ClassConstraint consToAdd = new ClassConstraint(tph, objectType, Relation.EXTENDS);
if (!checkForDuplicates(consToAdd, tempCC)) {
tempCC.add(consToAdd);
}*/
if(tph == allCons.getLeft() && posOfTphs.get(tph).fst == PositionFinder.Position.FIELD) {
ClassConstraint consToAdd = new ClassConstraint(tph, allCons.getRight(), allCons.getRel());
if (!checkForDuplicates(consToAdd, tempCC)) {
tempCC.add(consToAdd);
}
}
}
@ -205,13 +90,12 @@ public class FamilyOfGeneratedGenerics {
* {T' <. T'' | \exists T: (T <. T') \in cs_cl, (T' <. T'') \in cs }
*/
public static List<ClassConstraint> transitiveSubtypeForClassTypes(List<TPHConstraint> allConstraints, List<ClassConstraint> cs_cl) {
List<ClassConstraint> tempCC = new ArrayList<>();
ClassConstraint consToAdd;
List<ClassConstraint> tempCC= new ArrayList<>();
for(ClassConstraint cCons: cs_cl) {
if(cCons.getLeft() != null && cCons.getRel()==Relation.EXTENDS) {
for(TPHConstraint allCons: allConstraints) {
if(cCons.getRight() == allCons.getLeft() && allCons.getRight() != null && allCons.getRel()==Relation.EXTENDS){
consToAdd = new ClassConstraint(allCons.getLeft(), allCons.getRight(), allCons.getRel());
ClassConstraint consToAdd = new ClassConstraint(allCons.getLeft(), allCons.getRight(), allCons.getRel());
if (!checkForDuplicates(consToAdd, tempCC)) {
tempCC.add(consToAdd);
}
@ -227,108 +111,103 @@ public class FamilyOfGeneratedGenerics {
* {T <. Object | ((T is a type variable in a type of a node of a field
* or (\exists T~: (T~ <. T) \in cs_cl)) and (\existsnot T': T <. T') \in cs)}
*/
public static List<ClassConstraint> hasNoSupertypeForClassTypes(List<ClassConstraint> cs_cl, HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTphs) {
public static List<ClassConstraint> hasNoSupertypeForClassTypes(List<TPHConstraint> allConstraints, List<ClassConstraint> cs_cl, HashMap<String, PairTphMethod<PositionFinder.Position, String>> posOfTphs) {
List<ClassConstraint> tempCC= new ArrayList<>();
List<TPHConstraint> clCons = new ArrayList<>(cs_cl);
for(String tph: posOfTphs.keySet()) {
for(PairTphMethod pair: posOfTphs.get(tph)) {
boolean tvInField = pair.fst == PositionFinder.Position.FIELD;
boolean hasSmallerTVInClCons = hasSmallerTVInClCons(tph, cs_cl);
if ((tvInField || hasSmallerTVInClCons) &&
!checkUpperBound(clCons, tph)) {
ClassConstraint consToAdd = new ClassConstraint(tph, objectType, Relation.EXTENDS);
for(TPHConstraint allCons: allConstraints) {
for(ClassConstraint cCons: cs_cl) {
for(String tph: posOfTphs.keySet()) {
boolean tvInField = posOfTphs.get(tph).fst == PositionFinder.Position.FIELD;
boolean hasSmallerTVInClCons = (posOfTphs.containsKey(cCons.getRight()) && cCons.getRight() == tph && cCons.getLeft() != null);
if( ((tvInField || hasSmallerTVInClCons) && cCons.getRel()==Relation.EXTENDS) &&
checkUpperBound(allConstraints, tph) && allCons.getRel()==Relation.EXTENDS) {
ClassConstraint consToAdd = new ClassConstraint(tph, "Object", Relation.EXTENDS);
if (!checkForDuplicates(consToAdd, tempCC)){
tempCC.add(consToAdd);
}
}
}
}
}
return tempCC;
}
public static boolean checkUpperBound(List<TPHConstraint> cs, String tph) {
for(int i=0; i<cs.size(); i++) {
if(cs.get(i).getLeft() == tph) {
return false;
}
}
return true;
}
/**
* Def. FGG: erste Zeile von cs_m
* {T < .T' | T is a type variable in a type of the method/constructor m in cl_\sigma, (T <. T') \in cs}
*/
public static List<MethodConstraint> typeOfTheMethodInClSigma(List<TPHConstraint> allConstraints, List<MethodConstraint> cs_m, HashMap<String, PairTphMethod<PositionFinder.Position, String>> posOfTphs) { // cl_\sigma??
//TODO:
List<MethodConstraint> tempCC= new ArrayList<>();
for(TPHConstraint allCons: allConstraints){
if(posOfTphs.containsKey(allCons.getLeft()) && allCons.getRight()!=null && allCons.getRel()==Relation.EXTENDS) {
for(String tph: posOfTphs.keySet()) {
if(tph == allCons.getLeft() && (posOfTphs.get(tph).fst == PositionFinder.Position.METHOD || posOfTphs.get(tph).fst == PositionFinder.Position.CONSTRUCTOR)) {
MethodConstraint consToAdd = new MethodConstraint(allCons.getLeft(), allCons.getRight(), allCons.getRel());
if (!checkForDuplicates(consToAdd, tempCC)) {
tempCC.add(consToAdd);
}
}
}
}
}
return tempCC;
}
public static boolean hasSmallerTVInClCons(String tph, List<ClassConstraint> cs_cl) {
for(ClassConstraint cC: cs_cl) {
if(tph == cC.getRight() && cC.getRel() == Relation.EXTENDS) {
return true;
}
}
return false;
}
/**
* Def. FGG: erste Zeile von cs_m
* {T < .T' | T is a type variable in a type of the method/constructor m in cl_\sigma, (T <. T') \in cs}
*/
public static List<MethodConstraint> typeOfTheMethodInClSigma(List<TPHConstraint> allConstraints, HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTphs) { // cl_\sigma??
//TODO:
List<MethodConstraint> tempMC= new ArrayList<>();
for(TPHConstraint allCons: allConstraints){
if(posOfTphs.containsKey(allCons.getLeft()) && allCons.getRight()!=null && allCons.getRel()==Relation.EXTENDS) {
for(String tph: posOfTphs.keySet()) {
for(PairTphMethod pair: posOfTphs.get(tph)) {
if(tph == allCons.getLeft() && (pair.fst == PositionFinder.Position.METHOD || pair.fst == PositionFinder.Position.CONSTRUCTOR)) {
MethodConstraint consToAdd = new MethodConstraint(allCons.getLeft(), allCons.getRight(), allCons.getRel());
if (!checkForDuplicates(consToAdd, tempMC)) {
tempMC.add(consToAdd);
}
}
}
}
}
}
return tempMC;
}
/**
/**
* Def. FGG: zweite Zeile von cs_m
* {R' <. S | (R <. R'), (S <. S') \in cs_m and (R',S) is in the transitive closure of cs}
*/
public List<MethodConstraint> firstTransitiveSubtypeForMethodTypes(List<TPHConstraint> allConstraints, List<MethodConstraint> cs_m) { //transitive closure of cs
public static List<MethodConstraint> firstTransitiveSubtypeForMethodTypes(List<TPHConstraint> allConstraints, List<MethodConstraint> cs_m, HashMap<String, PairTphMethod<PositionFinder.Position, String>> posOfTphs) { //transitive closure of cs
//TODO:
List<MethodConstraint> tempMC= new ArrayList<>();
List<MethodConstraint> tempCC= new ArrayList<>();
List<TPHConstraint> tcOfCs = buildTransitiveClosure(allConstraints);
for(MethodConstraint mC1 : cs_m) { //(R <. R')
for(MethodConstraint mC2 : cs_m) { //(S <. S')
String lSide = mC1.getRight(); //R'
String rSide = mC2.getLeft(); //S
for(MethodConstraint mC1 : cs_m) {
for(MethodConstraint mC2 : cs_m) {
String rightSide = mC1.getRight();
String leftSide = mC2.getLeft();
for(TPHConstraint tphC : tcOfCs) {
if(tphC.getLeft().equals(lSide)&&tphC.getRight().equals(rSide)) { //is it (R',S)
MethodConstraint consToAdd = new MethodConstraint(lSide, rSide, tphC.getRel()); //create (R'<.S)
if (!checkForDuplicates(consToAdd, tempMC)) {
tempMC.add(consToAdd);
}
if(tphC.getLeft().equals(leftSide)&&tphC.getRight().equals(rightSide)) {
tempCC.add((MethodConstraint) tphC);
}
}
}
}
return tempMC;
return tempCC;
}
/**
/**
* Def. FGG: dritte Zeile von cs_m
* {R' <. S | (R <. R') \in cs_m, (S <. S') \in cs_cl and (R',S) is in the transitive closure of cs}
*/
public List<MethodConstraint> secondTransitiveSubtypeForMethodTypes(List<TPHConstraint> allConstraints, List<ClassConstraint> cs_cl, List<MethodConstraint> cs_m) {
public static List<MethodConstraint> secondTransitiveSubtypeForMethodTypes(List<TPHConstraint> allConstraints, List<ClassConstraint> cs_cl, List<MethodConstraint> cs_m, HashMap<String, PairTphMethod<PositionFinder.Position, String>> posOfTphs) {
//TODO:
List<MethodConstraint> tempMC= new ArrayList<>();
List<MethodConstraint> tempCC= new ArrayList<>();
List<TPHConstraint> tcOfCs = buildTransitiveClosure(allConstraints);
for(ClassConstraint cC : cs_cl) {
for(MethodConstraint mC : cs_m) {
String leftSide = mC.getRight();
String rightSide = cC.getLeft();
String rightSide = mC.getRight();
String leftSide = cC.getLeft();
for(TPHConstraint tphC : tcOfCs) {
if(tphC.getLeft().equals(leftSide)&&tphC.getRight().equals(rightSide)) {
MethodConstraint consToAdd = new MethodConstraint(tphC.getLeft(), tphC.getRight(), tphC.getRel());
if (!checkForDuplicates(consToAdd, tempMC)) {
tempMC.add(consToAdd);
}
tempCC.add((MethodConstraint) tphC);
}
}
}
}
return tempMC;
return tempCC;
}
/**
@ -336,73 +215,18 @@ public class FamilyOfGeneratedGenerics {
* {T <. Object | (T is a type variable in a type of a node of the method/constructor m in cl_\sigma),
* (\existsnot T': T <. T') \in cs)}
*/
public static List<MethodConstraint> hasNoSupertypeForMethodTypes(List<TPHConstraint> allConstraints, List<MethodConstraint> cs_m, HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTphs, List<MethodAndTPH> listOfMethodsAndTph) {
public static List<MethodConstraint> hasNoSupertypeForMethodTypes() {
//TODO:
List<MethodConstraint> tempMC= new ArrayList<>();
for(String tph: posOfTphs.keySet()) {
for(PairTphMethod pair: posOfTphs.get(tph)) {
for(TPHConstraint allCons: allConstraints) {
if((pair.fst.equals(PositionFinder.Position.METHOD) || pair.fst.equals(PositionFinder.Position.CONSTRUCTOR)) && !checkUpperBound(allConstraints,tph)) {
MethodConstraint consToAdd = new MethodConstraint(tph, objectType, Relation.EXTENDS);
if (!checkForDuplicates(consToAdd, tempMC)) {
tempMC.add(consToAdd);
}
}
}
List<TPHConstraint> tempMCObject1 = new ArrayList<>(cs_m);
String currentMethod = "";
for(MethodAndTPH mat: listOfMethodsAndTph) {
if(mat.getId().equals(pair.snd)) {
currentMethod = mat.getId();
}
for(TPHConstraint mc1: tempMCObject1) {
if(tph==mc1.getRight() && !checkUpperBound(tempMCObject1,tph)) {
MethodConstraint consToAdd = new MethodConstraint(tph, objectType, Relation.EXTENDS);
if (!checkForDuplicates(consToAdd, tempMC)) {
tempMC.add(consToAdd);
}
}
}
}
}
}
return tempMC;
return null;
}
/**
* nimm die Menge cs_cl aus cs_m raus
*/
public List<MethodConstraint> methodTypesWithoutClassTypes(List<ClassConstraint> cs_cl, List<MethodConstraint> cs_m) {
// erstelle Kopie der Liste cs_cl
List<TPHConstraint> tempCC = new ArrayList<>();
for(ClassConstraint cc: cs_cl) {
TPHConstraint tphC = new TPHConstraint(cc.getLeft(), cc.getRight(), cc.getRel());
tempCC.add(tphC);
}
// Transitive Hülle von cs_cl
List<TPHConstraint> tcOfCsCl = buildTransitiveClosure(tempCC);
List<TPHConstraint> tempMC = new ArrayList<>();
for(MethodConstraint mc: cs_m) {
TPHConstraint tphC = new TPHConstraint(mc.getLeft(), mc.getRight(), mc.getRel());
tempMC.add(tphC);
}
List<TPHConstraint> tempMC2 = new ArrayList<>();
tempMC2.addAll(tempMC);
List<MethodConstraint> tempMCToReturn = new ArrayList<>();
for(TPHConstraint cc: tcOfCsCl) {
for(TPHConstraint mc: tempMC) {
if(cc.getLeft().equals(mc.getLeft()) && cc.getRight().equals(mc.getRight())) {
tempMC2.remove(mc);
}
}
}
for(TPHConstraint tphC: tempMC2) {
MethodConstraint mCons = new MethodConstraint(tphC.getLeft(), tphC.getRight(), tphC.getRel());
tempMCToReturn.add(mCons);
}
return tempMCToReturn;
public static List<MethodConstraint> methodTypesWithoutClassTypes() {
//TODO:
return null;
}
public static boolean checkForDuplicates(TPHConstraint constraint, List list) {
@ -418,7 +242,7 @@ public class FamilyOfGeneratedGenerics {
return false;
}
public List<TPHConstraint> buildTransitiveClosure(List list) {
public static List<TPHConstraint> buildTransitiveClosure(List list) {
List<TPHConstraint> iterList = new ArrayList<>(list);
List<TPHConstraint> runList = new ArrayList<>(list);
List<TPHConstraint> tcList = new ArrayList<>(list);
@ -440,31 +264,19 @@ public class FamilyOfGeneratedGenerics {
return tcList;
}
public static boolean checkUpperBound(List<TPHConstraint> cs, String tph) {
for(int i=0; i<cs.size(); i++) {
if(cs.get(i).getLeft() == tph) {
//has upper bound
return true;
}
}
return false;
}
public static HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> positionConverter(HashMap<String, Boolean> allTphs, List<MethodAndTPH> listOfMethodsAndTphs) {
HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> convertedPositions = new HashMap<>();
public static HashMap<String, PairTphMethod<PositionFinder.Position, String>> positionConverter(HashMap<String, Boolean> allTphs, List<MethodAndTPH> listOfMethodsAndTphs) {
HashMap<String, PairTphMethod<PositionFinder.Position, String>> convertedPositions = new HashMap<>();
for(String tph: allTphs.keySet()) {
List<PairTphMethod<PositionFinder.Position, String>> currMeth = new ArrayList<>();
if(allTphs.get(tph)) { //if true, then tph is a method-TPH
for(MethodAndTPH methTph: listOfMethodsAndTphs) {
if (methTph.getTphs().contains(tph)) {
currMeth.add(new PairTphMethod<>(PositionFinder.Position.METHOD, methTph.getId()));
convertedPositions.put(tph, new PairTphMethod<>(PositionFinder.Position.METHOD, methTph.getId()));
}
}
} else { // else it is in the class-TPH
currMeth.add(new PairTphMethod<>(PositionFinder.Position.FIELD, null));
convertedPositions.put(tph, new PairTphMethod<>(PositionFinder.Position.FIELD, null));
}
convertedPositions.put(tph, currMeth);
}
return convertedPositions;
}
@ -488,393 +300,4 @@ public class FamilyOfGeneratedGenerics {
}
*/
public static List<MethodConstraint> firstLineMethodDefinition(List<TPHConstraint> allConstraints, HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTphs, MethodAndTPH methodAndTPH, ResultSet resSet) {
List<MethodConstraint> tempMC= new ArrayList<>();
MethodAndTPH methAndTphs = methodAndTPH;
Set<Pair> undCons = methAndTphs.constraints.getUndConstraints();
List<Set<Constraint<Pair>>> orCons = methAndTphs.constraints.getOderConstraints();
Iterator<Pair> it = undCons.iterator();
while(it.hasNext()) {
Pair p = it.next();
String ta1 = ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA1)).resolvedType)).getName();
String ta2 = ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA2)).resolvedType)).getName();
Relation r = null;
if(p.GetOperator() == PairOperator.SMALLERDOT) {
r = Relation.EXTENDS;
} else if(p.GetOperator() == PairOperator.EQUALSDOT) {
r = Relation.EQUAL;
}
MethodConstraint mc = new MethodConstraint(ta1, ta2, r);
if(mc.getRel() == Relation.EXTENDS) {
if (!mc.getLeft().equals(mc.getRight())) { //eliminieren der Fälle wie AA<.AA
if(!checkForDuplicates(mc, tempMC)) {
tempMC.add(mc);
}
}
}
}
return tempMC;
}
public List<MethodConstraint> secondLineMethodDefinition(List<TPHConstraint> allConstraints, HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTphs, MethodAndTPH methodAndTPH, ResultSet resSet, Set<Pair> oldCons) {
List<MethodConstraint> tempMC = new ArrayList<>(); //für Ergebnisse basierend auf der neuen Datenstruktur (Ali)
Set<Pair> tempSet = new HashSet<>(); //für Ergebnisse des ersten Teils der Bedinung basierend auf der alten Datenstruktur
Set<Pair> tempSet2 = new HashSet<>(); //für Ergebnisse des zweiten Teils der Bedingung basierend auf der alten Datenstruktur
Set<Pair> tcOfoldConsSet = buildTransitiveClosureForCP(oldCons, resSet);
List<TPHConstraint> tcOfCs = buildTransitiveClosure(allConstraints);
MethodAndTPH methAndTphs = methodAndTPH;
Set<Pair> undCons = methAndTphs.constraints.getUndConstraints();
List<Set<Constraint<Pair>>> orCons = methAndTphs.constraints.getOderConstraints();
List<HashMap<Relation, List<TPHConstraint>>> orConsListConverted = new ArrayList<>();
//gehe die OrConstraints der aktuellen Methode durch und teile nach Operator auf (
for(int i=0; i<orCons.size(); i++) {
List<TPHConstraint> orConsWithEQUAL = new ArrayList();
List<TPHConstraint> orConsWithEXTENDS = new ArrayList();
HashMap<Relation, List<TPHConstraint>> orConsInternal = new HashMap<>();
for(Constraint con: orCons.get(i)) {
Iterator<Pair> it = con.iterator();
while(it.hasNext()) {
Pair p = it.next();
Relation r = null;
if(p.GetOperator() == PairOperator.SMALLERDOT) {
r = Relation.EXTENDS;
orConsWithEXTENDS.add(new TPHConstraint(((TypePlaceholder) p.TA1).getName(), ((TypePlaceholder) p.TA2).getName(), r));
/*MethodConstraint mc = new MethodConstraint(((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA1)).resolvedType)).getName(), ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA2)).resolvedType)).getName(), r);
if(!checkForDuplicates(mc, tempMC)) {
tempMC.add(mc);
}*/
} else if(p.GetOperator() == PairOperator.EQUALSDOT) {
r = Relation.EQUAL;
orConsWithEQUAL.add(new TPHConstraint(((TypePlaceholder) p.TA1).getName(), ((TypePlaceholder) p.TA2).getName(), r));
/*MethodConstraint mc = new MethodConstraint(((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA1)).resolvedType)).getName(), ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA2)).resolvedType)).getName(), r);
if(!checkForDuplicates(mc, tempMC)) {
tempMC.add(mc);
}*/
}
}
}
orConsInternal.put(Relation.EXTENDS, orConsWithEXTENDS);
orConsInternal.put(Relation.EQUAL, orConsWithEQUAL);
orConsListConverted.add(orConsInternal);
}
// oldCons sind alle Und- und Oder-Constraints
// zunächst in meine Datenstruktur(Ali) konvertieren
List<Pair> oldConsList = new ArrayList<>(oldCons);
List<TPHConstraint> oldConsListConverted = new ArrayList<>();
for(Pair pair: oldConsList) {
Relation r = null;
if(pair.GetOperator() == PairOperator.SMALLERDOT) {
r = Relation.EXTENDS;
} else if(pair.GetOperator() == PairOperator.EQUALSDOT) {
r = Relation.EQUAL;
}
oldConsListConverted.add(new TPHConstraint(((TypePlaceholder) pair.TA1).getName(), ((TypePlaceholder) pair.TA2).getName(), r));
}
// Berechnung des zweiten Teils der Bedingung der Regel
for(int i=0; i<orCons.size(); i++) {
Constraint<Pair> extendsSet = new Constraint<Pair>();
Constraint<Pair> equalSet = new Constraint<Pair>();
//für jede einzelne OrConstraint-Menge gehe durch
for (Constraint con : orCons.get(i)) {
Iterator<Pair> it = con.iterator();
while (it.hasNext()) {
Pair p = it.next();
if (p.OperatorSmallerDot()) {
extendsSet.add(p);
} else if (p.OperatorEqual()) {
equalSet.add(p);
}
}
Iterator<Pair> itExtends2 = extendsSet.iterator();
while(itExtends2.hasNext()) {
Pair pairExtends2 = itExtends2.next();
Set<String> containedVars = new HashSet<>(methodAndTPH.getTphs());
String pairExtends2RHSName = ((TypePlaceholder)((resSet.resolveType((TypePlaceholder)pairExtends2.TA2)).resolvedType)).getName();
Iterator<Pair> itEqual2 = equalSet.iterator();
while (itEqual2.hasNext()) {
boolean transClo = false;
Pair pairEqual2 = itEqual2.next();
//TODO: Auf trans.FamilyOfGeneratedGenerics Huelle pruefen
Pair newPairOld = new Pair(pairExtends2.TA2, pairEqual2.TA1);
Pair newPair2 = new Pair(resSet.resolveType((TypePlaceholder) (pairExtends2.TA2)).resolvedType, resSet.resolveType((TypePlaceholder) (pairEqual2.TA1)).resolvedType, PairOperator.SMALLERDOT);
TPHConstraint newPairTPHConstraint = new TPHConstraint(newPair2);
if (tcOfCs.contains(newPairTPHConstraint)|| (newPairTPHConstraint.getLeft().equals(newPairTPHConstraint.getRight()))) {
transClo = true;
}
TypePlaceholder tphR = (TypePlaceholder) pairEqual2.TA2;
Iterator<Pair> itUndCons = undCons.iterator();
boolean rEqExRtilde = false;
while (itUndCons.hasNext()) {
Pair pairUndCons2 = itUndCons.next();
rEqExRtilde = rEqExRtilde || (tphR == pairUndCons2.TA1);
}
boolean isPairInTExTapostrophe = false;
for(Set<Constraint<Pair>> scp: orCons) {
Iterator<Constraint<Pair>> itSCP = scp.iterator();
while(itSCP.hasNext()) {
Constraint<Pair> cp = itSCP.next();
Iterator<Pair> itCP = cp.iterator();
while(itCP.hasNext()) {
Pair p = itCP.next();
if(p.OperatorSmallerDot()) {
isPairInTExTapostrophe = isPairInTExTapostrophe || tphR.equals(p.TA1);
}
}
}
}
if (transClo && (rEqExRtilde || isPairInTExTapostrophe)) {
if (!newPair2.TA1.equals(newPair2.TA2)) { //eliminieren der Fälle wie AA<.AA
if (!checkForDuplicatesForSets(newPair2, tempSet2)) {
tempSet2.add(newPair2);
}
}
if (!checkForDuplicatesForSets(pairExtends2, tempSet2)) {
tempSet2.add(pairExtends2);
}
}
else {
//containedVars.remove(((TypePlaceholder)newPair2.TA2).getName());
}
}
//String key = ((TypePlaceholder)((resSet.resolveType((TypePlaceholder)pairExtends2.TA2)).resolvedType)).getName();
//TODO: containedVars stimmt noch nicht. Ueberpruefen, ob ggf. mit den containedVars möglicherweise auch die anderen Faelle
// rEqExRtilde isPairInTExTapostrophe abgedeckt sind => ggf. integrieren
/*
posOfTphs.forEach((x,y) -> {
if (y.contains(new PairTphMethod<>(PositionFinder.Position.METHOD, methodAndTPH.getId()))) {
containedVars.add(x);
};
}
);
*/
//Referenzbeispiel Put.jav
if (containedVars.stream().filter(v -> tcOfCs.contains(new TPHConstraint(pairExtends2RHSName, v, Relation.EXTENDS)))
.count() > 0) {
System.out.println();
//tempSet2.add(pairExtends2);
}
if (posOfTphs.containsKey(pairExtends2RHSName)) {//Refrenzbeispiel TestVector.jav
if (posOfTphs.get(pairExtends2RHSName).contains(new PairTphMethod<>(PositionFinder.Position.METHOD, methodAndTPH.getId()))) {
tempSet2.add(pairExtends2);
}
}
}
}
}
// aus der alten Datenstruktur in die neue Datenstruktur (von Ali) für ersten Teil
Iterator<Pair> itTemp = tempSet.iterator();
while(itTemp.hasNext()) {
Pair p = itTemp.next();
String ta1 = ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA1)).resolvedType)).getName();
String ta2 = ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA2)).resolvedType)).getName();
Relation r = null;
if(p.GetOperator() == PairOperator.SMALLERDOT) {
r = Relation.EXTENDS;
} else if(p.GetOperator() == PairOperator.EQUALSDOT) {
r = Relation.EQUAL;
}
MethodConstraint mc = new MethodConstraint(ta1, ta2, r);
if(mc.getRel() == Relation.EXTENDS) {
if(!checkForDuplicates(mc, tempMC)) {
tempMC.add(mc);
}
}
}
// aus der alten Datenstruktur in die neue Datenstruktur (von Ali) für zweiten Teil
Iterator<Pair> itTemp2 = tempSet2.iterator();
while(itTemp2.hasNext()) {
Pair p = itTemp2.next();
String ta1 = ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA1)).resolvedType)).getName();
String ta2 = ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA2)).resolvedType)).getName();
Relation r = null;
if (p.GetOperator() == PairOperator.SMALLERDOT) {
r = Relation.EXTENDS;
} else if (p.GetOperator() == PairOperator.EQUALSDOT) {
r = Relation.EQUAL;
}
for(TPHConstraint tphCons: tcOfCs) {//TODO: hier werden Elemente der Trans. clo herausgenommen, aber die dazugehoerigen OrCons nicht.
if(ta1 == tphCons.getLeft() && ta2 == tphCons.getRight() && r==Relation.EXTENDS) {
MethodConstraint mc = new MethodConstraint(ta1, ta2, r);
if(!checkForDuplicates(mc, tempMC)) {
tempMC.add(mc);
}
}
}
}
return tempMC;
}
public static Set<Pair> buildTransitiveClosureForCP(Set constraint, ResultSet resSet) {
Set<Pair> iterSet = new HashSet<>(constraint);
Set<Pair> runSet = new HashSet<>(constraint);
Set<Pair> tcSet = new HashSet<>(constraint);
boolean addedConToList = false;
// for (TPHConstraint cons: iterList) {
Iterator<Pair> itIterSet = iterSet.iterator();
while(itIterSet.hasNext()) {
Pair pairIterSet = itIterSet.next();
// for (TPHConstraint cons2: runList) {
Iterator<Pair> itRunSet = runSet.iterator();
while (itRunSet.hasNext()) {
Pair pairRunSet = itRunSet.next();
// if(cons.getRight() == cons2.getLeft()) {
if(pairIterSet.TA2 == pairRunSet.TA1 && pairIterSet.OperatorSmallerDot() && pairRunSet.OperatorSmallerDot()) {
// TPHConstraint consToAdd = new TPHConstraint(cons.getLeft(), cons2.getRight(), Relation.EXTENDS);
Pair p = new Pair(resSet.resolveType((TypePlaceholder)(pairIterSet.TA1)).resolvedType, resSet.resolveType((TypePlaceholder)(pairRunSet.TA2)).resolvedType, PairOperator.SMALLERDOT);
// if (!checkForDuplicates(consToAdd,tcList)) {
if(!checkForDuplicatesForSets(p, tcSet)) {
// tcList.add(consToAdd);
tcSet.add(p);
addedConToList = true;
if (addedConToList) {
return buildTransitiveClosureForCP(tcSet, resSet);
}
}
}
}
}
System.out.println("tcSet: " + tcSet);
return tcSet;
}
public static boolean checkForDuplicatesForSets(Pair pair, Set set) {
Set<Pair> tempSet = set;
boolean hasSame = false;
// for (TPHConstraint tphC: tempList) {
Iterator<Pair> it = tempSet.iterator();
while (it.hasNext()) {
Pair p = it.next();
// hasSame = constraint.getLeft() == tphC.getLeft() &&
// constraint.getRight() == tphC.getRight() &&
// constraint.getRel() == tphC.getRel(); //constraint already in ArrayList if true
hasSame = pair.TA1 == p.TA1 &&
pair.TA2 == p.TA2 &&
pair.OperatorSmallerDot() && p.OperatorSmallerDot(); //constraint already in Set if true
if (hasSame)
return true;
}
return false;
}
public static List<MethodConstraint> hasNoSupertypeForMethodTypesNew(HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTphs, MethodAndTPH methodAndTPH, List<MethodConstraint> cs_m) {
List<MethodConstraint> tempMC = new ArrayList<>();
List<TPHConstraint> methCons = new ArrayList<>(cs_m);
MethodAndTPH methAndTphs = methodAndTPH;
for(String tph: posOfTphs.keySet()) {
for(int i=0; i<posOfTphs.get(tph).size(); i++)
if(posOfTphs.get(tph).get(i).fst == PositionFinder.Position.METHOD && posOfTphs.get(tph).get(i).snd == methAndTphs.getId() && !checkUpperBound(methCons,tph)) {
MethodConstraint mc2 = new MethodConstraint(tph, objectType, Relation.EXTENDS);
if (!checkForDuplicates(mc2, tempMC)) {
tempMC.add(mc2);
}
}
}
return tempMC;
}
public static List<MethodConstraint> methodTypesWithoutClassTypesNEW(List<String> tphsToCompute, List<MethodConstraint> cs_m) {
List<MethodConstraint> tempMC = new ArrayList<>(cs_m);
List<MethodConstraint> tempMC2 = new ArrayList<>(cs_m);
List<String> toRemove = new ArrayList<>();
for(String tph: tphsToCompute) {
for(TPHConstraint tphCons: tempMC) {
if(tphCons.getLeft() == tph) {
toRemove.add(tphCons.getRight());
tempMC2.remove(tphCons);
tempMC2 = methodTypesWithoutClassTypesNEW(toRemove,tempMC2);
}
}
}
return tempMC2;
}
public HashMap<String, List<MethodConstraint>> getMethodConstraintsWithPositionNew(List<TPHConstraint> cs, List<ClassConstraint> cs_cl, HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTphs, List<MethodAndTPH> listOfMethodsAndTph, ResultSet resSet, Set<Pair> oldCons) {
HashMap<String, List<MethodConstraint>> tempMethodConstraintsWithPosition = new HashMap<>();
List<MethodConstraint> newMCList = new ArrayList<>();
List<MethodConstraint> newMCList2 = new ArrayList<>();
List<MethodConstraint> hasNoSupType = new ArrayList<>();
List<MethodConstraint> mcWithoutCc = new ArrayList<>();
List<String> methodsAddedToHashMap = new ArrayList<>();
for(MethodAndTPH method: listOfMethodsAndTph){
String currentMethod = method.getId();
boolean containsCurrentMethod = false;
if(!containsCurrentMethod) {
methodsAddedToHashMap.add(currentMethod);
containsCurrentMethod = true;
List<MethodConstraint> listToAdd = new ArrayList<>();
HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> posOfTPHsForThisMethod = new HashMap<>();
for(String s: posOfTphs.keySet()) {
for(PairTphMethod pair: posOfTphs.get(s)) {
if(pair.snd == currentMethod && pair.snd != null) {
posOfTPHsForThisMethod.put(s,posOfTphs.get(s));
}
}
}
newMCList = firstLineMethodDefinition(cs, posOfTphs, method, resSet);
for(int i=0; i<newMCList.size(); i++) {
listToAdd.add(newMCList.get(i));
}
newMCList2 = secondLineMethodDefinition(cs, posOfTphs, method, resSet, oldCons);
for(int i=0; i<newMCList2.size(); i++) {
listToAdd.add(newMCList2.get(i));
}
/*if(!methodsAddedToHashMap.contains(currentMethod)) {
tempMethodConstraintsWithPosition.put(currentMethod, newMCList);
tempMethodConstraintsWithPosition.put(currentMethod, newMCList2);
}*/
hasNoSupType = hasNoSupertypeForMethodTypesNew(posOfTphs,method,listToAdd);
for (MethodConstraint cons: hasNoSupType) {
if (!checkForDuplicates(cons, listToAdd)) {
listToAdd.add(cons);
}
}
mcWithoutCc = listToAdd;
List<String> tphs = new ArrayList<>();
for(String tph: posOfTphs.keySet()) {
for (PairTphMethod p : posOfTphs.get(tph)) {
if(p.fst == PositionFinder.Position.FIELD) {
tphs.add(tph);
mcWithoutCc = methodTypesWithoutClassTypesNEW(tphs, listToAdd);
}
}
}
tempMethodConstraintsWithPosition.put(currentMethod, mcWithoutCc);
}
for(String curMeth: tempMethodConstraintsWithPosition.keySet()){
for(int i=0; i<tempMethodConstraintsWithPosition.get(curMeth).size(); i++) {
MethodConstraint currentMC = tempMethodConstraintsWithPosition.get(curMeth).get(i);
if(currentMC.getRight()!= objectType && !compareTphsOfConstraints(currentMC.getRight(), cs_cl) && !compareTphsOfConstraints(currentMC.getRight(), tempMethodConstraintsWithPosition.get(curMeth))) {
MethodConstraint mc = new MethodConstraint(currentMC.getRight(), objectType, Relation.EXTENDS);
tempMethodConstraintsWithPosition.get(curMeth).add(mc);
}
}
}
}
return tempMethodConstraintsWithPosition;
}
}

@ -1,7 +1,6 @@
package de.dhbwstuttgart.bytecode.insertGenerics;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
public class MethodConstraint extends TPHConstraint {
public MethodConstraint(String left, String right, Relation rel) {

@ -1,47 +0,0 @@
package de.dhbwstuttgart.bytecode.insertGenerics;
import java.util.Objects;
/** A generic class for pairs.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class PairMethodAndConstraint<A, B> {
public final A fst;
public final B snd;
public PairMethodAndConstraint(A fst, B snd) {
this.fst = fst;
this.snd = snd;
}
public String toString() {
return "PairTphMethod[" + fst + "," + snd + "]";
}
public boolean equals(Object other) {
return
other instanceof PairMethodAndConstraint<?,?> &&
Objects.equals(fst, ((PairMethodAndConstraint<?,?>)other).fst) &&
Objects.equals(snd, ((PairMethodAndConstraint<?,?>)other).snd);
}
public int hashCode() {
if (fst == null) return (snd == null) ? 0 : snd.hashCode() + 1;
else if (snd == null) return fst.hashCode() + 2;
else return fst.hashCode() * 17 + snd.hashCode();
}
public static <A,B> PairMethodAndConstraint<A,B> of(A a, B b) {
return new PairMethodAndConstraint<>(a,b);
}
public PairMethodAndConstraint add(A fst, B snd){
return new PairMethodAndConstraint<>(fst,snd);
}
}

@ -5,8 +5,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import de.dhbwstuttgart.bytecode.funN.FunNGenerator;
import de.dhbwstuttgart.bytecode.funN.FunNUtilities;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
@ -19,29 +17,18 @@ import de.dhbwstuttgart.syntaxtree.type.TypeVisitor;
public class TypeToSignature implements TypeVisitor<String> {
private List<GenericsGeneratorResult> constraints;
private final boolean specializedFunN;
public TypeToSignature() { this(new ArrayList<>(), true); }
public TypeToSignature(boolean specializedFunN) { this(new ArrayList<>(), specializedFunN); }
public TypeToSignature(List<GenericsGeneratorResult> constraints) {
this(constraints, true);
public TypeToSignature() {
this.constraints = new ArrayList<>();
}
public TypeToSignature(List<GenericsGeneratorResult> constraints, boolean specializedFunN){
public TypeToSignature(List<GenericsGeneratorResult> constraints) {
this.constraints = constraints;
this.specializedFunN = specializedFunN;
}
@Override
public String visit(RefType refType) {
if(refType.getName().toString().equals("void"))
return "V";
if (refType.getName().toString().matches("Fun\\d+\\$\\$") && specializedFunN){
FunNUtilities funNUtilities = FunNGenerator.getInstance();
return funNUtilities.getSpecializedSignature(funNUtilities.getArguments(refType.getParaList()), funNUtilities.getReturnType(refType.getParaList()));
}
// return refType.toString().replace(".", "/");
String params = "";
if(refType.getParaList().size()>0){
@ -102,20 +89,9 @@ public class TypeToSignature implements TypeVisitor<String> {
return sig;
}
/**
* Changed that the correct signature is returned:
* returns now T...; expect of only ...
* where ... is {@code genericRefType.getParsedName()}
*
* @since Studienarbeit Type Erasure
* @author etiennezink
*
* @param genericRefType
* @return
*/
@Override
public String visit(GenericRefType genericRefType) {
return String.format("T%s;", genericRefType.getParsedName()).replace(".", "/");
return genericRefType.getParsedName().replace(".", "/");
}
private Optional<GenericsGeneratorResult> getEqualTPHFromClassConstraints(List<GenericsGeneratorResult> listOfConstraints, String tph) {

@ -4,8 +4,6 @@ import java.util.ArrayList;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.result.GenericInsertPair;
import de.dhbwstuttgart.typeinference.result.ResultPair;
@ -17,21 +15,11 @@ public class MethodAndTPH {
private final ArrayList<ResultPair<TypePlaceholder, TypePlaceholder>> pairs = new ArrayList<>();
// tphs of local variables and parameters
private final ArrayList<String> localTphs = new ArrayList<>();
/*
* its Constraints
* eingefuegt PL 2021-02-15
*/
public final ConstraintSet constraints;
public MethodAndTPH(String name, ConstraintSet<Pair> constraints) {
public MethodAndTPH(String name) {
this.id = name;
this.constraints = constraints;
}
public void addTph(String tph) {
tphs.add(tph);
}
public ArrayList<String> getTphs() {
return tphs;
}
@ -51,9 +39,4 @@ public class MethodAndTPH {
return localTphs;
}
@Override
public String toString() {
return id;
}
}

@ -25,8 +25,4 @@ public class Resolver {
public String getResolvedType(RefTypeOrTPHOrWildcardOrGeneric type) {
return resultSet.resolveType(type).resolvedType.acceptTV(new TypeToDescriptor());
}
public RefTypeOrTPHOrWildcardOrGeneric resolve(RefTypeOrTPHOrWildcardOrGeneric type) {
return resultSet.resolveType(type).resolvedType;
}
}

@ -6,7 +6,6 @@ import de.dhbwstuttgart.bytecode.BytecodeGen;
import de.dhbwstuttgart.bytecode.Exception.BytecodeGeneratorError;
import de.dhbwstuttgart.bytecode.genericsGenerator.GeneratedGenericsFinder;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics;
import de.dhbwstuttgart.environment.CompilationEnvironment;
import de.dhbwstuttgart.environment.DirectoryClassLoader;
import de.dhbwstuttgart.exceptions.DebugException;
@ -21,12 +20,10 @@ import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.ParameterList;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.TypeScope;
import de.dhbwstuttgart.syntaxtree.FormalParameter;
import de.dhbwstuttgart.syntaxtree.GenericDeclarationList;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory;
import de.dhbwstuttgart.syntaxtree.statement.Block;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
@ -49,26 +46,16 @@ import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
import de.dhbwstuttgart.typeinference.unify.UnifyResultListener;
import de.dhbwstuttgart.typeinference.unify.UnifyResultListenerImpl;
import de.dhbwstuttgart.typeinference.unify.UnifyResultModel;
import de.dhbwstuttgart.typeinference.unify.UnifyTaskModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.antlr.v4.runtime.Token;
import org.apache.commons.io.output.NullOutputStream;
public class JavaTXCompiler {
@ -77,14 +64,8 @@ public class JavaTXCompiler {
Boolean resultmodel = true;
public final Map<File, SourceFile> sourceFiles = new HashMap<>();
Boolean log = true; //gibt an ob ein Log-File nach System.getProperty("user.dir")+"src/test/java/logFiles" geschrieben werden soll?
public volatile UnifyTaskModel usedTasks = new UnifyTaskModel();
private final ClassLoader classLoader;
//nur fuer Testzwecke of Generated Generics
//wieder loeschen PL 2021-03-22
public FamilyOfGeneratedGenerics fogg;
public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException {
this(Arrays.asList(sourceFile), null);
}
@ -200,7 +181,7 @@ public class JavaTXCompiler {
public List<ClassOrInterface> getAvailableClasses(SourceFile forSourceFile) throws ClassNotFoundException {
//PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal hinzugefuegt werden
//PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal hinzugefuegt werden
//List<ClassOrInterface> allClasses = new ArrayList<>();//environment.getAllAvailableClasses();
Set<ClassOrInterface> allClasses = new HashSet<>();
@ -235,321 +216,6 @@ public class JavaTXCompiler {
return new ArrayList<>(allClasses);
}
/*
* public List<ResultSet> typeInferenceOld() throws ClassNotFoundException {
* List<ClassOrInterface> allClasses = new
* ArrayList<>();//environment.getAllAvailableClasses(); //Alle Importierten
* Klassen in allen geparsten Sourcefiles kommen ins FC for(SourceFile sf :
* this.sourceFiles.values()) { allClasses.addAll(getAvailableClasses(sf));
* allClasses.addAll(sf.getClasses()); }
*
* final ConstraintSet<Pair> cons = getConstraints();
*
* FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses);
* System.out.println(finiteClosure); ConstraintSet<UnifyPair> unifyCons =
* UnifyTypeFactory.convert(cons);
*
* TypeUnify unify = new TypeUnify(); Set<Set<UnifyPair>> results = new
* HashSet<>(); try { File logPath = new
* File(System.getProperty("user.dir")+"/target/logFiles/"); logPath.mkdirs();
* FileWriter logFile = new FileWriter(new File(logPath, "log"));
* logFile.write("FC:\\" + finiteClosure.toString()+"\n"); for(SourceFile sf :
* this.sourceFiles.values()) { logFile.write(ASTTypePrinter.print(sf)); }
* logFile.flush(); Set<List<Constraint<UnifyPair>>> cardProd =
* unifyCons.cartesianProduct(); for (List<Constraint<UnifyPair>> xCons :
* cardProd ){ Set<UnifyPair> xConsSet = new HashSet<>(); for
* (Constraint<UnifyPair> constraint : xCons) { xConsSet.addAll(constraint); }
* //.collect(Collectors.toCollection(ArrayList::new))))
* System.out.println(xConsSet); Set<String> methodParaTypeVarNames =
* allClasses.stream().map(x -> x.getMethods().stream().map(y ->
* y.getParameterList().getFormalparalist() .stream().filter(z -> z.getType()
* instanceof TypePlaceholder) .map(z ->
* ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(
* HashSet::new))) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return
* a;}, (a,b) -> { a.addAll(b); return a;} ) ) .reduce(new HashSet<String>(),
* (a,b) -> { a.addAll(b); return a;} );
*
* Set<String> constructorParaTypeVarNames = allClasses.stream().map(x ->
* x.getConstructors().stream().map(y ->
* y.getParameterList().getFormalparalist() .stream().filter(z -> z.getType()
* instanceof TypePlaceholder) .map(z ->
* ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(
* HashSet::new))) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return
* a;}, (a,b) -> { a.addAll(b); return a;} ) ) .reduce(new HashSet<String>(),
* (a,b) -> { a.addAll(b); return a;} );
*
* Set<String> paraTypeVarNames = methodParaTypeVarNames;
* paraTypeVarNames.addAll(constructorParaTypeVarNames);
*
* Set<String> returnTypeVarNames = allClasses.stream().map(x ->
* x.getMethods().stream().filter(y -> y.getReturnType() instanceof
* TypePlaceholder) .map(z ->
* ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.
* toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;}
* ).get();
*
* Set<String> fieldTypeVarNames = allClasses.stream().map(x ->
* x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof
* TypePlaceholder) .map(z ->
* ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.
* toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;}
* ).get();
*
* returnTypeVarNames.addAll(fieldTypeVarNames);
*
* xConsSet = xConsSet.stream().map(x -> { //Hier muss ueberlegt werden, ob //1.
* alle Argument- und Retuntyp-Variablen in allen UnifyPairs // mit
* disableWildcardtable() werden. //2. alle Typvariablen mit Argument- oder
* Retuntyp-Variablen //in Beziehung auch auf disableWildcardtable() gesetzt
* werden muessen //PL 2018-04-23 if ((x.getLhsType() instanceof
* PlaceholderType)) { if (paraTypeVarNames.contains(x.getLhsType().getName()))
* { ((PlaceholderType)x.getLhsType()).setVariance((byte)1);
* ((PlaceholderType)x.getLhsType()).disableWildcardtable(); } if
* (returnTypeVarNames.contains(x.getLhsType().getName())) {
* ((PlaceholderType)x.getLhsType()).setVariance((byte)-1);
* ((PlaceholderType)x.getLhsType()).disableWildcardtable(); } } if
* ((x.getRhsType() instanceof PlaceholderType)) { if
* (paraTypeVarNames.contains(x.getRhsType().getName())) {
* ((PlaceholderType)x.getRhsType()).setVariance((byte)1);
* ((PlaceholderType)x.getRhsType()).disableWildcardtable(); } if
* (returnTypeVarNames.contains(x.getRhsType().getName())) {
* ((PlaceholderType)x.getRhsType()).setVariance((byte)-1);
* ((PlaceholderType)x.getRhsType()).disableWildcardtable(); } } return x;//HIER
* DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS
* ANDERE SEITE }).map( y -> { if ((y.getLhsType() instanceof PlaceholderType)
* && (y.getRhsType() instanceof PlaceholderType)) { if
* (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
* ((PlaceholderType)y.getRhsType()).getVariance() == 0) {
* ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType(
* )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0
* && ((PlaceholderType)y.getRhsType()).getVariance() != 0) {
* ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType(
* )).getVariance()); } } return y; } )
* .collect(Collectors.toCollection(HashSet::new));
* varianceInheritance(xConsSet); Set<Set<UnifyPair>> result =
* unify.unifySequential(xConsSet, finiteClosure, logFile, log);
* //Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
* System.out.println("RESULT: " + result); logFile.write("RES: " +
* result.toString()+"\n"); logFile.flush(); results.addAll(result); }
*
* results = results.stream().map(x -> { Optional<Set<UnifyPair>> res = new
* RuleSet().subst(x.stream().map(y -> { if (y.getPairOp() ==
* PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT); return y;
* //alle Paare a <.? b erden durch a =. b ersetzt
* }).collect(Collectors.toCollection(HashSet::new))); if (res.isPresent())
* {//wenn subst ein Erg liefert wurde was veraendert return new
* TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure); } else
* return x; //wenn nichts veraendert wurde wird x zurueckgegeben
* }).collect(Collectors.toCollection(HashSet::new));
* System.out.println("RESULT Final: " + results); logFile.write("RES_FINAL: " +
* results.toString()+"\n"); logFile.flush(); logFile.write("PLACEHOLDERS: " +
* PlaceholderType.EXISTING_PLACEHOLDERS); logFile.flush(); } catch (IOException
* e) { e.printStackTrace(); } return results.stream().map((unifyPairs -> new
* ResultSet(UnifyTypeFactory.convert(unifyPairs,
* generateTPHMap(cons))))).collect(Collectors.toList()); }
*/
/**
* Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine
* Variance !=0 hat auf alle Typvariablen in Theta.
*
*
*/
/*
* private void varianceInheritance(Set<UnifyPair> eq) { Set<PlaceholderType>
* usedTPH = new HashSet<>(); Set<PlaceholderType> phSet = eq.stream().map(x ->
* { Set<PlaceholderType> pair = new HashSet<>(); if (x.getLhsType() instanceof
* PlaceholderType) pair.add((PlaceholderType)x.getLhsType()); if
* (x.getRhsType() instanceof PlaceholderType)
* pair.add((PlaceholderType)x.getRhsType()); return pair; }).reduce(new
* HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d);
* return c;});
*
* ArrayList<PlaceholderType> phSetVariance = new ArrayList<>(phSet);
* phSetVariance.removeIf(x -> (x.getVariance() == 0));
* while(!phSetVariance.isEmpty()) { PlaceholderType a =
* phSetVariance.remove(0); usedTPH.add(a); //HashMap<PlaceholderType,Integer>
* ht = new HashMap<>(); //ht.put(a, a.getVariance()); Set<UnifyPair> eq1 = new
* HashSet<>(eq); eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType
* && ((PlaceholderType)x.getLhsType()).equals(a))); eq1.stream().forEach(x -> {
* x.getRhsType().accept(new distributeVariance(), a.getVariance());}); eq1 =
* new HashSet<>(eq); eq1.removeIf(x -> !(x.getRhsType() instanceof
* PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a)));
* eq1.stream().forEach(x -> { x.getLhsType().accept(new distributeVariance(),
* a.getVariance());}); phSetVariance = new ArrayList<>(phSet);
* phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x))); }
* }
*/
public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile)
throws ClassNotFoundException, IOException {
List<ClassOrInterface> allClasses = new ArrayList<>();// environment.getAllAvailableClasses();
// Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC
for (File f : this.sourceFiles.keySet()) {
SourceFile sf = sourceFiles.get(f);
allClasses.addAll(getAvailableClasses(sf));
allClasses.addAll(sf.getClasses());
allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(f,classLoader).stream().map(ASTFactory::createClass).collect(Collectors.toList()));
}
final ConstraintSet<Pair> cons = getConstraints();
Set<Set<UnifyPair>> results = new HashSet<>();
UnifyResultModel urm = null;
// urm.addUnifyResultListener(resultListener);
try {
logFile = logFile == null
? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName()))
: logFile;
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader);
System.out.println(finiteClosure);
urm = new UnifyResultModel(cons, finiteClosure);
urm.addUnifyResultListener(resultListener);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons);
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
UnifyType lhs, rhs;
if (((lhs = x.getLhsType()) instanceof PlaceholderType)
&& ((rhs = x.getRhsType()) instanceof PlaceholderType)
&& (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
((PlaceholderType) lhs).setInnerType(true);
((PlaceholderType) rhs).setInnerType(true);
}
return x;
};
logFile.write(unifyCons.toString());
unifyCons = unifyCons.map(distributeInnerVars);
logFile.write(unifyCons.toString());
TypeUnify unify = new TypeUnify();
// Set<Set<UnifyPair>> results = new HashSet<>(); Nach vorne gezogen
logFile.write("FC:\\" + finiteClosure.toString() + "\n");
for (SourceFile sf : this.sourceFiles.values()) {
logFile.write(ASTTypePrinter.print(sf));
}
logFile.flush();
Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream()
.map(y -> y.getParameterList().getFormalparalist().stream()
.filter(z -> z.getType() instanceof TypePlaceholder)
.map(z -> ((TypePlaceholder) z.getType()).getName())
.collect(Collectors.toCollection(HashSet::new)))
.reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
}, (a, b) -> {
a.addAll(b);
return a;
})).reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
});
Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream()
.map(y -> y.getParameterList().getFormalparalist().stream()
.filter(z -> z.getType() instanceof TypePlaceholder)
.map(z -> ((TypePlaceholder) z.getType()).getName())
.collect(Collectors.toCollection(HashSet::new)))
.reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
}, (a, b) -> {
a.addAll(b);
return a;
})).reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
});
Set<String> paraTypeVarNames = methodParaTypeVarNames;
paraTypeVarNames.addAll(constructorParaTypeVarNames);
Set<String> returnTypeVarNames = allClasses.stream()
.map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
.map(z -> ((TypePlaceholder) z.getReturnType()).getName())
.collect(Collectors.toCollection(HashSet::new)))
.reduce((a, b) -> {
a.addAll(b);
return a;
}).get();
Set<String> fieldTypeVarNames = allClasses.stream()
.map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
.map(z -> ((TypePlaceholder) z.getReturnType()).getName())
.collect(Collectors.toCollection(HashSet::new)))
.reduce((a, b) -> {
a.addAll(b);
return a;
}).get();
returnTypeVarNames.addAll(fieldTypeVarNames);
unifyCons = unifyCons.map(x -> {
// Hier muss ueberlegt werden, ob
// 1. alle Argument- und Retuntyp-Variablen in allen UnifyPairs
// mit disableWildcardtable() werden.
// 2. alle Typvariablen mit Argument- oder Retuntyp-Variablen
// in Beziehung auch auf disableWildcardtable() gesetzt werden muessen
// PL 2018-04-23
if ((x.getLhsType() instanceof PlaceholderType)) {
if (paraTypeVarNames.contains(x.getLhsType().getName())) {
((PlaceholderType) x.getLhsType()).setVariance((byte) 1);
((PlaceholderType) x.getLhsType()).disableWildcardtable();
}
if (returnTypeVarNames.contains(x.getLhsType().getName())) {
((PlaceholderType) x.getLhsType()).setVariance((byte) -1);
((PlaceholderType) x.getLhsType()).disableWildcardtable();
}
}
if ((x.getRhsType() instanceof PlaceholderType)) {
if (paraTypeVarNames.contains(x.getRhsType().getName())) {
((PlaceholderType) x.getRhsType()).setVariance((byte) 1);
((PlaceholderType) x.getRhsType()).disableWildcardtable();
}
if (returnTypeVarNames.contains(x.getRhsType().getName())) {
((PlaceholderType) x.getRhsType()).setVariance((byte) -1);
((PlaceholderType) x.getRhsType()).disableWildcardtable();
}
}
return x;// HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE
// JEWEILS ANDERE SEITE
});
Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons);
/*
* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL
* 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen
* //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH);
* varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y
* -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType()
* instanceof PlaceholderType)) { if
* (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
* ((PlaceholderType)y.getRhsType()).getVariance() == 0) {
* ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType(
* )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0
* && ((PlaceholderType)y.getRhsType()).getVariance() != 0) {
* ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType(
* )).getVariance()); } } return y; } ); } while
* (!varianceTPHold.equals(varianceTPH));
*/
// Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure,
// logFile, log);
// Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()/*.stream().map(x -> {
Set<Set<UnifyPair>> ret = new HashSet<>();
for (Constraint<UnifyPair> y : x) {
ret.add(new HashSet<>(y));
}
return ret;
}).collect(Collectors.toCollection(ArrayList::new))*/;
unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm,
usedTasks);
} catch (IOException e) {
System.err.println("kein LogFile");
}
return urm;
}
public List<ResultSet> typeInference() throws ClassNotFoundException, IOException {
List<ClassOrInterface> allClasses = new ArrayList<>();// environment.getAllAvailableClasses();
@ -698,46 +364,12 @@ public class JavaTXCompiler {
}
})));
*/
System.out.println("Unify nach Oder-Constraints-Anpassung:" + unifyCons.toString());
Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons);
/*
* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL
* 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen
* //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH);
* varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y
* -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType()
* instanceof PlaceholderType)) { if
* (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
* ((PlaceholderType)y.getRhsType()).getVariance() == 0) {
* ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType(
* )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0
* && ((PlaceholderType)y.getRhsType()).getVariance() != 0) {
* ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType(
* )).getVariance()); } } return y; } ); } while
* (!varianceTPHold.equals(varianceTPH));
*/
// Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure,
// logFile, log);
// Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()//.stream().map(x -> {
/*Set<Set<UnifyPair>> ret = new HashSet<>();
for (Constraint<UnifyPair> y : x) {
ret.add(new HashSet<>(y));
}
return ret;
}).collect(Collectors.toCollection(ArrayList::new))*/;
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints();
if (resultmodel) {
/* UnifyResultModel Anfang */
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
UnifyResultListenerImpl li = new UnifyResultListenerImpl();
urm.addUnifyResultListener(li);
unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm,
usedTasks);
unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm);
System.out.println("RESULT Final: " + li.getResults());
logFile.write("RES_FINAL: " + li.getResults().toString() + "\n");
logFile.flush();
@ -749,7 +381,7 @@ public class JavaTXCompiler {
// oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons,
// finiteClosure));
Set<Set<UnifyPair>> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints,
finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks);
finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure));
System.out.println("RESULT: " + result);
logFile.write("RES: " + result.toString() + "\n");
logFile.flush();
@ -878,7 +510,6 @@ public class JavaTXCompiler {
SourceFile sf = sourceFiles.get(f);
GeneratedGenericsFinder sResFinder = new GeneratedGenericsFinder(sf, typeinferenceResult);
GenericGenratorResultForSourceFile simplifyResOfSF = sResFinder.findGeneratedGenerics();
this.fogg = sResFinder.getFogg();
result.add(simplifyResOfSF);
}
return result;
@ -901,6 +532,10 @@ public class JavaTXCompiler {
/**
* @param path - can be null, then class file output is in the same directory as the parsed source files
*/
List<ResultSet> typeinferenceResult = this.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = getGeneratedGenericResultsForAllSourceFiles(
typeinferenceResult);
generateBytecode(path, typeinferenceResult, simplifyResultsForAllSourceFiles);
public void generateBytecode(File path) throws ClassNotFoundException, IOException, BytecodeGeneratorError {
List<ResultSet> typeinferenceResult = this.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = getGeneratedGenericResultsForAllSourceFiles(

@ -216,7 +216,6 @@ public class StatementGenerator {
MethodCall ret = new MethodCall(TypePlaceholder.fresh(methodInvocationContext.getStart()),
getReceiver(receiver), name, argumentList, TypePlaceholder.fresh(methodInvocationContext.getStart()),
argTypes, methodInvocationContext.getStart());
ret.setStatement();
return ret;
}
@ -272,10 +271,8 @@ public class StatementGenerator {
whole+=".";
}
if(parts.length < 2 || parts[0].contentEquals("this") ){
if(parts.length < 2){
receiver = new This(offset);
} else if (parts[0].contentEquals("super")) {
receiver = new Super(offset);
}else if(receiver == null){ //Handelt es sich um keinen Statischen Klassennamen:
String part = expression.substring(0,expression.length() - (1 + parts[parts.length-1].length()));
receiver = generateLocalOrFieldVarOrClassName(part, offset);
@ -305,45 +302,33 @@ public class StatementGenerator {
ArrayList<RefTypeOrTPHOrWildcardOrGeneric> argTypes = args.getArguments().stream()
.map(x -> TypePlaceholder.fresh(newExpression.getStart()))
.collect(Collectors.toCollection(ArrayList::new));
Statement ret = new NewClass(newClass, args, null, argTypes, newExpression.getStart());
ret.setStatement();
return ret;
return new NewClass(newClass, args, null, argTypes, newExpression.getStart());
}
private Statement convert(Java8Parser.PreIncrementExpressionContext stmt) {
Expression argument = convert(stmt.unaryExpression());
Token offset = stmt.getStart();
Statement ret = new UnaryExpr(UnaryExpr.Operation.PREINCREMENT, argument, TypePlaceholder.fresh(offset), offset);
ret.setStatement();
return ret;
}
return new UnaryExpr(UnaryExpr.Operation.PREINCREMENT, argument, TypePlaceholder.fresh(offset), offset);
}
private Statement convert(Java8Parser.PreDecrementExpressionContext stmt) {
Statement ret = new UnaryExpr(UnaryExpr.Operation.PREDECREMENT, convert(stmt.unaryExpression()),
return new UnaryExpr(UnaryExpr.Operation.PREDECREMENT, convert(stmt.unaryExpression()),
TypePlaceholder.fresh(stmt.getStart()), stmt.getStart());
ret.setStatement();
return ret;
}
private Statement convert(Java8Parser.PostIncrementExpressionContext stmt) {
Statement ret = new UnaryExpr(UnaryExpr.Operation.POSTINCREMENT, convert(stmt.postfixExpression()),
return new UnaryExpr(UnaryExpr.Operation.POSTINCREMENT, convert(stmt.postfixExpression()),
TypePlaceholder.fresh(stmt.getStart()), stmt.getStart());
ret.setStatement();
return ret;
}
private Statement convert(Java8Parser.PostDecrementExpressionContext stmt) {
Statement ret = new UnaryExpr(UnaryExpr.Operation.POSTDECREMENT, convert(stmt.postfixExpression()),
return new UnaryExpr(UnaryExpr.Operation.POSTDECREMENT, convert(stmt.postfixExpression()),
TypePlaceholder.fresh(stmt.getStart()), stmt.getStart());
ret.setStatement();
return ret;
}
private Statement convert(Java8Parser.AssignmentContext stmt) {
AssignLeftSide leftHandSide = convert(stmt.leftHandSide());
Statement ret = new Assign(leftHandSide, convert(stmt.expression()), stmt.getStart());
ret.setStatement();
return ret;
return new Assign(leftHandSide, convert(stmt.expression()), stmt.getStart());
}
private AssignLeftSide convert(Java8Parser.LeftHandSideContext leftHandSide) {

@ -126,7 +126,6 @@ public abstract class AbstractASTWalker implements ASTVisitor{
public void visit(Assign assign) {
assign.lefSide.accept(this);
assign.rightSide.accept(this);
assign.rightSide.getType().accept((ASTVisitor) this);
}
@Override
@ -187,10 +186,8 @@ public abstract class AbstractASTWalker implements ASTVisitor{
public void visit(MethodCall methodCall) {
methodCall.receiver.accept(this);
methodCall.getArgumentList().accept(this);
methodCall.getArgumentList().getArguments().forEach(a -> a.getType().accept((ASTVisitor) this));
}
@Override
public void visit(NewClass methodCall) {
visit((MethodCall) methodCall);
@ -214,7 +211,6 @@ public abstract class AbstractASTWalker implements ASTVisitor{
@Override
public void visit(Return aReturn) {
aReturn.retexpr.accept(this);
aReturn.getType().accept((ASTVisitor) this);
}
@Override

@ -31,14 +31,8 @@ public class Method extends SyntaxTreeNode implements IItemWithOffset, TypeScope
private ExceptionList exceptionlist;
private GenericDeclarationList generics;
private final RefTypeOrTPHOrWildcardOrGeneric returnType;
public final Boolean isInherited;
/*
* its Constraints
* eingefuegt PL 2021-02-15
*/
public final ConstraintSet constraints = new ConstraintSet();
public final Boolean isInherited;
public Method(int modifier, String name, RefTypeOrTPHOrWildcardOrGeneric returnType, ParameterList parameterList, Block block,
GenericDeclarationList gtvDeclarations, Token offset) {
super(offset);
@ -76,10 +70,6 @@ public class Method extends SyntaxTreeNode implements IItemWithOffset, TypeScope
return this.returnType;
}
public ConstraintSet getConstraints() {
return this.constraints;
}
@Override
public void accept(ASTVisitor visitor) {
visitor.visit(this);

@ -45,12 +45,6 @@ public class SourceFile extends SyntaxTreeNode{
public List<ClassOrInterface> getClasses() {
return KlassenVektor;
}
public List<Method> getAllMethods() {
List<Method> ret = new ArrayList<>();
getClasses().forEach(cl -> ret.addAll(cl.getMethods()));
return ret;
}
@Override
public void accept(ASTVisitor visitor) {

@ -36,7 +36,7 @@ public class ASTFactory {
List<Method> methoden = new ArrayList<>();
List<de.dhbwstuttgart.syntaxtree.Constructor> konstruktoren = new ArrayList<>();
for(java.lang.reflect.Constructor constructor : jreClass.getConstructors()){
createConstructor(constructor, jreClass).map(c -> konstruktoren.add(c));
konstruktoren.add(createConstructor(constructor, jreClass));
}
Set<java.lang.reflect.Method> allMethods = new HashSet<>(Arrays.asList(jreClass.getMethods()));
Set<java.lang.reflect.Method> allDeclaredMethods = new HashSet<>(Arrays.asList(jreClass.getDeclaredMethods()));
@ -87,7 +87,7 @@ public class ASTFactory {
// return createClass(classType).getType();
//}
private static Optional<de.dhbwstuttgart.syntaxtree.Constructor> createConstructor(Constructor constructor, Class inClass) {
private static de.dhbwstuttgart.syntaxtree.Constructor createConstructor(Constructor constructor, Class inClass) {
String name = constructor.getName();
RefTypeOrTPHOrWildcardOrGeneric returnType = createType(inClass);
Parameter[] jreParams = constructor.getParameters();
@ -106,10 +106,10 @@ public class ASTFactory {
int modifier = constructor.getModifiers();
if(inClass.equals(java.lang.Object.class)){
return Optional.empty();
return null;
}
return Optional.of(new de.dhbwstuttgart.syntaxtree.Constructor(modifier, name,returnType, parameterList, block, gtvDeclarations, offset /*, new ArrayList<>() geloescht PL 2018-11-24 */));
return new de.dhbwstuttgart.syntaxtree.Constructor(modifier, name,returnType, parameterList, block, gtvDeclarations, offset /*, new ArrayList<>() geloescht PL 2018-11-24 */);
}
public static Method createMethod(java.lang.reflect.Method jreMethod, java.lang.Class inClass, Boolean isInherited){

@ -4,16 +4,6 @@ public class NameGenerator {
private static String strNextName = "A";
/**
* Setzt den zu Beginn der Typinferenz auf "A" zurueck.
* Dies ist bei JUnit-Test noetig
* <code>TypePlaceholder</code>. <br>Author: Martin Pluemicke
* @return void
*/
public static void reset() {
strNextName = "A";
}
/**
* Berechnet einen neuen, eindeutigen Namen f�r eine neue
* <code>TypePlaceholder</code>. <br>Author: J�rg B�uerle

@ -18,7 +18,6 @@ import de.dhbwstuttgart.syntaxtree.type.WildcardType;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.result.PairNoResult;
import de.dhbwstuttgart.typeinference.result.PairTPHEqualTPH;
import de.dhbwstuttgart.typeinference.result.PairTPHequalRefTypeOrWildcardType;
import de.dhbwstuttgart.typeinference.result.PairTPHsmallerTPH;
@ -209,7 +208,6 @@ public class UnifyTypeFactory {
}
public static ResultPair convert(UnifyPair mp, Map<String,TypePlaceholder> tphs) {
if (mp == null) { return null;} //kann bei basePairs passieren
RefTypeOrTPHOrWildcardOrGeneric tl = UnifyTypeFactory.convert(mp.getLhsType(), tphs);
RefTypeOrTPHOrWildcardOrGeneric tr = UnifyTypeFactory.convert(mp.getRhsType(), tphs);
if(tl instanceof TypePlaceholder){
@ -220,7 +218,7 @@ public class UnifyTypeFactory {
//Einfach ignorieren TODO: Das hier muss ausgebessert werden:
//return new PairTPHequalRefTypeOrWildcardType((TypePlaceholder)tl, ASTFactory.createObjectType());
}else{
return new PairTPHsmallerTPH((TypePlaceholder)tl, (TypePlaceholder)tr, convert(mp.getBasePair(), tphs));
return new PairTPHsmallerTPH((TypePlaceholder)tl, (TypePlaceholder)tr);
}
}else if(tr instanceof RefType){
return new PairTPHequalRefTypeOrWildcardType((TypePlaceholder)tl, (RefType) tr);
@ -229,7 +227,7 @@ public class UnifyTypeFactory {
}else if(tr instanceof GenericRefType){
return new PairTPHequalRefTypeOrWildcardType((TypePlaceholder)tl, (GenericRefType) tr);
}else throw new NotImplementedException();
}else return new PairNoResult(tl, tr);//throw new NotImplementedException();
}else throw new NotImplementedException();
}
public static RefTypeOrTPHOrWildcardOrGeneric convert(ReferenceType t, Map<String,TypePlaceholder> tphs) {
@ -260,7 +258,6 @@ public class UnifyTypeFactory {
ret = TypePlaceholder.fresh(new NullToken());
tphs.put(t.getName(), ret);
}
ret.setVariance(t.getVariance());
return ret;
}

@ -24,9 +24,13 @@ public class MethodCall extends Statement
public final ArgumentList arglist;
/*
* noetig fuer Bytecodegenerierung
*/
public RefTypeOrTPHOrWildcardOrGeneric receiverType;
public final ArrayList<RefTypeOrTPHOrWildcardOrGeneric> argTypes;
public MethodCall(RefTypeOrTPHOrWildcardOrGeneric retType, Receiver receiver, String methodName, ArgumentList argumentList,
RefTypeOrTPHOrWildcardOrGeneric receiverType, ArrayList<RefTypeOrTPHOrWildcardOrGeneric> argTypes, Token offset){
super(retType,offset);
@ -36,7 +40,6 @@ public class MethodCall extends Statement
this.receiverType = receiverType;
this.argTypes = argTypes;
}
@Override
public void accept(StatementVisitor visitor) {

@ -6,20 +6,11 @@ import org.antlr.v4.runtime.Token;
public abstract class Statement extends Expression
{
/* zeigt an, dass eine StatementExpression als Statement benutzt wird
*/
private boolean isStatement = false;
public Statement(RefTypeOrTPHOrWildcardOrGeneric type, Token offset)
{
super(type, offset);
}
public void setStatement() {
isStatement=true;
}
public boolean getStatement() {
return isStatement;
}
}

@ -53,10 +53,4 @@ public class ExtendsWildcardType extends WildcardType{
public void accept(ResultSetVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
return false;
}
}

@ -4,8 +4,6 @@ import de.dhbwstuttgart.syntaxtree.ASTVisitor;
import de.dhbwstuttgart.typeinference.result.ResultSetVisitor;
import org.antlr.v4.runtime.Token;
import java.util.Objects;
public class GenericRefType extends RefTypeOrTPHOrWildcardOrGeneric
{
private String name;
@ -34,26 +32,5 @@ public class GenericRefType extends RefTypeOrTPHOrWildcardOrGeneric
public void accept(ResultSetVisitor visitor) {
visitor.visit(this);
}
/**
* @since Studienarbeit Type Erasure
* @author etiennezink
*
* @param o
* @return
*/
@Override
public boolean equals(Object o) {
if((! (o instanceof GenericRefType))) return false;
GenericRefType genericRefType = (GenericRefType) o;
return getParsedName().equals(genericRefType.getParsedName()) &&
Objects.equals(getOffset(), genericRefType.getOffset());
}
@Override
public String toString()
{
return "GTV " + this.name;
}
}

@ -77,8 +77,8 @@ public class RefType extends RefTypeOrTPHOrWildcardOrGeneric
if(obj instanceof RefType){
boolean ret = true;
//if(!(super.equals(obj))) PL 2020-03-12 muss vll. einkommentiert werden
// return false;
if(!super.equals(obj))
return false;
if(parameter==null || parameter.size()==0){
ret &= (((RefType)obj).getParaList()==null || ((RefType)obj).getParaList().size()==0);

@ -16,7 +16,4 @@ public abstract class RefTypeOrTPHOrWildcardOrGeneric extends SyntaxTreeNode{
public abstract <A> A acceptTV(TypeVisitor<A> visitor);
public abstract void accept(ResultSetVisitor visitor);
@Override
public abstract boolean equals(Object o);
}

@ -64,10 +64,4 @@ public class SuperWildcardType extends WildcardType{
public void accept(ResultSetVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
return false;
}
}

@ -20,9 +20,10 @@ public class TypePlaceholder extends RefTypeOrTPHOrWildcardOrGeneric
private final String name;
/**
* wird im Generate Generics Teil nach der Rueckumwandlung nach dem Unify genutzt
* wird bisher nicht genutzt
* setVariance muss ggf. auskommentiert werden.
*/
private int variance = 0;
int variance = 0;
/**
@ -77,9 +78,11 @@ public class TypePlaceholder extends RefTypeOrTPHOrWildcardOrGeneric
return name;
}
/* wird bisher nicht genutzt
public void setVariance(int variance) {
this.variance= variance;
}
*/
public int getVariance() {
return this.variance;

@ -1,78 +0,0 @@
package de.dhbwstuttgart.target.generate;
import de.dhbwstuttgart.syntaxtree.ASTVisitor;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.Field;
import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.statement.Block;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.target.tree.*;
import de.dhbwstuttgart.target.tree.expression.TargetBlock;
import de.dhbwstuttgart.target.tree.type.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ASTToTargetAST {
public TargetClass convert(ClassOrInterface input, Map<TypePlaceholder, TargetType> sigma){
List<TargetConstructor> targetConstructors = new ArrayList<>();
//TODO constructor conversion -> also reduce syntactic sugar
return new TargetClass(input.getModifiers(),input.getClassName().toString(), null,
sigma.get(input.getSuperClass()),
input.getSuperInterfaces().stream().map(it -> sigma.get(it)).collect(Collectors.toList()),
targetConstructors,
input.getFieldDecl().stream().map(it -> convert(it, sigma)).collect(Collectors.toList()),
input.getMethods().stream().map(it -> convert(it, sigma)).collect(Collectors.toList()));
}
private TargetMethod convert(Method input, Map<TypePlaceholder, TargetType> sigma) {
List<MethodParameter> params = input.getParameterList().getFormalparalist().stream()
.map(param -> new MethodParameter(convert(param.getType(), sigma), param.getName())).collect(Collectors.toList());
return new TargetMethod(input.name, params, convert(input.block));
}
private TargetBlock convert(Block block) {
return new TargetBlock(block.statements.stream().map(e -> {
StatementToTargetExpression converter = new StatementToTargetExpression();
e.accept(converter);
return converter.result;
}).collect(Collectors.toList()));
}
private TargetField convert(Field input, Map<TypePlaceholder, TargetType> sigma) {
return new TargetField(convert(input.getType(), sigma), input.getName());
}
private TargetType convert(RefTypeOrTPHOrWildcardOrGeneric input, Map<TypePlaceholder, TargetType> sigma) {
return input.acceptTV(new TypeVisitor<>() {
@Override
public TargetType visit(RefType refType) {
return new TargetRefType(refType.getName().toString(),
refType.getParaList().stream().map((it) -> convert(it, sigma)).collect(Collectors.toList()));
}
@Override
public TargetType visit(SuperWildcardType superWildcardType) {
return new TargetSuperWildcard(convert(superWildcardType.getInnerType(), sigma));
}
@Override
public TargetType visit(TypePlaceholder typePlaceholder) {
return sigma.get(typePlaceholder);
}
@Override
public TargetType visit(ExtendsWildcardType extendsWildcardType) {
return new TargetExtendsWildcard(convert(extendsWildcardType.getInnerType(), sigma));
}
@Override
public TargetType visit(GenericRefType genericRefType) {
return new TargetGenericType(genericRefType.getParsedName());
}
});
}
}

@ -1,156 +0,0 @@
package de.dhbwstuttgart.target.generate;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
import de.dhbwstuttgart.syntaxtree.ASTVisitor;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.statement.*;
import de.dhbwstuttgart.target.tree.expression.TargetExpression;
public class StatementToTargetExpression implements StatementVisitor {
public TargetExpression result;
@Override
public void visit(ArgumentList argumentList) {
}
@Override
public void visit(LambdaExpression lambdaExpression) {
}
@Override
public void visit(Assign assign) {
}
@Override
public void visit(BinaryExpr binary) {
}
@Override
public void visit(Block block) {
}
@Override
public void visit(CastExpr castExpr) {
}
@Override
public void visit(EmptyStmt emptyStmt) {
}
@Override
public void visit(FieldVar fieldVar) {
}
@Override
public void visit(ForStmt forStmt) {
}
@Override
public void visit(IfStmt ifStmt) {
}
@Override
public void visit(InstanceOf instanceOf) {
}
@Override
public void visit(LocalVar localVar) {
}
@Override
public void visit(LocalVarDecl localVarDecl) {
}
@Override
public void visit(MethodCall methodCall) {
}
@Override
public void visit(NewClass methodCall) {
}
@Override
public void visit(NewArray newArray) {
}
@Override
public void visit(Return aReturn) {
}
@Override
public void visit(ReturnVoid aReturn) {
}
@Override
public void visit(StaticClassName staticClassName) {
}
@Override
public void visit(Super aSuper) {
}
@Override
public void visit(This aThis) {
}
@Override
public void visit(WhileStmt whileStmt) {
}
@Override
public void visit(DoStmt whileStmt) {
}
@Override
public void visit(AssignToField assignLeftSide) {
}
@Override
public void visit(AssignToLocal assignLeftSide) {
}
@Override
public void visit(SuperCall superCall) {
}
@Override
public void visit(ExpressionReceiver expressionReceiver) {
}
@Override
public void visit(UnaryExpr unaryExpr) {
}
@Override
public void visit(Literal literal) {
}
}

@ -1,7 +0,0 @@
package de.dhbwstuttgart.target.tree;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.target.tree.type.TargetType;
public record GenericDeclaration(GenericRefType generic, TargetType bound) {
}

@ -1,6 +0,0 @@
package de.dhbwstuttgart.target.tree;
import de.dhbwstuttgart.target.tree.type.TargetType;
public record MethodParameter(TargetType type, String name) {
}

@ -1,11 +0,0 @@
package de.dhbwstuttgart.target.tree;
import de.dhbwstuttgart.target.tree.type.TargetRefType;
import de.dhbwstuttgart.target.tree.type.TargetType;
import java.util.List;
public record TargetClass(int modifiers, String qualifiedName, List<GenericDeclaration> generics, TargetType superType,
List<TargetType> implementingInterfaces,
List<TargetConstructor> constructors, List<TargetField> fields, List<TargetMethod> methods) {}

@ -1,9 +0,0 @@
package de.dhbwstuttgart.target.tree;
import de.dhbwstuttgart.target.tree.expression.TargetBlock;
import java.util.List;
public record TargetConstructor(List<MethodParameter> parameterTypes, TargetBlock block) {
}

@ -1,7 +0,0 @@
package de.dhbwstuttgart.target.tree;
import de.dhbwstuttgart.target.tree.type.TargetType;
public record TargetField(TargetType type, String name) {
}

@ -1,9 +0,0 @@
package de.dhbwstuttgart.target.tree;
import de.dhbwstuttgart.target.tree.expression.TargetBlock;
import java.util.List;
public record TargetMethod(String name, List<MethodParameter> parameterTypes, TargetBlock block) {
}

@ -1,4 +0,0 @@
package de.dhbwstuttgart.target.tree.expression;
public record TargetAssign(TargetExpression leftSide, TargetExpression rightSide) implements TargetExpression {
}

@ -1,6 +0,0 @@
package de.dhbwstuttgart.target.tree.expression;
import java.util.List;
public record TargetBlock(List<TargetExpression> statememts) implements TargetExpression {
}

@ -1,7 +0,0 @@
package de.dhbwstuttgart.target.tree.expression;
import de.dhbwstuttgart.target.tree.type.*;
public sealed interface TargetExpression
permits TargetBlock, TargetLambdaExpression, TargetReturn, TargetThis, TargetSuper, TargetNew, TargetAssign {
}

@ -1,8 +0,0 @@
package de.dhbwstuttgart.target.tree.expression;
import de.dhbwstuttgart.target.tree.MethodParameter;
import java.util.List;
public record TargetLambdaExpression(List<MethodParameter> params, TargetExpression block) implements TargetExpression {
}

@ -1,8 +0,0 @@
package de.dhbwstuttgart.target.tree.expression;
import de.dhbwstuttgart.target.tree.type.TargetType;
import java.util.List;
public record TargetNew(TargetType instantiatedType, List<TargetExpression> params) implements TargetExpression {
}

@ -1,4 +0,0 @@
package de.dhbwstuttgart.target.tree.expression;
public record TargetReturn(TargetExpression expression) implements TargetExpression {
}

@ -1,4 +0,0 @@
package de.dhbwstuttgart.target.tree.expression;
public record TargetSuper() implements TargetExpression {
}

@ -1,4 +0,0 @@
package de.dhbwstuttgart.target.tree.expression;
public record TargetThis() implements TargetExpression {
}

@ -1,5 +0,0 @@
package de.dhbwstuttgart.target.tree.type;
public record TargetExtendsWildcard(TargetType innerType) implements TargetType{
}

@ -1,6 +0,0 @@
package de.dhbwstuttgart.target.tree.type;
import java.util.List;
public record TargetFunNType(int N, List<TargetRefType> params) implements TargetType {
}

@ -1,4 +0,0 @@
package de.dhbwstuttgart.target.tree.type;
public record TargetGenericType(String name) implements TargetType {
}

@ -1,8 +0,0 @@
package de.dhbwstuttgart.target.tree.type;
import de.dhbwstuttgart.target.tree.type.TargetType;
import java.util.List;
public record TargetRefType(String name, List<TargetType> params) implements TargetType {
}

@ -1,4 +0,0 @@
package de.dhbwstuttgart.target.tree.type;
public record TargetSuperWildcard(TargetType innerType) implements TargetType {
}

@ -1,5 +0,0 @@
package de.dhbwstuttgart.target.tree.type;
public sealed interface TargetType
permits TargetExtendsWildcard, TargetFunNType, TargetGenericType, TargetRefType, TargetSuperWildcard {
}

@ -9,12 +9,6 @@ import java.util.Set;
public class Constraint<A> extends HashSet<A> {
private static final long serialVersionUID = 1L;
private Boolean isInherited = false;//wird nur für die Method-Constraints benoetigt
/* es darf kein Constraint für den Return-Type erstellt werden, sonst gibt
* es Probleme beim Generated Generics
*/
public boolean isStatement = false;
private Constraint<A> extendConstraint = null;
public Constraint() {
@ -47,7 +41,7 @@ public class Constraint<A> extends HashSet<A> {
}
public String toString() {
return super.toString() + "\nisInherited = " + isInherited + "\nisStatement = " + isStatement
return super.toString() + " isInherited = " + isInherited
//" + extendsContraint: " + (extendConstraint != null ? extendConstraint.toStringBase() : "null" )
+ "\n" ;
}

@ -23,17 +23,9 @@ public class ConstraintSet<A> {
oderConstraints.add(methodConstraints);
}
public void addAllUndConstraint(Constraint<A> allUndConstraints){
undConstraints.addAll(allUndConstraints);
}
public void addAllOderConstraint(List<Set<Constraint<A>>> allOderConstraints){
this.oderConstraints.addAll(allOderConstraints);
}
public void addAll(ConstraintSet constraints) {
this.addAllUndConstraint(constraints.undConstraints);
this.addAllOderConstraint(constraints.oderConstraints);
this.undConstraints.addAll(constraints.undConstraints);
this.oderConstraints.addAll(constraints.oderConstraints);
}
@Override

@ -1,32 +0,0 @@
package de.dhbwstuttgart.typeinference.result;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
/**
* enthaelt alle Paare, die in einem Ergebnis nicht vorkommen koennen
* sie sind noetig fuer origPairs in PairTPHsmallerTPH, da hier auch
* Paare vorkommen koennen die keine Result sind (z.B. bei FunN$$)
*/
public class PairNoResult extends ResultPair<RefTypeOrTPHOrWildcardOrGeneric, RefTypeOrTPHOrWildcardOrGeneric>{
//public final TypePlaceholder left;
//public final TypePlaceholder right;
/*
* urspruengliches Paar aus diesem dieses Resultpair erzeugt wurde
* wichtig fuer generated Generics
*/
ResultPair origPair;
public PairNoResult(RefTypeOrTPHOrWildcardOrGeneric left, RefTypeOrTPHOrWildcardOrGeneric right){
super(left, right);
}
/* noch nicht implementiert. */
@Override
public void accept(ResultPairVisitor visitor) {
throw new NotImplementedException();
//visitor.visit(this);
}
}

@ -9,12 +9,6 @@ import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
public class PairTPHsmallerTPH extends ResultPair{
public final TypePlaceholder left;
public final TypePlaceholder right;
/*
* urspruengliches Paar aus diesem dieses Resultpair erzeugt wurde
* wichtig fuer generated Generics
*/
ResultPair origPair;
public PairTPHsmallerTPH(TypePlaceholder left, TypePlaceholder right){
super(left, right);
@ -22,11 +16,6 @@ public class PairTPHsmallerTPH extends ResultPair{
this.right = right;
}
public PairTPHsmallerTPH(TypePlaceholder left, TypePlaceholder right, ResultPair origPair){
this(left, right);
this.origPair = origPair;
}
@Override
public void accept(ResultPairVisitor visitor) {
visitor.visit(this);

@ -4,7 +4,4 @@ public interface ResultPairVisitor {
void visit(PairTPHsmallerTPH p);
void visit(PairTPHequalRefTypeOrWildcardType p);
void visit(PairTPHEqualTPH p);
//bisher nicht umgesetzt
//void visit(PairNoResult p);
}

@ -32,10 +32,8 @@ public class TYPE {
private ConstraintSet getConstraintsClass(ClassOrInterface cl, TypeInferenceInformation info) {
ConstraintSet ret = new ConstraintSet();
ConstraintSet methConstrains;
for(Method m : cl.getMethods()){
ret.addAll(methConstrains = getConstraintsMethod(m,info, cl));
m.constraints.addAll(methConstrains);
ret.addAll(getConstraintsMethod(m,info, cl));
}
for(Constructor m : cl.getConstructors()){
ret.addAll(getConstraintsConstructor(m,info, cl));

@ -11,7 +11,6 @@ import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
import de.dhbwstuttgart.syntaxtree.statement.*;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.syntaxtree.type.Void;
import de.dhbwstuttgart.typeinference.assumptions.FieldAssumption;
import de.dhbwstuttgart.typeinference.assumptions.FunNClass;
import de.dhbwstuttgart.typeinference.assumptions.MethodAssumption;
@ -181,7 +180,6 @@ public class TYPEStmt implements StatementVisitor{
? new Pair(x.TA1, new ExtendsWildcardType(x.TA2, x.TA2.getOffset()), PairOperator.EQUALSDOT)
: x)
.collect(Collectors.toCollection(() -> new Constraint<Pair>(oneMethodConstraint.isInherited())));
extendsOneMethodConstraint.isStatement = oneMethodConstraint.isStatement;
oneMethodConstraint.setExtendConstraint(extendsOneMethodConstraint);
extendsOneMethodConstraint.setExtendConstraint(oneMethodConstraint);
methodConstraints.add(extendsOneMethodConstraint);
@ -492,7 +490,7 @@ public class TYPEStmt implements StatementVisitor{
@Override
public void visit(Return returnExpr) {
returnExpr.retexpr.accept(this);
constraintsSet.addUndConstraint(new Pair(returnExpr.getType(),info.getCurrentTypeScope().getReturnType(), PairOperator.EQUALSDOT));
constraintsSet.addUndConstraint(new Pair(returnExpr.getType(),info.getCurrentTypeScope().getReturnType(), PairOperator.SMALLERDOT));
}
@Override
@ -589,18 +587,12 @@ public class TYPEStmt implements StatementVisitor{
*/
RefTypeOrTPHOrWildcardOrGeneric retType = assumption.getReceiverType(resolver);
methodConstraint.add(new Pair(forMethod.receiver.getType(), retType,
PairOperator.EQUALSDOT));//PL 2020-03-17 SMALLERDOT in EQUALSDOT umgewandelt, weil alle geerbten Methoden in den jeweilen Klassen enthalten sind.
//Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ANFANG
//methodConstraint.add(new Pair(forMethod.receiverType, retType,
// PairOperator.EQUALSDOT));
//Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ENDE
methodConstraint.isStatement = forMethod.getStatement();
methodConstraint.add(forMethod.name.equals("apply") ? //PL 2019-11-29: Tenaerer Operator eingefügt, weil bei Lambda-Ausdrücken keine Suntype FunN$$ existiert
new Pair(forMethod.receiver.getType(), retType, PairOperator.EQUALSDOT)
: new Pair(forMethod.receiver.getType(), retType, PairOperator.SMALLERDOT));
methodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(),
PairOperator.EQUALSDOT));
PairOperator.EQUALSDOT));
methodConstraint.addAll(generateParameterConstraints(forMethod, assumption, info, resolver));
return methodConstraint;
}

@ -655,6 +655,7 @@ public class RuleSet implements IRuleSet{
else
t1.getTypeParams().forEach(x -> occuringTypes.push(x));
}
Queue<UnifyPair> result1 = new LinkedList<UnifyPair>(pairs);
ArrayList<UnifyPair> result = new ArrayList<UnifyPair>();
boolean applied = false;
@ -668,7 +669,6 @@ public class RuleSet implements IRuleSet{
&& pair.getLhsType() instanceof PlaceholderType)
lhsType = (PlaceholderType) pair.getLhsType();
rhsType = pair.getRhsType(); //PL eingefuegt 2017-09-29 statt !((rhsType = pair.getRhsType()) instanceof PlaceholderType)
if(lhsType != null
//&& !((rhsType = pair.getRhsType()) instanceof PlaceholderType) //PL geloescht am 2017-09-29 Begründung: auch Typvariablen muessen ersetzt werden.
&& typeMap.get(lhsType) > 1 // The type occurs in more pairs in the set than just the recent pair.

@ -28,8 +28,8 @@ public class TypeUnify {
* @param cons
* @return
*/
public Set<Set<UnifyPair>> unify(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, true, logFile, log, 0, ret, usedTasks);
public Set<Set<UnifyPair>> unify(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, true, logFile, log, 0, ret);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(unifyTask);
Set<Set<UnifyPair>> res = unifyTask.join();
@ -54,8 +54,8 @@ public class TypeUnify {
* @param ret
* @return
*/
public UnifyResultModel unifyAsync(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, true, logFile, log, 0, ret, usedTasks);
public UnifyResultModel unifyAsync(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, true, logFile, log, 0, ret);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(unifyTask);
return ret;
@ -68,12 +68,11 @@ public class TypeUnify {
* @param fc
* @param logFile
* @param log
* @param cons
* @param ret
* @return
*/
public UnifyResultModel unifyParallel(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, true, logFile, log, 0, ret, usedTasks);
public UnifyResultModel unifyParallel(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, true, logFile, log, 0, ret);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(unifyTask);
Set<Set<UnifyPair>> res = unifyTask.join();
@ -102,11 +101,10 @@ public class TypeUnify {
* @param fc
* @param logFile
* @param log
* @param cons
* @return
*/
public Set<Set<UnifyPair>> unifyOderConstraints(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, false, logFile, log, 0, ret, usedTasks);
public Set<Set<UnifyPair>> unifyOderConstraints(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, false, logFile, log, 0, ret);
Set<Set<UnifyPair>> res = unifyTask.compute();
try {
logFile.write("\nnoShortendElements: " + unifyTask.noShortendElements +"\n");

@ -0,0 +1,30 @@
package de.dhbwstuttgart.typeinference.unify;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.io.Writer;
import java.util.List;
import java.util.Set;
public class TypeUnify2Future {
Set<Set<UnifyPair>> setToFlatten;
public TypeUnify2Future(Set<Set<UnifyPair>> setToFlatten, Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, Set<UnifyPair> nextSetElement, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm) {
super(eq, oderConstraints, fc, parallel, logFile, log, rekTiefe, urm);
this.setToFlatten = setToFlatten;
this.nextSetElement = nextSetElement;
}
Set<UnifyPair> getNextSetElement() {
return nextSetElement;
}
@Override
protected Set<Set<UnifyPair>> compute() {
Set<Set<UnifyPair>> res = unify2(setToFlatten, eq, oderConstraintsField, fc, parallel, rekTiefeField, true);
return res;
}
}

@ -18,8 +18,8 @@ public class TypeUnify2Task extends TypeUnifyTask {
Set<Set<UnifyPair>> setToFlatten;
public TypeUnify2Task(Set<Set<UnifyPair>> setToFlatten, Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, Set<UnifyPair> nextSetElement, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm, UnifyTaskModel usedTasks) {
super(eq, oderConstraints, fc, parallel, logFile, log, rekTiefe, urm, usedTasks);
public TypeUnify2Task(Set<Set<UnifyPair>> setToFlatten, Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, Set<UnifyPair> nextSetElement, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm) {
super(eq, oderConstraints, fc, parallel, logFile, log, rekTiefe, urm);
this.setToFlatten = setToFlatten;
this.nextSetElement = nextSetElement;
}
@ -30,35 +30,7 @@ public class TypeUnify2Task extends TypeUnifyTask {
@Override
protected Set<Set<UnifyPair>> compute() {
if (one) {
System.out.println("two");
}
one = true;
Set<Set<UnifyPair>> res = unify2(setToFlatten, eq, oderConstraintsField, fc, parallel, rekTiefeField);
/*if (isUndefinedPairSetSet(res)) {
return new HashSet<>(); }
else
*/
//writeLog("xxx");
//noOfThread--;
synchronized (usedTasks) {
if (this.myIsCancelled()) {
return new HashSet<>();
}
else {
return res;
}
}
Set<Set<UnifyPair>> res = unify2(setToFlatten, eq, oderConstraintsField, fc, parallel, rekTiefeField, true);
return res;
}
public void closeLogFile() {
try {
logFile.close();
}
catch (IOException ioE) {
System.err.println("no log-File" + thNo);
}
}
}

File diff suppressed because it is too large Load Diff

@ -60,7 +60,33 @@ import com.google.common.collect.Ordering;
* Implementation of the type unification algorithm
* @author Florian Steurer
*/
public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
public class TypeUnifyTask {
public static Set<Set<UnifyPair>> typeUnifyTask(Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm){
Set<UnifyPair> neweq = new HashSet<>(eq);
/* 1-elementige Oder-Constraints werden in und-Constraints umgewandelt */
oderConstraints.stream()
.filter(x -> x.size()==1)
.map(y -> y.stream().findFirst().get()).forEach(x -> neweq.addAll(x));
ArrayList<Set<Constraint<UnifyPair>>> remainingOderconstraints = oderConstraints.stream()
.filter(x -> x.size()>1)
.collect(Collectors.toCollection(ArrayList::new));
Set<Set<UnifyPair>> res = unify(neweq, remainingOderconstraints, fc, parallel, rekTiefe, true);
try {
logFile.close();
}
catch (IOException ioE) {
System.err.println("no log-File");
}
if (isUndefinedPairSetSet(res)) {
throw new TypeinferenceException("Unresolved constraints: " + res.toString(), new NullToken()); //return new HashSet<>();
}
else {
return res;
}
}
private static final long serialVersionUID = 1L;
private static int i = 0;
@ -71,16 +97,11 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
* Element, das aus dem nextSet den Gleichunen dieses Threads hinzugefuegt wurde
*/
Set<UnifyPair> nextSetElement;
Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm
/**
* Fuer die Threads
*/
UnifyResultModel urm;
protected static int noOfThread = 0;
private static int totalnoOfThread = 0;
int thNo;
protected boolean one = false;
Integer MaxNoOfThreads = 8;
public static final String rootDirectory = System.getProperty("user.dir")+"/test/logFiles/";
Writer logFile;
@ -110,9 +131,6 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
protected boolean parallel;
//Gives if unify is not called from checkA
private boolean finalresult = true;
int rekTiefeField;
Integer nOfUnify = 0;
@ -126,31 +144,13 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
static int noBacktracking;
static Integer noShortendElements = 0;
Boolean myIsCanceled = false;
volatile UnifyTaskModel usedTasks;
public TypeUnifyTask() {
rules = new RuleSet();
}
/*
public TypeUnifyTask(Set<UnifyPair> eq, IFiniteClosure fc, boolean parallel, FileWriter logFile, Boolean log) {
this.eq = eq;
this.fc = fc;
this.oup = new OrderingUnifyPair(fc);
this.parallel = parallel;
this.logFile = logFile;
this.log = log;
rules = new RuleSet(logFile);
noOfThread++;
thNo = noOfThread;
}
*/
public TypeUnifyTask(Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm, UnifyTaskModel usedTasks) {
public TypeUnifyTask(Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm) {
synchronized (this) {
this.eq = eq;
//this.oderConstraints = oderConstraints.stream().map(x -> x.stream().map(y -> new HashSet<>(y)).collect(Collectors.toSet(HashSet::new))).collect(Collectors.toList(ArrayList::new));
@ -170,21 +170,7 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
this.parallel = parallel;
this.logFile = logFile;
this.log = log;
noOfThread++;
totalnoOfThread++;
//writeLog("thNo1 " + thNo);
thNo = totalnoOfThread;
writeLog("thNo2 " + thNo);
try {
this.logFile = //new OutputStreamWriter(new NullOutputStream());
//new FileWriter(new File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"Thread_"+thNo));
new FileWriter(new File(System.getProperty("user.dir")+"/logFiles/"+"Thread_"+thNo));
logFile.write("");
}
catch (IOException e) {
System.err.println("log-File nicht vorhanden");
}
/*Abbruchtest
if (thNo > 10) {
System.out.println("cancel");
@ -202,56 +188,10 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
rules = new RuleSet(logFile);
this.rekTiefeField = rekTiefe;
this.urm = urm;
this.usedTasks = usedTasks;
this.usedTasks.add(this);
}
}
/**
* Vererbt alle Variancen
* @param eq The set of constraints
*/
/* PL 2018-05- 17 verschoben nach JavaTXCompiler
private void varianceInheritance(Set<UnifyPair> eq) {
Set<PlaceholderType> usedTPH = new HashSet<>();
Set<PlaceholderType> phSet = eq.stream().map(x -> {
Set<PlaceholderType> pair = new HashSet<>();
if (x.getLhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getLhsType());
if (x.getRhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getRhsType());
return pair;
}).reduce(new HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d); return c;});
ArrayList<PlaceholderType> phSetVariance = new ArrayList<>(phSet);
phSetVariance.removeIf(x -> (x.getVariance() == 0));
while(!phSetVariance.isEmpty()) {
PlaceholderType a = phSetVariance.remove(0);
usedTPH.add(a);
//HashMap<PlaceholderType,Integer> ht = new HashMap<>();
//ht.put(a, a.getVariance());
Set<UnifyPair> eq1 = new HashSet<>(eq);
eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType && ((PlaceholderType)x.getLhsType()).equals(a)));
eq1.stream().forEach(x -> { x.getRhsType().accept(new distributeVariance(), a.getVariance());});
eq1 = new HashSet<>(eq);
eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a)));
eq1.stream().forEach(x -> { x.getLhsType().accept(new distributeVariance(), a.getVariance());});
phSetVariance = new ArrayList<>(phSet);
phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x)));
}
}
*/
void myCancel(Boolean b) {
myIsCanceled = true;
}
public boolean myIsCancelled() {
return myIsCanceled;
}
protected Set<Set<UnifyPair>> compute() {
if (one) {
System.out.println("two");
}
one = true;
Set<UnifyPair> neweq = new HashSet<>(eq);
/* 1-elementige Oder-Constraints werden in und-Constraints umgewandelt */
oderConstraintsField.stream()
@ -260,8 +200,7 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
ArrayList<Set<Constraint<UnifyPair>>> remainingOderconstraints = oderConstraintsField.stream()
.filter(x -> x.size()>1)
.collect(Collectors.toCollection(ArrayList::new));
Set<Set<UnifyPair>> res = unify(neweq, remainingOderconstraints, fc, parallel, rekTiefeField);
noOfThread--;
Set<Set<UnifyPair>> res = unify(neweq, remainingOderconstraints, fc, parallel, rekTiefeField, true);
try {
logFile.close();
}
@ -269,21 +208,13 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
System.err.println("no log-File");
}
if (isUndefinedPairSetSet(res)) {
//fuer debug-Zwecke
ArrayList al = res.stream().map(x -> x.stream().collect(Collectors.toCollection(ArrayList::new)))
.collect(Collectors.toCollection(ArrayList::new));
throw new TypeinferenceException("Unresolved constraints: " + res.toString(), new NullToken()); //return new HashSet<>();
}
else {
synchronized (usedTasks) {
if (this.myIsCancelled()) {
return new HashSet<>();
}
else {
return res;
}
}
}
}
/*
@Override
@ -305,26 +236,9 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
* @param fc The finite closure
* @return The set of all principal type unifiers
*/
protected Set<Set<UnifyPair>> unify(final Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe) {
//Set<UnifyPair> aas = eq.stream().filter(x -> x.getLhsType().getName().equals("AA") //&& x.getPairOp().equals(PairOperator.SMALLERDOT)
// ).collect(Collectors.toCollection(HashSet::new));
//writeLog(nOfUnify.toString() + " AA: " + aas.toString());
//if (aas.isEmpty()) {
// System.out.println("");
//}
protected static Set<Set<UnifyPair>> unify(final Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe, Boolean finalresult) {
//.collect(Collectors.toCollection(HashSet::new)));
synchronized (usedTasks) {
if (this.myIsCancelled()) {
return new HashSet<>();
}
}
rekTiefe++;
nOfUnify++;
writeLog(nOfUnify.toString() + " Unifikation: " + eq.toString());
writeLog(nOfUnify.toString() + " Oderconstraints: " + oderConstraints.toString());
/*
* Variancen auf alle Gleichungen vererben
@ -343,29 +257,6 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
return ret;
}
/*
* Occurs-Check durchfuehren
*/
Set<UnifyPair> ocurrPairs = eq.stream().filter(x -> {
UnifyType lhs, rhs;
return (lhs = x.getLhsType()) instanceof PlaceholderType
&& !((rhs = x.getRhsType()) instanceof PlaceholderType)
&& rhs.getTypeParams().occurs((PlaceholderType)lhs);})
.map(x -> { x.setUndefinedPair(); return x;})
.collect(Collectors.toCollection(HashSet::new));
writeLog("ocurrPairs: " + ocurrPairs);
if (ocurrPairs.size() > 0) {
Set<Set<UnifyPair>> ret = new HashSet<>();
ret.add(ocurrPairs);
return ret;
}
/*
* Step 1: Repeated application of reduce, adapt, erase, swap
*/
Set<UnifyPair> eq0;
Set<UnifyPair> eq0Prime;
Optional<Set<UnifyPair>> eqSubst = Optional.of(eq);
@ -484,30 +375,15 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
//Aufruf von computeCartesianRecursive ANFANG
//writeLog("topLevelSets: " + topLevelSets.toString());
return computeCartesianRecursive(new ArrayList<>(topLevelSets), eq, oderConstraintsOutput, fc, parallel, rekTiefe);
return computeCartesianRecursive(new HashSet<>(), new ArrayList<>(topLevelSets), eq, oderConstraintsOutput, fc, rekTiefe, finalresult);
}
Set<Set<UnifyPair>> unify2(Set<Set<UnifyPair>> setToFlatten, Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe) {
Set<Set<UnifyPair>> unify2(Set<Set<UnifyPair>> setToFlatten, Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe, Boolean finalresult) {
//Aufruf von computeCartesianRecursive ENDE
//keine Ahnung woher das kommt
//Set<Set<UnifyPair>> setToFlatten = topLevelSets.stream().map(x -> x.iterator().next()).collect(Collectors.toCollection(HashSet::new));
//Muss auskommentiert werden, wenn computeCartesianRecursive ANFANG
// Cartesian product over all (up to 10) top level sets
//Set<Set<Set<UnifyPair>>> eqPrimeSet = setOps.cartesianProduct(topLevelSets)
// .stream().map(x -> new HashSet<>(x))
// .collect(Collectors.toCollection(HashSet::new));
//Muss auskommentiert werden, wenn computeCartesianRecursive ENDE
synchronized (usedTasks) {
if (this.myIsCancelled()) {
return new HashSet<>();
}
}
Set<Set<UnifyPair>> eqPrimePrimeSet = new HashSet<>();
Set<TypeUnifyTask> forks = new HashSet<>();
@ -530,47 +406,9 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
Set<Set<UnifyPair>> unifyres1 = null;
Set<Set<UnifyPair>> unifyres2 = null;
if (!ocString.equals(newOderConstraints.toString())) writeLog("nach Subst: " + newOderConstraints);
//writeLog("nach Subst: " + eqPrimePrime);
/*
* Step 6 a) Restart (fork) for pairs where subst was applied
*/
/*
if(parallel) {
if (eqPrime.equals(eq) && !eqPrimePrime.isPresent()
&& oderConstraints.isEmpty()) //PL 2017-09-29 //(!eqPrimePrime.isPresent()) auskommentiert und durch
//PL 2017-09-29 dies ersetzt //(!eqPrimePrime.isPresent())
//PL 2018-05-18 beide Bedingungen muessen gelten, da eqPrime Veränderungen in allem ausser subst
//eqPrimePrime Veraenderungen in subst repraesentieren.
eqPrimePrimeSet.add(eqPrime);
else if(eqPrimePrime.isPresent()) {
//System.out.println("nextStep: " + eqPrimePrime.get());
TypeUnifyTask fork = new TypeUnifyTask(eqPrimePrime.get(), fc, true, logFile, log);
forks.add(fork);
fork.fork();
}
else {
//System.out.println("nextStep: " + eqPrime);
TypeUnifyTask fork = new TypeUnifyTask(eqPrime, fc, true, logFile, log);
forks.add(fork);
fork.fork();
}
}
else */
{// sequentiell (Step 6b is included)
if (printtag) System.out.println("nextStep: " + eqPrimePrime);
if (eqPrime.equals(eq) && !eqPrimePrime.isPresent()
&& oderConstraints.isEmpty()) { //PL 2017-09-29 //(!eqPrimePrime.isPresent()) auskommentiert und durch
//PL 2017-09-29 dies ersetzt //(!eqPrimePrime.isPresent())
//PL 2018-05-18 beide Bedingungen muessen gelten, da eqPrime Veränderungen in allem ausser subst
//eqPrimePrime Veraenderungen in subst repraesentieren.
//try {
//if (isSolvedForm(eqPrime)) {
// writeLog("eqPrime:" + eqPrime.toString()+"\n");
//}
//}
//catch (IOException e) {
// System.err.println("log-File nicht vorhanden");
//}
&& oderConstraints.isEmpty()) {
eqPrimePrimeSet.add(eqPrime);
if (finalresult && isSolvedForm(eqPrime)) {
writeLog("eqPrime:" + eqPrime.toString()+"\n");
@ -578,34 +416,17 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
}
}
else if(eqPrimePrime.isPresent()) {
Set<Set<UnifyPair>> unifyres = unifyres1 = unify(eqPrimePrime.get(), newOderConstraints, fc, parallel, rekTiefe);
Set<Set<UnifyPair>> unifyres = unifyres1 = unify(eqPrimePrime.get(), newOderConstraints, fc, parallel, rekTiefe, finalresult);
eqPrimePrimeSet.addAll(unifyres);
}
else {
Set<Set<UnifyPair>> unifyres = unifyres2 = unify(eqPrime, newOderConstraints, fc, parallel, rekTiefe);
Set<Set<UnifyPair>> unifyres = unifyres2 = unify(eqPrime, newOderConstraints, fc, parallel, rekTiefe, finalresult);
eqPrimePrimeSet.addAll(unifyres);
}
}
//Muss auskommentiert werden, wenn computeCartesianRecursive ANFANG
//}
//Muss auskommentiert werden, wenn computeCartesianRecursive ENDE
/*
* Step 6 b) Build the union over everything.
*/
/*
* PL 2019-01-22: geloescht
if(parallel)
for(TypeUnifyTask fork : forks)
eqPrimePrimeSet.addAll(fork.join());
*/
/*
* Step 7: Filter empty sets;
*/
eqPrimePrimeSet = eqPrimePrimeSet.stream().filter(x -> isSolvedForm(x) || this.isUndefinedPairSet(x)).collect(Collectors.toCollection(HashSet::new));
if (!eqPrimePrimeSet.isEmpty() && !isUndefinedPairSetSet(eqPrimePrimeSet)) {
writeLog("Result1 " + eqPrimePrimeSet.toString());
@ -614,56 +435,25 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
}
/**
* Computes the cartesian product of topLevelSets step by step.
* @param topLevelSets List of Sets of Sets, where a cartesian product have to be built
* Ex.: [{{a =. Integer}, {a = Object}}, {{a = Vector<b>, b =. Integer}, {a = Vector<b>, b =. Object}}]
* @param eq Original set of equations which should be unified
* @param oderConstraints Remaining or-constraints
* @param fc The finite closure
* @param parallel If the algorithm should be parallelized run
* @param rekTiefe Deep of recursive calls
* @return The set of all principal type unifiers
*/
Set<Set<UnifyPair>> computeCartesianRecursive(ArrayList<Set<? extends Set<UnifyPair>>> topLevelSets, Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe) {
//oneElems: Alle 1-elementigen Mengen, die nur ein Paar
//a <. theta, theta <. a oder a =. theta enthalten
Set<Set<UnifyPair>> oneElems = new HashSet<>();
oneElems.addAll(topLevelSets.stream()
Set<Set<UnifyPair>> computeCartesianRecursive(Set<Set<UnifyPair>> fstElems, ArrayList<Set<? extends Set<UnifyPair>>> topLevelSets, Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, int rekTiefe, Boolean finalresult) {
fstElems.addAll(topLevelSets.stream()
.filter(x -> x.size()==1)
.map(y -> y.stream().findFirst().get())
.collect(Collectors.toCollection(HashSet::new)));
//optNextSet: Eine mehrelementige Menge, wenn vorhanden
Optional<Set<? extends Set<UnifyPair>>> optNextSet = topLevelSets.stream().filter(x -> x.size()>1).findAny();
if (!optNextSet.isPresent()) {//Alle Elemente sind 1-elementig
Set<Set<UnifyPair>> result = unify2(oneElems, eq, oderConstraints, fc, parallel, rekTiefe);
ArrayList<Set<? extends Set<UnifyPair>>> remainingSets = topLevelSets.stream()
.filter(x -> x.size()>1)
.collect(Collectors.toCollection(ArrayList::new));
if (remainingSets.isEmpty()) {//Alle Elemente sind 1-elementig
Set<Set<UnifyPair>> result = unify2(fstElems, eq, oderConstraints, fc, parallel, rekTiefe, finalresult);
return result;
}
Set<? extends Set<UnifyPair>> nextSet = optNextSet.get();
//writeLog("nextSet: " + nextSet.toString());
Set<? extends Set<UnifyPair>> nextSet = remainingSets.remove(0);
List<Set<UnifyPair>> nextSetasList =new ArrayList<>(nextSet);
/*
try {
//List<Set<UnifyPair>>
//nextSetasList = oup.sortedCopy(nextSet);//new ArrayList<>(nextSet);
}
catch (java.lang.IllegalArgumentException e) {
System.out.print("");
}
*/
Set<Set<UnifyPair>> result = new HashSet<>();
int variance = 0;
/* Varianzbestimmung Anfang
* Oderconstraint, wenn entweder kein Basepair oder unterschiedliche Basepairs => oderConstraint = true;
* Varianz = 1 => Argumentvariable
* Varianz = -1 => Rückgabevariable
* Varianz = 0 => unklar
* Varianz = 2 => Operatoren oderConstraints */
ArrayList<UnifyPair> zeroNextElem = new ArrayList<>(nextSetasList.get(0));
UnifyPair fstBasePair = zeroNextElem.remove(0).getBasePair();
Boolean oderConstraint = false;
@ -686,15 +476,16 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
}
}
else {
//variance = 2;
oderConstraint = true;
}
}
else {
//variance = 2;
oderConstraint = true;
}
//Varianz-Bestimmung Oder-Constraints
if (oderConstraint) {
if (oderConstraint) {//Varianz-Bestimmung Oder-Constraints
if (printtag) System.out.println("nextSetasList " + nextSetasList);
Optional<Integer> optVariance =
nextSetasList.iterator()
@ -707,33 +498,24 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
((PlaceholderType)x.getGroundBasePair().getLhsType()).getVariance())
.findAny();
//Fuer Operatorenaufrufe wird variance auf 2 gesetzt.
//da kein Receiver existiert also kein x.getGroundBasePair().getLhsType() instanceof PlaceholderType
//Bei Varianz = 2 werden alle Elemente des Kartesischen Produkts abgearbeitet
//da kein Receiver existiert also keon x.getGroundBasePair().getLhsType() instanceof PlaceholderType
//Es werden alle Elemente des Kartesischen Produkts abgearbeitet
variance = optVariance.isPresent() ? optVariance.get() : 2;
}
/* Varianzbestimmung Ende */
//writeLog("nextSetasList: " + nextSetasList.toString());
if (!nextSetasList.iterator().hasNext())
System.out.print("");
if (nextSetasList.iterator().next().stream().filter(x -> x.getLhsType().getName().equals("D")).findFirst().isPresent() && nextSetasList.size()>1)
System.out.print("");
Set<UnifyPair> nextSetElem = nextSetasList.get(0);
//writeLog("BasePair1: " + nextSetElem + " " + nextSetElem.iterator().next().getBasePair());
/* sameEqSet-Bestimmung: Wenn a = ty \in nextSet dann enthaelt sameEqSet
* alle Paare a < ty1 oder ty2 < a aus oneElems */
/* sameEqSet-Bestimmung: Wenn a = ty \in nextSet dann enthaelt sameEqSet alle Paare a < ty1 oder ty2 < a aus fstElems */
Set<UnifyPair> sameEqSet = new HashSet<>();
//optOrigPair enthaelt ggf. das Paar a = ty \in nextSet
Optional<UnifyPair> optOrigPair = null;
//if (variance != 2) {
if (!oderConstraint) {
optOrigPair = nextSetElem.stream().filter(x -> (
//x.getBasePair() != null && ist gegeben wenn variance != 2
//x.getBasePair().getPairOp().equals(PairOperator.SMALLERDOT) &&
(x.getPairOp().equals(PairOperator.EQUALSDOT)
/*
(x.getBasePair().getLhsType() instanceof PlaceholderType
&& x.getLhsType().equals(x.getBasePair().getLhsType()))
|| (x.getBasePair().getRhsType() instanceof PlaceholderType
&& x.getLhsType().equals(x.getBasePair().getRhsType())
*/
(x.getPairOp().equals(PairOperator.EQUALSDOT)
))).filter(x -> //Sicherstellen, dass bei a = ty a auch wirklich die gesuchte Typvariable ist
x.getLhsType().equals(x.getBasePair().getLhsType()) ||
x.getLhsType().equals(x.getBasePair().getRhsType())
@ -746,7 +528,7 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
tyVar = origPair.getRhsType();
}
UnifyType tyVarEF = tyVar;
sameEqSet = oneElems.stream().map(xx -> xx.iterator().next())
sameEqSet = fstElems.stream().map(xx -> xx.iterator().next())
.filter(x -> (((x.getLhsType().equals(tyVarEF) && !(x.getRhsType() instanceof PlaceholderType))
|| (x.getRhsType().equals(tyVarEF) && !(x.getLhsType() instanceof PlaceholderType)))))
.collect(Collectors.toCollection(HashSet::new));
@ -755,21 +537,14 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
/* sameEqSet-Bestimmung Ende */
Set<UnifyPair> a = null;
while (nextSetasList.size() > 0) {
while (nextSetasList.size() > 0) { //(nextSetasList.size() != 0) {
Set<UnifyPair> a_last = a;
/* Liste der Faelle für die parallele Verarbeitung
* Enthaelt Elemente, die nicht in Relation zu aktuellem Fall in der
* Variablen a stehen. Diese muesse auf alle Faelle bearbeitet werden,
* Deshalb wird ihre Berechnung parallel angestossen.
*/
//Liste der Faelle für die parallele Verarbeitung
List<Set<UnifyPair>> nextSetasListRest = new ArrayList<>();
/* Liste der Faelle, bei dem Receiver jeweils "? extends" enthaelt bzw. nicht enthaelt
* In der Regel ist dies genau ein Element
* Dieses Element wird später aus nextSetasList geloescht, wenn das jeweils andere Element zum Erfolg
* gefuehrt hat.
*/
//Liste der Faelle, bei dem Receiver jeweils "? extends" enthaelt bzw. nicht enthaelt
//In der Regel ein Element
List<Set<UnifyPair>> nextSetasListOderConstraints = new ArrayList<>();
writeLog("nextSet: " + nextSet.toString());
@ -792,7 +567,6 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
}
//Alle maximale Elemente in nextSetasListRest bestimmen
//nur für diese wird parallele Berechnung angestossen.
nextSetasListRest = oup.maxElements(nextSetasListRest);
}
else if (variance == -1) {
@ -813,13 +587,10 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
}
}
//Alle minimalen Elemente in nextSetasListRest bestimmen
//nur für diese wird parallele Berechnung angestossen.
nextSetasListRest = oup.minElements(nextSetasListRest);
}
else if (variance == 2) {
a = nextSetasList.remove(0);
//Fuer alle Elemente wird parallele Berechnung angestossen.
nextSetasListRest = new ArrayList<>(nextSetasList);
}
else if (variance == 0) {
@ -845,33 +616,55 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
}
}
}
//writeLog("nextSet: " + nextSetasList.toString()+ "\n");
//nextSetasList.remove(a);
//PL 2018-03-01
//TODO: 1. Maximum und Minimum unterscheiden
//TODO: 2. compare noch für alle Elmemente die nicht X =. ty sind erweitern
//for(Set<UnifyPair> a : newSet) {
i++;
Set<Set<UnifyPair>> elems = new HashSet<Set<UnifyPair>>(oneElems);
Set<Set<UnifyPair>> elems = new HashSet<Set<UnifyPair>>(fstElems);
writeLog("a1: " + rekTiefe + " "+ "variance: "+ variance + " " + a.toString()+ "\n");
//Ergebnisvariable für den aktuelle Thread
//elems.add(a); PL 2019-01-20 Muss weg, weil das in jeweiligen Thread erfolgen muss. Fuer den sequentiellen Fall
//im else-Zweig
//if (remainingSets.isEmpty()) {//muss immer gegeben sein, weil nur 1 Element der topLevelSets mehr als ein Elemet enthaelt
//writeLog("Vor unify2 Aufruf: " + elems.toString());
Set<Set<UnifyPair>> res = new HashSet<>();
//Menge der Ergebnisse der geforkten Threads
Set<Set<Set<UnifyPair>>> add_res = new HashSet<>();
Set<Set<UnifyPair>> aParDef = new HashSet<>();
/* Wenn bei (a \in theta) \in a zu Widerspruch in oneElems wird
* a verworfen und zu nächstem Element von nextSetasList gegangen
*/
if (!oderConstraint && !sameEqSet.isEmpty() && !checkNoContradiction(a, sameEqSet, result)) {
a = null;
noShortendElements++;
continue;
}
/* PL 2019-03-11 Anfang eingefuegt Vergleich mit anderen Paaren ggf. loeschen */
if (!oderConstraint && !sameEqSet.isEmpty()) {
Optional<UnifyPair> optAPair = a.stream().filter(x -> (
//x.getBasePair() != null && ist gegeben wenn variance != 2
//x.getBasePair().getPairOp().equals(PairOperator.SMALLERDOT) &&
(x.getPairOp().equals(PairOperator.EQUALSDOT)
/*
(x.getBasePair().getLhsType() instanceof PlaceholderType
&& x.getLhsType().equals(x.getBasePair().getLhsType()))
|| (x.getBasePair().getRhsType() instanceof PlaceholderType
&& x.getLhsType().equals(x.getBasePair().getRhsType())
*/
))).filter(x -> //Sicherstellen, dass bei a = ty a auch wirklich die gesuchte Typvariable ist
x.getLhsType().equals(x.getBasePair().getLhsType()) ||
x.getLhsType().equals(x.getBasePair().getRhsType())
).findFirst();
/* Wenn parallel gearbeitet wird, wird je nach Varianz ein neuer Thread
* gestartet, der parallel weiterarbeitet.
*/
if(parallel && (variance == 1) && noOfThread <= MaxNoOfThreads) {
if (optAPair.isPresent()) {//basepair ist entweder a <. Ty oder ty <. a
UnifyPair aPair = optAPair.get();
//writeLog("optOrigPair: " + optOrigPair + " " + "aPair: " + aPair+ " " + "aPair.basePair(): " + aPair.getBasePair());
writeLog("variance: " + new Integer(variance).toString() + "sameEqSet:" + sameEqSet);
if (!checkA(aPair, sameEqSet, elems, result)) {
a = null;
noShortendElements++;
continue;
}
}
}
/* PL 2019-03-11 Ende eingefuegt Vergleich mit anderen Paaren ggf. loeschen */
if(parallel && (variance == 1)) {
Set<TypeUnify2Task> forks = new HashSet<>();
Set<UnifyPair> newEqOrig = new HashSet<>(eq);
Set<Set<UnifyPair>> newElemsOrig = new HashSet<>(elems);
@ -879,14 +672,8 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
newElemsOrig.add(a);
/* FORK ANFANG */
TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, parallel, logFile, log, rekTiefe, urm, usedTasks);
TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, parallel, logFile, log, rekTiefe, urm);
//forks.add(forkOrig);
synchronized(usedTasks) {
if (this.myIsCancelled()) {
return new HashSet<>();
}
forkOrig.fork();
}
/* FORK ENDE */
synchronized (this) {
@ -899,14 +686,35 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
writeLog("1 RM" + nSaL.toString());
}
if (!oderConstraint) {
//ueberpruefung ob zu a =. ty \in nSaL in sameEqSet ein Widerspruch besteht
if (!sameEqSet.isEmpty() && !checkNoContradiction(nSaL, sameEqSet, result)) {
nSaL = null;
noShortendElements++;
continue;
/* PL 2019-03-13 Anfang eingefuegt Vergleich mit anderen Paaren ggf. loeschen */
if (!oderConstraint) {//weiss nicht ob das wirklich stimmt
Optional<UnifyPair> optAPair = nSaL.stream().filter(x -> (
//x.getBasePair() != null && ist gegeben wenn variance != 2
//x.getBasePair().getPairOp().equals(PairOperator.SMALLERDOT) &&
(x.getPairOp().equals(PairOperator.EQUALSDOT)
/*
(x.getBasePair().getLhsType() instanceof PlaceholderType
&& x.getLhsType().equals(x.getBasePair().getLhsType()))
|| (x.getBasePair().getRhsType() instanceof PlaceholderType
&& x.getLhsType().equals(x.getBasePair().getRhsType())
*/
))).filter(x -> //Sicherstellen, dass bei a = ty a auch wirklich die gesuchte Typvariable ist
x.getLhsType().equals(x.getBasePair().getLhsType()) ||
x.getLhsType().equals(x.getBasePair().getRhsType())
).findFirst();
if (optAPair.isPresent()) {//basepair ist entweder a <. Ty oder ty <. a
UnifyPair aPair = optAPair.get();
//writeLog("optOrigPair: " + optOrigPair + " " + "aPair: " + aPair+ " " + "aPair.basePair(): " + aPair.getBasePair());
writeLog("variance: " + new Integer(variance).toString() + "sameEqSet:" + sameEqSet);
if (!sameEqSet.isEmpty() && !checkA(aPair, sameEqSet, elems, result)) {
nSaL = null;
noShortendElements++;
continue;
}
}
}
/* PL 2019-03-13 Ende eingefuegt Vergleich mit anderen Paaren ggf. loeschen */
else {
nextSetasListOderConstraints.add(((Constraint<UnifyPair>)nSaL).getExtendConstraint());
}
@ -914,41 +722,14 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
Set<Set<UnifyPair>> newElems = new HashSet<>(elems);
List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints);
newElems.add(nSaL);
TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, parallel, logFile, log, rekTiefe, urm, usedTasks);
forks.add(fork);
synchronized(usedTasks) {
if (this.myIsCancelled()) {
return new HashSet<>();
}
fork.fork();
}
TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, parallel, logFile, log, rekTiefe, urm);
}
//res = unify2(newElemsOrig, newEqOrig, newOderConstraintsOrig, fc, parallel, rekTiefe);
/* FORK ANFANG */
synchronized (this) {
writeLog("wait "+ forkOrig.thNo);
noOfThread--;
res = forkOrig.join();
synchronized (usedTasks) {
if (this.myIsCancelled()) {
return new HashSet<>();
}
}
//noOfThread++;
forkOrig.writeLog("final Orig 1");
forkOrig.closeLogFile();
//Set<Set<UnifyPair>> fork_res = forkOrig.join();
writeLog("JoinOrig " + new Integer(forkOrig.thNo).toString());
//noOfThread--; an das Ende von compute verschoben
//add_res.add(fork_res);
};
/* FORK ENDE */
forks.forEach(x -> writeLog("wait: " + x.thNo));
res = forkOrig.join();
for(TypeUnify2Task fork : forks) {
synchronized (this) {
noOfThread--;
Set<Set<UnifyPair>> fork_res = fork.join();
synchronized (usedTasks) {
if (this.myIsCancelled()) {
@ -965,28 +746,18 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
aParDef.add(fork.getNextSetElement());
}
fork.writeLog("final 1");
fork.closeLogFile();
};
}
//noOfThread++;
} else {
if(parallel && (variance == -1) && noOfThread <= MaxNoOfThreads) {
if((variance == -1)) {
Set<TypeUnify2Task> forks = new HashSet<>();
Set<UnifyPair> newEqOrig = new HashSet<>(eq);
Set<Set<UnifyPair>> newElemsOrig = new HashSet<>(elems);
List<Set<Constraint<UnifyPair>>> newOderConstraintsOrig = new ArrayList<>(oderConstraints);
newElemsOrig.add(a);
/* FORK ANFANG */
TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, parallel, logFile, log, rekTiefe, urm, usedTasks);
//forks.add(forkOrig);
synchronized(usedTasks) {
if (this.myIsCancelled()) {
return new HashSet<>();
}
forkOrig.fork();
}
/* FORK ENDE */
TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, parallel, logFile, log, rekTiefe, urm);
synchronized (this) {
writeLog("a in " + variance + " "+ a);
@ -998,14 +769,35 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
writeLog("-1 RM" + nSaL.toString());
}
if (!oderConstraint) {
//ueberpruefung ob zu a =. ty \in nSaL in sameEqSet ein Widerspruch besteht
if (!sameEqSet.isEmpty() && !checkNoContradiction(nSaL, sameEqSet, result)) {
nSaL = null;
noShortendElements++;
continue;
if (!oderConstraint) {//weiss nicht ob das wirklich stimmt
/* PL 2019-03-13 Anfang eingefuegt Vergleich mit anderen Paaren ggf. loeschen */
Optional<UnifyPair> optAPair = nSaL.stream().filter(x -> (
//x.getBasePair() != null && ist gegeben wenn variance != 2
//x.getBasePair().getPairOp().equals(PairOperator.SMALLERDOT) &&
(x.getPairOp().equals(PairOperator.EQUALSDOT)
/*
(x.getBasePair().getLhsType() instanceof PlaceholderType
&& x.getLhsType().equals(x.getBasePair().getLhsType()))
|| (x.getBasePair().getRhsType() instanceof PlaceholderType
&& x.getLhsType().equals(x.getBasePair().getRhsType())
*/
))).filter(x -> //Sicherstellen, dass bei a = ty a auch wirklich die gesuchte Typvariable ist
x.getLhsType().equals(x.getBasePair().getLhsType()) ||
x.getLhsType().equals(x.getBasePair().getRhsType())
).findFirst();
if (optAPair.isPresent()) {//basepair ist entweder a <. Ty oder ty <. a
UnifyPair aPair = optAPair.get();
//writeLog("optOrigPair: " + optOrigPair + " " + "aPair: " + aPair+ " " + "aPair.basePair(): " + aPair.getBasePair());
writeLog("variance: " + new Integer(variance).toString() + "sameEqSet:" + sameEqSet);
if (!sameEqSet.isEmpty() && !checkA(aPair, sameEqSet, elems, result)) {
nSaL = null;
noShortendElements++;
continue;
}
}
}
/* PL 2019-03-13 Ende eingefuegt Vergleich mit anderen Paaren ggf. loeschen */
else {
nextSetasListOderConstraints.add(((Constraint<UnifyPair>)nSaL).getExtendConstraint());
}
@ -1148,12 +940,11 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
};
}
//noOfThread++;
} else {//parallel = false oder MaxNoOfThreads ist erreicht, sequentiell weiterarbeiten
} else {
//parallel = false; //Wenn MaxNoOfThreads erreicht ist, sequentiell weiterarbeiten
elems.add(a); //PL 2019-01-16 muss das wirklich hin steht schon in Zeile 859 ja braucht man siehe Zeile 859
res = unify2(elems, eq, oderConstraints, fc, parallel, rekTiefe);
res = unify2(elems, eq, oderConstraints, fc, parallel, rekTiefe, finalresult);
}}}
//Ab hier alle parallele Berechnungen wieder zusammengeführt.
if (!isUndefinedPairSetSet(res) && isUndefinedPairSetSet(result)) {
//wenn korrektes Ergebnis gefunden alle Fehlerfaelle loeschen
result = res;
@ -1240,7 +1031,7 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
}
else {
//alle Fehlerfaelle und alle korrekten Ergebnis jeweils adden
writeLog("RES Fst: result: " + result.toString() + " res: " + res.toString());
writeLog("RES Fst: reuslt: " + result.toString() + " res: " + res.toString());
result.addAll(res);
}
}
@ -1252,6 +1043,10 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
//}
}
//}
//else {//duerfte gar nicht mehr vorkommen PL 2018-04-03
//result.addAll(computeCartesianRecursive(elems, remainingSets, eq, fc, parallel));
//}
if (parallel) {
for (Set<Set<UnifyPair>> par_res : add_res) {
if (!isUndefinedPairSetSet(par_res) && isUndefinedPairSetSet(result)) {
@ -1488,29 +1283,7 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
return result;
}
/**
* checks if there is for (a = ty) \in a in sameEqSet a constradiction
* @param a Set of actual element of constraints with a =. ty \in a
* @param sameEqSet Set of constraints where a <. ty' and ty' <. a
* @param result set of results which contains correct solution s and the
* the error constraints. Error constraints are added
* @result contradiction of (a = ty) in sameEqSet
*/
protected Boolean checkNoContradiction(Set<UnifyPair> a, Set<UnifyPair> sameEqSet, Set<Set<UnifyPair>> result) {
//optAPair enthaelt ggf. das Paar a = ty' \in a
//unterscheidet sich von optOrigPair, da dort a = ty
Optional<UnifyPair> optAPair =
a.stream().filter(x -> (x.getPairOp().equals(PairOperator.EQUALSDOT)))
.filter(x -> //Sicherstellen, dass bei a = ty a auch wirklich die gesuchte Typvariable ist
x.getLhsType().equals(x.getBasePair().getLhsType()) ||
x.getLhsType().equals(x.getBasePair().getRhsType()))
.findFirst();
if (optAPair.isPresent()) {//basepair ist entweder a <. Ty oder ty <. a
UnifyPair aPair = optAPair.get();
//writeLog("optOrigPair: " + optOrigPair + " " + "aPair: " + aPair+ " " + "aPair.basePair(): " + aPair.getBasePair());
protected Boolean checkA (UnifyPair aPair, Set<UnifyPair> sameEqSet, Set<Set<UnifyPair>> elems, Set<Set<UnifyPair>> result) {
writeLog("checkA: " + aPair + "sameEqSet: " + sameEqSet);
for (UnifyPair sameEq : sameEqSet) {
if (sameEq.getLhsType() instanceof PlaceholderType) {
@ -1520,14 +1293,12 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
unitedSubst.addAll(sameEq.getAllSubstitutions());
unitedSubst.addAll(sameEq.getAllBases());
localEq.add(new UnifyPair(aPair.getRhsType(), sameEq.getRhsType(), sameEq.getPairOp(), unitedSubst, null));
finalresult = false;
Set<Set<UnifyPair>> localRes = unify(localEq, new ArrayList<>(), fc, false, 0);
finalresult = true;
Set<Set<UnifyPair>> localRes = unify(localEq, new ArrayList<>(), fc, false, 0, false);
if (isUndefinedPairSetSet(localRes)) {
if (result.isEmpty() || isUndefinedPairSetSet(result)) {
result.addAll(localRes);
}
writeLog("FALSE: " + aPair + "sameEqSet: " + sameEqSet);
//writeLog("FALSE: " + aPair + "sameEqSet: " + sameEqSet);
return false;
}
}
@ -1538,25 +1309,20 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
unitedSubst.addAll(sameEq.getAllSubstitutions());
unitedSubst.addAll(sameEq.getAllBases());
localEq.add(new UnifyPair(sameEq.getLhsType(), aPair.getRhsType(), sameEq.getPairOp(), unitedSubst, null));
finalresult = false;
Set<Set<UnifyPair>> localRes = unify(localEq, new ArrayList<>(), fc, false, 0);
finalresult = true;
Set<Set<UnifyPair>> localRes = unify(localEq, new ArrayList<>(), fc, false, 0, false);
if (isUndefinedPairSetSet(localRes)) {
if (result.isEmpty() || isUndefinedPairSetSet(result)) {
result.addAll(localRes);
}
writeLog("FALSE: " + aPair + "sameEqSet: " + sameEqSet);
//writeLog("FALSE: " + aPair + "sameEqSet: " + sameEqSet);
return false;
}
}
}
writeLog("TRUE: " + aPair + "sameEqSet: " + sameEqSet);
return true;
}
//writeLog("TRUE: " + aPair + "sameEqSet: " + sameEqSet);
return true;
}
protected boolean couldBecorrect(Set<Pair<Set<UnifyPair>, UnifyPair>> reducedUndefResSubstGroundedBasePair, Set<UnifyPair> nextElem) {
return reducedUndefResSubstGroundedBasePair.stream()
.map(pair -> {
@ -1646,7 +1412,7 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
return true;}).reduce((xx, yy) -> xx || yy).get();
}
protected boolean isUndefinedPairSet(Set<UnifyPair> s) {
protected static boolean isUndefinedPairSet(Set<UnifyPair> s) {
if (s.size() >= 1 ) {
Boolean ret = s.stream().map(x -> x.isUndefinedPair()).reduce(true, (x,y)-> (x && y));
return ret;
@ -1656,7 +1422,7 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
}
}
protected boolean isUndefinedPairSetSet(Set<Set<UnifyPair>> s) {
protected static boolean isUndefinedPairSetSet(Set<Set<UnifyPair>> s) {
if (s.size() >= 1) {
Boolean ret = s.stream(). map(x -> isUndefinedPairSet(x)).reduce(true, (x,y)-> (x && y));
return ret;
@ -1715,7 +1481,7 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
/*
* Apply rules until the queue is empty
*/
while(!eqQueue.isEmpty()) {
while(!eqQueue.isEmpty()) {
UnifyPair pair = eqQueue.pollFirst();
// ReduceUp, ReduceLow, ReduceUpLow
@ -2184,12 +1950,6 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
Set<Set<UnifyPair>> result = new HashSet<>();
if (thetaPrime instanceof ReferenceType && ((ReferenceType)thetaPrime).isGenTypeVar()) {
Set<UnifyPair> resultOne = new HashSet<>();
resultOne.add(new UnifyPair (a, thetaPrime, PairOperator.EQUALSDOT, pair.getSubstitution(), pair));
result.add(resultOne);
}
boolean allGen = thetaPrime.getTypeParams().size() > 0;
for(UnifyType t : thetaPrime.getTypeParams())
if(!(t instanceof PlaceholderType) || !((PlaceholderType) t).isGenerated()) {
@ -2529,7 +2289,7 @@ public class TypeUnifyTask extends RecursiveTask<Set<Set<UnifyPair>>> {
void writeLog(String str) {
synchronized ( this ) {
if (log && finalresult) {
if (log) {
try {
logFile.write("Thread no.:" + thNo + "\n");
logFile.write("noOfThread:" + noOfThread + "\n");

@ -1,18 +0,0 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.List;
import de.dhbwstuttgart.typeinference.result.ResultSet;
public class UnifyResultEvent {
private List<ResultSet> newTypeResult;
public UnifyResultEvent(List<ResultSet> newTypeResult) {
this.newTypeResult = newTypeResult;
}
public List<ResultSet> getNewTypeResult() {
return newTypeResult;
}
}

@ -1,7 +0,0 @@
package de.dhbwstuttgart.typeinference.unify;
public interface UnifyResultListener {
void onNewTypeResultFound(UnifyResultEvent evt);
}

@ -1,21 +0,0 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.ArrayList;
import java.util.List;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
public class UnifyResultListenerImpl implements UnifyResultListener {
List<ResultSet> results = new ArrayList<>();
public synchronized void onNewTypeResultFound(UnifyResultEvent evt) {
results.addAll(evt.getNewTypeResult());
}
public List<ResultSet> getResults() {
return results;
}
}

@ -1,59 +0,0 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
public class UnifyResultModel {
ConstraintSet<de.dhbwstuttgart.typeinference.constraints.Pair> cons;
IFiniteClosure fc;
public UnifyResultModel(ConstraintSet<de.dhbwstuttgart.typeinference.constraints.Pair> cons,
IFiniteClosure fc) {
this.cons = cons;
this.fc = fc;
}
private List<UnifyResultListener> listeners = new ArrayList<>();
public void addUnifyResultListener(UnifyResultListener listenerToAdd) {
listeners.add(listenerToAdd);
}
public void removeUnifyResultListener(UnifyResultListener listenerToRemove) {
listeners.remove(listenerToRemove);
}
public void notify(Set<Set<UnifyPair>> eqPrimePrimeSet) {
Set<Set<UnifyPair>> eqPrimePrimeSetRet = eqPrimePrimeSet.stream().map(x -> {
Optional<Set<UnifyPair>> res = new RuleSet().subst(x.stream().map(y -> {
if (y.getPairOp() == PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT);
return y; //alle Paare a <.? b erden durch a =. b ersetzt
}).collect(Collectors.toCollection(HashSet::new)));
if (res.isPresent()) {//wenn subst ein Erg liefert wurde was veraendert
return new TypeUnifyTask().applyTypeUnificationRules(res.get(), fc);
}
else return x; //wenn nichts veraendert wurde wird x zurueckgegeben
}).collect(Collectors.toCollection(HashSet::new));
List<ResultSet> newResult = eqPrimePrimeSetRet.stream().map(unifyPairs ->
new ResultSet(UnifyTypeFactory.convert(unifyPairs, de.dhbwstuttgart.typeinference.constraints.Pair.generateTPHMap(cons))))
.collect(Collectors.toList());
UnifyResultEvent evt = new UnifyResultEvent(newResult);
for (UnifyResultListener listener : listeners) {
listener.onNewTypeResultFound(evt);
}
}
}

@ -1,18 +0,0 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.ArrayList;
public class UnifyTaskModel {
ArrayList<TypeUnifyTask> usedTasks = new ArrayList<>();
public synchronized void add(TypeUnifyTask t) {
usedTasks.add(t);
}
public synchronized void cancel() {
for(TypeUnifyTask t : usedTasks) {
t.myCancel(true);
}
}
}

@ -29,8 +29,6 @@ public class UnifyPair {
*/
private PairOperator pairOp;
private boolean undefinedPair = false;
/**
* Unifier/substitute that generated this pair
* PL 2018-03-15
@ -114,10 +112,7 @@ public class UnifyPair {
public void addSubstitutions(Set<UnifyPair> sup) {
substitution.addAll(sup);
}
public void setUndefinedPair() {
undefinedPair = true;
}
public Set<UnifyPair> getSubstitution() {
return new HashSet<>(substitution);
}
@ -125,10 +120,6 @@ public class UnifyPair {
public UnifyPair getBasePair() {
return basePair;
}
public boolean isUndefinedPair() {
return undefinedPair;
}
public Set<UnifyPair> getAllSubstitutions () {
Set<UnifyPair> ret = new HashSet<>();
ret.addAll(new ArrayList<>(getSubstitution()));

@ -40,8 +40,7 @@ public class AllgemeinTest {
//String className = "FCTest3";
//String className = "Var";
//String className = "Put";
//String className = "Twice";
String className = "TestSubTypless";
String className = "Cycle";
//PL 2019-10-24: genutzt fuer unterschiedliche Tests
path = System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/" + className + ".jav";
//path = System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/Overloading_Generics.jav";

@ -1,75 +0,0 @@
package bytecode;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import general.TestCleanUp;
import org.junit.*;
import de.dhbwstuttgart.core.JavaTXCompiler;
import static org.junit.Assert.*;
/**
* Test for the file {@code OLFun2.jav}.
* Tests if the expected overloading for the method {@code m} exists.
*
* @since Studienarbeit Type Erasure
* @author etiennezink
*/
public class OLFun2Test {
private static String path;
private static File fileToTest;
private static JavaTXCompiler compiler;
private static ClassLoader loader;
private static Class<?> classToTest;
private static Class<?> classFun1IntInt;
private static Class<?> classFun1IntDouble;
private static Class<?> classFun1DoubleDouble;
private static Class<?> classFun1DoubleInt;
private static String generatedByteCodeDirectory = System.getProperty("user.dir") + "/src/test/resources/testBytecode/generatedBC/";
@BeforeClass
public static void setUp() throws Exception {
path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/OLFun2.jav";
fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest);
compiler.generateBytecode(generatedByteCodeDirectory);
loader = new URLClassLoader(new URL[] {new URL("file://"+generatedByteCodeDirectory)});
classToTest = loader.loadClass("OLFun2");
classFun1IntInt = loader.loadClass("Fun1$$Ljava$lang$Integer$_$Ljava$lang$Integer$_$");
classFun1IntDouble = loader.loadClass("Fun1$$Ljava$lang$Integer$_$Ljava$lang$Double$_$");
classFun1DoubleDouble = loader.loadClass("Fun1$$Ljava$lang$Double$_$Ljava$lang$Double$_$");
classFun1DoubleInt = loader.loadClass("Fun1$$Ljava$lang$Double$_$Ljava$lang$Integer$_$");
}
@Test
public void mExistsWithIntegerInteger() throws Exception{
Method m = classToTest.getDeclaredMethod("m", classFun1IntInt);
assertNotNull(m);
}
@Test
public void mExistsWithIntegerDouble() throws Exception{
Method m = classToTest.getDeclaredMethod("m", classFun1IntDouble);
assertNotNull(m);
}
@Test
public void mExistsWithDoubleInteger() throws Exception{
Method m = classToTest.getDeclaredMethod("m", classFun1DoubleInt);
assertNotNull(m);
}
@Test
public void mExistsWithDoubleDouble() throws Exception{
Method m = classToTest.getDeclaredMethod("m", classFun1DoubleDouble);
assertNotNull(m);
}
@AfterClass
public static void cleanUp() {
TestCleanUp.cleanUpDirectory(new File(generatedByteCodeDirectory), f -> f.getName().contains(".class"));
}
}

@ -1,91 +1,52 @@
package bytecode;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import general.TestCleanUp;
import org.junit.*;
import de.dhbwstuttgart.core.JavaTXCompiler;
import static org.junit.Assert.*;
import org.junit.Test;
import de.dhbwstuttgart.core.JavaTXCompiler;
/**
* Test for the file {@code OLFun.jav}.
* Tests if the expected overloading for the method {@code m} exists.
*
* @since Studienarbeit Type Erasure
* @author etiennezink
*/
public class OLFunTest {
private static String path;
private static File fileToTest;
private static JavaTXCompiler compiler;
private static ClassLoader loader;
private static Class<?> classToTest;
private static Class<?> classFun1IntInt;
private static Class<?> classFun1IntDouble;
private static Class<?> classFun1DoubleDouble;
private static Class<?> classFun1DoubleInt;
private static Class<?> classFun1StringInt;
private static Class<?> classFun1StringDouble;
private static String generatedByteCodeDirectory = System.getProperty("user.dir") + "/src/test/resources/testBytecode/generatedBC/";
@BeforeClass
public static void setUp() throws Exception {
private static String pathToClassFile;
private static Object instanceOfClass;
@Test
public void generateBC() throws Exception {
path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/OLFun.jav";
fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest);
compiler.generateBytecode(generatedByteCodeDirectory);
loader = new URLClassLoader(new URL[] {new URL("file://"+generatedByteCodeDirectory)});
compiler.generateBytecode(System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/");
pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass("OLFun");
classFun1IntInt = loader.loadClass("Fun1$$Ljava$lang$Integer$_$Ljava$lang$Integer$_$");
classFun1IntDouble = loader.loadClass("Fun1$$Ljava$lang$Integer$_$Ljava$lang$Double$_$");
classFun1DoubleDouble = loader.loadClass("Fun1$$Ljava$lang$Double$_$Ljava$lang$Double$_$");
classFun1DoubleInt = loader.loadClass("Fun1$$Ljava$lang$Double$_$Ljava$lang$Integer$_$");
classFun1StringInt = loader.loadClass("Fun1$$Ljava$lang$String$_$Ljava$lang$Integer$_$");
classFun1StringDouble = loader.loadClass("Fun1$$Ljava$lang$String$_$Ljava$lang$Double$_$");
/*
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
Method m = classToTest.getDeclaredMethod("m");
Class<?> lambda = m.invoke(instanceOfClass).getClass();
Method apply = lambda.getMethod("apply", Object.class);
// Damit man auf die Methode zugreifen kann
apply.setAccessible(true);
Integer i = 77;
Integer result = (Integer) apply.invoke(m.invoke(instanceOfClass), i);
assertEquals(77, result);
*/
}
@Test
public void mExistsWithIntegerInteger() throws Exception{
Method m = classToTest.getDeclaredMethod("m", classFun1IntInt, Integer.class);
assertNotNull(m);
}
@Test
public void mExistsWithIntegerDouble() throws Exception{
Method m = classToTest.getDeclaredMethod("m", classFun1IntDouble, Integer.class);
assertNotNull(m);
}
@Test
public void mExistsWithDoubleInteger() throws Exception{
Method m = classToTest.getDeclaredMethod("m", classFun1DoubleInt, Double.class);
assertNotNull(m);
}
@Test
public void mExistsWithDoubleDouble() throws Exception{
Method m = classToTest.getDeclaredMethod("m", classFun1DoubleDouble, Double.class);
assertNotNull(m);
}
@Test
public void mExistsWithStringInteger() throws Exception{
Method m = classToTest.getDeclaredMethod("m", classFun1StringInt, String.class);
assertNotNull(m);
}
@Test
public void mExistsWithStringDouble() throws Exception{
Method m = classToTest.getDeclaredMethod("m", classFun1StringDouble, String.class);
assertNotNull(m);
}
@AfterClass
public static void cleanUp(){
TestCleanUp.cleanUpDirectory(new File(generatedByteCodeDirectory), f -> f.getName().contains(".class"));
}
}

@ -1,248 +0,0 @@
package bytecode.funN;
import de.dhbwstuttgart.bytecode.funN.FunNGenerator;
import de.dhbwstuttgart.bytecode.funN.FunNUtilities;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import org.junit.BeforeClass;
import org.junit.Test;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import java.util.Arrays;
import static org.junit.Assert.*;
import static org.objectweb.asm.Opcodes.*;
public class FunNGeneratorTest {
static FunNUtilities funNGenerator;
static RefType voidType;
static RefType integerType;
static GenericRefType genericT;
static TypePlaceholder tph;
@BeforeClass
public static void setUp(){
funNGenerator = FunNGenerator.getInstance();
voidType = new RefType(new JavaClassName(Type.getInternalName(Void.class)), null);
integerType = new RefType(new JavaClassName(Type.getInternalName(Integer.class)), null);
genericT = new GenericRefType("T", null);
tph = TypePlaceholder.fresh(null);
}
@Test
public void superClassName_0(){
var superClassName = funNGenerator.getSuperClassName(0);
assertEquals("Fun0$$", superClassName);
}
@Test
public void superClassName_1(){
var superClassName = funNGenerator.getSuperClassName(1);
assertEquals("Fun1$$", superClassName);
}
@Test
public void specializedClassName_VoidVoid(){
var specializedClassName = funNGenerator.getSpecializedClassName(Arrays.asList(), voidType);
assertEquals("Fun0$$Ljava$lang$Void$_$", specializedClassName);
}
@Test
public void specializedClassName_VoidInt(){
var specializedClassName = funNGenerator.getSpecializedClassName(Arrays.asList(), integerType);
assertEquals("Fun0$$Ljava$lang$Integer$_$", specializedClassName);
}
@Test
public void specializedClassName_IntInt(){
var specializedClassName = funNGenerator.getSpecializedClassName(Arrays.asList(integerType), integerType);
assertEquals("Fun1$$Ljava$lang$Integer$_$Ljava$lang$Integer$_$", specializedClassName);
}
@Test
public void specializedClassName_IntT(){
var specializedClassName = funNGenerator.getSpecializedClassName(Arrays.asList(integerType), genericT);
assertEquals("Fun1$$Ljava$lang$Integer$_$LT$_$", specializedClassName);
}
@Test
public void specializedClassName_IntTPH(){
var specializedClassName = funNGenerator.getSpecializedClassName(Arrays.asList(integerType), TypePlaceholder.fresh(null));
assertEquals("Fun1$$Ljava$lang$Integer$_$LTPH$_$", specializedClassName);
}
@Test
public void signature_IntInt(){
var classSignature = funNGenerator.getSpecializedSignature(Arrays.asList(integerType), integerType);
assertEquals("LFun1$$Ljava$lang$Integer$_$Ljava$lang$Integer$_$;", classSignature);
}
@Test
public void signature_IntT(){
var classSignature = funNGenerator.getSpecializedSignature(Arrays.asList(integerType), genericT);
assertEquals("LFun1$$Ljava$lang$Integer$_$LT$_$<TT;>;", classSignature);
}
@Test
public void signature_TPHTPH(){
var classSignature = funNGenerator.getSpecializedSignature(Arrays.asList(tph), tph);
assertEquals(String.format("LFun1$$LTPH$_$LTPH$_$<T%s$;T%s$;>;",tph.getName(), tph.getName()), classSignature);
}
@Test
public void descriptor_IntInt(){
var classDescriptor = funNGenerator.getSpecializedDescriptor(Arrays.asList(integerType), integerType);
//does not have to contain L and ; because TypeToDescriptor returns the descriptor without these characters as well
assertEquals("Fun1$$Ljava$lang$Integer$_$Ljava$lang$Integer$_$", classDescriptor);
}
@Test
public void descriptor_IntT(){
var classDescriptor = funNGenerator.getSpecializedDescriptor(Arrays.asList(integerType), genericT);
//does not have to contain L and ; because TypeToDescriptor returns the descriptor without these characters as well
assertEquals("Fun1$$Ljava$lang$Integer$_$LT$_$", classDescriptor);
}
@Test
public void descriptor_TPHTPH(){
var classDescriptor = funNGenerator.getSpecializedDescriptor(Arrays.asList(tph), tph);
//does not have to contain L and ; because TypeToDescriptor returns the descriptor without these characters as well
assertEquals("Fun1$$LTPH$_$LTPH$_$", classDescriptor);
}
@Test
public void getArguments_Empty(){
var arguments = funNGenerator.getArguments(Arrays.asList());
assertTrue(arguments.isEmpty());
}
@Test
public void getArguments_Int(){
var arguments = funNGenerator.getArguments(Arrays.asList(integerType));
assertTrue(arguments.isEmpty());
}
@Test
public void getArguments_IntT(){
var arguments = funNGenerator.getArguments(Arrays.asList(integerType, genericT));
assertTrue(arguments.size() == 1);
assertTrue(arguments.contains(integerType));
}
@Test
public void getArguments_IntTInt(){
var arguments = funNGenerator.getArguments(Arrays.asList(integerType, genericT, integerType));
assertTrue(arguments.size() == 2);
assertTrue(arguments.contains(integerType));
assertTrue(arguments.contains(genericT));
}
@Test
public void getReturnType_Empty(){
var returnType = funNGenerator.getReturnType(Arrays.asList());
assertNull(returnType);
}
@Test
public void getReturnType_Int(){
var returnType = funNGenerator.getReturnType(Arrays.asList(integerType));
assertEquals(integerType, returnType);
}
@Test
public void getReturnType_IntT(){
var returnType = funNGenerator.getReturnType(Arrays.asList(integerType, genericT));
assertEquals(genericT, returnType);
}
@Test
public void superBytecode_0(){
var superBytecode = funNGenerator.generateSuperBytecode(0);
assertArrayEquals(superBytecodeReference_0(), superBytecode);
}
@Test
public void superBytecode_1(){
var superBytecode = funNGenerator.generateSuperBytecode(1);
assertArrayEquals(superBytecodeReference_1(), superBytecode);
}
@Test
public void superBytecode_2(){
var superBytecode = funNGenerator.generateSuperBytecode(2);
assertArrayEquals(superBytecodeReference_2(), superBytecode);
}
@Test
public void specializedBytecode_VoidInt(){
var specializedBytecode = funNGenerator.generateSpecializedBytecode(Arrays.asList(), integerType);
assertArrayEquals(specializedBytecodeReference_VoidInt(), specializedBytecode);
}
@Test
public void specializedBytecode_IntInt(){
var specializedBytecode = funNGenerator.generateSpecializedBytecode(Arrays.asList(integerType), integerType);
assertArrayEquals(specializedBytecodeReference_IntInt(), specializedBytecode);
}
@Test
public void specializedBytecode_TIntInt(){
var specializedBytecode = funNGenerator.generateSpecializedBytecode(Arrays.asList(genericT, integerType), integerType);
assertArrayEquals(specializedBytecodeReference_TIntInt(), specializedBytecode);
}
//super bytecode reference methods
private static byte[] superBytecodeReference_0() {
var classWriter = new ClassWriter(0);
classWriter.visit(V1_8, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, "Fun0$$", "<R:Ljava/lang/Object;>Ljava/lang/Object;", "java/lang/Object", null);
var methodVisitor = classWriter.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "apply", "()Ljava/lang/Object;", "()TR;", null);
methodVisitor.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
private static byte[] superBytecodeReference_1() {
var classWriter = new ClassWriter(0);
classWriter.visit(V1_8, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, "Fun1$$", "<T1:Ljava/lang/Object;R:Ljava/lang/Object;>Ljava/lang/Object;", "java/lang/Object", null);
var methodVisitor = classWriter.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "apply", "(Ljava/lang/Object;)Ljava/lang/Object;", "(TT1;)TR;", null);
methodVisitor.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
private static byte[] superBytecodeReference_2() {
ClassWriter classWriter = new ClassWriter(0);
classWriter.visit(V1_8, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, "Fun2$$", "<T1:Ljava/lang/Object;T2:Ljava/lang/Object;R:Ljava/lang/Object;>Ljava/lang/Object;", "java/lang/Object", null);
var methodVisitor = classWriter.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "apply", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", "(TT1;TT2;)TR;", null);
methodVisitor.visitEnd();
classWriter.visitEnd();
return classWriter.toByteArray();
}
//specialized bytecode reference methods
private static byte[] specializedBytecodeReference_VoidInt() {
ClassWriter classWriter = new ClassWriter(0);
classWriter.visit(V1_8, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, "Fun0$$Ljava$lang$Integer$_$", "Ljava/lang/Object;LFun0$$<Ljava/lang/Integer;>;", "java/lang/Object", new String[]{"Fun0$$"});
classWriter.visitEnd();
return classWriter.toByteArray();
}
private static byte[] specializedBytecodeReference_IntInt() {
ClassWriter classWriter = new ClassWriter(0);
classWriter.visit(V1_8, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, "Fun1$$Ljava$lang$Integer$_$Ljava$lang$Integer$_$", "Ljava/lang/Object;LFun1$$<Ljava/lang/Integer;Ljava/lang/Integer;>;", "java/lang/Object", new String[]{"Fun1$$"});
classWriter.visitEnd();
return classWriter.toByteArray();
}
private static byte[] specializedBytecodeReference_TIntInt() {
ClassWriter classWriter = new ClassWriter(0);
classWriter.visit(V1_8, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, "Fun2$$LT$_$Ljava$lang$Integer$_$Ljava$lang$Integer$_$", "<T:Ljava/lang/Object;>Ljava/lang/Object;LFun2$$<TT;Ljava/lang/Integer;Ljava/lang/Integer;>;", "java/lang/Object", new String[]{"Fun2$$"});
classWriter.visitEnd();
return classWriter.toByteArray();
}
}

@ -1,14 +0,0 @@
package general;
import java.io.File;
import java.io.FileFilter;
public class TestCleanUp {
public static void cleanUpDirectory(File directory, FileFilter fileFilter){
if(!directory.isDirectory()) throw new RuntimeException("Directory for bytecode generation is wrong!");
for (File file: directory.listFiles(fileFilter)) {
file.delete();
}
}
}

@ -1,4 +1,3 @@
/*
package insertGenerics;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
@ -13,13 +12,11 @@ import java.util.List;
public class FamilyOfGeneratedGenericsTest extends TestCase {
public void testIdentityMethod(){
*/
/*
/*
Example method:
A id(B i) return i;
gives constraint: B <. A and A <. Object, which are method constraints
*//*
gives constraint: B <. A, which is a method constraint
*/
List<TPHConstraint> inputConstraints = new ArrayList<>();
inputConstraints.add(new TPHConstraint("B", "A", TPHConstraint.Relation.EXTENDS));
@ -32,29 +29,25 @@ public class FamilyOfGeneratedGenericsTest extends TestCase {
List<ClassConstraint> classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(inputConstraints, tphPositions);
assertTrue(classConstraints.isEmpty());
*/
/*
/*
MethodConstraints should be the same as the input constraint
*//*
// List<MethodConstraint> methodConstraints = FamilyOfGeneratedGenerics.getMethodConstraints(inputConstraints, new ArrayList<ClassConstraint>(), tphPositions);
// assertTrue(methodConstraints.size() == 2);
// assertTrue(methodConstraints.get(0).getLeft().equals("B"));
// assertTrue(methodConstraints.get(0).getRight().equals("A"));
*/
List<MethodConstraint> methodConstraints = FamilyOfGeneratedGenerics.getMethodConstraints(inputConstraints, tphPositions);
assertTrue(methodConstraints.size() == 1);
assertTrue(methodConstraints.get(0).getLeft().equals("B"));
assertTrue(methodConstraints.get(0).getRight().equals("A"));
}
public void testClassField(){
*/
/*
/*
class Example{
A f;
B fReturn(){
return f;
}
}
gives constraint: A <. B and B <. Object which are class constraints
*//*
gives constraint: A <. B, which is a class constraint
*/
List<TPHConstraint> inputConstraints = new ArrayList<>();
inputConstraints.add(new TPHConstraint("A", "B", TPHConstraint.Relation.EXTENDS));
@ -65,22 +58,18 @@ public class FamilyOfGeneratedGenericsTest extends TestCase {
PairTphMethod<PositionFinder.Position, String> posOfB = new PairTphMethod<>(PositionFinder.Position.METHOD, "fReturn");
tphPositions.put("B", posOfB);
*/
/*
/*
ClassConstraints should not be the same as the input constraint
*//*
*/
List<ClassConstraint> classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(inputConstraints, tphPositions);
System.out.println(classConstraints);
assertTrue(classConstraints.size() == 2);
//assertTrue(classConstraints.get(0).getLeft().equals("A"));
//assertTrue(classConstraints.get(0).getRight().equals("B"));
// HashMap<String, List<MethodConstraint>> methodConstraintsWithPosition = FamilyOfGeneratedGenerics.getMethodConstraintsWithPosition(inputConstraints,classConstraints,tphPositions,)
}
public void testSecondLineOfClassConstraints() {
*/
/*
/*
class Example() {
A a;
B b = a;
@ -94,8 +83,7 @@ public class FamilyOfGeneratedGenericsTest extends TestCase {
return e;
}
}
*//*
*/
List<TPHConstraint> inputConstraints = new ArrayList<>();
inputConstraints.add(new TPHConstraint("A", "B", TPHConstraint.Relation.EXTENDS));
@ -121,18 +109,13 @@ public class FamilyOfGeneratedGenericsTest extends TestCase {
List<ClassConstraint> classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(inputConstraints, tphPositions);
System.out.println(classConstraints);
// List<MethodConstraint> methodConstraints = FamilyOfGeneratedGenerics.getMethodConstraints(inputConstraints, classConstraints, tphPositions);
// System.out.println(methodConstraints);
assertFalse(classConstraints.isEmpty());
assertTrue(classConstraints.size() == 6);
// assertFalse(methodConstraints.isEmpty());
// assertTrue(methodConstraints.size() == 2);
}
public void testTPHsAndGenerics() {
*/
/*
/*
class TPHsAndGenerics {
Fun1<A,B> id = x -> x;
C id2 (D x) {
@ -146,8 +129,7 @@ public class FamilyOfGeneratedGenericsTest extends TestCase {
return b;
}
}
*//*
*/
List<TPHConstraint> inputConstraints = new ArrayList<>();
inputConstraints.add(new TPHConstraint("A","B", TPHConstraint.Relation.EXTENDS));
@ -183,13 +165,9 @@ public class FamilyOfGeneratedGenericsTest extends TestCase {
List<ClassConstraint> classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(inputConstraints, tphPositions);
System.out.println(classConstraints);
// List<MethodConstraint> methodConstraints = FamilyOfGeneratedGenerics.getMethodConstraints(inputConstraints, classConstraints, tphPositions);
// System.out.println(methodConstraints);
assertFalse(classConstraints.isEmpty());
assertTrue(classConstraints.size() == 3);
// assertFalse(methodConstraints.isEmpty());
// assertTrue(methodConstraints.size()==9);
}
@ -209,7 +187,7 @@ public class FamilyOfGeneratedGenericsTest extends TestCase {
HashMap<String, List<PairTphMethod<PositionFinder.Position, String>>> allTphsNew = FamilyOfGeneratedGenerics.positionConverter(allTphsOld, listOfMethodsAndTphs);
HashMap<String, PairTphMethod<PositionFinder.Position, String>> allTphsNew = FamilyOfGeneratedGenerics.positionConverter(allTphsOld, listOfMethodsAndTphs);
System.out.println(allTphsNew);
//was tun wenn zwei (oder mehr) Methoden gleiches TPH enthalten?
//ist dies möglich oder werden die TPHs immer verschieden initialisiert und dann erst am Ende gemappt?
@ -225,4 +203,4 @@ public class FamilyOfGeneratedGenericsTest extends TestCase {
}
}*/
}

@ -0,0 +1,30 @@
package insertGenerics;
import de.dhbwstuttgart.bytecode.genericsGenerator.GeneratedGenericsFinder;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import junit.framework.TestResult;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class MethodsTest {
public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/insertGenericsJav/";
public static final String fileDirectory = rootDirectory + "TestGGFinder.jav";
@Test
public void testVisit(ClassOrInterface coi) throws IOException, ClassNotFoundException {
JavaTXCompiler compiler = new JavaTXCompiler(new File(fileDirectory));
SourceFile sf = compiler.sourceFiles.get(compiler.sourceFiles.keySet());
List<ResultSet> results = compiler.typeInference();
GeneratedGenericsFinder ggf = new GeneratedGenericsFinder(sf, results);
ClassOrInterface coiHere = coi;
ggf.visit(coiHere);
//assert results.size()>0;
}
}

@ -1,112 +0,0 @@
package insertGenerics;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint;
import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics;
import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestAny {
public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/insertGenericsJav/";
@BeforeClass
public static void resetNamesOfTypePlaceholder() {
de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset();
}
@Test
public void ggFinder() throws IOException, ClassNotFoundException {
execute(new File(rootDirectory+"TestAny.jav"));
}
private static class TestResultSet{
}
public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException {
JavaTXCompiler compiler = new JavaTXCompiler(fileToTest);
for(File f : compiler.sourceFiles.keySet()){
SourceFile sf = compiler.sourceFiles.get(f);
}
List<ResultSet> results = compiler.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results);
List<ClassConstraint> classConstraintsTest = new ArrayList<>();
classConstraintsTest.add(new ClassConstraint("N", "O", Relation.EXTENDS));
classConstraintsTest.add(new ClassConstraint("N", "U", Relation.EXTENDS));
classConstraintsTest.add(new ClassConstraint("U", "O", Relation.EXTENDS));
classConstraintsTest.add(new ClassConstraint("O", "java/lang/Object", Relation.EXTENDS));
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionTest = new HashMap<>();
Set<MethodConstraint> lmc;
lmc = new HashSet<>();
lmc.add(new MethodConstraint("R", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH RanyMethod()", lmc);
lmc = new HashSet<>();
methodConstraintsWithPositionTest.put("TPH UotherMethod(TPH U)", lmc);
FamilyOfGeneratedGenerics fogg = compiler.fogg;
Set<ClassConstraint> computedClassCons = new HashSet<>(fogg.classConstraints);
Set<ClassConstraint> expectedClassCons = new HashSet<>(classConstraintsTest);
assertEquals(expectedClassCons, computedClassCons);
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionComputed = new HashMap<>();
fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l)));
assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed);
//compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles);
for(File f : compiler.sourceFiles.keySet()){
SourceFile sf = compiler.sourceFiles.get(f);
System.out.println(ASTTypePrinter.print(sf));
System.out.println(ASTPrinter.print(sf));
//List<ResultSet> results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen
assert results.size()>0;
Set<String> insertedTypes = new HashSet<>();
for(ResultSet resultSet : results){
Set<TypeInsert> result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, results, simplifyResultsForAllSourceFiles);
assert result.size()>0;
String content = readFile(f.getPath(), StandardCharsets.UTF_8);
for(TypeInsert tip : result){
insertedTypes.add(tip.insert(content));
}
}
for(String s : insertedTypes){
System.out.println(s);
}
}
return new TestResultSet();
}
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}

@ -1,112 +0,0 @@
package insertGenerics;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint;
import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics;
import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestContraVariant {
public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/insertGenericsJav/";
@BeforeClass
public static void resetNamesOfTypePlaceholder() {
de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset();
}
@Test
public void ggFinder() throws IOException, ClassNotFoundException {
execute(new File(rootDirectory+"TestContraVariant.jav"));
}
private static class TestResultSet{
}
public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException {
JavaTXCompiler compiler = new JavaTXCompiler(fileToTest);
for(File f : compiler.sourceFiles.keySet()){
SourceFile sf = compiler.sourceFiles.get(f);
}
List<ResultSet> results = compiler.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results);
List<ClassConstraint> classConstraintsTest = new ArrayList<>();
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionTest = new HashMap<>();
Set<MethodConstraint> lmc;
lmc = new HashSet<>();
lmc.add(new MethodConstraint("R", "O", Relation.EXTENDS));
lmc.add(new MethodConstraint("O", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH Rm(TPH O)", lmc);
lmc = new HashSet<>();
//lmc.add(new MethodConstraint("S", "O", Relation.EXTENDS));
lmc.add(new MethodConstraint("S", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("R", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH Rmain(TPH S)", lmc);
FamilyOfGeneratedGenerics fogg = compiler.fogg;
Set<ClassConstraint> computedClassCons = new HashSet<>(fogg.classConstraints);
Set<ClassConstraint> expectedClassCons = new HashSet<>(classConstraintsTest);
assertEquals(expectedClassCons, computedClassCons);
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionComputed = new HashMap<>();
fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l)));
assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed);
//compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles);
for(File f : compiler.sourceFiles.keySet()){
SourceFile sf = compiler.sourceFiles.get(f);
System.out.println(ASTTypePrinter.print(sf));
System.out.println(ASTPrinter.print(sf));
//List<ResultSet> results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen
assert results.size()>0;
Set<String> insertedTypes = new HashSet<>();
for(ResultSet resultSet : results){
Set<TypeInsert> result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, results, simplifyResultsForAllSourceFiles);
assert result.size()>0;
String content = readFile(f.getPath(), StandardCharsets.UTF_8);
for(TypeInsert tip : result){
insertedTypes.add(tip.insert(content));
}
}
for(String s : insertedTypes){
System.out.println(s);
}
}
return new TestResultSet();
}
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}

@ -1,11 +1,16 @@
/*
package insertGenerics;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.insertGenerics.*;
import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint;
import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics;
import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint;
import de.dhbwstuttgart.bytecode.insertGenerics.PositionFinder;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@ -22,41 +27,30 @@ public class TestExample42 {
return cs;
}
public HashMap<String, PairTphMethod<PositionFinder.Position, String>> fillPosOfTphs() {
HashMap<String, PairTphMethod<PositionFinder.Position, String>> posOfTphs = new HashMap<>();
// TPHs "U" und "L" auskommentiert, da nach Vorgaben L zu Z umbenannt und U als void interpretiert wird
PairTphMethod<PositionFinder.Position, String> posOfK = new PairTphMethod<>(PositionFinder.Position.FIELD, null);
// PairTphMethod<PositionFinder.Position, String> posOfL = new PairTphMethod<>(PositionFinder.Position.METHOD, "id");
PairTphMethod<PositionFinder.Position, String> posOfM = new PairTphMethod<>(PositionFinder.Position.METHOD, "id");
PairTphMethod<PositionFinder.Position, String> posOfN = new PairTphMethod<>(PositionFinder.Position.METHOD, "id");
PairTphMethod<PositionFinder.Position, String> posOfP = new PairTphMethod<>(PositionFinder.Position.METHOD, "setA");
PairTphMethod<PositionFinder.Position, String> posOfQ = new PairTphMethod<>(PositionFinder.Position.METHOD, "setA");
// PairTphMethod<PositionFinder.Position, String> posOfU = new PairTphMethod<>(PositionFinder.Position.METHOD, "m");
PairTphMethod<PositionFinder.Position, String> posOfV = new PairTphMethod<>(PositionFinder.Position.METHOD, "m");
PairTphMethod<PositionFinder.Position, String> posOfW = new PairTphMethod<>(PositionFinder.Position.METHOD, "m");
PairTphMethod<PositionFinder.Position, String> posOfZ = new PairTphMethod<>(PositionFinder.Position.METHOD, "m");
posOfTphs.put("K", posOfK);
// posOfTphs.put("L", posOfL);
posOfTphs.put("M", posOfM);
posOfTphs.put("N", posOfN);
posOfTphs.put("P", posOfP);
posOfTphs.put("Q", posOfQ);
// posOfTphs.put("U", posOfU);
posOfTphs.put("V", posOfV);
posOfTphs.put("W", posOfW);
posOfTphs.put("Z", posOfZ);
public HashMap<String, PositionFinder.Position> fillPosOfTphs() {
BufferedReader l;
HashMap<String, PositionFinder.Position> posOfTphs = new HashMap<>();
posOfTphs.put("K", PositionFinder.Position.FIELD);
posOfTphs.put("L", PositionFinder.Position.METHOD);
posOfTphs.put("M", PositionFinder.Position.METHOD);
posOfTphs.put("N", PositionFinder.Position.METHOD);
posOfTphs.put("P", PositionFinder.Position.METHOD);
posOfTphs.put("Q", PositionFinder.Position.METHOD);
posOfTphs.put("U", PositionFinder.Position.METHOD);
posOfTphs.put("V", PositionFinder.Position.METHOD);
posOfTphs.put("W", PositionFinder.Position.METHOD);
posOfTphs.put("Z", PositionFinder.Position.METHOD);
return posOfTphs;
}
@Test
public void genericTest() {
// List<ClassConstraint> classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(fillConstraintsList(),fillPosOfTphs());
// System.out.println("ClassConstraints: " + classConstraints);
// List<MethodConstraint> methodConstraints = FamilyOfGeneratedGenerics.getMethodConstraints(fillConstraintsList(),classConstraints,fillPosOfTphs());
// System.out.println("MethodConstraints: " + methodConstraints);
List<ClassConstraint> classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(fillConstraintsList(),fillPosOfTphs());
System.out.println("ClassConstraints: " + classConstraints);
List<MethodConstraint> methodConstraints = FamilyOfGeneratedGenerics.getMethodConstraints(fillConstraintsList(),fillPosOfTphs());
System.out.println("MethodConstraints: " + methodConstraints);
List<TPHConstraint> testCons;
}
}
*/

@ -1,61 +0,0 @@
package insertGenerics;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.insertGenerics.*;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class TestExample42_allInOneMethod {
public List<TPHConstraint> fillConstraintsList() {
List<TPHConstraint> cs = new ArrayList<>();
cs.add(new TPHConstraint("M", "N", Relation.EXTENDS));
cs.add(new TPHConstraint("N", "Z", Relation.EXTENDS));
cs.add(new TPHConstraint("Q", "K", Relation.EXTENDS));
cs.add(new TPHConstraint("K", "P", Relation.EXTENDS));
cs.add(new TPHConstraint("W", "M", Relation.EXTENDS));
cs.add(new TPHConstraint("Z", "V", Relation.EXTENDS));
return cs;
}
public HashMap<String, PairTphMethod<PositionFinder.Position, String>> fillPosOfTphs() {
HashMap<String, PairTphMethod<PositionFinder.Position, String>> posOfTphs = new HashMap<>();
// TPHs "U" und "L" auskommentiert, da nach Vorgaben L zu Z umbenannt und U als void interpretiert wird
PairTphMethod<PositionFinder.Position, String> posOfK = new PairTphMethod<>(PositionFinder.Position.FIELD, null);
// PairTphMethod<PositionFinder.Position, String> posOfL = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod");
PairTphMethod<PositionFinder.Position, String> posOfM = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod");
PairTphMethod<PositionFinder.Position, String> posOfN = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod");
PairTphMethod<PositionFinder.Position, String> posOfP = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod");
PairTphMethod<PositionFinder.Position, String> posOfQ = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod");
// PairTphMethod<PositionFinder.Position, String> posOfU = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod");
PairTphMethod<PositionFinder.Position, String> posOfV = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod");
PairTphMethod<PositionFinder.Position, String> posOfW = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod");
PairTphMethod<PositionFinder.Position, String> posOfZ = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod");
posOfTphs.put("K", posOfK);
// posOfTphs.put("L", posOfL);
posOfTphs.put("M", posOfM);
posOfTphs.put("N", posOfN);
posOfTphs.put("P", posOfP);
posOfTphs.put("Q", posOfQ);
// posOfTphs.put("U", posOfU);
posOfTphs.put("V", posOfV);
posOfTphs.put("W", posOfW);
posOfTphs.put("Z", posOfZ);
return posOfTphs;
}
@Test
public void genericTest() {
// List<ClassConstraint> classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(fillConstraintsList(),fillPosOfTphs());
// System.out.println("ClassConstraints: " + classConstraints);
// List<MethodConstraint> methodConstraints = FamilyOfGeneratedGenerics.getMethodConstraints(fillConstraintsList(),classConstraints,fillPosOfTphs(),);
// System.out.println("MethodConstraints: " + methodConstraints);
List<TPHConstraint> testCons;
}
}

@ -1,99 +0,0 @@
package insertGenerics;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint;
import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics;
import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestGGFinder {
private static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/insertGenericsJav/";
private String pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
private static ClassLoader loader;
private static Class<?> classToTest;
private static Object instanceOfClass;
private static String className = "TestGGFinder";
@BeforeClass
public static void resetNamesOfTypePlaceholder() {
de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset();
}
@Test
public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
execute(new File(rootDirectory+className+".jav"));
}
private static class TestResultSet{
}
public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
JavaTXCompiler compiler = new JavaTXCompiler(fileToTest);
List<ResultSet> results = compiler.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results);
List<ClassConstraint> classConstraintsTest = new ArrayList<>();
classConstraintsTest.add(new ClassConstraint("S", "java/lang/Object", Relation.EXTENDS));
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionTest = new HashMap<>();
Set<MethodConstraint> lmc;
lmc = new HashSet<>();
lmc.add(new MethodConstraint("P", "AC", Relation.EXTENDS));
lmc.add(new MethodConstraint("AC", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH ACid(TPH P)", lmc);
lmc = new HashSet<>();
lmc.add(new MethodConstraint("T", "S", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH SsetA(TPH T)", lmc);
lmc = new HashSet<>();
lmc.add(new MethodConstraint("AC", "Y", Relation.EXTENDS));
lmc.add(new MethodConstraint("Z", "P", Relation.EXTENDS));
lmc.add(new MethodConstraint("P", "AC", Relation.EXTENDS));
lmc.add(new MethodConstraint("Y", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("voidm(TPH YTPH Z)", lmc);
FamilyOfGeneratedGenerics fogg = compiler.fogg;
Set<ClassConstraint> computedClassCons = new HashSet<>(fogg.classConstraints);
Set<ClassConstraint> expectedClassCons = new HashSet<>(classConstraintsTest);
assertEquals(expectedClassCons, computedClassCons);
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionComputed = new HashMap<>();
fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l)));
assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed);
compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles);
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass(className);
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
return new TestResultSet();
}
}

@ -1,112 +0,0 @@
package insertGenerics;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint;
import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics;
import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestLocalVarLambda {
private static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/insertGenericsJav/";
private String pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
private static ClassLoader loader;
private static Class<?> classToTest;
private static Object instanceOfClass;
private static String className = "TestLocalVarLambda";
@BeforeClass
public static void resetNamesOfTypePlaceholder() {
de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset();
}
@Test
public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
execute(new File(rootDirectory+className+".jav"));
}
private static class TestResultSet{
}
public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
JavaTXCompiler compiler = new JavaTXCompiler(fileToTest);
List<ResultSet> results = compiler.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results);
List<ClassConstraint> classConstraintsTest = new ArrayList<>();
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionTest = new HashMap<>();
FamilyOfGeneratedGenerics fogg = compiler.fogg;
Set<MethodConstraint> lmc;
lmc = new HashSet<>();
if (fogg.allConstraints.contains((new MethodConstraint("O", "ALU", Relation.EXTENDS)))) {
lmc.add(new MethodConstraint("O", "ALU", Relation.EXTENDS));
lmc.add(new MethodConstraint("DIU", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("ALU", "DIU", Relation.EXTENDS));
lmc.add(new MethodConstraint("SY", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH DIUm(TPH O)", lmc);
}
else if (fogg.allConstraints.contains((new MethodConstraint("O", "DIV", Relation.EXTENDS)))) {
lmc.add(new MethodConstraint("O", "DIV", Relation.EXTENDS));
lmc.add(new MethodConstraint("N", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("DIV", "N", Relation.EXTENDS));
lmc.add(new MethodConstraint("SY", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH Nm(TPH O)", lmc);
}
else
{
lmc.add(new MethodConstraint("O", "DIU", Relation.EXTENDS));
lmc.add(new MethodConstraint("N", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("DIU", "N", Relation.EXTENDS));
lmc.add(new MethodConstraint("SY", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH Nm(TPH O)", lmc);
}
Set<ClassConstraint> computedClassCons = new HashSet<>(fogg.classConstraints);
Set<ClassConstraint> expectedClassCons = new HashSet<>(classConstraintsTest);
assertEquals(expectedClassCons, computedClassCons);
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionComputed = new HashMap<>();
fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l)));
assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed);
compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles);
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass(className);
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
return new TestResultSet();
}
}

@ -1,126 +0,0 @@
package insertGenerics;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint;
import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics;
import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestMutualRecursion {
private static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/insertGenericsJav/";
private String pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
private static ClassLoader loader;
private static Class<?> classToTest;
private static Object instanceOfClass;
private static String className;
@BeforeClass
public static void resetNamesOfTypePlaceholder() {
de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset();
}
@Test
public void TestMutualRecursion1() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
className = "TestMutualRecursion";
JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+className+".jav"));
List<ResultSet> results = compiler.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results);
List<ClassConstraint> classConstraintsTest = new ArrayList<>();
classConstraintsTest.add(new ClassConstraint("N", "java/lang/Object", Relation.EXTENDS));
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionTest = new HashMap<>();
Set<MethodConstraint> lmc;
lmc = new HashSet<>();
lmc.add(new MethodConstraint("P", "Q", Relation.EXTENDS));
lmc.add(new MethodConstraint("Q", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AL", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH ALid(TPH P)", lmc);
lmc = new HashSet<>();
lmc.add(new MethodConstraint("AL", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("Z", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH ALm(TPH ALTPH Z)", lmc);
lmc = new HashSet<>();
lmc.add(new MethodConstraint("AG", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AH", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AL", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH ALmain(TPH AGTPH AH)", lmc);
FamilyOfGeneratedGenerics fogg = compiler.fogg;
Set<ClassConstraint> computedClassCons = new HashSet<>(fogg.classConstraints);
Set<ClassConstraint> expectedClassCons = new HashSet<>(classConstraintsTest);
assertEquals(expectedClassCons, computedClassCons);
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionComputed = new HashMap<>();
fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l)));
assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed);
compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles);
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass(className);
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
}
@Test
public void TestMutualRecursionWithField() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
className = "TestMutualRecursionWithField";
execute(new File(rootDirectory+className+".jav"));
}
@Test
public void TestMutualRecursionWithField2() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
className = "TestMutualRecursionWithField2";
execute(new File(rootDirectory+className+".jav"));
}
@Test
public void TestMutualRecursionWithField3() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
className = "TestMutualRecursionWithField3";
execute(new File(rootDirectory+className+".jav"));
}
private static class TestResultSet{
}
public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
JavaTXCompiler compiler = new JavaTXCompiler(fileToTest);
List<ResultSet> results = compiler.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results);
compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles);
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass(className);
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
return new TestResultSet();
}
}

@ -1,79 +0,0 @@
package insertGenerics;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestReturnVar {
public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/insertGenericsJav/";
@BeforeClass
public static void resetNamesOfTypePlaceholder() {
de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset();
}
@Test
public void ggFinder() throws IOException, ClassNotFoundException {
execute(new File(rootDirectory+"TestReturnVar.jav"));
}
private static class TestResultSet{
}
public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException {
JavaTXCompiler compiler = new JavaTXCompiler(fileToTest);
for(File f : compiler.sourceFiles.keySet()){
SourceFile sf = compiler.sourceFiles.get(f);
}
List<ResultSet> results = compiler.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results);
//compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles);
for(File f : compiler.sourceFiles.keySet()){
SourceFile sf = compiler.sourceFiles.get(f);
System.out.println(ASTTypePrinter.print(sf));
System.out.println(ASTPrinter.print(sf));
//List<ResultSet> results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen
assert results.size()>0;
Set<String> insertedTypes = new HashSet<>();
for(ResultSet resultSet : results){
Set<TypeInsert> result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, results, simplifyResultsForAllSourceFiles);
assert result.size()>0;
String content = readFile(f.getPath(), StandardCharsets.UTF_8);
for(TypeInsert tip : result){
insertedTypes.add(tip.insert(content));
}
}
for(String s : insertedTypes){
System.out.println(s);
}
}
return new TestResultSet();
}
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}

@ -1,79 +0,0 @@
package insertGenerics;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestSecondLineOfClassConstraints {
public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/insertGenericsJav/";
@BeforeClass
public static void resetNamesOfTypePlaceholder() {
de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset();
}
@Test
public void ggFinder() throws IOException, ClassNotFoundException {
execute(new File(rootDirectory+"TestSecondLineOfClassConstraints.jav"));
}
private static class TestResultSet{
}
public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException {
JavaTXCompiler compiler = new JavaTXCompiler(fileToTest);
for(File f : compiler.sourceFiles.keySet()){
SourceFile sf = compiler.sourceFiles.get(f);
}
List<ResultSet> results = compiler.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results);
//compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles);
for(File f : compiler.sourceFiles.keySet()){
SourceFile sf = compiler.sourceFiles.get(f);
System.out.println(ASTTypePrinter.print(sf));
System.out.println(ASTPrinter.print(sf));
//List<ResultSet> results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen
assert results.size()>0;
Set<String> insertedTypes = new HashSet<>();
for(ResultSet resultSet : results){
Set<TypeInsert> result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, results, simplifyResultsForAllSourceFiles);
assert result.size()>0;
String content = readFile(f.getPath(), StandardCharsets.UTF_8);
for(TypeInsert tip : result){
insertedTypes.add(tip.insert(content));
}
}
for(String s : insertedTypes){
System.out.println(s);
}
}
return new TestResultSet();
}
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}

@ -1,154 +0,0 @@
package insertGenerics;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint;
import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics;
import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestTPHsAndGenerics {
private static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/insertGenericsJav/";
private String pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
private static ClassLoader loader;
private static Class<?> classToTest;
private static Object instanceOfClass;
private static String className = "TestTPHsAndGenerics";
@BeforeClass
public static void resetNamesOfTypePlaceholder() {
de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset();
}
@Test
public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
execute(new File(rootDirectory+className+".jav"));
}
private static class TestResultSet{
}
public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
JavaTXCompiler compiler = new JavaTXCompiler(fileToTest);
List<ResultSet> results = compiler.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results);
List<ClassConstraint> classConstraintsTest = new ArrayList<>();
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionTest = new HashMap<>();
FamilyOfGeneratedGenerics fogg = compiler.fogg;
Set<MethodConstraint> lmc;
lmc = new HashSet<>();
if (fogg.allConstraints.contains((new MethodConstraint("DZP", "ETW", Relation.EXTENDS)))) {
classConstraintsTest.add(new ClassConstraint("UD", "DZP", Relation.EXTENDS));
classConstraintsTest.add(new ClassConstraint("DZP", "ETW", Relation.EXTENDS));
classConstraintsTest.add(new ClassConstraint("ETW", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AI", "AE", Relation.EXTENDS));
lmc.add(new MethodConstraint("AD", "AI", Relation.EXTENDS));
//lmc.add(new MethodConstraint("AB", "AM", Relation.EXTENDS));
lmc.add(new MethodConstraint("AE", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AB", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH ABm(TPH ABTPH AD)", lmc);
lmc = new HashSet<>();
lmc.add(new MethodConstraint("V", "UD", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH ETWid2(TPH V)", lmc);
lmc = new HashSet<>();
lmc.add(new MethodConstraint("AM", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AI", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH AIm2(TPH AMTPH AI)", lmc);
} else {
if (fogg.allConstraints.contains((new MethodConstraint("DZP", "U", Relation.EXTENDS)))) {
classConstraintsTest.add(new ClassConstraint("ETW", "DZP", Relation.EXTENDS));
classConstraintsTest.add(new ClassConstraint("DZP", "U", Relation.EXTENDS));
classConstraintsTest.add(new ClassConstraint("U", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AI", "AE", Relation.EXTENDS));
lmc.add(new MethodConstraint("AD", "AI", Relation.EXTENDS));
//lmc.add(new MethodConstraint("AB", "AM", Relation.EXTENDS));
lmc.add(new MethodConstraint("AE", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AB", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH ABm(TPH ABTPH AD)", lmc);
lmc = new HashSet<>();
lmc.add(new MethodConstraint("V", "ETW", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH Uid2(TPH V)", lmc);
lmc = new HashSet<>();
lmc.add(new MethodConstraint("AM", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AI", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH AIm2(TPH AMTPH AI)", lmc);
} else {
if (fogg.allConstraints.contains((new MethodConstraint("EIM", "FEA", Relation.EXTENDS)))) {
classConstraintsTest.add(new ClassConstraint("VK", "EIM", Relation.EXTENDS));
classConstraintsTest.add(new ClassConstraint("EIM", "FEA", Relation.EXTENDS));
classConstraintsTest.add(new ClassConstraint("FEA", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AI", "AE", Relation.EXTENDS));
lmc.add(new MethodConstraint("AD", "AI", Relation.EXTENDS));
//lmc.add(new MethodConstraint("AB", "AM", Relation.EXTENDS));
lmc.add(new MethodConstraint("AE", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AB", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH ABm(TPH ABTPH AD)", lmc);
lmc = new HashSet<>();
lmc.add(new MethodConstraint("V", "VK", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH FEAid2(TPH V)", lmc);
lmc = new HashSet<>();
lmc.add(new MethodConstraint("AM", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AI", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH AIm2(TPH AMTPH AI)", lmc);
}
}
}
Set<ClassConstraint> computedClassCons = new HashSet<>(fogg.classConstraints);
Set<ClassConstraint> expectedClassCons = new HashSet<>(classConstraintsTest);
assertEquals(expectedClassCons, computedClassCons);
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionComputed = new HashMap<>();
fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l)));
assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed);
/*
compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles);
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass(className);
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
*/
return new TestResultSet();
}
}

@ -1,79 +0,0 @@
package insertGenerics;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestTPHsAndGenerics2 {
public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/insertGenericsJav/";
@BeforeClass
public static void resetNamesOfTypePlaceholder() {
de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset();
}
@Test
public void ggFinder() throws IOException, ClassNotFoundException {
execute(new File(rootDirectory+"TestTPHSAndGenerics2.jav"));
}
private static class TestResultSet{
}
public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException {
JavaTXCompiler compiler = new JavaTXCompiler(fileToTest);
for(File f : compiler.sourceFiles.keySet()){
SourceFile sf = compiler.sourceFiles.get(f);
}
List<ResultSet> results = compiler.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results);
//compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles);
for(File f : compiler.sourceFiles.keySet()){
SourceFile sf = compiler.sourceFiles.get(f);
System.out.println(ASTTypePrinter.print(sf));
System.out.println(ASTPrinter.print(sf));
//List<ResultSet> results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen
assert results.size()>0;
Set<String> insertedTypes = new HashSet<>();
for(ResultSet resultSet : results){
Set<TypeInsert> result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, results, simplifyResultsForAllSourceFiles);
assert result.size()>0;
String content = readFile(f.getPath(), StandardCharsets.UTF_8);
for(TypeInsert tip : result){
insertedTypes.add(tip.insert(content));
}
}
for(String s : insertedTypes){
System.out.println(s);
}
}
return new TestResultSet();
}
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}

@ -1,99 +0,0 @@
package insertGenerics;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint;
import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics;
import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestThreeArgs {
private static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/insertGenericsJav/";
private String pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
private static ClassLoader loader;
private static Class<?> classToTest;
private static Object instanceOfClass;
private static String className = "TestThreeArgs";
@BeforeClass
public static void resetNamesOfTypePlaceholder() {
de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset();
}
@Test
public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
execute(new File(rootDirectory+className+".jav"));
}
private static class TestResultSet{
}
public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
JavaTXCompiler compiler = new JavaTXCompiler(fileToTest);
List<ResultSet> results = compiler.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results);
List<ClassConstraint> classConstraintsTest = new ArrayList<>();
classConstraintsTest.add(new ClassConstraint("N", "java/lang/Object", Relation.EXTENDS));
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionTest = new HashMap<>();
Set<MethodConstraint> lmc;
lmc = new HashSet<>();
lmc.add(new MethodConstraint("P", "AF", Relation.EXTENDS));
lmc.add(new MethodConstraint("Q", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("AF", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH AFid(TPH P)", lmc);
lmc = new HashSet<>();
lmc.add(new MethodConstraint("AF", "W", Relation.EXTENDS));
lmc.add(new MethodConstraint("AB", "P", Relation.EXTENDS));
lmc.add(new MethodConstraint("P", "AF", Relation.EXTENDS));
lmc.add(new MethodConstraint("AC", "java/lang/Object", Relation.EXTENDS));
lmc.add(new MethodConstraint("W", "java/lang/Object", Relation.EXTENDS));
methodConstraintsWithPositionTest.put("TPH Wm(TPH WTPH ABTPH AC)", lmc);
FamilyOfGeneratedGenerics fogg = compiler.fogg;
Set<ClassConstraint> computedClassCons = new HashSet<>(fogg.classConstraints);
Set<ClassConstraint> expectedClassCons = new HashSet<>(classConstraintsTest);
assertEquals(expectedClassCons, computedClassCons);
HashMap<String, Set<MethodConstraint>> methodConstraintsWithPositionComputed = new HashMap<>();
fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l)));
assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed);
compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles);
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass(className);
//liefert Fehler, da Variable "a" nicht initialisiert ist.
//instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
return new TestResultSet();
}
}

Some files were not shown because too many files have changed in this diff Show More