Bug fixes für GeneralParserTest und Mehrfachaufrufe des Parsers entfernt

This commit is contained in:
luca9913 2023-03-20 22:07:47 +01:00
parent 78a898db37
commit 1ab0f42fd1
12 changed files with 301 additions and 481 deletions

18
pom.xml
View File

@ -53,22 +53,11 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version> <version>3.8.0</version>
<configuration> <configuration>
<release>19</release> <compilerArgs>--enable-preview</compilerArgs>
<compilerArgs>
--enable-preview
</compilerArgs>
<source>19</source> <source>19</source>
<target>19</target> <target>19</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
<plugin> <plugin>
<groupId>org.antlr</groupId> <groupId>org.antlr</groupId>
<artifactId>antlr4-maven-plugin</artifactId> <artifactId>antlr4-maven-plugin</artifactId>
@ -123,8 +112,9 @@ http://maven.apache.org/maven-v4_0_0.xsd">
</repository> </repository>
</repositories> </repositories>
<properties> <properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<mainClass>de.dhbwstuttgart.core.ConsoleInterface</mainClass> <mainClass>de.dhbwstuttgart.core.ConsoleInterface</mainClass>
<release>17</release>
</properties> </properties>
<distributionManagement> <distributionManagement>
<repository> <repository>
@ -133,4 +123,4 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<url>file:///${project.basedir}/maven-repository/</url> <url>file:///${project.basedir}/maven-repository/</url>
</repository> </repository>
</distributionManagement> </distributionManagement>
</project> </project>

View File

@ -543,7 +543,7 @@ statement
; ;
catchClause catchClause
: CATCH '(' variableModifier* catchType identifier ')' block : CATCH '(' variableModifier* catchType? identifier ')' block
; ;
catchType catchType
@ -652,7 +652,7 @@ expression
// Java17 // Java17
pattern pattern
: variableModifier* typeType annotation* identifier : variableModifier* typeType? annotation* identifier
; ;
// Java8 // Java8

View File

@ -58,6 +58,7 @@ import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.util.*; import java.util.*;
import java.util.Map.Entry;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -105,28 +106,22 @@ public class JavaTXCompiler {
public ConstraintSet<Pair> getConstraints() throws ClassNotFoundException, IOException { public ConstraintSet<Pair> getConstraints() throws ClassNotFoundException, IOException {
List<ClassOrInterface> allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); List<ClassOrInterface> allClasses = new ArrayList<>();// environment.getAllAvailableClasses();
List<ClassOrInterface> importedClasses = new ArrayList<>(); List<ClassOrInterface> importedClasses = new ArrayList<>();
ClassOrInterface objectClass = ASTFactory.createClass( ClassOrInterface objectClass = ASTFactory.createClass(classLoader.loadClass(new JavaClassName("java.lang.Object").toString()));
classLoader.loadClass(new JavaClassName("java.lang.Object").toString()));
// Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC
for (File forSourceFile : sourceFiles.keySet()) { for (Entry<File, SourceFile> source : sourceFiles.entrySet()) {
for (JavaClassName name : sourceFiles.get(forSourceFile).getImports()) { for (JavaClassName name : source.getValue().getImports()) {
// TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet // TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet
ClassOrInterface importedClass = ASTFactory.createClass( ClassOrInterface importedClass = ASTFactory.createClass(classLoader.loadClass(name.toString()));
classLoader.loadClass(name.toString()));
importedClasses.add(importedClass); importedClasses.add(importedClass);
} }
for (Class c : CompilationEnvironment.loadDefaultPackageClasses(forSourceFile, classLoader)) { for (Class c : CompilationEnvironment.loadDefaultPackageClasses(source.getValue().getPkgName(), source.getKey(), classLoader)) {
ClassOrInterface importedClass = ASTFactory.createClass(c); ClassOrInterface importedClass = ASTFactory.createClass(c);
importedClasses.add(importedClass); importedClasses.add(importedClass);
} }
} }
for (File f : this.sourceFiles.keySet()) { for (File f : this.sourceFiles.keySet()) {
SourceFile sf = sourceFiles.get(f); SourceFile sf = sourceFiles.get(f);
sf = new SourceFile(sf.getPkgName(), sf = new SourceFile(sf.getPkgName(), sf.KlassenVektor.stream().map(cl -> new ClassOrInterface(cl)).collect(Collectors.toCollection(ArrayList::new)), sf.imports);
sf.KlassenVektor.stream()
.map(cl -> new ClassOrInterface(cl))
.collect(Collectors.toCollection(ArrayList::new)),
sf.imports);
// sf enthaelt neues Source-File, neue Klassen-Objekte und neue // sf enthaelt neues Source-File, neue Klassen-Objekte und neue
// ArrayListen-Objekte fuer Fields, Construktoren und Methoden // ArrayListen-Objekte fuer Fields, Construktoren und Methoden
// Alle anderen Objekte werden nur kopiert. // Alle anderen Objekte werden nur kopiert.
@ -139,20 +134,17 @@ public class JavaTXCompiler {
return ty.getConstraints(); return ty.getConstraints();
} }
void addMethods(SourceFile sf, ClassOrInterface cl, List<ClassOrInterface> importedClasses, void addMethods(SourceFile sf, ClassOrInterface cl, List<ClassOrInterface> importedClasses, ClassOrInterface objectClass) {
ClassOrInterface objectClass) {
if (!cl.areMethodsAdded()) { if (!cl.areMethodsAdded()) {
ClassOrInterface superclass = null; ClassOrInterface superclass = null;
if (cl.getSuperClass().getName().equals(new JavaClassName("java.lang.Object"))) { if (cl.getSuperClass().getName().equals(new JavaClassName("java.lang.Object"))) {
superclass = objectClass; superclass = objectClass;
} else { } else {
Optional<ClassOrInterface> optSuperclass = importedClasses.stream().filter(x -> x.getClassName().equals( Optional<ClassOrInterface> optSuperclass = importedClasses.stream().filter(x -> x.getClassName().equals(cl.getSuperClass().getName())).findFirst();
cl.getSuperClass().getName())).findFirst();
if (optSuperclass.isPresent()) { if (optSuperclass.isPresent()) {
superclass = optSuperclass.get(); superclass = optSuperclass.get();
} else { } else {
optSuperclass = sf.KlassenVektor.stream().filter(x -> x.getClassName().equals( optSuperclass = sf.KlassenVektor.stream().filter(x -> x.getClassName().equals(cl.getSuperClass().getName())).findFirst();
cl.getSuperClass().getName())).findFirst();
if (optSuperclass.isPresent()) { if (optSuperclass.isPresent()) {
superclass = optSuperclass.get(); superclass = optSuperclass.get();
addMethods(sf, superclass, importedClasses, objectClass); addMethods(sf, superclass, importedClasses, objectClass);
@ -173,21 +165,11 @@ public class JavaTXCompiler {
// werden // werden
while (methodIt.hasNext()) { while (methodIt.hasNext()) {
Method m = methodIt.next(); Method m = methodIt.next();
ParameterList newParaList = new ParameterList( ParameterList newParaList = new ParameterList(m.getParameterList().getFormalparalist().stream().map(fp -> new FormalParameter(fp.getName(), fp.getType().acceptTV(new TypeExchanger(gtvs)), fp.getOffset())).collect(Collectors.toCollection(ArrayList::new)), m.getParameterList().getOffset());
m.getParameterList() cl.getMethods().add(new Method(m.modifier, m.name, m.getReturnType().acceptTV(new TypeExchanger(gtvs)), newParaList, m.block,
.getFormalparalist() // new GenericDeclarationList(newGenericsList,
.stream() // ((GenericDeclarationList)m.getGenerics()).getOffset()),
.map(fp -> new FormalParameter(fp.getName(), fp.getType().acceptTV(new TypeExchanger(gtvs)), (GenericDeclarationList) m.getGenerics(), m.getOffset(), true));
fp.getOffset()))
.collect(Collectors.toCollection(ArrayList::new)),
m.getParameterList().getOffset());
cl.getMethods()
.add(new Method(m.modifier, m.name, m.getReturnType().acceptTV(new TypeExchanger(gtvs)), newParaList,
m.block,
// new GenericDeclarationList(newGenericsList,
// ((GenericDeclarationList)m.getGenerics()).getOffset()),
(GenericDeclarationList) m.getGenerics(),
m.getOffset(), true));
} }
} }
@ -202,23 +184,18 @@ public class JavaTXCompiler {
Set<ClassOrInterface> allClasses = new HashSet<>(); Set<ClassOrInterface> allClasses = new HashSet<>();
/* /*
* PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt * PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt }
* }
* allClasses.addAll(importedClasses); * allClasses.addAll(importedClasses);
* *
* return new TYPE(sourceFiles.values(), allClasses).getConstraints(); * return new TYPE(sourceFiles.values(), allClasses).getConstraints(); }
* }
* *
* public List<ClassOrInterface> getAvailableClasses(SourceFile forSourceFile) * public List<ClassOrInterface> getAvailableClasses(SourceFile forSourceFile)
* throws ClassNotFoundException { * throws ClassNotFoundException { // PL 2018-09-18: List durch Set ersetzt,
* // PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal * damit die Klassen nur einmal // hinzugefuegt werden // List<ClassOrInterface>
* // hinzugefuegt werden * allClasses = new // ArrayList<>();//environment.getAllAvailableClasses();
* // List<ClassOrInterface> allClasses = new
* // ArrayList<>();//environment.getAllAvailableClasses();
* Set<ClassOrInterface> allClasses = new HashSet<>(); * Set<ClassOrInterface> allClasses = new HashSet<>();
* *
* /* * /* PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt for
* PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt for
* (SourceFile sf : sourceFiles.values()) { allClasses.addAll(sf.getClasses()); * (SourceFile sf : sourceFiles.values()) { allClasses.addAll(sf.getClasses());
* } * }
*/ */
@ -226,8 +203,7 @@ public class JavaTXCompiler {
List<ClassOrInterface> importedClasses = new ArrayList<>(); List<ClassOrInterface> importedClasses = new ArrayList<>();
for (JavaClassName name : forSourceFile.getImports()) { for (JavaClassName name : forSourceFile.getImports()) {
// TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet // TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet
ClassOrInterface importedClass = ASTFactory ClassOrInterface importedClass = ASTFactory.createClass(classLoader.loadClass(name.toString()));
.createClass(classLoader.loadClass(name.toString()));
importedClasses.add(importedClass); importedClasses.add(importedClass);
allClasses.addAll(importedClasses); allClasses.addAll(importedClasses);
} }
@ -379,16 +355,14 @@ public class JavaTXCompiler {
* } * }
*/ */
public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) throws ClassNotFoundException, IOException {
throws ClassNotFoundException, IOException {
List<ClassOrInterface> allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); List<ClassOrInterface> allClasses = new ArrayList<>();// environment.getAllAvailableClasses();
// Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC
for (File f : this.sourceFiles.keySet()) { for (Entry<File, SourceFile> source : this.sourceFiles.entrySet()) {
SourceFile sf = sourceFiles.get(f); SourceFile sf = source.getValue();
allClasses.addAll(getAvailableClasses(sf)); allClasses.addAll(getAvailableClasses(sf));
allClasses.addAll(sf.getClasses()); allClasses.addAll(sf.getClasses());
allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(f, classLoader).stream() allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(sf.getPkgName(), source.getKey(), classLoader).stream().map(ASTFactory::createClass).collect(Collectors.toList()));
.map(ASTFactory::createClass).collect(Collectors.toList()));
} }
final ConstraintSet<Pair> cons = getConstraints(); final ConstraintSet<Pair> cons = getConstraints();
@ -396,9 +370,7 @@ public class JavaTXCompiler {
UnifyResultModel urm = null; UnifyResultModel urm = null;
// urm.addUnifyResultListener(resultListener); // urm.addUnifyResultListener(resultListener);
try { try {
logFile = logFile == null logFile = logFile == null ? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName())) : logFile;
? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName()))
: logFile;
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader);
System.out.println(finiteClosure); System.out.println(finiteClosure);
urm = new UnifyResultModel(cons, finiteClosure); urm = new UnifyResultModel(cons, finiteClosure);
@ -407,9 +379,7 @@ public class JavaTXCompiler {
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> { Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
UnifyType lhs, rhs; UnifyType lhs, rhs;
if (((lhs = x.getLhsType()) instanceof PlaceholderType) if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
&& ((rhs = x.getRhsType()) instanceof PlaceholderType)
&& (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
((PlaceholderType) lhs).setInnerType(true); ((PlaceholderType) lhs).setInnerType(true);
((PlaceholderType) rhs).setInnerType(true); ((PlaceholderType) rhs).setInnerType(true);
} }
@ -427,58 +397,40 @@ public class JavaTXCompiler {
} }
logFile.flush(); logFile.flush();
Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream() Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist().stream().filter(z -> z.getType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce(new HashSet<String>(), (a, b) -> {
.map(y -> y.getParameterList().getFormalparalist().stream() a.addAll(b);
.filter(z -> z.getType() instanceof TypePlaceholder) return a;
.map(z -> ((TypePlaceholder) z.getType()).getName()) }, (a, b) -> {
.collect(Collectors.toCollection(HashSet::new))) a.addAll(b);
.reduce(new HashSet<String>(), (a, b) -> { return a;
a.addAll(b); })).reduce(new HashSet<String>(), (a, b) -> {
return a; a.addAll(b);
}, (a, b) -> { return a;
a.addAll(b); });
return a;
})).reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
});
Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream() Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream().map(y -> y.getParameterList().getFormalparalist().stream().filter(z -> z.getType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce(new HashSet<String>(), (a, b) -> {
.map(y -> y.getParameterList().getFormalparalist().stream() a.addAll(b);
.filter(z -> z.getType() instanceof TypePlaceholder) return a;
.map(z -> ((TypePlaceholder) z.getType()).getName()) }, (a, b) -> {
.collect(Collectors.toCollection(HashSet::new))) a.addAll(b);
.reduce(new HashSet<String>(), (a, b) -> { return a;
a.addAll(b); })).reduce(new HashSet<String>(), (a, b) -> {
return a; a.addAll(b);
}, (a, b) -> { return a;
a.addAll(b); });
return a;
})).reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
});
Set<String> paraTypeVarNames = methodParaTypeVarNames; Set<String> paraTypeVarNames = methodParaTypeVarNames;
paraTypeVarNames.addAll(constructorParaTypeVarNames); paraTypeVarNames.addAll(constructorParaTypeVarNames);
Set<String> returnTypeVarNames = allClasses.stream() Set<String> returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a, b) -> {
.map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) a.addAll(b);
.map(z -> ((TypePlaceholder) z.getReturnType()).getName()) return a;
.collect(Collectors.toCollection(HashSet::new))) }).get();
.reduce((a, b) -> {
a.addAll(b);
return a;
}).get();
Set<String> fieldTypeVarNames = allClasses.stream() Set<String> fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a, b) -> {
.map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) a.addAll(b);
.map(z -> ((TypePlaceholder) z.getReturnType()).getName()) return a;
.collect(Collectors.toCollection(HashSet::new))) }).get();
.reduce((a, b) -> {
a.addAll(b);
return a;
}).get();
returnTypeVarNames.addAll(fieldTypeVarNames); returnTypeVarNames.addAll(fieldTypeVarNames);
@ -537,19 +489,11 @@ public class JavaTXCompiler {
// logFile, log); // logFile, log);
// Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure); // Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()/* List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()/*
* .stream().map(x -> { * .stream().map(x -> { Set<Set<UnifyPair>> ret = new HashSet<>(); for
* Set<Set<UnifyPair>> ret = new * (Constraint<UnifyPair> y : x) { ret.add(new HashSet<>(y)); } return ret;
* HashSet<>(); * }).collect(Collectors. toCollection(ArrayList::new))
* for (Constraint<UnifyPair> y
* : x) {
* ret.add(new HashSet<>(y));
* }
* return ret;
* }).collect(Collectors.
* toCollection(ArrayList::new))
*/; */;
unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks);
usedTasks);
} catch (IOException e) { } catch (IOException e) {
System.err.println("kein LogFile"); System.err.println("kein LogFile");
} }
@ -559,12 +503,11 @@ public class JavaTXCompiler {
public List<ResultSet> typeInference() throws ClassNotFoundException, IOException { public List<ResultSet> typeInference() throws ClassNotFoundException, IOException {
List<ClassOrInterface> allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); List<ClassOrInterface> allClasses = new ArrayList<>();// environment.getAllAvailableClasses();
// Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC
for (File f : this.sourceFiles.keySet()) { for (Entry<File, SourceFile> source : this.sourceFiles.entrySet()) {
SourceFile sf = sourceFiles.get(f); SourceFile sf = source.getValue();
allClasses.addAll(getAvailableClasses(sf)); allClasses.addAll(getAvailableClasses(sf));
allClasses.addAll(sf.getClasses()); allClasses.addAll(sf.getClasses());
allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(f, classLoader).stream() allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(sf.getPkgName(), source.getKey(), classLoader).stream().map(ASTFactory::createClass).collect(Collectors.toList()));
.map(ASTFactory::createClass).collect(Collectors.toList()));
} }
final ConstraintSet<Pair> cons = getConstraints(); final ConstraintSet<Pair> cons = getConstraints();
@ -573,17 +516,14 @@ public class JavaTXCompiler {
Writer logFile = // new OutputStreamWriter(new NullOutputStream()); Writer logFile = // new OutputStreamWriter(new NullOutputStream());
// new FileWriter(new // new FileWriter(new
// File(System.getProperty("user.dir")+"/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); // File(System.getProperty("user.dir")+"/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName()));
new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" + sourceFiles.keySet().iterator().next().getName()));
+ sourceFiles.keySet().iterator().next().getName()));
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader);
System.out.println(finiteClosure); System.out.println(finiteClosure);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons); ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons);
System.out.println("xxx1"); System.out.println("xxx1");
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> { Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
UnifyType lhs, rhs; UnifyType lhs, rhs;
if (((lhs = x.getLhsType()) instanceof PlaceholderType) if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
&& ((rhs = x.getRhsType()) instanceof PlaceholderType)
&& (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
((PlaceholderType) lhs).setInnerType(true); ((PlaceholderType) lhs).setInnerType(true);
((PlaceholderType) rhs).setInnerType(true); ((PlaceholderType) rhs).setInnerType(true);
} }
@ -604,58 +544,40 @@ public class JavaTXCompiler {
} }
logFile.flush(); logFile.flush();
Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream() Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist().stream().filter(z -> z.getType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce(new HashSet<String>(), (a, b) -> {
.map(y -> y.getParameterList().getFormalparalist().stream() a.addAll(b);
.filter(z -> z.getType() instanceof TypePlaceholder) return a;
.map(z -> ((TypePlaceholder) z.getType()).getName()) }, (a, b) -> {
.collect(Collectors.toCollection(HashSet::new))) a.addAll(b);
.reduce(new HashSet<String>(), (a, b) -> { return a;
a.addAll(b); })).reduce(new HashSet<String>(), (a, b) -> {
return a; a.addAll(b);
}, (a, b) -> { return a;
a.addAll(b); });
return a;
})).reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
});
Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream() Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream().map(y -> y.getParameterList().getFormalparalist().stream().filter(z -> z.getType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce(new HashSet<String>(), (a, b) -> {
.map(y -> y.getParameterList().getFormalparalist().stream() a.addAll(b);
.filter(z -> z.getType() instanceof TypePlaceholder) return a;
.map(z -> ((TypePlaceholder) z.getType()).getName()) }, (a, b) -> {
.collect(Collectors.toCollection(HashSet::new))) a.addAll(b);
.reduce(new HashSet<String>(), (a, b) -> { return a;
a.addAll(b); })).reduce(new HashSet<String>(), (a, b) -> {
return a; a.addAll(b);
}, (a, b) -> { return a;
a.addAll(b); });
return a;
})).reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
});
Set<String> paraTypeVarNames = methodParaTypeVarNames; Set<String> paraTypeVarNames = methodParaTypeVarNames;
paraTypeVarNames.addAll(constructorParaTypeVarNames); paraTypeVarNames.addAll(constructorParaTypeVarNames);
Set<String> returnTypeVarNames = allClasses.stream() Set<String> returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a, b) -> {
.map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) a.addAll(b);
.map(z -> ((TypePlaceholder) z.getReturnType()).getName()) return a;
.collect(Collectors.toCollection(HashSet::new))) }).get();
.reduce((a, b) -> {
a.addAll(b);
return a;
}).get();
Set<String> fieldTypeVarNames = allClasses.stream() Set<String> fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a, b) -> {
.map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) a.addAll(b);
.map(z -> ((TypePlaceholder) z.getReturnType()).getName()) return a;
.collect(Collectors.toCollection(HashSet::new))) }).get();
.reduce((a, b) -> {
a.addAll(b);
return a;
}).get();
returnTypeVarNames.addAll(fieldTypeVarNames); returnTypeVarNames.addAll(fieldTypeVarNames);
@ -699,14 +621,10 @@ public class JavaTXCompiler {
/* /*
* unifyCons.getOderConstraints().forEach(z -> z.forEach(y -> y.forEach(x -> { * unifyCons.getOderConstraints().forEach(z -> z.forEach(y -> y.forEach(x -> {
* if ((x.getLhsType() instanceof PlaceholderType) && * if ((x.getLhsType() instanceof PlaceholderType) &&
* x.getPairOp().compareTo(PairOperator.SMALLERDOT) == 0) { * x.getPairOp().compareTo(PairOperator.SMALLERDOT) == 0) { ((PlaceholderType)
* ((PlaceholderType) x.getLhsType()).setVariance((byte)1); * x.getLhsType()).setVariance((byte)1); } else if ((x.getRhsType() instanceof
* } * PlaceholderType) && x.getPairOp().compareTo(PairOperator.EQUALSDOT) == 0) {
* else if ((x.getRhsType() instanceof PlaceholderType) && * ((PlaceholderType) x.getRhsType()).setVariance((byte)-1); } })));
* x.getPairOp().compareTo(PairOperator.EQUALSDOT) == 0) {
* ((PlaceholderType) x.getRhsType()).setVariance((byte)-1);
* }
* })));
*/ */
System.out.println("Unify nach Oder-Constraints-Anpassung:" + unifyCons.toString()); System.out.println("Unify nach Oder-Constraints-Anpassung:" + unifyCons.toString());
@ -736,11 +654,8 @@ public class JavaTXCompiler {
// Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure); // Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()// .stream().map(x -> { List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()// .stream().map(x -> {
/* /*
* Set<Set<UnifyPair>> ret = new HashSet<>(); * Set<Set<UnifyPair>> ret = new HashSet<>(); for (Constraint<UnifyPair> y : x)
* for (Constraint<UnifyPair> y : x) { * { ret.add(new HashSet<>(y)); } return ret;
* ret.add(new HashSet<>(y));
* }
* return ret;
* }).collect(Collectors.toCollection(ArrayList::new)) * }).collect(Collectors.toCollection(ArrayList::new))
*/; */;
if (resultmodel) { if (resultmodel) {
@ -748,8 +663,7 @@ public class JavaTXCompiler {
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure); UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
UnifyResultListenerImpl li = new UnifyResultListenerImpl(); UnifyResultListenerImpl li = new UnifyResultListenerImpl();
urm.addUnifyResultListener(li); urm.addUnifyResultListener(li);
unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks);
usedTasks);
System.out.println("RESULT Final: " + li.getResults()); System.out.println("RESULT Final: " + li.getResults());
System.out.println("Constraints for Generated Generics: " + " ???"); System.out.println("Constraints for Generated Generics: " + " ???");
logFile.write("RES_FINAL: " + li.getResults().toString() + "\n"); logFile.write("RES_FINAL: " + li.getResults().toString() + "\n");
@ -761,8 +675,7 @@ public class JavaTXCompiler {
// Set<Set<UnifyPair>> result = unify.unify(unifyCons.getUndConstraints(), // Set<Set<UnifyPair>> result = unify.unify(unifyCons.getUndConstraints(),
// oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, // oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons,
// finiteClosure)); // finiteClosure));
Set<Set<UnifyPair>> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, Set<Set<UnifyPair>> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks);
finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks);
System.out.println("RESULT: " + result); System.out.println("RESULT: " + result);
logFile.write("RES: " + result.toString() + "\n"); logFile.write("RES: " + result.toString() + "\n");
logFile.flush(); logFile.flush();
@ -789,9 +702,7 @@ public class JavaTXCompiler {
} catch (IOException e) { } catch (IOException e) {
System.err.println("kein LogFile"); System.err.println("kein LogFile");
} }
return results.stream() return results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))).collect(Collectors.toList());
.map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons)))))
.collect(Collectors.toList());
} }
/** /**
@ -852,8 +763,7 @@ public class JavaTXCompiler {
private SourceFile parse(File sourceFile) throws IOException, java.lang.ClassNotFoundException { private SourceFile parse(File sourceFile) throws IOException, java.lang.ClassNotFoundException {
SourceFileContext tree = JavaTXParser.parse(sourceFile); SourceFileContext tree = JavaTXParser.parse(sourceFile);
SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(sourceFile, classLoader), SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(tree, sourceFile, classLoader), new GenericsRegistry(null));
new GenericsRegistry(null));
SourceFile ret = generator.convert(tree, environment.packageCrawler, classLoader); SourceFile ret = generator.convert(tree, environment.packageCrawler, classLoader);
return ret; return ret;
} }
@ -891,9 +801,8 @@ public class JavaTXCompiler {
} }
/** /**
* @param outputPath - can be null, then class file output * @param outputPath - can be null, then class file output is in the
* is in the same directory as the * same directory as the parsed source files
* parsed source files
* @param typeinferenceResult * @param typeinferenceResult
* @throws IOException * @throws IOException
*/ */
@ -969,8 +878,7 @@ public class JavaTXCompiler {
@Override @Override
public RefTypeOrTPHOrWildcardOrGeneric visit(SuperWildcardType superWildcardType) { public RefTypeOrTPHOrWildcardOrGeneric visit(SuperWildcardType superWildcardType) {
SuperWildcardType ret = new SuperWildcardType(superWildcardType.getInnerType().acceptTV(this), SuperWildcardType ret = new SuperWildcardType(superWildcardType.getInnerType().acceptTV(this), superWildcardType.getOffset());
superWildcardType.getOffset());
return ret; return ret;
} }
@ -982,8 +890,7 @@ public class JavaTXCompiler {
@Override @Override
public RefTypeOrTPHOrWildcardOrGeneric visit(ExtendsWildcardType extendsWildcardType) { public RefTypeOrTPHOrWildcardOrGeneric visit(ExtendsWildcardType extendsWildcardType) {
ExtendsWildcardType ret = new ExtendsWildcardType(extendsWildcardType.getInnerType().acceptTV(this), ExtendsWildcardType ret = new ExtendsWildcardType(extendsWildcardType.getInnerType().acceptTV(this), extendsWildcardType.getOffset());
extendsWildcardType.getOffset());
return ret; return ret;
} }

View File

@ -20,8 +20,8 @@ import de.dhbwstuttgart.parser.scope.JavaClassRegistry;
/** /**
* Stellt die Java-Environment dar und speichert alle Binarys, Librarys und * Stellt die Java-Environment dar und speichert alle Binarys, Librarys und
* Sourcefiles im zu kompilierenden Projekt * Sourcefiles im zu kompilierenden Projekt Sie erstellt anhand dieser
* Sie erstellt anhand dieser Informationen die JavaClassNameRegistry * Informationen die JavaClassNameRegistry
* *
* TODO: Zur Initialisierung der CompilationEnvironment sollten alle SourceFiles * TODO: Zur Initialisierung der CompilationEnvironment sollten alle SourceFiles
* mit ANTLR geparst werden und alle Klassen Generics und Typen herausgefunden * mit ANTLR geparst werden und alle Klassen Generics und Typen herausgefunden
@ -34,16 +34,14 @@ public class CompilationEnvironment {
/** /**
* Imitiert die Environment beim Aufruf des JavaCompilers auf einer Menge von * Imitiert die Environment beim Aufruf des JavaCompilers auf einer Menge von
* java-Dateien * java-Dateien Die Environment enth<EFBFBD>lt automatisch die Java Standard Library
* Die Environment enth<EFBFBD>lt automatisch die Java Standard Library
* *
* @param sourceFiles die zu kompilierenden Dateien * @param sourceFiles die zu kompilierenden Dateien
*/ */
public CompilationEnvironment(List<File> sourceFiles) { public CompilationEnvironment(List<File> sourceFiles) {
/** /**
* Java 9 bringt einige Änderungen am Classloader * Java 9 bringt einige Änderungen am Classloader So funktioniert der
* So funktioniert der BootClassLoader nicht mehr. * BootClassLoader nicht mehr. hier gibts ein paar Quellen zum nachlesen:
* hier gibts ein paar Quellen zum nachlesen:
* http://java9.wtf/class-loading/ * http://java9.wtf/class-loading/
* https://stackoverflow.com/questions/46494112/classloaders-hierarchy-in-java-9 * https://stackoverflow.com/questions/46494112/classloaders-hierarchy-in-java-9
* *
@ -66,13 +64,11 @@ public class CompilationEnvironment {
this.packageCrawler = new PackageCrawler(librarys); this.packageCrawler = new PackageCrawler(librarys);
} }
public JavaClassRegistry getRegistry(File forSourceFile, ClassLoader classLoader) public JavaClassRegistry getRegistry(SourceFileContext tree, File sourceFile, ClassLoader classLoader) throws ClassNotFoundException, IOException {
throws ClassNotFoundException, IOException {
Map<String, Integer> allNames; Map<String, Integer> allNames;
SourceFileContext tree = JavaTXParser.parse(forSourceFile);
if (tree instanceof SrcfileContext srcfile) { if (tree instanceof SrcfileContext srcfile) {
allNames = GatherNames.getNames((SrcfileContext) tree, packageCrawler, classLoader); allNames = GatherNames.getNames((SrcfileContext) tree, packageCrawler, classLoader);
for (Class c : loadDefaultPackageClasses(forSourceFile, classLoader)) { for (Class c : loadDefaultPackageClasses(getPackageName(srcfile), sourceFile, classLoader)) {
allNames.put(c.getName(), c.getTypeParameters().length); allNames.put(c.getName(), c.getTypeParameters().length);
} }
return new JavaClassRegistry(allNames); return new JavaClassRegistry(allNames);
@ -82,18 +78,10 @@ public class CompilationEnvironment {
} }
public static List<Class> loadDefaultPackageClasses(File forSourceFile, ClassLoader classLoader) public static List<Class> loadDefaultPackageClasses(String packageName, File sourceFile, ClassLoader classLoader) throws IOException, ClassNotFoundException {
throws IOException, ClassNotFoundException {
List<Class> ret = new ArrayList<>(); List<Class> ret = new ArrayList<>();
SourceFileContext srcfilectx = JavaTXParser.parse(forSourceFile);
String packageName;
if (srcfilectx instanceof SrcfileContext) {
packageName = getPackageName((SrcfileContext) srcfilectx);
} else {
packageName = "";
}
// Set classLoader to include default package for this specific source file // Set classLoader to include default package for this specific source file
File dir = new File(forSourceFile.getAbsoluteFile().getParent()); File dir = sourceFile.getParentFile();
String dirPath = dir.toString() + "/"; String dirPath = dir.toString() + "/";
if (packageName.length() > 0) if (packageName.length() > 0)
dirPath = dirPath.substring(0, dirPath.length() - packageName.length() - 1); dirPath = dirPath.substring(0, dirPath.length() - packageName.length() - 1);

View File

@ -51,6 +51,7 @@ import de.dhbwstuttgart.parser.antlr.Java17Parser.ModifierContext;
import de.dhbwstuttgart.parser.antlr.Java17Parser.NoclassorinterfaceContext; import de.dhbwstuttgart.parser.antlr.Java17Parser.NoclassorinterfaceContext;
import de.dhbwstuttgart.parser.antlr.Java17Parser.ReftypeContext; import de.dhbwstuttgart.parser.antlr.Java17Parser.ReftypeContext;
import de.dhbwstuttgart.parser.antlr.Java17Parser.SrcfileContext; import de.dhbwstuttgart.parser.antlr.Java17Parser.SrcfileContext;
import de.dhbwstuttgart.parser.antlr.Java17Parser.TypeArgumentsContext;
import de.dhbwstuttgart.parser.scope.GatherNames; import de.dhbwstuttgart.parser.scope.GatherNames;
import de.dhbwstuttgart.parser.scope.GenericsRegistry; import de.dhbwstuttgart.parser.scope.GenericsRegistry;
import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.parser.scope.JavaClassName;
@ -112,18 +113,15 @@ public class SyntaxTreeGenerator {
} }
public String convertQualifiedName(Java17Parser.QualifiedNameContext ctx) { public String convertQualifiedName(Java17Parser.QualifiedNameContext ctx) {
String ret = ""; /*
for (Java17Parser.IdentifierContext ident : ctx.identifier()) { * String ret = ""; for (Java17Parser.IdentifierContext ident :
ret += ident.getText(); * ctx.identifier()) { ret += ident.getText(); if
if (ctx.identifier().iterator().hasNext()) { * (ctx.identifier().iterator().hasNext()) { ret += '.'; } }
ret += '.'; */
} return ctx.getText();
}
return ret;
} }
public SourceFile convert(Java17Parser.SourceFileContext ctx, PackageCrawler packageCrawler, ClassLoader classLoader) public SourceFile convert(Java17Parser.SourceFileContext ctx, PackageCrawler packageCrawler, ClassLoader classLoader) throws ClassNotFoundException, NotImplementedException {
throws ClassNotFoundException, NotImplementedException {
SrcfileContext srcfile; SrcfileContext srcfile;
List<ClassOrInterface> classes = new ArrayList<>(); List<ClassOrInterface> classes = new ArrayList<>();
if (ctx instanceof Java17Parser.SrcfileContext) { if (ctx instanceof Java17Parser.SrcfileContext) {
@ -172,14 +170,12 @@ public class SyntaxTreeGenerator {
} }
private ClassOrInterface convertClass(Java17Parser.ClassDeclarationContext ctx, int modifiers) { private ClassOrInterface convertClass(Java17Parser.ClassDeclarationContext ctx, int modifiers) {
String className = this.pkgName.length() > 0 ? this.pkgName + "." : ctx.identifier().getText(); String className = this.pkgName + (this.pkgName.length() > 0 ? "." : "") + ctx.identifier().getText();
JavaClassName name = reg.getName(className); // Holt den Package Namen mit dazu JavaClassName name = reg.getName(className); // Holt den Package Namen mit dazu
if (!name.toString().equals(className)) { // Kommt die Klasse schon in einem anderen Package vor? if (!name.toString().equals(className)) { // Kommt die Klasse schon in einem anderen Package vor?
throw new TypeinferenceException( throw new TypeinferenceException("Name " + className + " bereits vorhanden in " + reg.getName(className).toString(), ctx.getStart());
"Name " + className + " bereits vorhanden in " + reg.getName(className).toString(), ctx.getStart());
} }
GenericsRegistry generics = createGenerics(ctx.genericDeclarationList(), name, "", reg, GenericsRegistry generics = createGenerics(ctx.genericDeclarationList(), name, "", reg, new GenericsRegistry(globalGenerics));
new GenericsRegistry(globalGenerics));
Token offset = ctx.getStart(); Token offset = ctx.getStart();
GenericDeclarationList genericClassParameters; GenericDeclarationList genericClassParameters;
if (ctx.genericDeclarationList() == null) { if (ctx.genericDeclarationList() == null) {
@ -209,30 +205,29 @@ public class SyntaxTreeGenerator {
membermodifiers += allmodifiers.get(mod.getText()); membermodifiers += allmodifiers.get(mod.getText());
} }
switch (member.memberDeclaration()) { switch (member.memberDeclaration()) {
case MemberclassorinterfaceContext memberclsoif: { case MemberclassorinterfaceContext memberclsoif: {
break; break;
} }
case MemberfieldContext memberfield: { case MemberfieldContext memberfield: {
fielddecl.addAll(convert(memberfield.fieldDeclaration(), membermodifiers, generics)); fielddecl.addAll(convert(memberfield.fieldDeclaration(), membermodifiers, generics));
break; break;
} }
case MembermethodContext membermethod: { case MembermethodContext membermethod: {
methods.add(convert(membermodifiers, membermethod.method(), name, superClass, generics)); methods.add(convert(membermodifiers, membermethod.method(), name, superClass, generics));
break; break;
} }
case MemberconstructorContext memberconstructor: { case MemberconstructorContext memberconstructor: {
constructors.add(convert(membermodifiers, memberconstructor.constructor(), name, superClass, generics)); constructors.add(convert(membermodifiers, memberconstructor.constructor(), name, superClass, generics));
break; break;
} }
default: default:
break; break;
} }
} else { } else {
continue; continue;
} }
if (constructors.isEmpty()) { if (constructors.isEmpty()) {
constructors.add(generateStandardConstructor( constructors.add(generateStandardConstructor(ctx.identifier().getText(), name, superClass, genericClassParameters, offset));
ctx.identifier().getText(), name, superClass, genericClassParameters, offset));
} }
if (ctx.IMPLEMENTS() != null) { if (ctx.IMPLEMENTS() != null) {
implementedInterfaces.addAll(convert(ctx.typeList(0), generics)); implementedInterfaces.addAll(convert(ctx.typeList(0), generics));
@ -240,38 +235,33 @@ public class SyntaxTreeGenerator {
// Ist Bit für 'sealed'-Modifier gesetzt // Ist Bit für 'sealed'-Modifier gesetzt
if ((modifiers & 4096) != 0) { if ((modifiers & 4096) != 0) {
switch (ctx.typeList().size()) { switch (ctx.typeList().size()) {
case 1: { case 1: {
permittedSubtypes.addAll(convert(ctx.typeList(0), generics)); permittedSubtypes.addAll(convert(ctx.typeList(0), generics));
break; break;
} }
case 2: { case 2: {
permittedSubtypes.addAll(convert(ctx.typeList(1), generics)); permittedSubtypes.addAll(convert(ctx.typeList(1), generics));
break; break;
} }
default: { default: {
break; break;
} }
} }
} }
} }
return new ClassOrInterface(modifiers, name, fielddecl, return new ClassOrInterface(modifiers, name, fielddecl, Optional.of(this.generatePseudoConstructor(ctx.identifier().getText(), name, superClass, genericClassParameters, offset)), methods, constructors, genericClassParameters, superClass, isInterface, implementedInterfaces, offset);
Optional.of(this.generatePseudoConstructor(ctx.identifier().getText(), name, superClass, genericClassParameters,
offset)),
methods, constructors, genericClassParameters, superClass, isInterface, implementedInterfaces, offset);
} }
private ClassOrInterface convertInterface(Java17Parser.InterfaceDeclarationContext ctx, int modifiers) { private ClassOrInterface convertInterface(Java17Parser.InterfaceDeclarationContext ctx, int modifiers) {
String className = this.pkgName.length() > 0 ? this.pkgName + "." : "" + ctx.identifier().getText(); String className = this.pkgName.length() > 0 ? this.pkgName + "." : "" + ctx.identifier().getText();
JavaClassName name = reg.getName(className); // Holt den Package Namen mit dazu JavaClassName name = reg.getName(className); // Holt den Package Namen mit dazu
if (!name.toString().equals(className)) { // Kommt die Klasse schon in einem anderen Package vor? if (!name.toString().equals(className)) { // Kommt die Klasse schon in einem anderen Package vor?
throw new TypeinferenceException( throw new TypeinferenceException("Name " + className + " bereits vorhanden in " + reg.getName(className).toString(), ctx.getStart());
"Name " + className + " bereits vorhanden in " + reg.getName(className).toString(), ctx.getStart());
} }
if (!Modifier.isInterface(modifiers)) if (!Modifier.isInterface(modifiers))
modifiers += Modifier.INTERFACE; modifiers += Modifier.INTERFACE;
GenericsRegistry generics = createGenerics(ctx.genericDeclarationList(), name, "", reg, GenericsRegistry generics = createGenerics(ctx.genericDeclarationList(), name, "", reg, new GenericsRegistry(globalGenerics));
new GenericsRegistry(globalGenerics));
GenericDeclarationList genericParams; GenericDeclarationList genericParams;
if (!Objects.isNull(ctx.genericDeclarationList())) { if (!Objects.isNull(ctx.genericDeclarationList())) {
@ -294,32 +284,29 @@ public class SyntaxTreeGenerator {
} }
int methodmodifiers = membermodifiers; int methodmodifiers = membermodifiers;
switch (interfacemember.interfaceMemberDeclaration()) { switch (interfacemember.interfaceMemberDeclaration()) {
case InterfaceconstContext constant: case InterfaceconstContext constant:
fields.add(convert(constant)); fields.add(convert(constant));
break; break;
case InterfacemethodContext method: case InterfacemethodContext method:
InterfaceMethodDeclarationContext declaration = method.interfaceMethodDeclaration(); InterfaceMethodDeclarationContext declaration = method.interfaceMethodDeclaration();
for (InterfaceMethodModifierContext mod : declaration.interfaceMethodModifier()) { for (InterfaceMethodModifierContext mod : declaration.interfaceMethodModifier()) {
methodmodifiers += allmodifiers.get(mod.getText()); methodmodifiers += allmodifiers.get(mod.getText());
} }
InterfaceCommonBodyDeclarationContext commonbody = declaration.interfaceCommonBodyDeclaration(); InterfaceCommonBodyDeclarationContext commonbody = declaration.interfaceCommonBodyDeclaration();
methods.add(convert(methodmodifiers, commonbody, new GenericDeclarationList(new ArrayList<>(), methods.add(convert(methodmodifiers, commonbody, new GenericDeclarationList(new ArrayList<>(), commonbody.getStart()), generics));
commonbody.getStart()), generics)); break;
break; case GenericinterfacemethodContext genericmethod:
case GenericinterfacemethodContext genericmethod: GenericInterfaceMethodDeclarationContext genericdeclaration = genericmethod.genericInterfaceMethodDeclaration();
GenericInterfaceMethodDeclarationContext genericdeclaration = genericmethod int genericmethodmodifiers = 0;
.genericInterfaceMethodDeclaration(); for (InterfaceMethodModifierContext mod : genericdeclaration.interfaceMethodModifier()) {
int genericmethodmodifiers = 0; genericmethodmodifiers += allmodifiers.get(mod.getText());
for (InterfaceMethodModifierContext mod : genericdeclaration.interfaceMethodModifier()) { }
genericmethodmodifiers += allmodifiers.get(mod.getText()); commonbody = genericdeclaration.interfaceCommonBodyDeclaration();
} GenericDeclarationList gtv = TypeGenerator.convert(genericdeclaration.genericDeclarationList(), name, commonbody.identifier().getText(), reg, generics);
commonbody = genericdeclaration.interfaceCommonBodyDeclaration(); methods.add(convert(genericmethodmodifiers, commonbody, gtv, generics));
GenericDeclarationList gtv = TypeGenerator.convert(genericdeclaration.genericDeclarationList(), name, break;
commonbody.identifier().getText(), reg, generics); default:
methods.add(convert(genericmethodmodifiers, commonbody, gtv, generics)); throw new NotImplementedException();
break;
default:
throw new NotImplementedException();
} }
} }
} }
@ -327,8 +314,7 @@ public class SyntaxTreeGenerator {
if (!Objects.isNull(ctx.EXTENDS())) { if (!Objects.isNull(ctx.EXTENDS())) {
extendedInterfaces.addAll(convert(ctx.typeList(0), generics)); extendedInterfaces.addAll(convert(ctx.typeList(0), generics));
} }
return new ClassOrInterface(modifiers, name, fields, Optional.empty(), methods, new ArrayList<>(), return new ClassOrInterface(modifiers, name, fields, Optional.empty(), methods, new ArrayList<>(), genericParams, superClass, true, extendedInterfaces, ctx.getStart());
genericParams, superClass, true, extendedInterfaces, ctx.getStart());
} }
private GenericDeclarationList createEmptyGenericDeclarationList(Token classNameIdentifier) { private GenericDeclarationList createEmptyGenericDeclarationList(Token classNameIdentifier) {
@ -343,9 +329,7 @@ public class SyntaxTreeGenerator {
throw new NotImplementedException(); throw new NotImplementedException();
} }
private Method convert(int modifiers, InterfaceCommonBodyDeclarationContext bodydeclaration, private Method convert(int modifiers, InterfaceCommonBodyDeclarationContext bodydeclaration, GenericDeclarationList gtvDeclarations, GenericsRegistry generics) {
GenericDeclarationList gtvDeclarations,
GenericsRegistry generics) {
String name = bodydeclaration.identifier().getText(); String name = bodydeclaration.identifier().getText();
RefTypeOrTPHOrWildcardOrGeneric retType; RefTypeOrTPHOrWildcardOrGeneric retType;
@ -372,8 +356,7 @@ public class SyntaxTreeGenerator {
/** /**
* http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.9 * http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.9
*/ */
private Constructor generateStandardConstructor(String className, JavaClassName parentClass, RefType superClass, private Constructor generateStandardConstructor(String className, JavaClassName parentClass, RefType superClass, GenericDeclarationList classGenerics, Token offset) {
GenericDeclarationList classGenerics, Token offset) {
RefType classType = ClassOrInterface.generateTypeOfClass(reg.getName(className), classGenerics, offset); RefType classType = ClassOrInterface.generateTypeOfClass(reg.getName(className), classGenerics, offset);
ParameterList params = new ParameterList(new ArrayList<>(), offset); ParameterList params = new ParameterList(new ArrayList<>(), offset);
Block block = new Block(new ArrayList<>(), offset); Block block = new Block(new ArrayList<>(), offset);
@ -388,15 +371,12 @@ public class SyntaxTreeGenerator {
* fieldInitializations werden in einem Psedokonstruktor in der abstrakten * fieldInitializations werden in einem Psedokonstruktor in der abstrakten
* Syntax gespeichert * Syntax gespeichert
*/ */
private Constructor generatePseudoConstructor(String className, JavaClassName parentClass, RefType superClass, private Constructor generatePseudoConstructor(String className, JavaClassName parentClass, RefType superClass, GenericDeclarationList classGenerics, Token offset) {
GenericDeclarationList classGenerics, Token offset) {
RefType classType = ClassOrInterface.generateTypeOfClass(reg.getName(className), classGenerics, offset); RefType classType = ClassOrInterface.generateTypeOfClass(reg.getName(className), classGenerics, offset);
ParameterList params = new ParameterList(new ArrayList<>(), offset); ParameterList params = new ParameterList(new ArrayList<>(), offset);
Block block = new Block(new ArrayList<>(fieldInitializations), offset); Block block = new Block(new ArrayList<>(fieldInitializations), offset);
return new Constructor(Modifier.PUBLIC, className, classType, params, block, classGenerics, offset /* return new Constructor(Modifier.PUBLIC, className, classType, params, block, classGenerics, offset /*
* fieldInitializations * fieldInitializations geloescht PL 2018-11-24
* geloescht PL
* 2018-11-24
*/); */);
} }
@ -405,11 +385,8 @@ public class SyntaxTreeGenerator {
if (supertypecontext != null && supertypecontext.DOT().size() > 0) { if (supertypecontext != null && supertypecontext.DOT().size() > 0) {
throw new NotImplementedException(); throw new NotImplementedException();
} else { } else {
RefTypeOrTPHOrWildcardOrGeneric ret = TypeGenerator.convertTypeName( TypeArgumentsContext typeArguments = (typeType.classOrInterfaceType().typeArguments().size() > 0) ? typeType.classOrInterfaceType().typeArguments().get(typeType.classOrInterfaceType().typeArguments().size() - 1) : null;
typeType.classOrInterfaceType().typeIdentifier().getText(), RefTypeOrTPHOrWildcardOrGeneric ret = TypeGenerator.convertTypeName(typeType.classOrInterfaceType().typeIdentifier().getText(), typeArguments, typeType.getStart(), reg, globalGenerics);
typeType.classOrInterfaceType().typeArguments()
.get(typeType.classOrInterfaceType().typeArguments().size() - 1),
typeType.getStart(), reg, globalGenerics);
if (ret instanceof RefType) { if (ret instanceof RefType) {
return (RefType) ret; return (RefType) ret;
} else { } else {
@ -426,8 +403,7 @@ public class SyntaxTreeGenerator {
return ret; return ret;
} }
public Method convert(int modifiers, Java17Parser.MethodContext methodContext, JavaClassName parentClass, public Method convert(int modifiers, Java17Parser.MethodContext methodContext, JavaClassName parentClass, RefType superClass, GenericsRegistry generics) {
RefType superClass, GenericsRegistry generics) {
GenericsRegistry localgenerics = generics; GenericsRegistry localgenerics = generics;
MethodDeclarationContext methoddeclaration; MethodDeclarationContext methoddeclaration;
GenericDeclarationListContext genericdeclarations; GenericDeclarationListContext genericdeclarations;
@ -475,9 +451,7 @@ public class SyntaxTreeGenerator {
return new Method(modifiers, name, retType, paramlist, block, gtvDeclarations, header.getStart()); return new Method(modifiers, name, retType, paramlist, block, gtvDeclarations, header.getStart());
} }
public Constructor convert(int modifiers, Java17Parser.ConstructorContext constructorContext, public Constructor convert(int modifiers, Java17Parser.ConstructorContext constructorContext, JavaClassName parentClass, RefType superClass, GenericsRegistry generics) {
JavaClassName parentClass,
RefType superClass, GenericsRegistry generics) {
GenericsRegistry localgenerics = generics; GenericsRegistry localgenerics = generics;
GenericDeclarationListContext genericdeclarations; GenericDeclarationListContext genericdeclarations;
GenericDeclarationList gtvDeclarations; GenericDeclarationList gtvDeclarations;
@ -497,17 +471,14 @@ public class SyntaxTreeGenerator {
name = constructordeclaration.identifier().getText(); name = constructordeclaration.identifier().getText();
gtvDeclarations = new GenericDeclarationList(new ArrayList<>(), constructordeclaration.getStart()); gtvDeclarations = new GenericDeclarationList(new ArrayList<>(), constructordeclaration.getStart());
} }
RefTypeOrTPHOrWildcardOrGeneric retType = TypeGenerator.convertTypeName(name, constructordeclaration.getStart(), RefTypeOrTPHOrWildcardOrGeneric retType = TypeGenerator.convertTypeName(name, constructordeclaration.getStart(), reg, localgenerics);
reg, localgenerics);
StatementGenerator stmtgen = new StatementGenerator(reg, localgenerics, fields, new HashMap<>()); StatementGenerator stmtgen = new StatementGenerator(reg, localgenerics, fields, new HashMap<>());
ParameterList paramlist = stmtgen.convert(constructordeclaration.formalParameters().formalParameterList()); ParameterList paramlist = stmtgen.convert(constructordeclaration.formalParameters().formalParameterList());
Block block = stmtgen.convert(constructordeclaration.constructorBody, true); Block block = stmtgen.convert(constructordeclaration.constructorBody, true);
return new Constructor(modifiers, name, retType, paramlist, block, gtvDeclarations, return new Constructor(modifiers, name, retType, paramlist, block, gtvDeclarations, constructordeclaration.getStart());
constructordeclaration.getStart());
} }
private List<? extends Field> convert(Java17Parser.FieldDeclarationContext fieldDeclContext, int modifiers, private List<? extends Field> convert(Java17Parser.FieldDeclarationContext fieldDeclContext, int modifiers, GenericsRegistry generics) {
GenericsRegistry generics) {
List<Field> ret = new ArrayList<>(); List<Field> ret = new ArrayList<>();
RefTypeOrTPHOrWildcardOrGeneric fieldType; RefTypeOrTPHOrWildcardOrGeneric fieldType;
if (fieldDeclContext.typeType() != null) { if (fieldDeclContext.typeType() != null) {
@ -533,8 +504,7 @@ public class SyntaxTreeGenerator {
} }
// Initialize a field by creating implicit constructor. // Initialize a field by creating implicit constructor.
private void initializeField(Java17Parser.VariableDeclaratorContext ctx, RefTypeOrTPHOrWildcardOrGeneric typeOfField, private void initializeField(Java17Parser.VariableDeclaratorContext ctx, RefTypeOrTPHOrWildcardOrGeneric typeOfField, GenericsRegistry generics) {
GenericsRegistry generics) {
StatementGenerator statementGenerator = new StatementGenerator(reg, generics, fields, new HashMap<>()); StatementGenerator statementGenerator = new StatementGenerator(reg, generics, fields, new HashMap<>());
fieldInitializations.add(statementGenerator.generateFieldAssignment(ctx, typeOfField)); fieldInitializations.add(statementGenerator.generateFieldAssignment(ctx, typeOfField));
} }
@ -543,8 +513,7 @@ public class SyntaxTreeGenerator {
return allmodifiers.get(modifier); return allmodifiers.get(modifier);
} }
private GenericsRegistry createGenerics(Java17Parser.GenericDeclarationListContext ctx, JavaClassName parentClass, private GenericsRegistry createGenerics(Java17Parser.GenericDeclarationListContext ctx, JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) {
String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) {
GenericsRegistry ret = new GenericsRegistry(this.globalGenerics); GenericsRegistry ret = new GenericsRegistry(this.globalGenerics);
ret.putAll(generics); ret.putAll(generics);
if (ctx == null) if (ctx == null)

View File

@ -29,23 +29,19 @@ import java.util.regex.Pattern;
public class TypeGenerator { public class TypeGenerator {
public static RefTypeOrTPHOrWildcardOrGeneric convert( public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.ClassOrInterfaceTypeContext classOrInterfaceTypeContext, JavaClassRegistry reg, GenericsRegistry generics) {
Java17Parser.ClassOrInterfaceTypeContext classOrInterfaceTypeContext, JavaClassRegistry reg,
GenericsRegistry generics) {
Java17Parser.TypeArgumentsContext arguments = null; Java17Parser.TypeArgumentsContext arguments = null;
/* /*
* PL 2019-03-19 auskommentiert ANFANG * PL 2019-03-19 auskommentiert ANFANG if(unannClassOrInterfaceTypeContext.
* unannClassType_lfno_unannClassOrInterfaceType() != null){ arguments =
* unannClassOrInterfaceTypeContext.
* unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); }else{//
* if(unannClassOrInterfaceTypeContext. * if(unannClassOrInterfaceTypeContext.
* unannClassType_lfno_unannClassOrInterfaceType() != null){ * unannInterfaceType_lfno_unannClassOrInterfaceType() != null){ arguments =
* arguments = unannClassOrInterfaceTypeContext. * unannClassOrInterfaceTypeContext.
* unannClassType_lfno_unannClassOrInterfaceType().typeArguments();
* }else{// if(unannClassOrInterfaceTypeContext.
* unannInterfaceType_lfno_unannClassOrInterfaceType() != null){
* arguments = unannClassOrInterfaceTypeContext.
* unannInterfaceType_lfno_unannClassOrInterfaceType(). * unannInterfaceType_lfno_unannClassOrInterfaceType().
* unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); * unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); } PL
* } * 2019-03-19 auskommentiert ENDE
* PL 2019-03-19 auskommentiert ENDE
*/ */
/** /**
* Problem sind hier die verschachtelten Typen mit verschachtelten Typargumenten * Problem sind hier die verschachtelten Typen mit verschachtelten Typargumenten
@ -56,13 +52,12 @@ public class TypeGenerator {
String name = ""; String name = "";
for (IdentifierContext id : classOrInterfaceTypeContext.identifier()) { for (IdentifierContext id : classOrInterfaceTypeContext.identifier()) {
name += id.getText(); name += id.getText() + '.';
} }
name += classOrInterfaceTypeContext.typeIdentifier(); name += classOrInterfaceTypeContext.typeIdentifier().getText();
if (classOrInterfaceTypeContext.getStop().getText().equals(">")) { if (classOrInterfaceTypeContext.getStop().getText().equals(">")) {
/* /*
* Fuer Debug-Zwecke * Fuer Debug-Zwecke unannClassOrInterfaceTypeContext.
* unannClassOrInterfaceTypeContext.
* unannInterfaceType_lfno_unannClassOrInterfaceType(); * unannInterfaceType_lfno_unannClassOrInterfaceType();
* unannClassOrInterfaceTypeContext. * unannClassOrInterfaceTypeContext.
* unannClassType_lfno_unannClassOrInterfaceType().getText(); * unannClassType_lfno_unannClassOrInterfaceType().getText();
@ -77,8 +72,7 @@ public class TypeGenerator {
* unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType( * unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType(
* 1); * 1);
* unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType( * unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType(
* 1).getText(); * 1).getText(); unannClassOrInterfaceTypeContext.
* unannClassOrInterfaceTypeContext.
* unannClassType_lfno_unannClassOrInterfaceType().getText(); * unannClassType_lfno_unannClassOrInterfaceType().getText();
* //unannClassOrInterfaceTypeContext. * //unannClassOrInterfaceTypeContext.
* unannInterfaceType_lf_unannClassOrInterfaceType(); * unannInterfaceType_lf_unannClassOrInterfaceType();
@ -95,8 +89,7 @@ public class TypeGenerator {
return convertTypeName(name, arguments, classOrInterfaceTypeContext.getStart(), reg, generics); return convertTypeName(name, arguments, classOrInterfaceTypeContext.getStart(), reg, generics);
} }
public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.TypeTypeContext typeContext, public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.TypeTypeContext typeContext, JavaClassRegistry reg, GenericsRegistry genericsRegistry) {
JavaClassRegistry reg, GenericsRegistry genericsRegistry) {
if (typeContext.primitiveType() != null) { if (typeContext.primitiveType() != null) {
if (typeContext.primitiveType().getText().equals("boolean")) { if (typeContext.primitiveType().getText().equals("boolean")) {
return new RefType(ASTFactory.createClass(Boolean.class).getClassName(), typeContext.getStart()); return new RefType(ASTFactory.createClass(Boolean.class).getClassName(), typeContext.getStart());
@ -111,17 +104,16 @@ public class TypeGenerator {
} else if (!typeContext.LBRACK().isEmpty()) { // ArrayType über eckige Klammer prüfen } else if (!typeContext.LBRACK().isEmpty()) { // ArrayType über eckige Klammer prüfen
// System.out.println(unannTypeContext.getText()); // System.out.println(unannTypeContext.getText());
throw new NotImplementedException(); throw new NotImplementedException();
} else if (typeContext.classOrInterfaceType() != null) {
JavaClassName name = reg
.getName(typeContext.classOrInterfaceType().typeIdentifier().getText());
return new RefType(name, typeContext.getStart());
} }
return TypeGenerator.convert(typeContext.classOrInterfaceType(), reg, /*
genericsRegistry); * else if (typeContext.classOrInterfaceType() != null) { JavaClassName name =
* reg .getName(typeContext.classOrInterfaceType().typeIdentifier().getText());
* return new RefType(name, typeContext.getStart()); }
*/
return TypeGenerator.convert(typeContext.classOrInterfaceType(), reg, genericsRegistry);
} }
public static GenericDeclarationList convert(Java17Parser.GenericDeclarationListContext typeParametersContext, public static GenericDeclarationList convert(Java17Parser.GenericDeclarationListContext typeParametersContext, JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) {
JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) {
Token endOffset = typeParametersContext.getStop(); Token endOffset = typeParametersContext.getStop();
List<GenericTypeVar> typeVars = new ArrayList<>(); List<GenericTypeVar> typeVars = new ArrayList<>();
for (Java17Parser.GenericTypeVarContext typeParameter : typeParametersContext.genericTypeVar()) { for (Java17Parser.GenericTypeVarContext typeParameter : typeParametersContext.genericTypeVar()) {
@ -131,8 +123,7 @@ public class TypeGenerator {
return new GenericDeclarationList(typeVars, endOffset); return new GenericDeclarationList(typeVars, endOffset);
} }
public static GenericTypeVar convert(Java17Parser.GenericTypeVarContext typeVar, JavaClassName parentClass, public static GenericTypeVar convert(Java17Parser.GenericTypeVarContext typeVar, JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) {
String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) {
String name = typeVar.identifier().getText(); String name = typeVar.identifier().getText();
// TODO: Es müssen erst alle GenericTypeVars generiert werden, dann können die // TODO: Es müssen erst alle GenericTypeVars generiert werden, dann können die
// bounds dieser Generics ermittelt werden // bounds dieser Generics ermittelt werden
@ -144,8 +135,7 @@ public class TypeGenerator {
return ret; return ret;
} }
public static List<RefTypeOrTPHOrWildcardOrGeneric> convert(Java17Parser.TypeBoundContext typeBoundContext, public static List<RefTypeOrTPHOrWildcardOrGeneric> convert(Java17Parser.TypeBoundContext typeBoundContext, JavaClassRegistry reg, GenericsRegistry generics) {
JavaClassRegistry reg, GenericsRegistry generics) {
List<RefTypeOrTPHOrWildcardOrGeneric> ret = new ArrayList<>(); List<RefTypeOrTPHOrWildcardOrGeneric> ret = new ArrayList<>();
if (Objects.isNull(typeBoundContext)) { if (Objects.isNull(typeBoundContext)) {
ret.add(ASTFactory.createObjectType()); ret.add(ASTFactory.createObjectType());
@ -160,29 +150,23 @@ public class TypeGenerator {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.WildcardTypeContext wildcardContext, public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.WildcardTypeContext wildcardContext, JavaClassRegistry reg, GenericsRegistry generics) {
JavaClassRegistry reg, GenericsRegistry generics) {
if (wildcardContext.getChildCount() < 3) { if (wildcardContext.getChildCount() < 3) {
if (!Objects.isNull(wildcardContext.extendsWildcardType())) { if (!Objects.isNull(wildcardContext.extendsWildcardType())) {
return new ExtendsWildcardType(convert(wildcardContext.extendsWildcardType().typeType(), reg, generics), return new ExtendsWildcardType(convert(wildcardContext.extendsWildcardType().typeType(), reg, generics), wildcardContext.getStart());
wildcardContext.getStart());
} else { } else {
return new SuperWildcardType(convert(wildcardContext.superWildcardType().typeType(), reg, generics), return new SuperWildcardType(convert(wildcardContext.superWildcardType().typeType(), reg, generics), wildcardContext.getStart());
wildcardContext.getStart());
} }
} else { } else {
throw new NotImplementedException(); // Wildcard ohne Bound throw new NotImplementedException(); // Wildcard ohne Bound
} }
} }
public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(String name, Token offset, JavaClassRegistry reg, public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(String name, Token offset, JavaClassRegistry reg, GenericsRegistry generics) {
GenericsRegistry generics) {
return convertTypeName(name, (Java17Parser.TypeArgumentsContext) null, offset, reg, generics); return convertTypeName(name, (Java17Parser.TypeArgumentsContext) null, offset, reg, generics);
} }
public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName( public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(String name, Java17Parser.TypeArgumentsContext typeArguments, Token offset, JavaClassRegistry reg, GenericsRegistry generics) {
String name, Java17Parser.TypeArgumentsContext typeArguments, Token offset, JavaClassRegistry reg,
GenericsRegistry generics) {
if (!reg.contains(name)) { // Dann könnte es ein generischer Type oder ein FunN$$-Type sein if (!reg.contains(name)) { // Dann könnte es ein generischer Type oder ein FunN$$-Type sein
if (generics.contains(name)) { if (generics.contains(name)) {
return new GenericRefType(name, offset); return new GenericRefType(name, offset);
@ -207,10 +191,7 @@ public class TypeGenerator {
} }
} }
public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName( public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(String name, Java17Parser.NonWildcardTypeArgumentsContext typeArguments, Token offset, JavaClassRegistry reg, GenericsRegistry generics) {
String name, Java17Parser.NonWildcardTypeArgumentsContext typeArguments, Token offset,
JavaClassRegistry reg,
GenericsRegistry generics) {
if (!reg.contains(name)) { // Dann könnte es ein generischer Type oder ein FunN$$-Type sein if (!reg.contains(name)) { // Dann könnte es ein generischer Type oder ein FunN$$-Type sein
if (generics.contains(name)) { if (generics.contains(name)) {
return new GenericRefType(name, offset); return new GenericRefType(name, offset);
@ -235,8 +216,7 @@ public class TypeGenerator {
} }
} }
public static List<RefTypeOrTPHOrWildcardOrGeneric> convert(Java17Parser.TypeArgumentsContext typeArguments, public static List<RefTypeOrTPHOrWildcardOrGeneric> convert(Java17Parser.TypeArgumentsContext typeArguments, JavaClassRegistry reg, GenericsRegistry generics) {
JavaClassRegistry reg, GenericsRegistry generics) {
List<RefTypeOrTPHOrWildcardOrGeneric> ret = new ArrayList<>(); List<RefTypeOrTPHOrWildcardOrGeneric> ret = new ArrayList<>();
for (Java17Parser.TypeArgumentContext arg : typeArguments.typeArgument()) { for (Java17Parser.TypeArgumentContext arg : typeArguments.typeArgument()) {
WildcardTypeContext wc = arg.wildcardType(); WildcardTypeContext wc = arg.wildcardType();
@ -249,9 +229,7 @@ public class TypeGenerator {
return ret; return ret;
} }
public static List<RefTypeOrTPHOrWildcardOrGeneric> convert( public static List<RefTypeOrTPHOrWildcardOrGeneric> convert(Java17Parser.NonWildcardTypeArgumentsContext typeArguments, JavaClassRegistry reg, GenericsRegistry generics) {
Java17Parser.NonWildcardTypeArgumentsContext typeArguments,
JavaClassRegistry reg, GenericsRegistry generics) {
List<RefTypeOrTPHOrWildcardOrGeneric> ret = new ArrayList<>(); List<RefTypeOrTPHOrWildcardOrGeneric> ret = new ArrayList<>();
for (Java17Parser.TypeTypeContext arg : typeArguments.typeList().typeType()) { for (Java17Parser.TypeTypeContext arg : typeArguments.typeList().typeType()) {
ret.add(convert(arg, reg, generics)); ret.add(convert(arg, reg, generics));

View File

@ -10,8 +10,7 @@ import de.dhbwstuttgart.parser.antlr.Java17Parser;
public class GatherNames { public class GatherNames {
public static Map<String, Integer> getNames(SrcfileContext ctx, PackageCrawler packages, public static Map<String, Integer> getNames(SrcfileContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException {
ClassLoader classLoader) throws ClassNotFoundException {
Map<String, Integer> ret = new HashMap<>(); Map<String, Integer> ret = new HashMap<>();
String pkgName = getPackageName(ctx); String pkgName = getPackageName(ctx);
String nameString = ""; String nameString = "";
@ -22,27 +21,20 @@ public class GatherNames {
ClassorinterfacedeclContext clsoif = (ClassorinterfacedeclContext) member; ClassorinterfacedeclContext clsoif = (ClassorinterfacedeclContext) member;
if (clsoif.interfaceDeclaration() != null) { if (clsoif.interfaceDeclaration() != null) {
if (pkgName != "") { if (pkgName != "") {
nameString = pkgName + "." nameString = pkgName + "." + clsoif.interfaceDeclaration().identifier().getText();
+ clsoif.interfaceDeclaration().identifier().getText();
} else { } else {
nameString = clsoif.interfaceDeclaration().identifier().getText(); nameString = clsoif.interfaceDeclaration().identifier().getText();
} }
int numGenerics = clsoif.interfaceDeclaration().genericDeclarationList() != null int numGenerics = clsoif.interfaceDeclaration().genericDeclarationList() != null ? clsoif.interfaceDeclaration().genericDeclarationList().genericTypeVar().size() : 0;
? clsoif.interfaceDeclaration().genericDeclarationList().genericTypeVar().size()
: 0;
// Die Generic TypeParameter Definitionen Nicht! an die JavaClassName-Registry // Die Generic TypeParameter Definitionen Nicht! an die JavaClassName-Registry
// anfügen: // anfügen:
/* /*
* //Diese gelängen dadurch in den globalen Scope, was sie schließlich nicht * //Diese gelängen dadurch in den globalen Scope, was sie schließlich nicht
* sind * sind if(clsoif.classDeclaration().normalClassDeclaration().typeParameters()
* if(clsoif.classDeclaration().normalClassDeclaration().typeParameters() != * != null){ for(Java17Parser.TypeParameterContext tp :
* null){
* for(Java17Parser.TypeParameterContext tp :
* clsoif.classDeclaration().normalClassDeclaration().typeParameters(). * clsoif.classDeclaration().normalClassDeclaration().typeParameters().
* typeParameterList().typeParameter()){ * typeParameterList().typeParameter()){
* //this.reg.add(tp.Identifier().toString()); * //this.reg.add(tp.Identifier().toString()); } }
* }
* }
*/ */
ret.put(nameString, numGenerics); ret.put(nameString, numGenerics);
} else { } else {
@ -55,19 +47,13 @@ public class GatherNames {
// anfügen: // anfügen:
/* /*
* //Diese gelängen dadurch in den globalen Scope, was sie schließlich nicht * //Diese gelängen dadurch in den globalen Scope, was sie schließlich nicht
* sind * sind if(clsoif.classDeclaration().normalClassDeclaration().typeParameters()
* if(clsoif.classDeclaration().normalClassDeclaration().typeParameters() != * != null){ for(Java17Parser.TypeParameterContext tp :
* null){
* for(Java17Parser.TypeParameterContext tp :
* clsoif.classDeclaration().normalClassDeclaration().typeParameters(). * clsoif.classDeclaration().normalClassDeclaration().typeParameters().
* typeParameterList().typeParameter()){ * typeParameterList().typeParameter()){
* this.reg.add(tp.Identifier().toString()); * this.reg.add(tp.Identifier().toString()); } }
* }
* }
*/ */
int numGenerics = clsoif.classDeclaration().genericDeclarationList() != null int numGenerics = clsoif.classDeclaration().genericDeclarationList() != null ? clsoif.classDeclaration().genericDeclarationList().genericTypeVar().size() : 0;
? clsoif.classDeclaration().genericDeclarationList().genericTypeVar().size()
: 0;
ret.put(nameString, numGenerics); ret.put(nameString, numGenerics);
} }
@ -76,8 +62,7 @@ public class GatherNames {
return ret; return ret;
} }
public static Map<String, Integer> getImports(Java17Parser.SrcfileContext ctx, PackageCrawler packages, public static Map<String, Integer> getImports(Java17Parser.SrcfileContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException {
ClassLoader classLoader) throws ClassNotFoundException {
Map<String, Integer> ret = new HashMap<>(); Map<String, Integer> ret = new HashMap<>();
// ret.putAll(packages.getClassNames("java.lang")); // ret.putAll(packages.getClassNames("java.lang"));
for (Java17Parser.ImportDeclarationContext importDeclCtx : ctx.importDeclaration()) { for (Java17Parser.ImportDeclarationContext importDeclCtx : ctx.importDeclaration()) {

View File

@ -1,12 +1,12 @@
package de.dhbwstuttgart.parser.scope; package de.dhbwstuttgart.parser.scope;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* Stellt den Namen einer Java Klasse dar. * Stellt den Namen einer Java Klasse dar.
* Dieser kann auch den Packagenamen mit beinhalten: de.dhbwstuttgart.typeinference.Menge * Dieser kann auch den Packagenamen mit beinhalten:
* de.dhbwstuttgart.typeinference.Menge
* *
* @author Andreas Stadelmeier * @author Andreas Stadelmeier
*/ */
@ -16,22 +16,23 @@ public class JavaClassName {
private String name; private String name;
private PackageName packageName; private PackageName packageName;
public JavaClassName(String name){ public JavaClassName(String name) {
if(name == null)throw new NullPointerException(); if (name == null)
throw new NullPointerException();
String[] names = name.split("[.]"); String[] names = name.split("[.]");
boolean match = true; boolean match = true;
if(names.length == 1){ if (names.length == 1) {
//packageName = new PackageName(); // packageName = new PackageName();
this.name = name; this.name = name;
}else { } else {
name = names[names.length-1]; name = names[names.length - 1];
List<String> packageNames = new ArrayList<String>(); List<String> packageNames = new ArrayList<String>();
for(int i = 0; i<names.length-1;i++){ for (int i = 0; i < names.length - 1; i++) {
packageNames.add(names[i]); packageNames.add(names[i]);
} }
packageName = new PackageName(packageNames); packageName = new PackageName(packageNames);
this.name = names[names.length-1]; this.name = names[names.length - 1];
} }
} }
@ -43,21 +44,23 @@ public class JavaClassName {
public static String stripClassName(String className) { public static String stripClassName(String className) {
return new JavaClassName(className).name; return new JavaClassName(className).name;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode());
/* /*
result = prime * result * result = prime * result
+ ((packageName == null) ? 0 : packageName.hashCode()); //PackageName does not infect hashCode * + ((packageName == null) ? 0 : packageName.hashCode()); //PackageName does
*/ * not infect hashCode
*/
return result; return result;
} }
/** /**
* Namen sind nur gleich, wenn bei den beiden zu vergleichenden JavaClassNames auch das Package angegeben ist * Namen sind nur gleich, wenn bei den beiden zu vergleichenden JavaClassNames
* auch das Package angegeben ist
*/ */
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
@ -65,8 +68,11 @@ public class JavaClassName {
return true; return true;
if (obj == null) if (obj == null)
return false; return false;
if(obj instanceof String) if (obj instanceof String)
return this.toString().equals(obj) || (this.name != null && this.name.equals(obj)); //Auch mit Strings als Klassennamen kompatibel TODO: sollte bald obsolet sein return this.toString().equals(obj) || (this.name != null && this.name.equals(obj)); // Auch mit Strings als
// Klassennamen kompatibel
// TODO: sollte bald obsolet
// sein
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
JavaClassName other = (JavaClassName) obj; JavaClassName other = (JavaClassName) obj;
@ -77,35 +83,36 @@ public class JavaClassName {
return false; return false;
if (packageName != null && other.packageName != null) { if (packageName != null && other.packageName != null) {
if (!packageName.equals(other.packageName)) if (!packageName.equals(other.packageName))
return false;//Spezialfall, nicht beide Typen ¼ssen eindeutig mit Packagenamen angegeben werden return false;// Spezialfall, nicht beide Typen ¼ssen eindeutig mit Packagenamen angegeben
// werden
} }
return true; return true;
} }
@Override @Override
public String toString() { public String toString() {
return (packageName!=null ? packageName.toString() + "." : "") + name; return (packageName != null ? packageName.toString() + "." : "") + name;
} }
public String getPackageName() { public String getPackageName() {
return (packageName!=null ? packageName.toString() : ""); return (packageName != null ? packageName.toString() : "");
} }
public String getClassName(){ public String getClassName() {
return name; return name;
} }
} }
class PackageName{ class PackageName {
List<String> names = new ArrayList<>(); List<String> names = new ArrayList<>();
public PackageName(List<String> packageNames) { public PackageName(List<String> packageNames) {
names = packageNames; names = packageNames;
} }
public PackageName() { public PackageName() {
//Do nothing // Do nothing
} }
@Override @Override
@ -132,12 +139,14 @@ class PackageName{
return false; return false;
return true; return true;
} }
@Override @Override
public String toString() { public String toString() {
String ret = ""; String ret = "";
if(names == null)return ""; if (names == null)
for(String n : names)ret+=n+"."; return "";
for (String n : names)
ret += n + ".";
if (ret != null && ret.length() > 0 && ret.charAt(ret.length() - 1) == '.') { if (ret != null && ret.length() > 0 && ret.charAt(ret.length() - 1) == '.') {
ret = ret.substring(0, ret.length() - 1); ret = ret.substring(0, ret.length() - 1);
} }

View File

@ -13,16 +13,13 @@ import java.net.URLClassLoader;
public class LoadDefaultPackageClassesTest extends TestCase { public class LoadDefaultPackageClassesTest extends TestCase {
public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/packageTest/"; public static final String rootDirectory = System.getProperty("user.dir") + "/resources/javFiles/packageTest/";
public LoadDefaultPackageClassesTest() throws ClassNotFoundException, IOException { public LoadDefaultPackageClassesTest() throws ClassNotFoundException, IOException {
/* /*
Generate ToImport class in rootDirectory and in output-Directory * Generate ToImport class in rootDirectory and in output-Directory
*/ */
JavaTXCompiler compiler = new JavaTXCompiler( JavaTXCompiler compiler = new JavaTXCompiler(Lists.newArrayList(new File(rootDirectory + "Gen.jav")), Lists.newArrayList(new File(rootDirectory + "/de/test/output/")));
Lists.newArrayList(new File(rootDirectory+"Gen.jav")),
Lists.newArrayList(new File(rootDirectory+"/de/test/output/")));
compiler.typeInference(); compiler.typeInference();
compiler.generateBytecode(); compiler.generateBytecode();
File f = new File(rootDirectory + "Gen.class"); File f = new File(rootDirectory + "Gen.class");
@ -30,26 +27,22 @@ public class LoadDefaultPackageClassesTest extends TestCase {
} }
public void testLoadGenClass() throws IOException, ClassNotFoundException { public void testLoadGenClass() throws IOException, ClassNotFoundException {
CompilationEnvironment.loadDefaultPackageClasses(new File( rootDirectory + "Test.jav"), ClassLoader.getSystemClassLoader()); CompilationEnvironment.loadDefaultPackageClasses("", new File(rootDirectory + "Test.jav"), ClassLoader.getSystemClassLoader());
} }
public void testURLClassLoader() throws IOException, ClassNotFoundException { public void testURLClassLoader() throws IOException, ClassNotFoundException {
URLClassLoader cl = new URLClassLoader(new URL[]{new URL("file://"+rootDirectory)}, ClassLoader.getSystemClassLoader()); URLClassLoader cl = new URLClassLoader(new URL[] { new URL("file://" + rootDirectory) }, ClassLoader.getSystemClassLoader());
cl.loadClass("Gen"); cl.loadClass("Gen");
} }
/* /*
public void testE2E() throws IOException, ClassNotFoundException { * public void testE2E() throws IOException, ClassNotFoundException {
JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"OL.jav")); * JavaTXCompiler compiler = new JavaTXCompiler(new
compiler.typeInference(); * File(rootDirectory+"OL.jav")); compiler.typeInference();
compiler.generateBytecode(); * compiler.generateBytecode(); File f = new File(rootDirectory + "OL.class");
File f = new File(rootDirectory + "OL.class"); * assertTrue(f.exists());
assertTrue(f.exists()); *
* compiler = new JavaTXCompiler(new File(rootDirectory+"OLMain.jav"));
compiler = new JavaTXCompiler(new File(rootDirectory+"OLMain.jav")); * compiler.typeInference(); compiler.generateBytecode(); f = new
compiler.typeInference(); * File(rootDirectory + "OLMain.class"); assertTrue(f.exists()); }
compiler.generateBytecode(); */
f = new File(rootDirectory + "OLMain.class");
assertTrue(f.exists());
}
*/
} }

View File

@ -1,3 +1,5 @@
import java.lang.Object;
class C1 extends Object class C1 extends Object
{ {
m(para) { return para; } m(para) { return para; }

View File

@ -33,7 +33,6 @@ public class GeneralParserTest {
filenames.add("StatementsTest.jav"); filenames.add("StatementsTest.jav");
// filenames.add("Methods.jav"); // filenames.add("Methods.jav");
filenames.add("ImportTestGeneric.jav"); filenames.add("ImportTestGeneric.jav");
filenames.add("CastTest.jav");
// filenames.add("BoundedParameter.jav"); // filenames.add("BoundedParameter.jav");
// filenames.add("GenericFieldVarTest.jav"); // filenames.add("GenericFieldVarTest.jav");
filenames.add("FieldVarTest.jav"); filenames.add("FieldVarTest.jav");

View File

@ -353,7 +353,7 @@ class Records {
} }
final record R1(@Dummy2 @Dummy x) { final record R1(x) {
R1(x) { R1(x) {
this.x = x; this.x = x;