Merge branch 'targetBytecode' of https://gitea.hb.dhbw-stuttgart.de/JavaTX/JavaCompilerCore into targetBytecode

This commit is contained in:
pl@gohorb.ba-horb.de 2024-05-27 17:44:29 +02:00
commit 5d03995f10
30 changed files with 286 additions and 121 deletions

12
pom.xml
View File

@ -29,14 +29,14 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<version>2.6</version> <version>2.6</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>io.github.classgraph</groupId>
<artifactId>guava</artifactId> <artifactId>classgraph</artifactId>
<version>22.0</version> <version>4.8.172</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.reflections</groupId> <groupId>com.google.guava</groupId>
<artifactId>reflections</artifactId> <artifactId>guava</artifactId>
<version>0.9.11</version> <version>33.2.0-jre</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm --> <!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<dependency> <dependency>

View File

@ -2,9 +2,7 @@ class Box<A> {
A a; A a;
Box(A a) { public Box(A a) {
this.a = a; this.a = a;
} }
} }

View File

@ -1,7 +1,9 @@
class B { } public class Box<A> {
class Box_Main extends B {
m(b) { A a;
b.m(new Box_Main());
b.m(new B()); public Box() { }
} public Box(A a) {
} //this.a = a;
}
}

View File

@ -0,0 +1,11 @@
import java.lang.String;
public class Bug333 {
public static String Bar = "Bar";
}
class Bar {
public bar() {
String s = Bug333.Bar;
}
}

View File

@ -0,0 +1,11 @@
import java.util.List;
import java.lang.Integer;
import java.lang.String;
import java.lang.Object;
import java.util.List;
public class Bug338 {
public hashCode() {
return List.of(42);
}
}

View File

@ -0,0 +1,5 @@
import java.lang.*;
public class ImportWildcard {
m(a, b) { return a * b; }
}

View File

@ -9,4 +9,13 @@ public class While {
} }
return x; return x;
} }
public m2() {
int i = 0;
do {
++i;
} while(i < 10);
return i;
}
} }

View File

@ -978,6 +978,27 @@ public class Codegen {
mv.visitLabel(end); mv.visitLabel(end);
break; break;
} }
case TargetDo _do: {
Label start = new Label();
Label end = new Label();
Label check = new Label();
var env = new BreakEnv();
env.startLabel = check;
env.endLabel = end;
mv.visitLabel(start);
state.breakStack.push(env);
generate(state, _do.body());
state.breakStack.pop();
mv.visitLabel(check);
generate(state, _do.cond());
mv.visitJumpInsn(IFEQ, end);
mv.visitJumpInsn(GOTO, start);
mv.visitLabel(end);
break;
}
case TargetIf _if: { case TargetIf _if: {
generate(state, _if.cond()); generate(state, _if.cond());
Label _else = new Label(); Label _else = new Label();

View File

@ -98,7 +98,7 @@ public class JavaTXCompiler {
} }
if (outputPath != null) path.add(outputPath); if (outputPath != null) path.add(outputPath);
classLoader = new DirectoryClassLoader(path, ClassLoader.getSystemClassLoader()); classLoader = new DirectoryClassLoader(path, ClassLoader.getSystemClassLoader());
environment = new CompilationEnvironment(sources); environment = new CompilationEnvironment(sources, classLoader);
classPath = path; classPath = path;
this.outputPath = outputPath; this.outputPath = outputPath;

View File

@ -34,7 +34,7 @@ public class CompilationEnvironment {
* *
* @param sourceFiles die zu kompilierenden Dateien * @param sourceFiles die zu kompilierenden Dateien
*/ */
public CompilationEnvironment(List<File> sourceFiles) { public CompilationEnvironment(List<File> sourceFiles, DirectoryClassLoader classLoader) {
/** /**
* Java 9 bringt einige Änderungen am Classloader So funktioniert der BootClassLoader nicht mehr. hier gibts ein paar Quellen zum nachlesen: http://java9.wtf/class-loading/ https://stackoverflow.com/questions/46494112/classloaders-hierarchy-in-java-9 * Java 9 bringt einige Änderungen am Classloader So funktioniert der BootClassLoader nicht mehr. hier gibts ein paar Quellen zum nachlesen: http://java9.wtf/class-loading/ https://stackoverflow.com/questions/46494112/classloaders-hierarchy-in-java-9
* *
@ -54,7 +54,7 @@ public class CompilationEnvironment {
// librarys = Arrays.asList(loader.getURLs()); // librarys = Arrays.asList(loader.getURLs());
this.sourceFiles = sourceFiles; this.sourceFiles = sourceFiles;
this.packageCrawler = new PackageCrawler(librarys); this.packageCrawler = new PackageCrawler(classLoader);
} }
public void addClassesToRegistry(JavaClassRegistry registry, SourceFileContext tree, File sourceFile, JavaTXCompiler compiler) throws ClassNotFoundException, IOException { public void addClassesToRegistry(JavaClassRegistry registry, SourceFileContext tree, File sourceFile, JavaTXCompiler compiler) throws ClassNotFoundException, IOException {
@ -104,12 +104,4 @@ public class CompilationEnvironment {
return packageName; return packageName;
} }
public List<ClassOrInterface> getAllAvailableClasses() {
List<ClassOrInterface> ret = new ArrayList<>();
for (Class c : new PackageCrawler(librarys).getAllAvailableClasses()) {
ret.add(ASTFactory.createClass(c));
}
return ret;
}
} }

View File

@ -5,31 +5,61 @@ import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.nio.file.Files; import java.nio.file.*;
import java.nio.file.Path; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class DirectoryClassLoader extends URLClassLoader implements IByteArrayClassLoader { public class DirectoryClassLoader extends URLClassLoader implements IByteArrayClassLoader {
public DirectoryClassLoader(File directory, java.lang.ClassLoader parent) { // public DirectoryClassLoader(File directory, java.lang.ClassLoader parent) {
super(generateURLArray(dirToURL(directory)), parent); // super(generateURLArray(dirToURL(directory)), parent);
} // }
public DirectoryClassLoader(List<File> directory, java.lang.ClassLoader parent) { public DirectoryClassLoader(List<File> directory, java.lang.ClassLoader parent) {
super(directory.stream().map(DirectoryClassLoader::dirToURL).collect(Collectors.toList()).toArray(new URL[0]), parent); super(directory.stream().map(DirectoryClassLoader::dirToURL).flatMap(List::stream).collect(Collectors.toList()).toArray(new URL[0]), parent.getParent());
} }
private static URL[] generateURLArray(URL url) { private static URL[] generateURLArray(URL url) {
return new URL[]{url}; return new URL[]{url};
} }
private static URL dirToURL(File url){ private static List<URL> dirToURL(File file) {
if(!url.isDirectory())throw new RuntimeException(url.toString() + " is not a directory"); //if(!url.isDirectory())throw new RuntimeException(url.toString() + " is not a directory");
try {
return url.toURI().toURL(); Path dir;
} catch (MalformedURLException e) { if (file.isDirectory()) {
throw new RuntimeException(e); try {
return List.of(file.toURI().toURL()); // if file is a directory, use it as is
} catch (MalformedURLException e) {
e.printStackTrace();
return List.of();
}
} }
dir = file.toPath().getParent(); // if file is not a directory, get its parent directory
String pattern = file.toPath().getFileName().toString(); // use the file name as a glob pattern
List<URL> urls = new ArrayList<>();
try {
urls = Files.walk(dir)
.filter(Files::isRegularFile) // only consider files (not directories)
.filter(path -> {
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
return matcher.matches(path.getFileName()); // match the file name against the pattern
})
.map(path -> {
try {
return path.toUri().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}) // convert the path to a URL
.toList(); // print the path of each matching file
} catch (IOException | RuntimeException e) {
e.printStackTrace();
}
return urls;
} }
@Override @Override

View File

@ -1,17 +1,10 @@
package de.dhbwstuttgart.environment; package de.dhbwstuttgart.environment;
import java.net.URL; import io.github.classgraph.ClassGraph;
import io.github.classgraph.ScanResult;
import java.util.*; import java.util.*;
import org.reflections.Reflections;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import org.reflections.vfs.SystemDir;
/** /**
* Hilft beim Durchsuchen von Packages * Hilft beim Durchsuchen von Packages
* Benutzt die Reflections-Library (https://github.com/ronmamo/reflections) * Benutzt die Reflections-Library (https://github.com/ronmamo/reflections)
@ -19,48 +12,30 @@ import org.reflections.vfs.SystemDir;
*/ */
public class PackageCrawler { public class PackageCrawler {
final URL[] urls; final DirectoryClassLoader classLoader;
public PackageCrawler(List<URL> urlList) { public PackageCrawler(DirectoryClassLoader classLoader) {
urls = urlList.toArray(new URL[0]); this.classLoader = classLoader;
} }
public Set<Class<?>> getClassesInPackage(String packageName){ public Set<Class<?>> getClassesInPackage(String packageName) {
/* var res = new HashSet<Class<?>>();
List<DirectoryClassLoader> classLoadersList = new LinkedList<DirectoryClassLoader>();
classLoadersList.add(Thread.currentThread().getContextClassLoader());
classLoadersList.add(ClasspathHelper.staticClassLoader());
classLoadersList.add(Thread.currentThread().getContextClassLoader().getParent());
classLoadersList.add(DirectoryClassLoader.getSystemClassLoader());
String bootClassPath = System.getProperty("sun.boot.class.path");
ArrayList<URL> urlList = new ArrayList<>();
for(String path : bootClassPath.split(";")) {
try {
urlList.add(new URL("file:"+path));
} catch (MalformedURLException e) {
new DebugException("Fehler im Classpath auf diesem System");
}
}
URL[] urls = urlList.toArray(new URL[0]);
classLoadersList.add(new URLClassLoader(urls, DirectoryClassLoader.getSystemClassLoader()));
*/
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
.setUrls(urls)
.filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName))));
Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); try (ScanResult result = new ClassGraph()
.enableClassInfo()
.enableSystemJarsAndModules()
.addClassLoader(classLoader)
.acceptPackages(packageName)
.scan()) {
return classes; for (var info : result.getAllClasses()) {
} try {
var clazz = Class.forName(info.getName());
res.add(clazz);
} catch (ClassNotFoundException ignored) {}
}
};
public Set<Class<?>> getAllAvailableClasses(){ return res;
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
.setUrls(urls));
Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);
return classes;
} }
public Map<String, Integer> getClassNames(String packageName){ public Map<String, Integer> getClassNames(String packageName){

View File

@ -597,8 +597,12 @@ public class StatementGenerator {
} }
private Statement convert(Java17Parser.ContinuestmtContext stmt) { private Statement convert(Java17Parser.ContinuestmtContext stmt) {
// TODO Token offset = stmt.getStart();
throw new NotImplementedException(); if (!Objects.isNull(stmt.identifier())) {
return new Continue(localVars.get(stmt.identifier().getText()), offset);
} else {
return new Continue(TypePlaceholder.fresh(offset), offset);
}
} }
private Statement convert(Java17Parser.SemistmtContext stmt) { private Statement convert(Java17Parser.SemistmtContext stmt) {
@ -804,6 +808,7 @@ public class StatementGenerator {
// Check for Classname: // Check for Classname:
if (reg.contains(whole)) { if (reg.contains(whole)) {
receiver = generateStaticClassName(whole, offset); receiver = generateStaticClassName(whole, offset);
break;
} }
whole += "."; whole += ".";
} }

View File

@ -71,10 +71,6 @@ import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.syntaxtree.type.Void; import de.dhbwstuttgart.syntaxtree.type.Void;
import de.dhbwstuttgart.typeinference.constraints.GenericsResolver;
import javassist.compiler.SyntaxError;
import javax.swing.text.html.Option;
public class SyntaxTreeGenerator { public class SyntaxTreeGenerator {
private JavaClassRegistry reg; private JavaClassRegistry reg;

View File

@ -236,6 +236,11 @@ public abstract class AbstractASTWalker implements ASTVisitor {
aBreak.accept(this); aBreak.accept(this);
} }
@Override
public void visit(Continue aContinue) {
aContinue.accept(this);
}
@Override @Override
public void visit(StaticClassName staticClassName) { public void visit(StaticClassName staticClassName) {

View File

@ -53,6 +53,8 @@ public interface StatementVisitor {
void visit(Break aBreak); void visit(Break aBreak);
void visit(Continue aContinue);
void visit(Yield aYield); void visit(Yield aYield);
void visit(StaticClassName staticClassName); void visit(StaticClassName staticClassName);

View File

@ -0,0 +1,18 @@
package de.dhbwstuttgart.syntaxtree.statement;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import org.antlr.v4.runtime.Token;
public class Continue extends Statement {
public Continue(RefTypeOrTPHOrWildcardOrGeneric type, Token offset) {
super(type, offset);
}
@Override
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}

View File

@ -333,6 +333,11 @@ public class OutputGenerator implements ASTVisitor {
out.append("break"); out.append("break");
} }
@Override
public void visit(Continue aContinue) {
out.append("continue");
}
@Override @Override
public void visit(StaticClassName staticClassName) { public void visit(StaticClassName staticClassName) {

View File

@ -1,5 +1,6 @@
package de.dhbwstuttgart.target.generate; package de.dhbwstuttgart.target.generate;
import de.dhbwstuttgart.bytecode.CodeGenException;
import de.dhbwstuttgart.bytecode.FunNGenerator; import de.dhbwstuttgart.bytecode.FunNGenerator;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import de.dhbwstuttgart.environment.ByteArrayClassLoader;
@ -160,11 +161,11 @@ public class ASTToTargetAST {
var superInterfaces = input.getSuperInterfaces().stream().map(clazz -> convert(clazz, generics.javaGenerics)).toList(); var superInterfaces = input.getSuperInterfaces().stream().map(clazz -> convert(clazz, generics.javaGenerics)).toList();
var constructors = input.getConstructors().stream().map(constructor -> this.convert(input, constructor, finalFieldInitializer)).flatMap(List::stream).toList(); var constructors = input.getConstructors().stream().map(constructor -> this.convert(input, constructor, finalFieldInitializer)).flatMap(List::stream).toList();
var fields = input.getFieldDecl().stream().map(this::convert).toList(); var fields = input.getFieldDecl().stream().map(this::convert).toList();
var methods = groupOverloads(input.getMethods()).stream().map(m -> convert(input, m)).flatMap(List::stream).toList(); var methods = groupOverloads(input.getMethods()).stream().map(m -> convert(input, m)).flatMap(Set::stream).toList();
TargetMethod staticConstructor = null; TargetMethod staticConstructor = null;
if (input.getStaticInitializer().isPresent()) if (input.getStaticInitializer().isPresent())
staticConstructor = this.convert(input, input.getStaticInitializer().get()).get(0); staticConstructor = this.convert(input, input.getStaticInitializer().get()).stream().findFirst().orElseThrow();
if (input instanceof Record) if (input instanceof Record)
return new TargetRecord(input.getModifiers(), input.getClassName(), javaGenerics, txGenerics, superInterfaces, constructors, staticConstructor, fields, methods); return new TargetRecord(input.getModifiers(), input.getClassName(), javaGenerics, txGenerics, superInterfaces, constructors, staticConstructor, fields, methods);
@ -289,11 +290,11 @@ public class ASTToTargetAST {
return res.toString(); return res.toString();
} }
private List<TargetMethod> convert(ClassOrInterface clazz, List<Method> overloadedMethods) { private Set<TargetMethod> convert(ClassOrInterface clazz, List<Method> overloadedMethods) {
if (overloadedMethods.size() == 1) { if (overloadedMethods.size() == 1) {
return convert(clazz, overloadedMethods.get(0)); return convert(clazz, overloadedMethods.getFirst());
} }
var res = new ArrayList<Method>(); var methods = new ArrayList<Method>();
for (var method : overloadedMethods) { for (var method : overloadedMethods) {
var newMethod = new Method( var newMethod = new Method(
method.modifier, method.modifier,
@ -305,7 +306,7 @@ public class ASTToTargetAST {
method.getGenerics(), method.getGenerics(),
method.getOffset() method.getOffset()
); );
res.add(newMethod); methods.add(newMethod);
} }
// TODO Record overloading // TODO Record overloading
@ -328,7 +329,15 @@ public class ASTToTargetAST {
var entryPoint = new Method(template.modifier, template.name, template.getReturnType(), params, block, template.getGenerics(), new NullToken()); var entryPoint = new Method(template.modifier, template.name, template.getReturnType(), params, block, template.getGenerics(), new NullToken());
res.add(entryPoint); // TODO*/ res.add(entryPoint); // TODO*/
return res.stream().map(m -> convert(clazz, m)).flatMap(List::stream).toList(); var res = new HashSet<TargetMethod>();
for (var method : methods) {
var overloads = convert(clazz, method);
for (var overload : overloads) {
if (res.contains(overload)) throw new CodeGenException("Duplicate method found: " + overload.name() + " with signature " + overload.signature().getSignature());
res.add(overload);
}
}
return res;
} }
private Expression makeRecordSwitch(RefTypeOrTPHOrWildcardOrGeneric returnType, ParameterList params, List<Method> overloadedMethods) { private Expression makeRecordSwitch(RefTypeOrTPHOrWildcardOrGeneric returnType, ParameterList params, List<Method> overloadedMethods) {
@ -366,16 +375,15 @@ public class ASTToTargetAST {
for (var i = 0; i < params.size(); i++) { for (var i = 0; i < params.size(); i++) {
var a = TargetType.toPrimitive(params.get(i).pattern().type()); var a = TargetType.toPrimitive(params.get(i).pattern().type());
var b = convert(sParams.getFormalparalist().get(i).getType()); var b = convert(sParams.getFormalparalist().get(i).getType());
System.out.println(a + " " + b);
if (!Objects.equals(a, b)) return false; if (!Objects.equals(a, b)) return false;
} }
return true; return true;
}).findFirst(); }).findFirst();
} }
private List<TargetMethod> convert(ClassOrInterface currentClass, Method method) { private Set<TargetMethod> convert(ClassOrInterface currentClass, Method method) {
generics = all.get(0); generics = all.get(0);
List<TargetMethod> result = new ArrayList<>(); Set<TargetMethod> result = new HashSet<>();
Set<List<MethodParameter>> parameterSet = new HashSet<>(); Set<List<MethodParameter>> parameterSet = new HashSet<>();
for (var s : all) { for (var s : all) {
@ -387,8 +395,11 @@ public class ASTToTargetAST {
var superMethod = findSuperMethodToOverride(currentClass, method.getName(), params); var superMethod = findSuperMethodToOverride(currentClass, method.getName(), params);
if (superMethod.isPresent()) { if (superMethod.isPresent()) {
// If we find a super method to override, use its parameters and return types // If we find a super method to override, use its parameters and return types
returnType = convert(superMethod.get().getReturnType(), this.generics.javaGenerics); var newReturnType = convert(superMethod.get().getReturnType(), this.generics.javaGenerics);
params = convert(superMethod.get().getParameterList(), method.getParameterList(), this.generics.javaGenerics); if (newReturnType instanceof TargetPrimitiveType && TargetType.toPrimitive(returnType).equals(newReturnType)) {
returnType = newReturnType;
params = convert(superMethod.get().getParameterList(), method.getParameterList(), this.generics.javaGenerics);
}
} }
List<MethodParameter> finalParams = params; List<MethodParameter> finalParams = params;
@ -400,10 +411,12 @@ public class ASTToTargetAST {
var javaSignature = new TargetMethod.Signature(javaMethodGenerics, params, returnType); var javaSignature = new TargetMethod.Signature(javaMethodGenerics, params, returnType);
var txSignature = new TargetMethod.Signature(txMethodGenerics, txParams, convert(method.getReturnType(), this.generics.txGenerics)); var txSignature = new TargetMethod.Signature(txMethodGenerics, txParams, convert(method.getReturnType(), this.generics.txGenerics));
result.add(new TargetMethod(method.modifier, method.name, convert(method.block), javaSignature, txSignature)); var newMethod = new TargetMethod(method.modifier, method.name, convert(method.block), javaSignature, txSignature);
result.add(newMethod);
parameterSet.add(params); parameterSet.add(params);
} }
} }
return result; return result;
} }

View File

@ -228,6 +228,7 @@ public class StatementToTargetExpression implements ASTVisitor {
isInterface = receiverClass.isInterface(); isInterface = receiverClass.isInterface();
} }
System.out.println(argList);
result = new TargetMethodCall(converter.convert(methodCall.getType()), returnType, argList, converter.convert(methodCall.receiver), methodCall.getArgumentList().getArguments().stream().map(converter::convert).toList(), receiverType, methodCall.name, isStatic, isInterface, isPrivate); result = new TargetMethodCall(converter.convert(methodCall.getType()), returnType, argList, converter.convert(methodCall.receiver), methodCall.getArgumentList().getArguments().stream().map(converter::convert).toList(), receiverType, methodCall.name, isStatic, isInterface, isPrivate);
} }
@ -260,6 +261,11 @@ public class StatementToTargetExpression implements ASTVisitor {
result = new TargetBreak(); result = new TargetBreak();
} }
@Override
public void visit(Continue aContinue) {
result = new TargetContinue();
}
@Override @Override
public void visit(StaticClassName staticClassName) { public void visit(StaticClassName staticClassName) {
result = new TargetClassName(converter.convert(staticClassName.getType())); result = new TargetClassName(converter.convert(staticClassName.getType()));
@ -282,7 +288,7 @@ public class StatementToTargetExpression implements ASTVisitor {
@Override @Override
public void visit(DoStmt whileStmt) { public void visit(DoStmt whileStmt) {
throw new NotImplementedException(); result = new TargetDo(converter.convert(whileStmt.expr), converter.convert(whileStmt.loopBlock));
} }
// TODO These two might not be necessary // TODO These two might not be necessary

View File

@ -124,6 +124,11 @@ public abstract class TracingStatementVisitor implements StatementVisitor {
} }
@Override
public void visit(Continue aContinue) {
}
@Override @Override
public void visit(StaticClassName staticClassName) { public void visit(StaticClassName staticClassName) {

View File

@ -6,6 +6,7 @@ import de.dhbwstuttgart.target.tree.type.TargetType;
import org.objectweb.asm.Opcodes; import org.objectweb.asm.Opcodes;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.Set; import java.util.Set;
public record TargetMethod(int access, String name, TargetBlock block, Signature signature, Signature txSignature) { public record TargetMethod(int access, String name, TargetBlock block, Signature signature, Signature txSignature) {
@ -64,5 +65,16 @@ public record TargetMethod(int access, String name, TargetBlock block, Signature
public boolean isStatic() { public boolean isStatic() {
return (access & Opcodes.ACC_STATIC) != 0; return (access & Opcodes.ACC_STATIC) != 0;
} }
@Override
public boolean equals(Object other) {
if (!(other instanceof TargetMethod otherMethod)) return false;
return otherMethod.signature.equals(this.signature) && otherMethod.name.equals(this.name);
}
@Override
public int hashCode() {
return Objects.hash(name, signature);
}
} }

View File

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

View File

@ -3,7 +3,7 @@ package de.dhbwstuttgart.target.tree.expression;
import de.dhbwstuttgart.target.tree.type.*; import de.dhbwstuttgart.target.tree.type.*;
public sealed interface TargetExpression public sealed interface TargetExpression
permits TargetBinaryOp, TargetBlock, TargetBreak, TargetCast, TargetClassName, TargetContinue, TargetFieldVar, TargetFor, TargetForEach, TargetIf, TargetInstanceOf, TargetLambdaExpression, TargetLiteral, TargetLocalVar, TargetPattern, TargetReturn, TargetStatementExpression, TargetSuper, TargetSwitch, TargetTernary, TargetThis, TargetThrow, TargetUnaryOp, TargetVarDecl, TargetWhile, TargetYield { permits TargetBinaryOp, TargetBlock, TargetBreak, TargetCast, TargetClassName, TargetContinue, TargetDo, TargetFieldVar, TargetFor, TargetForEach, TargetIf, TargetInstanceOf, TargetLambdaExpression, TargetLiteral, TargetLocalVar, TargetPattern, TargetReturn, TargetStatementExpression, TargetSuper, TargetSwitch, TargetTernary, TargetThis, TargetThrow, TargetUnaryOp, TargetVarDecl, TargetWhile, TargetYield {
default TargetType type() { default TargetType type() {
return null; return null;

View File

@ -1,6 +1,4 @@
package de.dhbwstuttgart.target.tree.expression; package de.dhbwstuttgart.target.tree.expression;
import de.dhbwstuttgart.target.tree.type.TargetType;
public record TargetWhile(TargetExpression cond, TargetExpression body) implements TargetExpression { public record TargetWhile(TargetExpression cond, TargetExpression body) implements TargetExpression {
} }

View File

@ -35,7 +35,6 @@ public class TypeInferenceBlockInformation extends TypeInferenceInformation {
public ClassOrInterface getSuperClass() { public ClassOrInterface getSuperClass() {
for (var clazz : getAvailableClasses()) { for (var clazz : getAvailableClasses()) {
System.out.println(currentClass.getSuperClass().getName());
if (clazz.getClassName().equals(currentClass.getSuperClass().getName())) if (clazz.getClassName().equals(currentClass.getSuperClass().getName()))
return clazz; return clazz;
} }

View File

@ -514,6 +514,11 @@ public class TYPEStmt implements StatementVisitor {
} }
@Override
public void visit(Continue aContinue) {
}
@Override @Override
public void visit(StaticClassName staticClassName) { public void visit(StaticClassName staticClassName) {
// Hier entstehen keine Constraints // Hier entstehen keine Constraints
@ -569,7 +574,10 @@ public class TYPEStmt implements StatementVisitor {
@Override @Override
public void visit(DoStmt whileStmt) { public void visit(DoStmt whileStmt) {
throw new NotImplementedException(); RefType booleanType = new RefType(ASTFactory.createClass(java.lang.Boolean.class).getClassName(), new NullToken());
whileStmt.expr.accept(this);
constraintsSet.addUndConstraint(new Pair(whileStmt.expr.getType(), booleanType, PairOperator.EQUALSDOT, loc(whileStmt.expr.getOffset())));
whileStmt.loopBlock.accept(this);
} }
@Override @Override

View File

@ -1,6 +1,7 @@
import static org.junit.Assert.*; import static org.junit.Assert.*;
import static targetast.TestCodegen.generateClassFiles;
import java.io.File; import java.io.File;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -14,6 +15,7 @@ import org.junit.Test;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
public class AllgemeinTest { public class AllgemeinTest {
@ -63,6 +65,8 @@ public class AllgemeinTest {
//String className = "TripleTest"; //String className = "TripleTest";
//String className = "WildcardList"; //String className = "WildcardList";
//String className = "List"; //String className = "List";
//String className = "Box";
//String className = "GenBox";
String className = "Foo"; String className = "Foo";
//PL 2019-10-24: genutzt fuer unterschiedliche Tests //PL 2019-10-24: genutzt fuer unterschiedliche Tests
path = System.getProperty("user.dir")+"/resources/AllgemeinTest/" + className + ".jav"; path = System.getProperty("user.dir")+"/resources/AllgemeinTest/" + className + ".jav";
@ -75,7 +79,7 @@ public class AllgemeinTest {
Lists.newArrayList(new File(System.getProperty("user.dir")+"/resources/bytecode/classFiles/")), Lists.newArrayList(new File(System.getProperty("user.dir")+"/resources/bytecode/classFiles/")),
new File(System.getProperty("user.dir")+"/resources/bytecode/classFiles/")); new File(System.getProperty("user.dir")+"/resources/bytecode/classFiles/"));
//*/ //*/
compiler.generateBytecode(new File(path)); compiler.generateBytecode();
pathToClassFile = System.getProperty("user.dir")+"/resources/bytecode/classFiles/"; pathToClassFile = System.getProperty("user.dir")+"/resources/bytecode/classFiles/";
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass(className); classToTest = loader.loadClass(className);

View File

@ -606,10 +606,10 @@ public class TestComplete {
} }
@Test @Test
@Ignore("This one isn't working") //@Ignore("This one isn't working")
public void boxTest() throws Exception { public void boxTest() throws Exception {
var classFiles = generateClassFiles(new ByteArrayClassLoader(), "Box.jav"); var classFiles = generateClassFiles(new ByteArrayClassLoader(), "Box.jav");
var instance = classFiles.get("Box_Main").getDeclaredConstructor().newInstance(); var instance = classFiles.get("Box").getDeclaredConstructor().newInstance();
} }
@Test @Test
@ -925,6 +925,22 @@ public class TestComplete {
assertEquals(clazz.getDeclaredMethod("main", Integer.class).invoke(instance, 5), "small"); assertEquals(clazz.getDeclaredMethod("main", Integer.class).invoke(instance, 5), "small");
} }
@Test
public void testWhile() throws Exception {
var classFiles = generateClassFiles(new ByteArrayClassLoader(), "While.jav");
var clazz = classFiles.get("While");
var instance = clazz.getDeclaredConstructor().newInstance();
assertEquals(clazz.getDeclaredMethod("m", Integer.class).invoke(instance, 5), 5);
assertEquals(clazz.getDeclaredMethod("m2").invoke(instance), 10);
}
@Test
public void testImportWildcard() throws Exception {
var classFiles = generateClassFiles(new ByteArrayClassLoader(), "ImportWildcard.jav");
var clazz = classFiles.get("ImportWildcard");
var instance = clazz.getDeclaredConstructor().newInstance();
}
@Test @Test
public void testBug122() throws Exception { public void testBug122() throws Exception {
var classFiles = generateClassFiles(new ByteArrayClassLoader(), "Bug122.jav"); var classFiles = generateClassFiles(new ByteArrayClassLoader(), "Bug122.jav");
@ -1085,6 +1101,7 @@ public class TestComplete {
var res = clazz.getDeclaredMethod("convert", List.class).invoke(instance, list); var res = clazz.getDeclaredMethod("convert", List.class).invoke(instance, list);
assertEquals(res, List.of(6, 7, 8)); assertEquals(res, List.of(6, 7, 8));
} }
@Test @Test
public void testBug325() throws Exception { public void testBug325() throws Exception {
var classFiles = generateClassFiles(new ByteArrayClassLoader(), "Bug325.jav"); var classFiles = generateClassFiles(new ByteArrayClassLoader(), "Bug325.jav");
@ -1108,4 +1125,18 @@ public class TestComplete {
var clazz = classFiles.get("Bug328"); var clazz = classFiles.get("Bug328");
var instance = clazz.getDeclaredConstructor().newInstance(); var instance = clazz.getDeclaredConstructor().newInstance();
} }
@Test
public void testBug333() throws Exception {
var classFiles = generateClassFiles(new ByteArrayClassLoader(), "Bug333.jav");
var clazz = classFiles.get("Bug333");
var instance = clazz.getDeclaredConstructor().newInstance();
}
@Test
public void testBug338() throws Exception {
var classFiles = generateClassFiles(new ByteArrayClassLoader(), "Bug338.jav");
var clazz = classFiles.get("Bug338");
var instance = clazz.getDeclaredConstructor().newInstance();
}
} }

View File

@ -57,7 +57,7 @@ public class ASTToTypedTargetAST {
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Tph2.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Tph2.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(resultSet); var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var tphAndGenerics = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var tphAndGenerics = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
@ -68,7 +68,7 @@ public class ASTToTypedTargetAST {
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Cycle.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Cycle.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(resultSet); var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var cycle = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var cycle = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
@ -79,7 +79,7 @@ public class ASTToTypedTargetAST {
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Infimum.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Infimum.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(resultSet); var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var infimum = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var infimum = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
@ -90,7 +90,7 @@ public class ASTToTypedTargetAST {
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Gen.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Gen.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(resultSet); var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var generics = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var generics = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
@ -124,7 +124,7 @@ public class ASTToTypedTargetAST {
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics2.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics2.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(resultSet); var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var generics2 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var generics2 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
@ -140,7 +140,7 @@ public class ASTToTypedTargetAST {
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics3.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics3.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(resultSet); var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var generics3 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var generics3 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());