Compare commits

..

17 Commits

Author SHA1 Message Date
Ruben
bc43ea749d feat: update compiler Interface
All checks were successful
Build and Test with Maven / Build-and-test-with-Maven (push) Successful in 7m22s
2025-08-07 16:18:51 +02:00
Ruben
c479b044b3 feat: add Method to only get AST
All checks were successful
Build and Test with Maven / Build-and-test-with-Maven (push) Successful in 5m43s
2025-07-16 14:18:22 +02:00
Ruben
9046fb09e5 fix: directly use .generate Method instead of compiling each file by hand
All checks were successful
Build and Test with Maven / Build-and-test-with-Maven (push) Successful in 7m20s
2025-07-16 11:53:48 +02:00
Ruben
42e31a3471 Merge branch 'master' into LSP-Interface
All checks were successful
Build and Test with Maven / Build-and-test-with-Maven (push) Successful in 4m49s
2025-05-13 16:01:20 +02:00
Ruben
d3b3f92193 feat: make dir when /out does not exist
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Failing after 43s
2025-05-12 18:57:46 +02:00
Ruben
8208abcaea fix: exclude Files that do not end on .jav
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Failing after 45s
2025-05-12 18:43:10 +02:00
Ruben
e4a3939ce9 test: change TEstnames
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Failing after 41s
2025-05-09 14:11:39 +02:00
Ruben
d903ec0ebb test: change TEstnames
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Has been cancelled
2025-05-09 14:11:11 +02:00
Ruben
61de81cf92 feat: compile all classes in workspace
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Failing after 42s
2025-05-08 19:00:12 +02:00
Ruben
59888006e0 feat: compile all classes in workspace
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Failing after 42s
2025-05-08 18:51:25 +02:00
Ruben
94034912b4 feat: clean out file when generating Bytecode
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Failing after 42s
2025-05-08 17:51:17 +02:00
Ruben
f303163118 feat: clean out file when generating Bytecode
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Failing after 43s
2025-05-08 17:10:35 +02:00
Ruben
7d99fba044 fix: update Interface for Language Server to not throw random Errors anymore
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Failing after 43s
2025-05-07 18:53:47 +02:00
Ruben
3740d34954 fix: create Path if its non existent and add Try-Catch Clause when deleting Files in Case they dont exist
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Failing after 41s
2025-05-06 15:31:27 +02:00
Ruben
d8b861ea95 feat: add Method in Interface to generate Bytecode
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Failing after 43s
2025-05-06 15:10:55 +02:00
Ruben
cf45ea68bd feat: include Bytecode in /out Folder
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Failing after 42s
2025-05-05 17:26:10 +02:00
Ruben
be72e4d7fb feat: add Compiler Interface
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Failing after 1m6s
2025-05-05 14:34:23 +02:00
57 changed files with 1694 additions and 1336 deletions

View File

@@ -15,7 +15,7 @@ jobs:
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '24'
java-version: '23'
cache: 'maven'
- name: Compile project
run: |

28
pom.xml
View File

@@ -12,37 +12,37 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.13.2</version>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.antlr/antlr4 -->
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4</artifactId>
<version>4.13.2</version>
<version>4.11.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.19.0</version>
<version>2.16.1</version>
</dependency>
<dependency>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
<version>4.8.180</version>
<version>4.8.172</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.4.8-jre</version>
<version>33.2.0-jre</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>9.8</version>
<version>9.5</version>
</dependency>
</dependencies>
@@ -51,17 +51,17 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version>
<version>3.11.0</version>
<configuration>
<compilerArgs>--enable-preview</compilerArgs>
<source>24</source>
<target>24</target>
<source>23</source>
<target>23</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.3</version>
<version>3.1.0</version>
<configuration>
<redirectTestOutputToFile>true</redirectTestOutputToFile>
<reportsDirectory>${project.build.directory}/test-reports</reportsDirectory>
@@ -77,7 +77,7 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<plugin>
<groupId>org.antlr</groupId>
<artifactId>antlr4-maven-plugin</artifactId>
<version>4.13.2</version>
<version>4.11.1</version>
<executions>
<execution>
<id>antlr</id>
@@ -90,7 +90,7 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
<version>3.3.0</version>
<configuration>
<archive>
<manifest>

View File

@@ -1,22 +0,0 @@
import java.lang.String;
public class Bug363 {
uncurry (f){
return x -> f.apply(x);
}
uncurry (f){
return (x, y) -> f.apply(x).apply(y);
}
uncurry (f){
return (x, y, z) -> f.apply(x).apply(y).apply(z);
}
public test(){
var f = x -> y -> z -> x + y + z;
var g = uncurry(f);
return g.apply("A", "B", "C"); // Outputs: 6
}
}

View File

@@ -1,8 +0,0 @@
import java.lang.String;
public class Bug364{
public main(){
var f = x -> y -> z -> x + y + z;
return f.apply("A").apply("B").apply("C");
}
}

View File

@@ -1,21 +0,0 @@
import java.lang.String;
import java.lang.Object;
public class Bug365{
swap(f){
return x -> y -> f.apply(y).apply(x);
}
swap(Fun1$$<String, Fun1$$<String, Fun1$$<String, Object>>> f){
return x -> y -> z -> f.apply(z).apply(y).apply(x);
}
public ex1() {
var func = x -> y -> z -> x + y + z;
return func.apply("A").apply("B").apply("C");
}
public ex2() {
var func = x -> y -> z -> x + y + z;
return swap(func).apply("A").apply("B").apply("C");
}
}

View File

@@ -1,12 +0,0 @@
import java.lang.Integer;
public class Bug366 {
public static lambda() {
return (a, b) -> a + b;
}
public static test() {
var l = lambda();
return l.apply(10, 20);
}
}

View File

@@ -1,10 +0,0 @@
import java.lang.Boolean;
public class Bug371 {
static m1(x, y) { return x || y; }
static m2(x, y) { return x && y; }
public static test() {
return m2(m1(true, false), true);
}
}

View File

@@ -0,0 +1,16 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.lang.String;
import java.util.stream.Stream;
import java.util.function.Function;
import java.util.function.Predicate;
import java.lang.Integer;
class BugXXX {
public main() {
List<Integer> i = new ArrayList<>(List.of(1,2,3,4,5,6,7,8,9,10));
Optional<Integer> tmp = i.stream().filter(x -> x == 5).map(x -> x*2).findFirst();
return tmp;
}
}

View File

@@ -13,7 +13,6 @@ import org.objectweb.asm.*;
import java.lang.invoke.*;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.stream.Collectors;
import static org.objectweb.asm.Opcodes.*;
import static de.dhbwstuttgart.target.tree.expression.TargetBinaryOp.*;
@@ -85,16 +84,14 @@ public class Codegen {
int localCounter;
MethodVisitor mv;
TargetType returnType;
boolean isStatic = false;
Stack<BreakEnv> breakStack = new Stack<>();
Stack<Integer> switchResultValue = new Stack<>();
State(TargetType returnType, MethodVisitor mv, int localCounter, boolean isStatic) {
State(TargetType returnType, MethodVisitor mv, int localCounter) {
this.returnType = returnType;
this.mv = mv;
this.localCounter = localCounter;
this.isStatic = isStatic;
}
void enterScope() {
@@ -760,16 +757,6 @@ public class Codegen {
}
}
private static TargetType removeGenerics(TargetType param) {
return switch (param) {
case null -> null;
case TargetFunNType funNType -> new TargetFunNType(funNType.name(), funNType.funNParams(), List.of(), funNType.returnArguments());
case TargetRefType refType -> new TargetRefType(refType.name());
case TargetGenericType targetGenericType -> TargetType.Object;
default -> param;
};
}
private void generateLambdaExpression(State state, TargetLambdaExpression lambda) {
var mv = state.mv;
@@ -781,8 +768,7 @@ public class Codegen {
var parameters = new ArrayList<>(lambda.captures());
parameters.addAll(signature.parameters());
parameters = parameters.stream().map(param -> param.withType(removeGenerics(param.pattern().type()))).collect(Collectors.toCollection(ArrayList::new));
var implSignature = new TargetMethod.Signature(Set.of(), parameters, removeGenerics(lambda.signature().returnType()));
var implSignature = new TargetMethod.Signature(Set.of(), parameters, lambda.signature().returnType());
TargetMethod impl;
if (lambdas.containsKey(lambda)) {
@@ -790,22 +776,21 @@ public class Codegen {
} else {
var name = "lambda$" + lambdaCounter++;
impl = new TargetMethod(state.isStatic ? ACC_STATIC : 0, name, lambda.block(), implSignature, null);
generateMethod(impl, state);
impl = new TargetMethod(0, name, lambda.block(), implSignature, null);
generateMethod(impl);
lambdas.put(lambda, impl);
}
var mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class, MethodType.class, MethodHandle.class, MethodType.class);
var bootstrap = new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", mt.toMethodDescriptorString(), false);
var handle = new Handle(state.isStatic ? H_INVOKESTATIC : H_INVOKEVIRTUAL, clazz.getName(), impl.name(), implSignature.getDescriptor(), false);
var handle = new Handle(H_INVOKEVIRTUAL, clazz.getName(), impl.name(), implSignature.getDescriptor(), false);
var params = new ArrayList<TargetType>();
if(!state.isStatic) params.add(new TargetRefType(clazz.qualifiedName().getClassName()));
params.add(new TargetRefType(clazz.qualifiedName().getClassName()));
params.addAll(lambda.captures().stream().map(mp -> mp.pattern().type()).toList());
if (!state.isStatic)
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, 0);
for (var index = 0; index < lambda.captures().size(); index++) {
var capture = lambda.captures().get(index);
var pattern = (TargetTypePattern) capture.pattern();
@@ -1533,7 +1518,7 @@ public class Codegen {
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "<clinit>", "()V", null, null);
mv.visitCode();
var state = new State(null, mv, 0, true);
var state = new State(null, mv, 0);
generate(state, constructor.block());
mv.visitInsn(RETURN);
@@ -1547,7 +1532,7 @@ public class Codegen {
mv.visitAttribute(new JavaTXSignatureAttribute(constructor.getTXSignature()));
mv.visitCode();
var state = new State(null, mv, 1, false);
var state = new State(null, mv, 1);
for (var param : constructor.parameters()) {
var pattern = param.pattern();
if (pattern instanceof TargetTypePattern tp)
@@ -1593,11 +1578,8 @@ public class Codegen {
}
}
}
private void generateMethod(TargetMethod method) {
generateMethod(method, null);
}
private void generateMethod(TargetMethod method, State parent) {
private void generateMethod(TargetMethod method) {
var access = method.access();
if (method.block() == null)
access |= ACC_ABSTRACT;
@@ -1612,10 +1594,7 @@ public class Codegen {
if (method.block() != null) {
mv.visitCode();
var state = new State(method.signature().returnType(), mv, method.isStatic() ? 0 : 1, method.isStatic());
if (parent != null) {
state.scope.parent = parent.scope;
}
var state = new State(method.signature().returnType(), mv, method.isStatic() ? 0 : 1);
var offset = 1;
for (var param : method.signature().parameters()) {
state.createVariable(param.pattern().name(), param.pattern().type());
@@ -1625,8 +1604,6 @@ public class Codegen {
bindLocalVariables(state, cp, offset);
offset++;
}
//if (parent != null) System.out.println("parent: " + parent.scope.locals.keySet());
//System.out.println(state.scope.locals.keySet());
generate(state, method.block());
if (method.signature().returnType() == null)
mv.visitInsn(RETURN);
@@ -1733,7 +1710,7 @@ public class Codegen {
// Generate wrapper method
var mv = cw2.visitMethod(ACC_PUBLIC, toMethod.name, toDescriptor, null, null);
var state = new State(null, mv, 0, false);
var state = new State(null, mv, 0);
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, className, "wrapped", pair.from.toDescriptor());
@@ -1765,7 +1742,7 @@ public class Codegen {
converter.classLoader.findClass(className);
} catch (ClassNotFoundException e) {
try {
converter.classLoader.loadClass(className, bytes);
converter.classLoader.loadClass(bytes);
} catch (LinkageError ignored) {}
}
}

View File

@@ -39,10 +39,6 @@ public class FunNGenerator {
public final List<TargetType> inParams;
public final List<TargetType> realParams;
public GenericParameters(TargetFunNType funNType) {
this(funNType.funNParams(), funNType.returnArguments());
}
public GenericParameters(List<TargetType> params, int numReturns) {
this.realParams = params;
this.inParams = flattenTypeParams(params);

View File

@@ -5,6 +5,7 @@ import de.dhbwstuttgart.bytecode.Codegen;
import de.dhbwstuttgart.environment.CompilationEnvironment;
import de.dhbwstuttgart.environment.DirectoryClassLoader;
import de.dhbwstuttgart.exceptions.DebugException;
import de.dhbwstuttgart.languageServerInterface.model.LanguageServerTransferObject;
import de.dhbwstuttgart.parser.JavaTXParser;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.scope.GenericsRegistry;
@@ -393,12 +394,7 @@ public class JavaTXCompiler {
logFile.write(ASTTypePrinter.print(sf));
System.out.println(ASTTypePrinter.print(sf));
logFile.flush();
List<UnifyPair> andConstraintsSorted = unifyCons.getUndConstraints().stream()
.sorted(Comparator.comparing(UnifyPair::getPairOp).thenComparing(UnifyPair::getLhsType, Comparator.comparing(UnifyType::getName)))
.collect(Collectors.toList());
System.out.println(andConstraintsSorted);
System.out.println("Unify nach Oder-Constraints-Anpassung:" + unifyCons.toString());
Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons);
@@ -421,14 +417,7 @@ public class JavaTXCompiler {
UnifyResultListenerImpl li = new UnifyResultListenerImpl();
urm.addUnifyResultListener(li);
unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks);
//System.out.println("RESULT Final: " + li.getResults());
var finalResults = li.getResults().stream().sorted().toList();
int i = 0;
System.out.println("RESULT Final: ");
for (var result : finalResults){
System.out.println("Result: " + i++);
System.out.println(result.getSortedResults());
}
System.out.println("RESULT Final: " + li.getResults());
System.out.println("Constraints for Generated Generics: " + " ???");
logFile.write("RES_FINAL: " + li.getResults().toString() + "\n");
logFile.flush();
@@ -469,6 +458,85 @@ public class JavaTXCompiler {
return results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))).collect(Collectors.toList());
}
/**
* TEMPORARY - Only for Language Server Usage
*/
public LanguageServerTransferObject getResultSetAndAbstractSyntax(File file) throws IOException, ClassNotFoundException {
var sf = sourceFiles.get(file);
if(sf == null){
sf = sourceFiles.values().stream().findFirst().get();
}
Set<ClassOrInterface> allClasses = new HashSet<>();
allClasses.addAll(getAvailableClasses(sf));
allClasses.addAll(sf.getClasses());
var newClasses = CompilationEnvironment.loadDefaultPackageClasses(sf.getPkgName(), file, this).stream().map(ASTFactory::createClass).collect(Collectors.toSet());
for (var clazz : newClasses) {
// Don't load classes that get recompiled
if (sf.getClasses().stream().anyMatch(nf -> nf.getClassName().equals(clazz.getClassName())))
continue;
if (allClasses.stream().noneMatch(old -> old.getClassName().equals(clazz.getClassName())))
allClasses.add(clazz);
}
final ConstraintSet<Pair> cons = getConstraints(file);
Set<Set<UnifyPair>> results = new HashSet<>();
try {
Writer logFile = new OutputStreamWriter(new NullOutputStream());
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses.stream().toList(), logFile, classLoader, this);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(this, 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;
};
unifyCons = unifyCons.map(distributeInnerVars);
TypeUnify unify = new TypeUnify();
Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons);
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);
generateBytecode(sf, li.getResults());
return new LanguageServerTransferObject(li.getResults(), sf, ASTTypePrinter.print(sf), generatedGenerics);
}
/* UnifyResultModel End */
else {
Set<Set<UnifyPair>> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks);
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));
}
} catch (ClassNotFoundException e) {
}
generateBytecode(sf, results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))).collect(Collectors.toList()));
return new LanguageServerTransferObject(results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))).collect(Collectors.toList()), sf, ASTTypePrinter.print(sf), generatedGenerics);
}
/**
* Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine Variance !=0 hat auf alle Typvariablen in Theta.
*
@@ -643,12 +711,12 @@ public class JavaTXCompiler {
var codegen = new Codegen(converter.convert(clazz), this, converter);
var code = codegen.generate();
generatedClasses.put(clazz.getClassName(), code);
converter.auxiliaries.forEach((name, source) -> {
generatedClasses.put(new JavaClassName(name), source);
});
}
generatedGenerics.put(sf, converter.javaGenerics());
converter.generateFunNTypes();
converter.auxiliaries.forEach((name, source) -> {
generatedClasses.put(new JavaClassName(name), source);
});
return generatedClasses;
}

View File

@@ -0,0 +1,13 @@
package de.dhbwstuttgart.environment;
public class ByteArrayClassLoader extends ClassLoader implements IByteArrayClassLoader {
@Override
public Class _defineClass(String name, byte[] code, int i, int length) throws ClassFormatError {
return defineClass(name, code, i, length);
}
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
return super.findClass(name);
}
}

View File

@@ -6,22 +6,18 @@ import java.nio.file.Path;
public interface IByteArrayClassLoader {
Class<?> loadClass(String path) throws ClassNotFoundException;
Class loadClass(String path) throws ClassNotFoundException;
default Class<?> loadClass(byte[] code) {
return this.loadClass(null, code);
default Class loadClass(byte[] code) {
return this._defineClass(null, code, 0, code.length);
}
default Class<?> loadClass(String name, byte[] code) {
return this._defineClass(name, code, 0, code.length);
}
default Class<?> loadClass(Path path) throws IOException {
default Class loadClass(Path path) throws IOException {
var code = Files.readAllBytes(path);
return this._defineClass(null, code, 0, code.length);
}
public Class<?> findClass(String name) throws ClassNotFoundException;
Class<?> _defineClass(String name, byte[] code, int i, int length) throws ClassFormatError;
Class _defineClass(String name, byte[] code, int i, int length) throws ClassFormatError;
}

View File

@@ -0,0 +1,277 @@
package de.dhbwstuttgart.languageServerInterface;
import de.dhbwstuttgart.bytecode.Codegen;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import de.dhbwstuttgart.environment.IByteArrayClassLoader;
import de.dhbwstuttgart.languageServerInterface.model.LanguageServerTransferObject;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
import de.dhbwstuttgart.target.generate.ASTToTargetAST;
import de.dhbwstuttgart.target.generate.GenericsResult;
import de.dhbwstuttgart.target.tree.TargetStructure;
import org.apache.commons.io.FileUtils;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Implementation of an Interface for the Language-Server to get the Resultset and abstract Syntax.
*/
public class LanguageServerInterface {
public LanguageServerTransferObject getResultSetAndAbastractSyntax(String path, String resetNamesTo) throws IOException, URISyntaxException, ClassNotFoundException {
NameGenerator.resetTo(resetNamesTo);
return getResultSetAndAbstractSyntax(path);
}
public SourceFile getAst(String path, String resetNamesTo) throws IOException, URISyntaxException, ClassNotFoundException {
NameGenerator.resetTo(resetNamesTo);
return getAST(path);
}
/**
* returns the ResultSets, GenericResultSet and the AST
* You have to give the input as well as the path because of potential locks when the File is currently opened in an IDE.
* Example: file:///c:/test/main.jav -> file:///c:/test/out/main.class
*
* @param path the URI of the File. See Example.
* @throws IOException
* @throws ClassNotFoundException
* @throws URISyntaxException
*/
public LanguageServerTransferObject getResultSetAndAbstractSyntax(String path) throws IOException, ClassNotFoundException, URISyntaxException {
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
URI uri = new URI(path);
ArrayList<String> pathWithoutName = new ArrayList<>(List.of(uri.getPath().split("/")));
pathWithoutName.remove(List.of(uri.getPath().split("/")).size() - 1);
String stringPathWithoutName = "";
for (String i : pathWithoutName) {
stringPathWithoutName += "/" + i;
}
try {
FileUtils.cleanDirectory(new File(stringPathWithoutName + "/out"));
} catch (Exception e) {
}
try {
(new File(stringPathWithoutName + "/out")).mkdirs();
} catch (Exception e) {
}
var test = getLanguageServerTransferObject(uri.getPath().split("/")[uri.getPath().split("/").length - 1], new ByteArrayClassLoader(), new File(stringPathWithoutName).getPath());
System.setOut(System.out);
return test;
// File oldTempSourcefile = new File(stringPathWithoutName + "/out/" + uri.getPath().split("/")[uri.getPath().split("/").length - 1].replace(".jav", ".tmp"));
// File oldTempOutFile = new File(stringPathWithoutName + "/out/" + uri.getPath().split("/")[uri.getPath().split("/").length - 1].replace(".jav", ".class"));
// Files.deleteIfExists(oldTempSourcefile.toPath());
// Files.deleteIfExists(oldTempOutFile.toPath());
// FileUtils.deleteDirectory(oldTempSourcefile);
//
// File tempSourcefile = new File(stringPathWithoutName + "/out/" + uri.getPath().split("/")[uri.getPath().split("/").length - 1].replace(".jav", ".tmp"));
// File tempOutFile = new File(stringPathWithoutName + "/out/");
// FileUtils.writeStringToFile(tempSourcefile, input, "UTF-8");
//
// //TODO: Enable for multiple Class-Files
// JavaTXCompiler tx = new JavaTXCompiler(new ArrayList<File>(List.of(tempSourcefile)), new ArrayList<File>(List.of((tempSourcefile))), tempOutFile);
// var result = tx.getResultSetAndAbstractSyntax(tempSourcefile);
// System.setOut(System.out);
// tempSourcefile.delete();
// tempOutFile.delete();
// return result;
}
/**
* returns the AST without calculating the result
* You have to give the input as well as the path because of potential locks when the File is currently opened in an IDE.
* Example: file:///c:/test/main.jav -> file:///c:/test/out/main.class
*
* @param path the URI of the File. See Example.
* @throws IOException
* @throws ClassNotFoundException
* @throws URISyntaxException
*/
public SourceFile getAST(String path) throws IOException, ClassNotFoundException, URISyntaxException {
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
URI uri = new URI(path);
ArrayList<String> pathWithoutName = new ArrayList<>(List.of(uri.getPath().split("/")));
pathWithoutName.remove(List.of(uri.getPath().split("/")).size() - 1);
String stringPathWithoutName = "";
for (String i : pathWithoutName) {
stringPathWithoutName += "/" + i;
}
try {
FileUtils.cleanDirectory(new File(stringPathWithoutName + "/out"));
} catch (Exception e) {
}
try {
(new File(stringPathWithoutName + "/out")).mkdirs();
} catch (Exception e) {
}
var test = getAST(uri.getPath().split("/")[uri.getPath().split("/").length - 1], new File(stringPathWithoutName).getPath());
System.setOut(System.out);
return test;
}
private static void writeClassFile(String name, byte[] code, Path outputPath) throws IOException {
Files.createDirectories(outputPath);
Files.write(outputPath.resolve(name + ".class"), code);
}
public static Map<String, ? extends Class<?>> generateClassFiles(IByteArrayClassLoader classLoader, Path path, Path outputPath, String... files) throws IOException, ClassNotFoundException {
Files.createDirectories(outputPath);
var filenames = Arrays.stream(files).map(filename -> Path.of(path.toString(), filename).toFile()).toList();
var compiler = new JavaTXCompiler(filenames, List.of(path.toFile(), outputPath.toFile()), outputPath.toFile());
var result = new HashMap<String, Class<?>>();
for (var file : filenames) {
var resultSet = compiler.typeInference(file);
var sourceFile = compiler.sourceFiles.get(file);
var converter = new ASTToTargetAST(compiler, resultSet, sourceFile, classLoader);
var classes = compiler.sourceFiles.get(file).getClasses();
result.putAll(classes.stream().map(cli -> {
try {
return generateClass(converter.convert(cli), classLoader, converter, outputPath);
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}).collect(Collectors.toMap(Class::getName, Function.identity())));
converter.generateFunNTypes();
for (var entry : converter.auxiliaries.entrySet()) {
writeClassFile(entry.getKey(), entry.getValue(), outputPath);
}
}
for (var entry : compiler.loadedClasses.entrySet()) {
var name = entry.getKey().toString();
result.put(name, classLoader.loadClass(Path.of(entry.getValue().classFile().toURI())));
}
return result;
}
public static Class<?> generateClass(TargetStructure clazz, IByteArrayClassLoader classLoader, ASTToTargetAST converter, Path outputPath) throws IOException {
Codegen codegen = new Codegen(clazz, converter.compiler, converter);
var code = codegen.generate();
writeClassFile(clazz.qualifiedName().getClassName(), code, outputPath);
return classLoader.loadClass(code);
}
public static Map<String, ? extends Class<?>> generateClassFiles(String filename, IByteArrayClassLoader classLoader, String filePath) throws IOException, ClassNotFoundException {
var file = Path.of(filePath, filename).toFile();
var compiler = new JavaTXCompiler(List.of(file), List.of(file.getParentFile()), Path.of(filePath + "/out").toFile());
var resultSet = compiler.typeInference(file);
var sourceFile = compiler.sourceFiles.get(file);
var converter = new ASTToTargetAST(compiler, resultSet, sourceFile, classLoader);
var classes = compiler.sourceFiles.get(file).getClasses();
var result = classes.stream().map(cli -> {
try {
return generateClass(converter.convert(cli), classLoader, converter, Path.of(filePath + "/out/"));
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}).collect(Collectors.toMap(Class::getName, Function.identity()));
converter.generateFunNTypes();
for (var entry : converter.auxiliaries.entrySet()) {
writeClassFile(entry.getKey(), entry.getValue(), Path.of(filePath + "/out/"));
}
return result;
}
public static SourceFile getAST(String filename, String filePath) throws IOException, ClassNotFoundException {
var file = Path.of(filePath, filename).toFile();
var compiler = new JavaTXCompiler(List.of(file), List.of(file.getParentFile()), Path.of(filePath + "/out").toFile());
return compiler.sourceFiles.get(file);
}
public static LanguageServerTransferObject getLanguageServerTransferObject(String filename, IByteArrayClassLoader classLoader, String filePath) throws IOException, ClassNotFoundException {
var file = Path.of(filePath, filename).toFile();
var compiler = new JavaTXCompiler(List.of(file), List.of(file.getParentFile()), Path.of(filePath + "/out").toFile());
var resultSet = compiler.typeInference(file);
var sourceFile = compiler.sourceFiles.get(file);
var converter = new ASTToTargetAST(compiler, resultSet, sourceFile, classLoader);
compiler.generateBytecode();
converter.generateFunNTypes();
var ta = converter.javaGenerics();
var tb = converter.txGenerics();
Map<SourceFile, List<GenericsResult>> generics = new HashMap<>();
ArrayList<GenericsResult> genericsResults = new ArrayList<>();
genericsResults.addAll(ta);
genericsResults.addAll(tb);
generics.put(converter.compiler.sourceFiles.values().stream().findFirst().get(), ta);
var test = new LanguageServerTransferObject(resultSet, converter.compiler.sourceFiles.values().stream().findFirst().get(), "", generics);
return test;
}
/**
* generates Bytecode for the given Path of the File.
* The Generated Bytecode can be found in the same place as the path, except the File lies in an /out/ Directory
* Example: file:///c:/test/main.jav -> file:///c:/test/out/main.class
*
* @param uri the URI of the File. See Example.
* @throws IOException
* @throws ClassNotFoundException
* @throws URISyntaxException
*/
public void generateBytecode(URI uri) throws IOException, ClassNotFoundException, URISyntaxException {
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
File inputDir = new File(uri.getPath());
File outFile = new File(uri.getPath() + "/out");
FileUtils.cleanDirectory(outFile);
String[] allowedEndings = {".jav"};
ArrayList<File> files = new ArrayList<>();
try (Stream<Path> stream = Files.walk(Paths.get(inputDir.toURI()))) {
stream.filter(Files::isRegularFile)
.forEach(el -> files.add(el.toFile()));
}
List<String> javFiles = files.stream().filter(el -> el.getName().split("\\.").length >= 2 && el.getName().split("\\.")[el.getName().split("\\.").length - 1].contains("jav")).map(el -> el.getPath().replace(inputDir.getPath(), "").substring(1)).toList();
//TODO: Link between Files
generateClassFiles(new ByteArrayClassLoader(), Path.of(inputDir.toURI()), Path.of(outFile.toURI()), javFiles.toArray(new String[0]));
System.setOut(System.out);
}
}

View File

@@ -0,0 +1,40 @@
package de.dhbwstuttgart.languageServerInterface;
import de.dhbwstuttgart.languageServerInterface.model.CustomParserErrorHandler;
import de.dhbwstuttgart.languageServerInterface.model.ParserError;
import de.dhbwstuttgart.parser.antlr.Java17Lexer;
import de.dhbwstuttgart.parser.antlr.Java17Parser;
import de.dhbwstuttgart.parser.antlr.Java17ParserBaseListener;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import java.util.List;
public class ParserInterface {
public List<ParserError> getParseErrors(String input){
CustomParserErrorHandler errorListener = new CustomParserErrorHandler();
CharStream charStream = CharStreams.fromString(input);
Java17Lexer lexer = new Java17Lexer(charStream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
Java17Parser parser = new Java17Parser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(errorListener);
ParseTree tree = parser.sourceFile();
ParseTreeWalker walker = new ParseTreeWalker();
Java17ParserBaseListener listener = new Java17ParserBaseListener();
walker.walk(listener, tree);
return errorListener.getErrorMessages();
}
}

View File

@@ -0,0 +1,47 @@
package de.dhbwstuttgart.languageServerInterface.model;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.atn.ATNConfigSet;
import org.antlr.v4.runtime.dfa.DFA;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
public class CustomParserErrorHandler implements ANTLRErrorListener {
private final List<ParserError> errorMessages = new ArrayList<>();
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
int endCharPosition = charPositionInLine;
if (offendingSymbol instanceof Token) {
Token offendingToken = (Token) offendingSymbol;
endCharPosition = charPositionInLine + offendingToken.getText().length();
}
ParserError parserError = new ParserError(line, charPositionInLine, endCharPosition, msg);
errorMessages.add(parserError);
}
@Override
public void reportAmbiguity(Parser parser, DFA dfa, int i, int i1, boolean b, BitSet bitSet, ATNConfigSet atnConfigSet) {
}
@Override
public void reportAttemptingFullContext(Parser parser, DFA dfa, int i, int i1, BitSet bitSet, ATNConfigSet atnConfigSet) {
}
@Override
public void reportContextSensitivity(Parser parser, DFA dfa, int i, int i1, int i2, ATNConfigSet atnConfigSet) {
}
public List<ParserError> getErrorMessages() {
return errorMessages;
}
}

View File

@@ -0,0 +1,31 @@
package de.dhbwstuttgart.languageServerInterface.model;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.target.generate.GenericsResult;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LanguageServerTransferObject {
List<ResultSet> resultSets;
SourceFile Ast;
String printedAst;
Map<SourceFile, List<GenericsResult>> generatedGenerics = new HashMap<>();
public LanguageServerTransferObject(List<ResultSet> resultSets, SourceFile Ast, String printedAst, Map<SourceFile, List<GenericsResult>> generatedGenerics) {
this.resultSets = resultSets;
this.Ast = Ast;
this.printedAst = printedAst;
this.generatedGenerics = generatedGenerics;
}
public List<ResultSet> getResultSets() {return resultSets;}
public SourceFile getAst() {return Ast;}
public String getPrintedAst() {return printedAst;}
public Map<SourceFile, List<GenericsResult>> getGeneratedGenerics() {return generatedGenerics;}
}

View File

@@ -0,0 +1,48 @@
package de.dhbwstuttgart.languageServerInterface.model;
public class ParserError {
private int line;
private int charPositionInLine;
private int endCharPosition;
String msg;
public ParserError(int line, int charPositionInLine, int endCharPosition, String msg) {
this.line = line;
this.charPositionInLine = charPositionInLine;
this. endCharPosition = endCharPosition;
this.msg = msg;
}
public int getEndCharPosition() {
return endCharPosition;
}
public void setEndCharPosition(int endCharPosition) {
this.endCharPosition = endCharPosition;
}
public void setCharPositionInLine(int charPositionInLine) {
this.charPositionInLine = charPositionInLine;
}
public void setLine(int line) {
this.line = line;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCharPositionInLine() {
return charPositionInLine;
}
public int getLine() {
return line;
}
public String getMsg() {
return msg;
}
}

View File

@@ -0,0 +1,20 @@
package de.dhbwstuttgart.languageServerInterface.model;
import com.google.common.reflect.TypeResolver;
import de.dhbwstuttgart.typeinference.unify.UnifyResultEvent;
import de.dhbwstuttgart.typeinference.unify.UnifyResultListener;
public class ResultSetListener implements UnifyResultListener {
TypeResolver typeResolver;
public ResultSetListener(TypeResolver typeResolver){
this.typeResolver = typeResolver;
}
@Override
public void onNewTypeResultFound(UnifyResultEvent evt) {
}
}

View File

@@ -1099,9 +1099,9 @@ public class StatementGenerator {
block = lambdaGenerator.convert(expression.lambdaBody().block(), true);
}
List<RefTypeOrTPHOrWildcardOrGeneric> funNParams = new ArrayList<>();
funNParams.add(TypePlaceholder.fresh(expression.getStart(), -1, false));// ret-Type
funNParams.add(TypePlaceholder.fresh(expression.getStart()));// ret-Type
params.getFormalparalist().forEach(formalParameter -> // Für jeden Parameter einen TPH anfügen:
funNParams.add(TypePlaceholder.fresh(expression.getStart(), 1, false)));
funNParams.add(TypePlaceholder.fresh(expression.getStart())));
RefTypeOrTPHOrWildcardOrGeneric lambdaType = TypePlaceholder.fresh(expression.getStart());
// RefType lambdaType = new
// RefType(reg.getName("Fun"+params.getFormalparalist().size()),

View File

@@ -7,7 +7,7 @@ import java.util.*;
/**
* Speichert die Klassen f<>r einen bestimmten Projektscope
*/
public class JavaClassRegistry{
public class JavaClassRegistry {
final Map<JavaClassName, Integer> existingClasses = new HashMap<>();
public JavaClassRegistry(Map<String, Integer> initialNames) {
@@ -22,10 +22,6 @@ public class JavaClassRegistry{
}
}
public Set<JavaClassName> getAllClassNames(){
return existingClasses.keySet();
}
public void addName(String className, int numberOfGenerics) {
existingClasses.put(new JavaClassName(className), numberOfGenerics);
}

View File

@@ -13,6 +13,10 @@ public class NameGenerator {
public static void reset() {
strNextName = "A";
}
public static void resetTo(String name) {
strNextName = name;
}
/**
* Berechnet einen neuen, eindeutigen Namen f�r eine neue

View File

@@ -2,6 +2,7 @@ package de.dhbwstuttgart.target.generate;
import de.dhbwstuttgart.bytecode.FunNGenerator;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import de.dhbwstuttgart.environment.IByteArrayClassLoader;
import de.dhbwstuttgart.exceptions.DebugException;
import de.dhbwstuttgart.parser.NullToken;
@@ -11,8 +12,6 @@ import de.dhbwstuttgart.syntaxtree.Record;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.statement.*;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.OutputGenerator;
import de.dhbwstuttgart.target.tree.*;
import de.dhbwstuttgart.target.tree.expression.*;
import de.dhbwstuttgart.target.tree.type.*;
@@ -67,11 +66,11 @@ public class ASTToTargetAST {
public IByteArrayClassLoader classLoader;
protected SourceFile sourceFile;
public ASTToTargetAST(List<ResultSet> resultSets, IByteArrayClassLoader classLoader) {
this(null, resultSets, classLoader);
public ASTToTargetAST(List<ResultSet> resultSets) {
this(null, resultSets);
}
public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets, IByteArrayClassLoader classLoader) {
this(compiler, resultSets, null, classLoader);
public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets) {
this(compiler, resultSets, null, new ByteArrayClassLoader());
}
public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets, SourceFile sourceFile, IByteArrayClassLoader classLoader) {
@@ -782,15 +781,7 @@ public class ASTToTargetAST {
return TargetFunNType.fromParams(params, filteredParams, gep.getReturnType() != null ? 1 : 0);
}
private FunNGenerator.GenericParameters convertToParameters(TargetFunNType input) {
return null;
}
private boolean isSubtype(TargetType test, TargetType other) {
if (other.equals(TargetType.Object)) return true;
if (test instanceof TargetFunNType tfun && other instanceof TargetFunNType ofun)
return isSubtype(new FunNGenerator.GenericParameters(tfun), new FunNGenerator.GenericParameters(ofun));
var testClass = compiler.getClass(new JavaClassName(test.name()));
var otherClass = compiler.getClass(new JavaClassName(other.name()));
if (testClass == null) return false;
@@ -827,6 +818,14 @@ public class ASTToTargetAST {
.toList();
var code = FunNGenerator.generateSpecializedBytecode(gep, superInterfaces);
try {
classLoader.findClass(entry.getKey());
} catch (ClassNotFoundException e) {
try {
classLoader.loadClass(code);
} catch (LinkageError ignored) {}
}
auxiliaries.put(entry.getKey(), code);
}
}
@@ -857,7 +856,7 @@ public class ASTToTargetAST {
classLoader.findClass(superClassName);
} catch (ClassNotFoundException e) {
try {
classLoader.loadClass(superClassName, code);
classLoader.loadClass(code);
} catch (LinkageError ignored) {}
}
auxiliaries.put(superClassName, code);

View File

@@ -14,7 +14,6 @@ import de.dhbwstuttgart.target.tree.expression.*;
import de.dhbwstuttgart.target.tree.type.*;
import java.lang.reflect.Modifier;
import java.sql.Array;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@@ -33,71 +32,54 @@ public class StatementToTargetExpression implements ASTVisitor {
throw new NotImplementedException();
}
private class LambdaCaptureFinder extends TracingStatementVisitor {
// TODO The same mechanism is implemented in Codegen, maybe use it from there?
final Stack<Set<String>> localVariables = new Stack<>();
private final List<MethodParameter> parameters;
private final List<MethodParameter> captures;
LambdaCaptureFinder(List<MethodParameter> parameters, List<MethodParameter> captures) {
localVariables.push(new HashSet<>());
this.parameters = parameters;
this.captures = captures;
}
boolean hasLocalVar(String name) {
for (var localVariables : this.localVariables) {
if (localVariables.contains(name))
return true;
}
return false;
}
@Override
public void visit(Block block) {
localVariables.push(new HashSet<>());
super.visit(block);
localVariables.pop();
}
@Override
public void visit(LocalVar localVar) {
super.visit(localVar);
var capture = new MethodParameter(new TargetTypePattern(converter.convert(localVar.getType()), localVar.name));
if (!hasLocalVar(localVar.name) && !parameters.contains(capture) && !captures.contains(capture))
captures.add(capture);
}
@Override
public void visit(LocalVarDecl varDecl) {
var localVariables = this.localVariables.peek();
localVariables.add(varDecl.getName());
}
@Override
public void visit(LambdaExpression lambda) {
var newCaptures = new ArrayList<MethodParameter>();
var captureFinder = new LambdaCaptureFinder(createParameters(lambda), newCaptures);
lambda.methodBody.accept(captureFinder);
newCaptures.removeAll(parameters);
captures.addAll(newCaptures);
}
}
private List<MethodParameter> createParameters(LambdaExpression lambda) {
return StreamSupport.stream(lambda.params.spliterator(), false)
.map(p -> (FormalParameter) p)
.map(p -> new MethodParameter(new TargetTypePattern(converter.convert(p.getType()), p.getName())))
.toList();
}
@Override
public void visit(LambdaExpression lambdaExpression) {
var parameters = createParameters(lambdaExpression);
var parameters = StreamSupport.stream(lambdaExpression.params.spliterator(), false)
.map(p -> (FormalParameter) p)
.map(p -> new MethodParameter(new TargetTypePattern(converter.convert(p.getType()), p.getName())))
.toList();
List<MethodParameter> captures = new ArrayList<>();
var visitor = new LambdaCaptureFinder(parameters, captures);
lambdaExpression.methodBody.accept(visitor);
lambdaExpression.methodBody.accept(new TracingStatementVisitor() {
// TODO The same mechanism is implemented in Codegen, maybe use it from there?
final Stack<Set<String>> localVariables = new Stack<>();
{
localVariables.push(new HashSet<>());
}
boolean hasLocalVar(String name) {
for (var localVariables : this.localVariables) {
if (localVariables.contains(name))
return true;
}
return false;
}
@Override
public void visit(Block block) {
localVariables.push(new HashSet<>());
super.visit(block);
localVariables.pop();
}
@Override
public void visit(LocalVar localVar) {
super.visit(localVar);
var capture = new MethodParameter(new TargetTypePattern(converter.convert(localVar.getType()), localVar.name));
if (!hasLocalVar(localVar.name) && !parameters.contains(capture) && !captures.contains(capture))
captures.add(capture);
}
@Override
public void visit(LocalVarDecl varDecl) {
var localVariables = this.localVariables.peek();
localVariables.add(varDecl.getName());
}
@Override
public void visit(LambdaExpression lambda) {
} // Don't look at lambda expressions
});
TargetMethod.Signature signature = new TargetMethod.Signature(Set.of(), parameters, converter.convert(lambdaExpression.getReturnType()));;
var tpe = converter.convert(lambdaExpression.getType());
@@ -138,10 +120,7 @@ public class StatementToTargetExpression implements ASTVisitor {
@Override
public void visit(BoolExpression bool) {
result = switch(bool.operation) {
case OR -> new TargetBinaryOp.Or(converter.convert(bool.getType()), converter.convert(bool.lexpr), converter.convert(bool.rexpr));
case AND -> new TargetBinaryOp.And(converter.convert(bool.getType()), converter.convert(bool.lexpr), converter.convert(bool.rexpr));
};
System.out.println("BoolExpression");
}
@Override

View File

@@ -6,7 +6,7 @@ import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class Constraint<A> extends HashSet<A> implements Comparable<Constraint<A>> {
public class Constraint<A> extends HashSet<A> {
private static final long serialVersionUID = 1L;
private Boolean isInherited = false;//wird beides nur für die Method-Constraints benoetigt
private Boolean isImplemented = false;
@@ -73,9 +73,5 @@ public class Constraint<A> extends HashSet<A> implements Comparable<Constraint<A
public String toStringBase() {
return super.toString();
}
@Override
public int compareTo(Constraint<A> o) {
return this.toString().compareTo(o.toString());
}
}

View File

@@ -5,7 +5,7 @@ import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
/**
* Paare, welche das Unifikationsergebnis darstellen
*/
public abstract class ResultPair<A extends RefTypeOrTPHOrWildcardOrGeneric, B extends RefTypeOrTPHOrWildcardOrGeneric> implements Comparable<ResultPair<A,B>> {
public abstract class ResultPair<A extends RefTypeOrTPHOrWildcardOrGeneric,B extends RefTypeOrTPHOrWildcardOrGeneric> {
private final A left;
private final B right;
@@ -58,14 +58,5 @@ public abstract class ResultPair<A extends RefTypeOrTPHOrWildcardOrGeneric, B ex
return false;
return true;
}
@Override
public int compareTo(ResultPair<A, B> o) {
if (o == null) {
return 1; // this is greater than null
}
return o.left.toString().compareTo(this.left.toString());
}
}

View File

@@ -1,8 +1,6 @@
package de.dhbwstuttgart.typeinference.result;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import de.dhbwstuttgart.exceptions.NotImplementedException;
@@ -14,7 +12,7 @@ import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
@SuppressWarnings("rawtypes")
public class ResultSet implements Comparable<ResultSet>{
public class ResultSet {
public final Set<ResultPair> results;
public Set<ResultPair<TypePlaceholder, TypePlaceholder>> genIns;
@@ -24,10 +22,6 @@ public class ResultSet implements Comparable<ResultSet>{
this.genIns = new HashSet<>();
results.forEach(x -> { if (x instanceof PairTPHsmallerTPH) { this.genIns.add(x);}} );
}
public List<ResultPair> getSortedResults() {
return results.stream().sorted().toList();
}
public boolean contains(ResultPair toCheck) {
return this.results.contains(toCheck);
@@ -69,21 +63,6 @@ public class ResultSet implements Comparable<ResultSet>{
public int hashCode() {
return results.hashCode();
}
@Override
public int compareTo(ResultSet o) {
List<ResultPair> thisSorted = this.getSortedResults();
List<ResultPair> otherSorted = o.getSortedResults();
int sizeCompare = Integer.compare(thisSorted.size(), otherSorted.size());
if (sizeCompare != 0) return sizeCompare;
for (int i = 0; i < thisSorted.size(); i++) {
int cmp = thisSorted.get(i).compareTo(otherSorted.get(i));
if (cmp != 0) return cmp;
}
return 0;
}
}
class Resolver implements ResultSetVisitor {

View File

@@ -73,7 +73,7 @@ public class TYPEStmt implements StatementVisitor {
@Override
public void visit(LambdaExpression lambdaExpression) {
TypePlaceholder tphRetType = TypePlaceholder.fresh(new NullToken(), -1, false);
TypePlaceholder tphRetType = TypePlaceholder.fresh(new NullToken());
List<RefTypeOrTPHOrWildcardOrGeneric> lambdaParams = lambdaExpression.params.getFormalparalist().stream().map((formalParameter -> formalParameter.getType())).collect(Collectors.toList());
lambdaParams.add(tphRetType);
// lambdaParams.add(0,tphRetType);
@@ -635,7 +635,6 @@ public class TYPEStmt implements StatementVisitor {
params.add(resolver.resolve(new GenericRefType(gtv.getName(), new NullToken())));
}
RefTypeOrTPHOrWildcardOrGeneric receiverType;
if (receiver instanceof FunNClass) {
receiverType = new RefType(new JavaClassName(receiver.getClassName().toString() + "$$"), params, new NullToken()); // new FunN(params);
} else {

View File

@@ -53,7 +53,7 @@ class Node<T> {
addDescendant(descendant);
}
}
/**
* Adds a directed edge from the predecessor to this node (predecessor -> this)
*/
@@ -73,7 +73,7 @@ class Node<T> {
addPredecessor(predecessor);
}
}
/**
* The content of this node.
*/

View File

@@ -1,6 +1,6 @@
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.*;
import static targetast.TestCodegen.generateClassFiles;
import java.io.File;
@@ -9,12 +9,13 @@ import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.collect.Lists;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
public class AllgemeinTest {

View File

@@ -6,12 +6,12 @@ import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.target.generate.ASTToTargetAST;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.*;
public class GenericsParserTest {

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
import de.dhbwstuttgart.core.JavaTXCompiler;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.util.List;
@@ -24,7 +24,7 @@ public class TestPackages {
}
@Test
@Disabled("This doesn't work")
@Ignore("This doesn't work")
public void testPackagesCircular() throws Exception {
var cmp = new JavaTXCompiler(
List.of(

View File

@@ -4,7 +4,7 @@ import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.io.File;
import java.nio.file.Path;

View File

@@ -4,7 +4,7 @@ package astfactory;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
@@ -12,8 +12,7 @@ import java.lang.reflect.TypeVariable;
import java.util.Arrays;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.*;
public class ASTFactoryTest<A> extends HashMap<String, A>{
@Test

View File

@@ -3,7 +3,7 @@ package finiteClosure;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.FCGenerator;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;

View File

@@ -0,0 +1,51 @@
package languageServerInterfaceTest;
import de.dhbwstuttgart.core.ConsoleInterface;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import org.junit.Ignore;
import org.junit.Test;
import de.dhbwstuttgart.languageServerInterface.LanguageServerInterface;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class LangaugeServerInterfaceTest {
@Test
@Ignore
public void consoleInterfaceTest() throws IOException, ClassNotFoundException, URISyntaxException {
LanguageServerInterface languageServerInterface = new LanguageServerInterface();
var resp = languageServerInterface.getResultSetAndAbstractSyntax("/home/ruben/code/JavaCompilerCore/src/test/java/languageServerInterfaceTest/test.jav");
System.out.println("\n-----------------------------------------\n");
System.out.println(ASTPrinter.print(resp.getAst()));
System.out.println("\n-----------------------------------------\n");
LanguageServerInterface languageServerInterface2 = new LanguageServerInterface();
var ast = languageServerInterface2.getAst("/home/ruben/code/JavaCompilerCore/src/test/java/languageServerInterfaceTest/test.jav", "N");
System.out.println("\n-----------------------------------------\n");
System.out.println(ASTPrinter.print(ast));
System.out.println("\n-----------------------------------------\n");
System.out.println("");
}
@Test
@Ignore
public void testBytecodeGen() throws IOException, ClassNotFoundException, URISyntaxException {
//TODO: Ordner und Datei löschen wenn sie bereits existieren
LanguageServerInterface languageServerInterface = new LanguageServerInterface();
languageServerInterface.generateBytecode(new URI("c%3A/Users/ruben/Neuer%20Ordner%20%282%29/LSP-Vortrag/images/"));
}
}

View File

@@ -0,0 +1,5 @@
public class t{
public mofus(){
return 1;
}
}

View File

@@ -1,5 +1,9 @@
package syntaxtreegenerator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
@@ -8,23 +12,21 @@ import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.BeforeClass;
import org.junit.Test;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import static org.junit.jupiter.api.Assertions.*;
/**
* Unit-Tests für den 'SyntaxTreeGenerator' aus dem Package 'parser' nach Vorbild der Klasse 'TestComplete' aus dem Test-Package 'targetast'
*/
public class TestComplete {
private static HashMap<String, File[]> javFiles = new HashMap<>();
@BeforeAll
@BeforeClass
public static void setUp() {
final String testFileDirectory = "resources/bytecode/javFiles/";
final String expectedASTDirectory = "resources/syntaxtreegenerator/";
@@ -351,7 +353,7 @@ public class TestComplete {
assertEquals("Comparing expected and resulting AST for mathStrucInteger.jav", expectedAST, resultingAST);
} catch (Exception exc) {
exc.printStackTrace();
assertInstanceOf(NotImplementedException.class, exc);
assertTrue("An error occured while generating the AST for mathStrucInteger.jav", exc instanceof NotImplementedException);
}
}

View File

@@ -1,15 +1,15 @@
package syntaxtreegenerator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.util.HashMap;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.BeforeClass;
import org.junit.Test;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
@@ -17,7 +17,7 @@ import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
public class TestNewFeatures {
private static HashMap<String, File[]> javFiles = new HashMap<>();
@BeforeAll
@BeforeClass
public static void setUp() {
final String testFileDirectory = "resources/syntaxtreegenerator/javFiles/";
final String expectedASTDirectory = "resources/syntaxtreegenerator/";

View File

@@ -2,6 +2,7 @@ package targetast;
import com.google.common.reflect.TypeToken;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.syntaxtree.*;
@@ -9,13 +10,13 @@ import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.target.generate.ASTToTargetAST;
import de.dhbwstuttgart.target.tree.TargetStructure;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.Ignore;
import org.junit.Test;
import java.nio.file.Path;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.*;
public class ASTToTypedTargetAST {
@@ -23,7 +24,7 @@ public class ASTToTypedTargetAST {
public void emptyClass() {
ClassOrInterface emptyClass = new ClassOrInterface(0, new JavaClassName("EmptyClass"), new ArrayList<>(), Optional.empty(), Optional.empty(), new ArrayList<>(), new ArrayList<>(), new GenericDeclarationList(new ArrayList<>(), new NullToken()), new RefType(new JavaClassName("Object"), new NullToken()), false, false, new ArrayList<>(), new ArrayList<>(), new NullToken(), null);
ResultSet emptyResultSet = new ResultSet(new HashSet<>());
TargetStructure emptyTargetClass = new ASTToTargetAST(List.of(emptyResultSet), TestCodegen.createClassLoader()).convert(emptyClass);
TargetStructure emptyTargetClass = new ASTToTargetAST(List.of(emptyResultSet)).convert(emptyClass);
assert emptyTargetClass.getName().equals("EmptyClass");
assert emptyTargetClass.methods().size() == 0;
assert emptyTargetClass.fields().size() == 0;
@@ -31,14 +32,13 @@ public class ASTToTypedTargetAST {
@Test
public void overloading() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Overloading.jav").toFile();
var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses();
var classLoader = new ByteArrayClassLoader();
var overloading = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
var overloading2 = TestCodegen.generateClass(converter.convert(classes.get(1)), classLoader);
@@ -54,54 +54,46 @@ public class ASTToTypedTargetAST {
@Test
public void tphsAndGenerics() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Tph2.jav").toFile();
var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses();
var tphAndGenerics = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
var tphAndGenerics = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
}
@Test
public void cycles() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Cycle.jav").toFile();
var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses();
var cycle = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
var cycle = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
}
@Test
public void infimum() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Infimum.jav").toFile();
var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses();
var infimum = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
var infimum = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
}
@Test
public void gen() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Gen.jav").toFile();
var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses();
var generics = TestCodegen.generateClass(converter.convert(classes.get(0)), TestCodegen.createClassLoader());
var generics = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
var m = generics.getDeclaredMethod("m", Vector.class);
var mReturnType = m.getGenericReturnType();
assertEquals(mReturnType, m.getParameters()[0].getParameterizedType());
@@ -111,15 +103,13 @@ public class ASTToTypedTargetAST {
@Test
public void definedGenerics() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics.jav").toFile();
var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses();
var generics = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
var generics = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
var B = generics.getTypeParameters()[0];
var mt1 = generics.getDeclaredMethod("mt1", Object.class);
var constructor = generics.getDeclaredConstructor(Object.class);
@@ -131,15 +121,13 @@ public class ASTToTypedTargetAST {
@Test
public void definedGenerics2() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics2.jav").toFile();
var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses();
var generics2 = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
var generics2 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
assertEquals(generics2.getTypeParameters()[0].getBounds()[0], String.class);
var m = generics2.getDeclaredMethod("m1", Object.class);
assertEquals(m.getTypeParameters()[0].getBounds()[0], Integer.class);
@@ -147,30 +135,26 @@ public class ASTToTypedTargetAST {
}
@Test
@Disabled("Not implemented")
@Ignore("Not implemented")
public void definedGenerics3() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics3.jav").toFile();
var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses();
var generics3 = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
var generics3 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
}
@Test
public void definedGenerics4() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics4.jav").toFile();
var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var converter = new ASTToTargetAST(compiler, resultSet);
var classes = compiler.sourceFiles.get(file).getClasses();
var generics4 = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
var generics4 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader());
// var instance = generics4.getDeclaredConstructor().newInstance();
// var method = generics4.getDeclaredMethod("m2", Object.class);

View File

@@ -1,21 +1,22 @@
package targetast;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class GreaterEqualTest {
static Class<?> classToTest;
static Object instance;
@BeforeAll
@BeforeClass
public static void beforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "GreaterEqual.jav");
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "GreaterEqual.jav");
classToTest = classFiles.get("GreaterEqual");
instance = classToTest.getDeclaredConstructor().newInstance();
}

View File

@@ -1,20 +1,21 @@
package targetast;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class GreaterThanTest {
static Class<?> classToTest;
static Object instance;
@BeforeAll
@BeforeClass
public static void beforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "GreaterThan.jav");
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "GreaterThan.jav");
classToTest = classFiles.get("GreaterThan");
instance = classToTest.getDeclaredConstructor().newInstance();
}

View File

@@ -1,20 +1,22 @@
package targetast;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.util.Vector;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertEquals;
public class InheritTest {
private static Class<?> classToTest, classToTestAA, classToTestBB, classToTestCC, classToTestDD;
private static Object instanceOfClass, instanceOfClassAA, instanceOfClassBB, instanceOfClassCC, instanceOfClassDD;
@BeforeAll
@BeforeClass
public static void setUpBeforeClass() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var classLoader = new ByteArrayClassLoader();
var classes = TestCodegen.generateClassFiles(classLoader, "Inherit.jav");
classToTest = classes.get("Inherit");
@@ -33,72 +35,72 @@ public class InheritTest {
@Test
public void testmainAA() throws Exception {
Method m = classToTestAA.getDeclaredMethod("m", Integer.class);
assertEquals("AA", m.invoke(instanceOfClassAA, 5));
assertEquals(m.invoke(instanceOfClassAA, 5), "AA");
Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class);
assertEquals("AA", main.invoke(instanceOfClass, instanceOfClassAA, 5));
assertEquals(main.invoke(instanceOfClass, instanceOfClassAA, 5), "AA");
}
@Test
public void testmainBB() throws Exception {
Method m = classToTestAA.getDeclaredMethod("m", Integer.class);
assertEquals("AA", m.invoke(instanceOfClassBB, 5));
assertEquals(m.invoke(instanceOfClassBB, 5), "AA");
Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class);
assertEquals("AA", main.invoke(instanceOfClass, instanceOfClassBB, 5));
assertEquals(main.invoke(instanceOfClass, instanceOfClassBB, 5), "AA");
}
@Test
public void testmainCC() throws Exception {
Method m = classToTestCC.getDeclaredMethod("m", Integer.class);
assertEquals("CC", m.invoke(instanceOfClassCC, 5));
assertEquals(m.invoke(instanceOfClassCC, 5), "CC");
Method main = classToTest.getDeclaredMethod("main", classToTestCC, Integer.class);
assertEquals("CC", main.invoke(instanceOfClass, instanceOfClassCC, 5));
assertEquals(main.invoke(instanceOfClass, instanceOfClassCC, 5), "CC");
}
@Test
public void testmainDD() throws Exception {
Method m = classToTestCC.getDeclaredMethod("m", Integer.class);
assertEquals("CC", m.invoke(instanceOfClassDD, 5));
assertEquals(m.invoke(instanceOfClassDD, 5), "CC");
Method main = classToTest.getDeclaredMethod("main", classToTestCC, Integer.class);
assertEquals("CC", main.invoke(instanceOfClass, instanceOfClassDD, 5));
assertEquals(main.invoke(instanceOfClass, instanceOfClassDD, 5), "CC");
}
@Test
public void testmainVectorAA() throws Exception {
Method m = classToTestAA.getDeclaredMethod("m", Integer.class);
assertEquals("AA", m.invoke(instanceOfClassAA, 5));
assertEquals(m.invoke(instanceOfClassAA, 5), "AA");
Vector v = new Vector<>();
v.add(instanceOfClassAA);
Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class);
assertEquals("AA", main.invoke(instanceOfClass, v, 5));
assertEquals(main.invoke(instanceOfClass, v, 5), "AA");
}
@Test
public void testmainVectorBB() throws Exception {
Method m = classToTestAA.getDeclaredMethod("m", Integer.class);
assertEquals("AA", m.invoke(instanceOfClassBB, 5));
assertEquals(m.invoke(instanceOfClassBB, 5), "AA");
Vector v = new Vector<>();
v.add(instanceOfClassBB);
Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class);
assertEquals("AA", main.invoke(instanceOfClass, v, 5));
assertEquals(main.invoke(instanceOfClass, v, 5), "AA");
}
@Test
public void testmainVectorCC() throws Exception {
Method m = classToTestCC.getDeclaredMethod("m", Integer.class);
assertEquals("CC", m.invoke(instanceOfClassCC, 5));
assertEquals(m.invoke(instanceOfClassCC, 5), "CC");
Vector v = new Vector<>();
v.add(instanceOfClassCC);
Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class);
assertEquals("CC", main.invoke(instanceOfClass, v, 5));
assertEquals(main.invoke(instanceOfClass, v, 5), "CC");
}
@Test
public void testmainVectorDD() throws Exception {
Method m = classToTestCC.getDeclaredMethod("m", Integer.class);
assertEquals("CC", m.invoke(instanceOfClassDD, 5));
assertEquals(m.invoke(instanceOfClassDD, 5), "CC");
Vector v = new Vector<>();
v.add(instanceOfClassDD);
Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class);
assertEquals("CC", main.invoke(instanceOfClass, v, 5));
assertEquals(main.invoke(instanceOfClass, v, 5), "CC");
}
}

View File

@@ -1,22 +1,23 @@
package targetast;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.lang.reflect.Method;
import java.util.Vector;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertEquals;
@Disabled("FIXME")
@Ignore("FIXME")
public class InheritTest2 {
private static Class<?> classToTest, classToTestAA, classToTestBB, classToTestCC, classToTestDD;
private static Object instanceOfClass, instanceOfClassAA, instanceOfClassBB, instanceOfClassCC, instanceOfClassDD;
@BeforeAll
@BeforeClass
public static void setUpBeforeClass() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var classLoader = new ByteArrayClassLoader();
classToTest = TestCodegen.generateClassFiles(classLoader, "Inherit2.jav").get("Inherit2");
classToTestAA = TestCodegen.generateClassFiles(classLoader, "AA.jav").get("AA");
classToTestBB = TestCodegen.generateClassFiles(classLoader, "BB.jav").get("BB");

View File

@@ -1,20 +1,21 @@
package targetast;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class LessEqualTest {
static Class<?> classToTest;
static Object instance;
@BeforeAll
@BeforeClass
public static void beforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "LessEqual.jav");
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "LessEqual.jav");
classToTest = classFiles.get("LessEqual");
instance = classToTest.getDeclaredConstructor().newInstance();
}

View File

@@ -1,20 +1,21 @@
package targetast;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class LessThanTest {
static Class<?> classToTest;
static Object instance;
@BeforeAll
@BeforeClass
public static void beforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "LessThan.jav");
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "LessThan.jav");
classToTest = classFiles.get("LessThan");
instance = classToTest.getDeclaredConstructor().newInstance();
}

View File

@@ -1,12 +1,12 @@
package targetast;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertEquals;
public class OLTest {
private static Class<?> classToTest;
@@ -14,9 +14,9 @@ public class OLTest {
private static Object instanceOfClass;
private static Object instanceOfClass1;
@BeforeAll
@BeforeClass
public static void setUpBeforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "OL.jav");
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "OL.jav");
classToTest = classFiles.get("OL");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
classToTest1 = classFiles.get("OLMain");

View File

@@ -1,19 +1,20 @@
package targetast;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertEquals;
public class PostIncTest {
private static Class<?> classToTest;
private static Object instanceOfClass;
@BeforeAll
@BeforeClass
public static void setUpBeforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "PostIncDec.jav");
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "PostIncDec.jav");
classToTest = classFiles.get("PostIncDec");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
}

View File

@@ -1,19 +1,20 @@
package targetast;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertEquals;
public class PreIncTest {
private static Class<?> classToTest;
private static Object instanceOfClass;
@BeforeAll
@BeforeClass
public static void setUpBeforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "PreInc.jav");
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "PreInc.jav");
classToTest = classFiles.get("PreInc");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
}

View File

@@ -1,21 +1,22 @@
package targetast;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Method;
import java.util.Stack;
import java.util.Vector;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertEquals;
public class PutTest {
private static Class<?> classToTest;
private static Object instanceOfClass;
@BeforeAll
@BeforeClass
public static void setUpBeforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "Put.jav");
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "Put.jav");
classToTest = classFiles.get("Put");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
}

View File

@@ -2,7 +2,7 @@ package targetast;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.bytecode.Codegen;
import de.dhbwstuttgart.environment.DirectoryClassLoader;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import de.dhbwstuttgart.environment.IByteArrayClassLoader;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.target.generate.ASTToTargetAST;
@@ -14,10 +14,10 @@ import de.dhbwstuttgart.target.tree.expression.*;
import de.dhbwstuttgart.target.tree.type.TargetFunNType;
import de.dhbwstuttgart.target.tree.type.TargetRefType;
import de.dhbwstuttgart.target.tree.type.TargetType;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.*;
import org.objectweb.asm.Opcodes;
@@ -37,10 +37,6 @@ public class TestCodegen {
Files.write(outputPath.resolve(name + ".class"), code);
}
public static IByteArrayClassLoader createClassLoader() {
return new DirectoryClassLoader(List.of(outputPath.toFile()), ClassLoader.getSystemClassLoader());
}
public static Path path = Path.of(System.getProperty("user.dir"), "resources/bytecode/javFiles/");
public static Map<String, ? extends Class<?>> generateClassFiles(IByteArrayClassLoader classLoader, String... files) throws IOException, ClassNotFoundException {
@@ -123,7 +119,7 @@ public class TestCodegen {
public void testEmptyClass() throws Exception {
var clazz = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("Empty"));
clazz.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "main", List.of(), null, new TargetBlock(List.of()));
generateClass(clazz, createClassLoader()).getDeclaredMethod("main").invoke(null);
generateClass(clazz, new ByteArrayClassLoader()).getDeclaredMethod("main").invoke(null);
}
@Test
@@ -136,7 +132,7 @@ public class TestCodegen {
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "mul", List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Mul(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b"))))));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "rem", List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Rem(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b"))))));
var clazz = generateClass(targetClass, createClassLoader());
var clazz = generateClass(targetClass, new ByteArrayClassLoader());
assertEquals(clazz.getDeclaredMethod("add", Integer.class, Integer.class).invoke(null, 10, 10), 20);
assertEquals(clazz.getDeclaredMethod("sub", Integer.class, Integer.class).invoke(null, 20, 10), 10);
assertEquals(clazz.getDeclaredMethod("div", Integer.class, Integer.class).invoke(null, 20, 10), 2);
@@ -152,7 +148,7 @@ public class TestCodegen {
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "neg", List.of(new MethodParameter(TargetType.Integer, "a")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetUnaryOp.Negate(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"))))));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "add", List.of(new MethodParameter(TargetType.Integer, "a")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetUnaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"))))));
var clazz = generateClass(targetClass, createClassLoader());
var clazz = generateClass(targetClass, new ByteArrayClassLoader());
assertEquals(clazz.getDeclaredMethod("not", Integer.class).invoke(null, 10), -11);
assertEquals(clazz.getDeclaredMethod("neg", Integer.class).invoke(null, 10), -10);
assertEquals(clazz.getDeclaredMethod("add", Integer.class).invoke(null, 10), 10);
@@ -166,7 +162,7 @@ public class TestCodegen {
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "and", List.of(new MethodParameter(TargetType.Boolean, "a"), new MethodParameter(TargetType.Boolean, "b")), TargetType.Boolean, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.And(TargetType.Boolean, new TargetLocalVar(TargetType.Boolean, "a"), new TargetLocalVar(TargetType.Boolean, "b"))))));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "or", List.of(new MethodParameter(TargetType.Boolean, "a"), new MethodParameter(TargetType.Boolean, "b")), TargetType.Boolean, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Or(TargetType.Boolean, new TargetLocalVar(TargetType.Boolean, "a"), new TargetLocalVar(TargetType.Boolean, "b"))))));
var clazz = generateClass(targetClass, createClassLoader());
var clazz = generateClass(targetClass, new ByteArrayClassLoader());
var and = clazz.getDeclaredMethod("and", Boolean.class, Boolean.class);
var or = clazz.getDeclaredMethod("or", Boolean.class, Boolean.class);
assertEquals(and.invoke(null, true, false), false);
@@ -180,7 +176,7 @@ public class TestCodegen {
public void testArithmeticConvert() throws Exception {
var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("ArithmeticConvert"));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "add", List.of(), TargetType.Long, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Add(TargetType.Long, new TargetLiteral.CharLiteral((char) 10), new TargetLiteral.LongLiteral((long) 20))))));
var clazz = generateClass(targetClass, createClassLoader());
var clazz = generateClass(targetClass, new ByteArrayClassLoader());
assertEquals(clazz.getDeclaredMethod("add").invoke(null), (long) 30);
}
@@ -189,7 +185,7 @@ public class TestCodegen {
var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("HelloWorld"));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "helloWorld", List.of(), null, new TargetBlock(List.of(new TargetMethodCall(null, new TargetFieldVar(new TargetRefType("java.io.PrintStream"), new TargetRefType("java.lang.System"), true, new TargetClassName(new TargetRefType("java.lang.System")), "out"), List.of(new TargetLiteral.StringLiteral("Hello World!")), new TargetRefType("java.io.PrintStream"), "println", false, false, false))));
var clazz = generateClass(targetClass, createClassLoader());
var clazz = generateClass(targetClass, new ByteArrayClassLoader());
clazz.getDeclaredMethod("helloWorld").invoke(null);
}
@@ -197,7 +193,7 @@ public class TestCodegen {
public void testIfStatement() throws Exception {
var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("IfStmt"));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "ifStmt", List.of(new MethodParameter(TargetType.Integer, "val")), TargetType.Integer, new TargetBlock(List.of(new TargetIf(new TargetBinaryOp.Equal(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "val"), new TargetLiteral.IntLiteral(10)), new TargetReturn(new TargetLiteral.IntLiteral(1)), new TargetIf(new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "val"), new TargetLiteral.IntLiteral(5)), new TargetReturn(new TargetLiteral.IntLiteral(2)), new TargetReturn(new TargetLiteral.IntLiteral(3)))))));
var clazz = generateClass(targetClass, createClassLoader());
var clazz = generateClass(targetClass, new ByteArrayClassLoader());
var ifStmt = clazz.getDeclaredMethod("ifStmt", Integer.class);
assertEquals(ifStmt.invoke(null, 10), 1);
assertEquals(ifStmt.invoke(null, 3), 2);
@@ -208,7 +204,7 @@ public class TestCodegen {
public void testFor() throws Exception {
var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("For"));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "forLoop", List.of(), TargetType.Integer, new TargetBlock(List.of(new TargetVarDecl(TargetType.Integer, "sum", new TargetLiteral.IntLiteral(0)), new TargetFor(List.of(new TargetVarDecl(TargetType.Integer, "i", new TargetLiteral.IntLiteral(0))), new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(10)), List.of(new TargetAssign(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(1)))), new TargetBlock(List.of(new TargetAssign(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "sum"), new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "sum"), new TargetLocalVar(TargetType.Integer, "i")))))), new TargetReturn(new TargetLocalVar(TargetType.Integer, "sum")))));
var clazz = generateClass(targetClass, createClassLoader());
var clazz = generateClass(targetClass, new ByteArrayClassLoader());
assertEquals(clazz.getDeclaredMethod("forLoop").invoke(null), 45);
}
@@ -216,7 +212,7 @@ public class TestCodegen {
public void testWhile() throws Exception {
var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("While"));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "whileLoop", List.of(), TargetType.Integer, new TargetBlock(List.of(new TargetVarDecl(TargetType.Integer, "i", new TargetLiteral.IntLiteral(0)), new TargetWhile(new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(10)), new TargetBlock(List.of(new TargetAssign(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(1)))))), new TargetReturn(new TargetLocalVar(TargetType.Integer, "i")))));
var clazz = generateClass(targetClass, createClassLoader());
var clazz = generateClass(targetClass, new ByteArrayClassLoader());
assertEquals(clazz.getDeclaredMethod("whileLoop").invoke(null), 10);
}
@@ -239,7 +235,7 @@ public class TestCodegen {
new TargetReturn(new TargetLocalVar(TargetType.Integer, "res"))
)));
var clazz = generateClass(targetClass, createClassLoader());
var clazz = generateClass(targetClass, new ByteArrayClassLoader());
var m = clazz.getDeclaredMethod("switchClassic", Integer.class);
assertEquals(m.invoke(null, 10), 0);
assertEquals(m.invoke(null, 15), 1);
@@ -268,7 +264,7 @@ public class TestCodegen {
List.of(new TargetLiteral.IntLiteral(2))
), true), TargetType.Integer)
))));
var clazz = generateClass(targetClass, createClassLoader());
var clazz = generateClass(targetClass, new ByteArrayClassLoader());
var m = clazz.getDeclaredMethod("switchType", Object.class);
assertEquals(m.invoke(null, "String"), 0);
assertEquals(m.invoke(null, 10), 1);
@@ -277,9 +273,9 @@ public class TestCodegen {
}
@Test
@Disabled("The lambda class is not generated because we don't call ASTToTargetAST")
@Ignore("The lambda class is not generated because we don't call ASTToTargetAST")
public void testLambda() throws Exception {
var classLoader = createClassLoader();
var classLoader = new ByteArrayClassLoader();
// var fun = classLoader.loadClass(Path.of(System.getProperty("user.dir"), "src/test/java/targetast/Fun1$$.class"));
var interfaceType = TargetFunNType.fromParams(List.of(TargetType.Integer), 1);

View File

@@ -12,9 +12,9 @@ import de.dhbwstuttgart.target.generate.Bound;
import static de.dhbwstuttgart.target.generate.Bound.*;
import de.dhbwstuttgart.target.generate.BoundsList;
import de.dhbwstuttgart.target.generate.GenericsResult;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
@@ -22,7 +22,7 @@ import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@Disabled("TODO: Rewrite with the new algorithm")
@Ignore("TODO: Rewrite with the new algorithm")
public class TestGenerics {
private static final String rootDirectory = System.getProperty("user.dir") + "/resources/insertGenerics/javFiles/";
private static final String bytecodeDirectory = System.getProperty("user.dir") + "targetTest";

View File

@@ -1,21 +1,21 @@
package targetast;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertEquals;
public class TphTest {
private static Class<?> classToTest;
private static Object instanceOfClass;
@BeforeAll
@BeforeClass
public static void setUpBeforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "Tph.jav");
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "Tph.jav");
classToTest = classFiles.get("Tph");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
}

View File

@@ -1,19 +1,20 @@
package targetast;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertEquals;
public class WhileTest {
private static Class<?> classToTest;
private static Object instanceOfClass;
@BeforeAll
@BeforeClass
public static void setUpBeforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "While.jav");
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "While.jav");
classToTest = classFiles.get("While");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
}

View File

@@ -8,8 +8,8 @@ import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Disabled;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
@@ -22,7 +22,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Disabled("To be renewed")
@Ignore("To be renewed")
public class JavaTXCompilerTest {
public static final String rootDirectory = System.getProperty("user.dir") + "/src/test/resources/javFiles/";