From 1ab0f42fd1f5a276bb074553a91478323f663ade Mon Sep 17 00:00:00 2001 From: luca9913 Date: Mon, 20 Mar 2023 22:07:47 +0100 Subject: [PATCH] =?UTF-8?q?Bug=20fixes=20f=C3=BCr=20GeneralParserTest=20un?= =?UTF-8?q?d=20Mehrfachaufrufe=20des=20Parsers=20entfernt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 18 +- .../parser/antlr/Java17Parser.g4 | 4 +- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 307 ++++++------------ .../environment/CompilationEnvironment.java | 30 +- .../SyntaxTreeGenerator.java | 191 +++++------ .../SyntaxTreeGenerator/TypeGenerator.java | 84 ++--- .../parser/scope/GatherNames.java | 37 +-- .../parser/scope/JavaClassName.java | 67 ++-- .../LoadDefaultPackageClassesTest.java | 39 +-- src/test/java/parser/ExtendsTest.jav | 2 + src/test/java/parser/GeneralParserTest.java | 1 - src/test/java/parser/Java17Rules.jav | 2 +- 12 files changed, 301 insertions(+), 481 deletions(-) diff --git a/pom.xml b/pom.xml index ed39f4db..adef032f 100644 --- a/pom.xml +++ b/pom.xml @@ -53,22 +53,11 @@ http://maven.apache.org/maven-v4_0_0.xsd"> maven-compiler-plugin 3.8.0 - 19 - - --enable-preview - + --enable-preview 19 19 - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - --enable-preview - - org.antlr antlr4-maven-plugin @@ -123,8 +112,9 @@ http://maven.apache.org/maven-v4_0_0.xsd"> + 19 + 19 de.dhbwstuttgart.core.ConsoleInterface - 17 @@ -133,4 +123,4 @@ http://maven.apache.org/maven-v4_0_0.xsd"> file:///${project.basedir}/maven-repository/ - + \ No newline at end of file diff --git a/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java17Parser.g4 b/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java17Parser.g4 index 2117b822..678c905c 100644 --- a/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java17Parser.g4 +++ b/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java17Parser.g4 @@ -543,7 +543,7 @@ statement ; catchClause - : CATCH '(' variableModifier* catchType identifier ')' block + : CATCH '(' variableModifier* catchType? identifier ')' block ; catchType @@ -652,7 +652,7 @@ expression // Java17 pattern - : variableModifier* typeType annotation* identifier + : variableModifier* typeType? annotation* identifier ; // Java8 diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index c66a6679..17f342bc 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -58,6 +58,7 @@ import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.*; +import java.util.Map.Entry; import java.util.function.Function; import java.util.stream.Collectors; @@ -105,28 +106,22 @@ public class JavaTXCompiler { public ConstraintSet getConstraints() throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); List importedClasses = new ArrayList<>(); - ClassOrInterface objectClass = ASTFactory.createClass( - classLoader.loadClass(new JavaClassName("java.lang.Object").toString())); + ClassOrInterface objectClass = ASTFactory.createClass(classLoader.loadClass(new JavaClassName("java.lang.Object").toString())); // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for (File forSourceFile : sourceFiles.keySet()) { - for (JavaClassName name : sourceFiles.get(forSourceFile).getImports()) { + for (Entry source : sourceFiles.entrySet()) { + for (JavaClassName name : source.getValue().getImports()) { // TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet - ClassOrInterface importedClass = ASTFactory.createClass( - classLoader.loadClass(name.toString())); + ClassOrInterface importedClass = ASTFactory.createClass(classLoader.loadClass(name.toString())); 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); importedClasses.add(importedClass); } } for (File f : this.sourceFiles.keySet()) { SourceFile sf = sourceFiles.get(f); - sf = new SourceFile(sf.getPkgName(), - sf.KlassenVektor.stream() - .map(cl -> new ClassOrInterface(cl)) - .collect(Collectors.toCollection(ArrayList::new)), - sf.imports); + sf = new SourceFile(sf.getPkgName(), 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 // ArrayListen-Objekte fuer Fields, Construktoren und Methoden // Alle anderen Objekte werden nur kopiert. @@ -139,20 +134,17 @@ public class JavaTXCompiler { return ty.getConstraints(); } - void addMethods(SourceFile sf, ClassOrInterface cl, List importedClasses, - ClassOrInterface objectClass) { + void addMethods(SourceFile sf, ClassOrInterface cl, List importedClasses, ClassOrInterface objectClass) { if (!cl.areMethodsAdded()) { ClassOrInterface superclass = null; if (cl.getSuperClass().getName().equals(new JavaClassName("java.lang.Object"))) { superclass = objectClass; } else { - Optional optSuperclass = importedClasses.stream().filter(x -> x.getClassName().equals( - cl.getSuperClass().getName())).findFirst(); + Optional optSuperclass = importedClasses.stream().filter(x -> x.getClassName().equals(cl.getSuperClass().getName())).findFirst(); if (optSuperclass.isPresent()) { superclass = optSuperclass.get(); } else { - optSuperclass = sf.KlassenVektor.stream().filter(x -> x.getClassName().equals( - cl.getSuperClass().getName())).findFirst(); + optSuperclass = sf.KlassenVektor.stream().filter(x -> x.getClassName().equals(cl.getSuperClass().getName())).findFirst(); if (optSuperclass.isPresent()) { superclass = optSuperclass.get(); addMethods(sf, superclass, importedClasses, objectClass); @@ -173,21 +165,11 @@ public class JavaTXCompiler { // werden while (methodIt.hasNext()) { Method m = methodIt.next(); - 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()); - 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)); + 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()); + 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 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); * - * return new TYPE(sourceFiles.values(), allClasses).getConstraints(); - * } + * return new TYPE(sourceFiles.values(), allClasses).getConstraints(); } * * public List getAvailableClasses(SourceFile forSourceFile) - * throws ClassNotFoundException { - * // PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal - * // hinzugefuegt werden - * // List allClasses = new - * // ArrayList<>();//environment.getAllAvailableClasses(); + * throws ClassNotFoundException { // PL 2018-09-18: List durch Set ersetzt, + * damit die Klassen nur einmal // hinzugefuegt werden // List + * allClasses = new // ArrayList<>();//environment.getAllAvailableClasses(); * Set 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()); * } */ @@ -226,8 +203,7 @@ public class JavaTXCompiler { List importedClasses = new ArrayList<>(); for (JavaClassName name : forSourceFile.getImports()) { // TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet - ClassOrInterface importedClass = ASTFactory - .createClass(classLoader.loadClass(name.toString())); + ClassOrInterface importedClass = ASTFactory.createClass(classLoader.loadClass(name.toString())); importedClasses.add(importedClass); allClasses.addAll(importedClasses); } @@ -379,16 +355,14 @@ public class JavaTXCompiler { * } */ - public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) - throws ClassNotFoundException, IOException { + public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for (File f : this.sourceFiles.keySet()) { - SourceFile sf = sourceFiles.get(f); + for (Entry source : this.sourceFiles.entrySet()) { + SourceFile sf = source.getValue(); allClasses.addAll(getAvailableClasses(sf)); allClasses.addAll(sf.getClasses()); - allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(f, classLoader).stream() - .map(ASTFactory::createClass).collect(Collectors.toList())); + allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(sf.getPkgName(), source.getKey(), classLoader).stream().map(ASTFactory::createClass).collect(Collectors.toList())); } final ConstraintSet cons = getConstraints(); @@ -396,9 +370,7 @@ public class JavaTXCompiler { UnifyResultModel urm = null; // urm.addUnifyResultListener(resultListener); try { - logFile = logFile == null - ? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName())) - : logFile; + logFile = logFile == null ? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName())) : logFile; IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); System.out.println(finiteClosure); urm = new UnifyResultModel(cons, finiteClosure); @@ -407,9 +379,7 @@ public class JavaTXCompiler { Function distributeInnerVars = x -> { UnifyType lhs, rhs; - if (((lhs = x.getLhsType()) instanceof PlaceholderType) - && ((rhs = x.getRhsType()) instanceof PlaceholderType) - && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) { + 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); } @@ -427,58 +397,40 @@ public class JavaTXCompiler { } logFile.flush(); - Set 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(), (a, b) -> { - a.addAll(b); - return a; - }, (a, b) -> { - a.addAll(b); - return a; - })).reduce(new HashSet(), (a, b) -> { - a.addAll(b); - return a; - }); + Set 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(), (a, b) -> { + a.addAll(b); + return a; + }, (a, b) -> { + a.addAll(b); + return a; + })).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }); - Set 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(), (a, b) -> { - a.addAll(b); - return a; - }, (a, b) -> { - a.addAll(b); - return a; - })).reduce(new HashSet(), (a, b) -> { - a.addAll(b); - return a; - }); + Set 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(), (a, b) -> { + a.addAll(b); + return a; + }, (a, b) -> { + a.addAll(b); + return a; + })).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }); Set paraTypeVarNames = methodParaTypeVarNames; paraTypeVarNames.addAll(constructorParaTypeVarNames); - Set returnTypeVarNames = allClasses.stream() - .map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder) z.getReturnType()).getName()) - .collect(Collectors.toCollection(HashSet::new))) - .reduce((a, b) -> { - a.addAll(b); - return a; - }).get(); + Set returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a, b) -> { + a.addAll(b); + return a; + }).get(); - Set fieldTypeVarNames = allClasses.stream() - .map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder) z.getReturnType()).getName()) - .collect(Collectors.toCollection(HashSet::new))) - .reduce((a, b) -> { - a.addAll(b); - return a; - }).get(); + Set fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a, b) -> { + a.addAll(b); + return a; + }).get(); returnTypeVarNames.addAll(fieldTypeVarNames); @@ -537,19 +489,11 @@ public class JavaTXCompiler { // logFile, log); // Set> result = unify.unify(xConsSet, finiteClosure); List>> oderConstraints = unifyCons.getOderConstraints()/* - * .stream().map(x -> { - * Set> ret = new - * HashSet<>(); - * for (Constraint y - * : x) { - * ret.add(new HashSet<>(y)); - * } - * return ret; - * }).collect(Collectors. - * toCollection(ArrayList::new)) + * .stream().map(x -> { Set> ret = new HashSet<>(); for + * (Constraint y : x) { ret.add(new HashSet<>(y)); } return ret; + * }).collect(Collectors. toCollection(ArrayList::new)) */; - unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, - usedTasks); + unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks); } catch (IOException e) { System.err.println("kein LogFile"); } @@ -559,12 +503,11 @@ public class JavaTXCompiler { public List typeInference() throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for (File f : this.sourceFiles.keySet()) { - SourceFile sf = sourceFiles.get(f); + for (Entry source : this.sourceFiles.entrySet()) { + SourceFile sf = source.getValue(); allClasses.addAll(getAvailableClasses(sf)); allClasses.addAll(sf.getClasses()); - allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(f, classLoader).stream() - .map(ASTFactory::createClass).collect(Collectors.toList())); + allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(sf.getPkgName(), source.getKey(), classLoader).stream().map(ASTFactory::createClass).collect(Collectors.toList())); } final ConstraintSet cons = getConstraints(); @@ -573,17 +516,14 @@ public class JavaTXCompiler { Writer logFile = // new OutputStreamWriter(new NullOutputStream()); // new FileWriter(new // File(System.getProperty("user.dir")+"/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); - new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" - + sourceFiles.keySet().iterator().next().getName())); + new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" + sourceFiles.keySet().iterator().next().getName())); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); System.out.println(finiteClosure); ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); System.out.println("xxx1"); Function distributeInnerVars = x -> { UnifyType lhs, rhs; - if (((lhs = x.getLhsType()) instanceof PlaceholderType) - && ((rhs = x.getRhsType()) instanceof PlaceholderType) - && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) { + 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); } @@ -604,58 +544,40 @@ public class JavaTXCompiler { } logFile.flush(); - Set 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(), (a, b) -> { - a.addAll(b); - return a; - }, (a, b) -> { - a.addAll(b); - return a; - })).reduce(new HashSet(), (a, b) -> { - a.addAll(b); - return a; - }); + Set 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(), (a, b) -> { + a.addAll(b); + return a; + }, (a, b) -> { + a.addAll(b); + return a; + })).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }); - Set 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(), (a, b) -> { - a.addAll(b); - return a; - }, (a, b) -> { - a.addAll(b); - return a; - })).reduce(new HashSet(), (a, b) -> { - a.addAll(b); - return a; - }); + Set 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(), (a, b) -> { + a.addAll(b); + return a; + }, (a, b) -> { + a.addAll(b); + return a; + })).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }); Set paraTypeVarNames = methodParaTypeVarNames; paraTypeVarNames.addAll(constructorParaTypeVarNames); - Set returnTypeVarNames = allClasses.stream() - .map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder) z.getReturnType()).getName()) - .collect(Collectors.toCollection(HashSet::new))) - .reduce((a, b) -> { - a.addAll(b); - return a; - }).get(); + Set returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a, b) -> { + a.addAll(b); + return a; + }).get(); - Set fieldTypeVarNames = allClasses.stream() - .map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder) z.getReturnType()).getName()) - .collect(Collectors.toCollection(HashSet::new))) - .reduce((a, b) -> { - a.addAll(b); - return a; - }).get(); + Set fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a, b) -> { + a.addAll(b); + return a; + }).get(); returnTypeVarNames.addAll(fieldTypeVarNames); @@ -699,14 +621,10 @@ public class JavaTXCompiler { /* * unifyCons.getOderConstraints().forEach(z -> z.forEach(y -> y.forEach(x -> { * if ((x.getLhsType() instanceof PlaceholderType) && - * x.getPairOp().compareTo(PairOperator.SMALLERDOT) == 0) { - * ((PlaceholderType) x.getLhsType()).setVariance((byte)1); - * } - * else if ((x.getRhsType() instanceof PlaceholderType) && - * x.getPairOp().compareTo(PairOperator.EQUALSDOT) == 0) { - * ((PlaceholderType) x.getRhsType()).setVariance((byte)-1); - * } - * }))); + * x.getPairOp().compareTo(PairOperator.SMALLERDOT) == 0) { ((PlaceholderType) + * x.getLhsType()).setVariance((byte)1); } else if ((x.getRhsType() instanceof + * PlaceholderType) && x.getPairOp().compareTo(PairOperator.EQUALSDOT) == 0) { + * ((PlaceholderType) x.getRhsType()).setVariance((byte)-1); } }))); */ System.out.println("Unify nach Oder-Constraints-Anpassung:" + unifyCons.toString()); @@ -736,11 +654,8 @@ public class JavaTXCompiler { // Set> result = unify.unify(xConsSet, finiteClosure); List>> oderConstraints = unifyCons.getOderConstraints()// .stream().map(x -> { /* - * Set> ret = new HashSet<>(); - * for (Constraint y : x) { - * ret.add(new HashSet<>(y)); - * } - * return ret; + * Set> ret = new HashSet<>(); for (Constraint y : x) + * { ret.add(new HashSet<>(y)); } return ret; * }).collect(Collectors.toCollection(ArrayList::new)) */; if (resultmodel) { @@ -748,8 +663,7 @@ public class JavaTXCompiler { UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure); UnifyResultListenerImpl li = new UnifyResultListenerImpl(); urm.addUnifyResultListener(li); - unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, - usedTasks); + unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks); System.out.println("RESULT Final: " + li.getResults()); System.out.println("Constraints for Generated Generics: " + " ???"); logFile.write("RES_FINAL: " + li.getResults().toString() + "\n"); @@ -761,8 +675,7 @@ public class JavaTXCompiler { // Set> result = unify.unify(unifyCons.getUndConstraints(), // oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, // finiteClosure)); - Set> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, - finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks); + Set> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks); System.out.println("RESULT: " + result); logFile.write("RES: " + result.toString() + "\n"); logFile.flush(); @@ -789,9 +702,7 @@ public class JavaTXCompiler { } catch (IOException e) { System.err.println("kein LogFile"); } - return results.stream() - .map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))) - .collect(Collectors.toList()); + return results.stream().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 { SourceFileContext tree = JavaTXParser.parse(sourceFile); - SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(sourceFile, classLoader), - new GenericsRegistry(null)); + SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(tree, sourceFile, classLoader), new GenericsRegistry(null)); SourceFile ret = generator.convert(tree, environment.packageCrawler, classLoader); return ret; } @@ -891,9 +801,8 @@ public class JavaTXCompiler { } /** - * @param outputPath - can be null, then class file output - * is in the same directory as the - * parsed source files + * @param outputPath - can be null, then class file output is in the + * same directory as the parsed source files * @param typeinferenceResult * @throws IOException */ @@ -969,8 +878,7 @@ public class JavaTXCompiler { @Override public RefTypeOrTPHOrWildcardOrGeneric visit(SuperWildcardType superWildcardType) { - SuperWildcardType ret = new SuperWildcardType(superWildcardType.getInnerType().acceptTV(this), - superWildcardType.getOffset()); + SuperWildcardType ret = new SuperWildcardType(superWildcardType.getInnerType().acceptTV(this), superWildcardType.getOffset()); return ret; } @@ -982,8 +890,7 @@ public class JavaTXCompiler { @Override public RefTypeOrTPHOrWildcardOrGeneric visit(ExtendsWildcardType extendsWildcardType) { - ExtendsWildcardType ret = new ExtendsWildcardType(extendsWildcardType.getInnerType().acceptTV(this), - extendsWildcardType.getOffset()); + ExtendsWildcardType ret = new ExtendsWildcardType(extendsWildcardType.getInnerType().acceptTV(this), extendsWildcardType.getOffset()); return ret; } diff --git a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java index d4c04a95..ccc0d47e 100644 --- a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -20,8 +20,8 @@ import de.dhbwstuttgart.parser.scope.JavaClassRegistry; /** * Stellt die Java-Environment dar und speichert alle Binarys, Librarys und - * Sourcefiles im zu kompilierenden Projekt - * Sie erstellt anhand dieser Informationen die JavaClassNameRegistry + * Sourcefiles im zu kompilierenden Projekt Sie erstellt anhand dieser + * Informationen die JavaClassNameRegistry * * TODO: Zur Initialisierung der CompilationEnvironment sollten alle SourceFiles * 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 - * java-Dateien - * Die Environment enth�lt automatisch die Java Standard Library + * java-Dateien Die Environment enth�lt automatisch die Java Standard Library * * @param sourceFiles die zu kompilierenden Dateien */ public CompilationEnvironment(List sourceFiles) { /** - * Java 9 bringt einige Änderungen am Classloader - * So funktioniert der BootClassLoader nicht mehr. - * hier gibts ein paar Quellen zum nachlesen: + * Java 9 bringt einige Änderungen am Classloader So funktioniert der + * BootClassLoader nicht mehr. hier gibts ein paar Quellen zum nachlesen: * http://java9.wtf/class-loading/ * https://stackoverflow.com/questions/46494112/classloaders-hierarchy-in-java-9 * @@ -66,13 +64,11 @@ public class CompilationEnvironment { this.packageCrawler = new PackageCrawler(librarys); } - public JavaClassRegistry getRegistry(File forSourceFile, ClassLoader classLoader) - throws ClassNotFoundException, IOException { + public JavaClassRegistry getRegistry(SourceFileContext tree, File sourceFile, ClassLoader classLoader) throws ClassNotFoundException, IOException { Map allNames; - SourceFileContext tree = JavaTXParser.parse(forSourceFile); if (tree instanceof SrcfileContext srcfile) { 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); } return new JavaClassRegistry(allNames); @@ -82,18 +78,10 @@ public class CompilationEnvironment { } - public static List loadDefaultPackageClasses(File forSourceFile, ClassLoader classLoader) - throws IOException, ClassNotFoundException { + public static List loadDefaultPackageClasses(String packageName, File sourceFile, ClassLoader classLoader) throws IOException, ClassNotFoundException { List 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 - File dir = new File(forSourceFile.getAbsoluteFile().getParent()); + File dir = sourceFile.getParentFile(); String dirPath = dir.toString() + "/"; if (packageName.length() > 0) dirPath = dirPath.substring(0, dirPath.length() - packageName.length() - 1); diff --git a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java index b04868ed..acf869cd 100644 --- a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java +++ b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java @@ -51,6 +51,7 @@ import de.dhbwstuttgart.parser.antlr.Java17Parser.ModifierContext; import de.dhbwstuttgart.parser.antlr.Java17Parser.NoclassorinterfaceContext; import de.dhbwstuttgart.parser.antlr.Java17Parser.ReftypeContext; 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.GenericsRegistry; import de.dhbwstuttgart.parser.scope.JavaClassName; @@ -112,18 +113,15 @@ public class SyntaxTreeGenerator { } public String convertQualifiedName(Java17Parser.QualifiedNameContext ctx) { - String ret = ""; - for (Java17Parser.IdentifierContext ident : ctx.identifier()) { - ret += ident.getText(); - if (ctx.identifier().iterator().hasNext()) { - ret += '.'; - } - } - return ret; + /* + * String ret = ""; for (Java17Parser.IdentifierContext ident : + * ctx.identifier()) { ret += ident.getText(); if + * (ctx.identifier().iterator().hasNext()) { ret += '.'; } } + */ + return ctx.getText(); } - public SourceFile convert(Java17Parser.SourceFileContext ctx, PackageCrawler packageCrawler, ClassLoader classLoader) - throws ClassNotFoundException, NotImplementedException { + public SourceFile convert(Java17Parser.SourceFileContext ctx, PackageCrawler packageCrawler, ClassLoader classLoader) throws ClassNotFoundException, NotImplementedException { SrcfileContext srcfile; List classes = new ArrayList<>(); if (ctx instanceof Java17Parser.SrcfileContext) { @@ -172,14 +170,12 @@ public class SyntaxTreeGenerator { } 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 if (!name.toString().equals(className)) { // Kommt die Klasse schon in einem anderen Package vor? - throw new TypeinferenceException( - "Name " + className + " bereits vorhanden in " + reg.getName(className).toString(), ctx.getStart()); + throw new TypeinferenceException("Name " + className + " bereits vorhanden in " + reg.getName(className).toString(), ctx.getStart()); } - GenericsRegistry generics = createGenerics(ctx.genericDeclarationList(), name, "", reg, - new GenericsRegistry(globalGenerics)); + GenericsRegistry generics = createGenerics(ctx.genericDeclarationList(), name, "", reg, new GenericsRegistry(globalGenerics)); Token offset = ctx.getStart(); GenericDeclarationList genericClassParameters; if (ctx.genericDeclarationList() == null) { @@ -209,30 +205,29 @@ public class SyntaxTreeGenerator { membermodifiers += allmodifiers.get(mod.getText()); } switch (member.memberDeclaration()) { - case MemberclassorinterfaceContext memberclsoif: { - break; - } - case MemberfieldContext memberfield: { - fielddecl.addAll(convert(memberfield.fieldDeclaration(), membermodifiers, generics)); - break; - } - case MembermethodContext membermethod: { - methods.add(convert(membermodifiers, membermethod.method(), name, superClass, generics)); - break; - } - case MemberconstructorContext memberconstructor: { - constructors.add(convert(membermodifiers, memberconstructor.constructor(), name, superClass, generics)); - break; - } - default: - break; + case MemberclassorinterfaceContext memberclsoif: { + break; + } + case MemberfieldContext memberfield: { + fielddecl.addAll(convert(memberfield.fieldDeclaration(), membermodifiers, generics)); + break; + } + case MembermethodContext membermethod: { + methods.add(convert(membermodifiers, membermethod.method(), name, superClass, generics)); + break; + } + case MemberconstructorContext memberconstructor: { + constructors.add(convert(membermodifiers, memberconstructor.constructor(), name, superClass, generics)); + break; + } + default: + break; } } else { continue; } if (constructors.isEmpty()) { - constructors.add(generateStandardConstructor( - ctx.identifier().getText(), name, superClass, genericClassParameters, offset)); + constructors.add(generateStandardConstructor(ctx.identifier().getText(), name, superClass, genericClassParameters, offset)); } if (ctx.IMPLEMENTS() != null) { implementedInterfaces.addAll(convert(ctx.typeList(0), generics)); @@ -240,38 +235,33 @@ public class SyntaxTreeGenerator { // Ist Bit für 'sealed'-Modifier gesetzt if ((modifiers & 4096) != 0) { switch (ctx.typeList().size()) { - case 1: { - permittedSubtypes.addAll(convert(ctx.typeList(0), generics)); - break; - } - case 2: { - permittedSubtypes.addAll(convert(ctx.typeList(1), generics)); - break; - } - default: { - break; - } + case 1: { + permittedSubtypes.addAll(convert(ctx.typeList(0), generics)); + break; + } + case 2: { + permittedSubtypes.addAll(convert(ctx.typeList(1), generics)); + break; + } + default: { + break; + } } } } - return new ClassOrInterface(modifiers, name, fielddecl, - Optional.of(this.generatePseudoConstructor(ctx.identifier().getText(), name, superClass, genericClassParameters, - offset)), - methods, constructors, genericClassParameters, superClass, isInterface, implementedInterfaces, offset); + return new ClassOrInterface(modifiers, name, fielddecl, 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) { String className = this.pkgName.length() > 0 ? this.pkgName + "." : "" + ctx.identifier().getText(); 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? - throw new TypeinferenceException( - "Name " + className + " bereits vorhanden in " + reg.getName(className).toString(), ctx.getStart()); + throw new TypeinferenceException("Name " + className + " bereits vorhanden in " + reg.getName(className).toString(), ctx.getStart()); } if (!Modifier.isInterface(modifiers)) modifiers += Modifier.INTERFACE; - GenericsRegistry generics = createGenerics(ctx.genericDeclarationList(), name, "", reg, - new GenericsRegistry(globalGenerics)); + GenericsRegistry generics = createGenerics(ctx.genericDeclarationList(), name, "", reg, new GenericsRegistry(globalGenerics)); GenericDeclarationList genericParams; if (!Objects.isNull(ctx.genericDeclarationList())) { @@ -294,32 +284,29 @@ public class SyntaxTreeGenerator { } int methodmodifiers = membermodifiers; switch (interfacemember.interfaceMemberDeclaration()) { - case InterfaceconstContext constant: - fields.add(convert(constant)); - break; - case InterfacemethodContext method: - InterfaceMethodDeclarationContext declaration = method.interfaceMethodDeclaration(); - for (InterfaceMethodModifierContext mod : declaration.interfaceMethodModifier()) { - methodmodifiers += allmodifiers.get(mod.getText()); - } - InterfaceCommonBodyDeclarationContext commonbody = declaration.interfaceCommonBodyDeclaration(); - methods.add(convert(methodmodifiers, commonbody, new GenericDeclarationList(new ArrayList<>(), - commonbody.getStart()), generics)); - break; - case GenericinterfacemethodContext genericmethod: - GenericInterfaceMethodDeclarationContext genericdeclaration = genericmethod - .genericInterfaceMethodDeclaration(); - int genericmethodmodifiers = 0; - 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); - methods.add(convert(genericmethodmodifiers, commonbody, gtv, generics)); - break; - default: - throw new NotImplementedException(); + case InterfaceconstContext constant: + fields.add(convert(constant)); + break; + case InterfacemethodContext method: + InterfaceMethodDeclarationContext declaration = method.interfaceMethodDeclaration(); + for (InterfaceMethodModifierContext mod : declaration.interfaceMethodModifier()) { + methodmodifiers += allmodifiers.get(mod.getText()); + } + InterfaceCommonBodyDeclarationContext commonbody = declaration.interfaceCommonBodyDeclaration(); + methods.add(convert(methodmodifiers, commonbody, new GenericDeclarationList(new ArrayList<>(), commonbody.getStart()), generics)); + break; + case GenericinterfacemethodContext genericmethod: + GenericInterfaceMethodDeclarationContext genericdeclaration = genericmethod.genericInterfaceMethodDeclaration(); + int genericmethodmodifiers = 0; + 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); + methods.add(convert(genericmethodmodifiers, commonbody, gtv, generics)); + break; + default: + throw new NotImplementedException(); } } } @@ -327,8 +314,7 @@ public class SyntaxTreeGenerator { if (!Objects.isNull(ctx.EXTENDS())) { extendedInterfaces.addAll(convert(ctx.typeList(0), generics)); } - return new ClassOrInterface(modifiers, name, fields, Optional.empty(), methods, new ArrayList<>(), - genericParams, superClass, true, extendedInterfaces, ctx.getStart()); + return new ClassOrInterface(modifiers, name, fields, Optional.empty(), methods, new ArrayList<>(), genericParams, superClass, true, extendedInterfaces, ctx.getStart()); } private GenericDeclarationList createEmptyGenericDeclarationList(Token classNameIdentifier) { @@ -343,9 +329,7 @@ public class SyntaxTreeGenerator { throw new NotImplementedException(); } - private Method convert(int modifiers, InterfaceCommonBodyDeclarationContext bodydeclaration, - GenericDeclarationList gtvDeclarations, - GenericsRegistry generics) { + private Method convert(int modifiers, InterfaceCommonBodyDeclarationContext bodydeclaration, GenericDeclarationList gtvDeclarations, GenericsRegistry generics) { String name = bodydeclaration.identifier().getText(); 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 */ - private Constructor generateStandardConstructor(String className, JavaClassName parentClass, RefType superClass, - GenericDeclarationList classGenerics, Token offset) { + private Constructor generateStandardConstructor(String className, JavaClassName parentClass, RefType superClass, GenericDeclarationList classGenerics, Token offset) { RefType classType = ClassOrInterface.generateTypeOfClass(reg.getName(className), classGenerics, offset); ParameterList params = new ParameterList(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 * Syntax gespeichert */ - private Constructor generatePseudoConstructor(String className, JavaClassName parentClass, RefType superClass, - GenericDeclarationList classGenerics, Token offset) { + private Constructor generatePseudoConstructor(String className, JavaClassName parentClass, RefType superClass, GenericDeclarationList classGenerics, Token offset) { RefType classType = ClassOrInterface.generateTypeOfClass(reg.getName(className), classGenerics, offset); ParameterList params = new ParameterList(new ArrayList<>(), offset); Block block = new Block(new ArrayList<>(fieldInitializations), offset); return new Constructor(Modifier.PUBLIC, className, classType, params, block, classGenerics, offset /* - * fieldInitializations - * geloescht PL - * 2018-11-24 + * fieldInitializations geloescht PL 2018-11-24 */); } @@ -405,11 +385,8 @@ public class SyntaxTreeGenerator { if (supertypecontext != null && supertypecontext.DOT().size() > 0) { throw new NotImplementedException(); } else { - RefTypeOrTPHOrWildcardOrGeneric ret = TypeGenerator.convertTypeName( - typeType.classOrInterfaceType().typeIdentifier().getText(), - typeType.classOrInterfaceType().typeArguments() - .get(typeType.classOrInterfaceType().typeArguments().size() - 1), - typeType.getStart(), reg, globalGenerics); + TypeArgumentsContext typeArguments = (typeType.classOrInterfaceType().typeArguments().size() > 0) ? typeType.classOrInterfaceType().typeArguments().get(typeType.classOrInterfaceType().typeArguments().size() - 1) : null; + RefTypeOrTPHOrWildcardOrGeneric ret = TypeGenerator.convertTypeName(typeType.classOrInterfaceType().typeIdentifier().getText(), typeArguments, typeType.getStart(), reg, globalGenerics); if (ret instanceof RefType) { return (RefType) ret; } else { @@ -426,8 +403,7 @@ public class SyntaxTreeGenerator { return ret; } - public Method convert(int modifiers, Java17Parser.MethodContext methodContext, JavaClassName parentClass, - RefType superClass, GenericsRegistry generics) { + public Method convert(int modifiers, Java17Parser.MethodContext methodContext, JavaClassName parentClass, RefType superClass, GenericsRegistry generics) { GenericsRegistry localgenerics = generics; MethodDeclarationContext methoddeclaration; GenericDeclarationListContext genericdeclarations; @@ -475,9 +451,7 @@ public class SyntaxTreeGenerator { return new Method(modifiers, name, retType, paramlist, block, gtvDeclarations, header.getStart()); } - public Constructor convert(int modifiers, Java17Parser.ConstructorContext constructorContext, - JavaClassName parentClass, - RefType superClass, GenericsRegistry generics) { + public Constructor convert(int modifiers, Java17Parser.ConstructorContext constructorContext, JavaClassName parentClass, RefType superClass, GenericsRegistry generics) { GenericsRegistry localgenerics = generics; GenericDeclarationListContext genericdeclarations; GenericDeclarationList gtvDeclarations; @@ -497,17 +471,14 @@ public class SyntaxTreeGenerator { name = constructordeclaration.identifier().getText(); gtvDeclarations = new GenericDeclarationList(new ArrayList<>(), constructordeclaration.getStart()); } - RefTypeOrTPHOrWildcardOrGeneric retType = TypeGenerator.convertTypeName(name, constructordeclaration.getStart(), - reg, localgenerics); + RefTypeOrTPHOrWildcardOrGeneric retType = TypeGenerator.convertTypeName(name, constructordeclaration.getStart(), reg, localgenerics); StatementGenerator stmtgen = new StatementGenerator(reg, localgenerics, fields, new HashMap<>()); ParameterList paramlist = stmtgen.convert(constructordeclaration.formalParameters().formalParameterList()); Block block = stmtgen.convert(constructordeclaration.constructorBody, true); - return new Constructor(modifiers, name, retType, paramlist, block, gtvDeclarations, - constructordeclaration.getStart()); + return new Constructor(modifiers, name, retType, paramlist, block, gtvDeclarations, constructordeclaration.getStart()); } - private List convert(Java17Parser.FieldDeclarationContext fieldDeclContext, int modifiers, - GenericsRegistry generics) { + private List convert(Java17Parser.FieldDeclarationContext fieldDeclContext, int modifiers, GenericsRegistry generics) { List ret = new ArrayList<>(); RefTypeOrTPHOrWildcardOrGeneric fieldType; if (fieldDeclContext.typeType() != null) { @@ -533,8 +504,7 @@ public class SyntaxTreeGenerator { } // Initialize a field by creating implicit constructor. - private void initializeField(Java17Parser.VariableDeclaratorContext ctx, RefTypeOrTPHOrWildcardOrGeneric typeOfField, - GenericsRegistry generics) { + private void initializeField(Java17Parser.VariableDeclaratorContext ctx, RefTypeOrTPHOrWildcardOrGeneric typeOfField, GenericsRegistry generics) { StatementGenerator statementGenerator = new StatementGenerator(reg, generics, fields, new HashMap<>()); fieldInitializations.add(statementGenerator.generateFieldAssignment(ctx, typeOfField)); } @@ -543,8 +513,7 @@ public class SyntaxTreeGenerator { return allmodifiers.get(modifier); } - private GenericsRegistry createGenerics(Java17Parser.GenericDeclarationListContext ctx, JavaClassName parentClass, - String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) { + private GenericsRegistry createGenerics(Java17Parser.GenericDeclarationListContext ctx, JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) { GenericsRegistry ret = new GenericsRegistry(this.globalGenerics); ret.putAll(generics); if (ctx == null) diff --git a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/TypeGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/TypeGenerator.java index d8a4e60f..ba17193c 100644 --- a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/TypeGenerator.java +++ b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/TypeGenerator.java @@ -29,23 +29,19 @@ import java.util.regex.Pattern; public class TypeGenerator { - public static RefTypeOrTPHOrWildcardOrGeneric convert( - Java17Parser.ClassOrInterfaceTypeContext classOrInterfaceTypeContext, JavaClassRegistry reg, - GenericsRegistry generics) { + public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.ClassOrInterfaceTypeContext classOrInterfaceTypeContext, JavaClassRegistry reg, GenericsRegistry generics) { 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. - * unannClassType_lfno_unannClassOrInterfaceType() != null){ - * arguments = unannClassOrInterfaceTypeContext. - * unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); - * }else{// if(unannClassOrInterfaceTypeContext. - * unannInterfaceType_lfno_unannClassOrInterfaceType() != null){ - * arguments = unannClassOrInterfaceTypeContext. + * unannInterfaceType_lfno_unannClassOrInterfaceType() != null){ arguments = + * unannClassOrInterfaceTypeContext. * unannInterfaceType_lfno_unannClassOrInterfaceType(). - * unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); - * } - * PL 2019-03-19 auskommentiert ENDE + * unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); } PL + * 2019-03-19 auskommentiert ENDE */ /** * Problem sind hier die verschachtelten Typen mit verschachtelten Typargumenten @@ -56,13 +52,12 @@ public class TypeGenerator { String name = ""; for (IdentifierContext id : classOrInterfaceTypeContext.identifier()) { - name += id.getText(); + name += id.getText() + '.'; } - name += classOrInterfaceTypeContext.typeIdentifier(); + name += classOrInterfaceTypeContext.typeIdentifier().getText(); if (classOrInterfaceTypeContext.getStop().getText().equals(">")) { /* - * Fuer Debug-Zwecke - * unannClassOrInterfaceTypeContext. + * Fuer Debug-Zwecke unannClassOrInterfaceTypeContext. * unannInterfaceType_lfno_unannClassOrInterfaceType(); * unannClassOrInterfaceTypeContext. * unannClassType_lfno_unannClassOrInterfaceType().getText(); @@ -77,8 +72,7 @@ public class TypeGenerator { * unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType( * 1); * unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType( - * 1).getText(); - * unannClassOrInterfaceTypeContext. + * 1).getText(); unannClassOrInterfaceTypeContext. * unannClassType_lfno_unannClassOrInterfaceType().getText(); * //unannClassOrInterfaceTypeContext. * unannInterfaceType_lf_unannClassOrInterfaceType(); @@ -95,8 +89,7 @@ public class TypeGenerator { return convertTypeName(name, arguments, classOrInterfaceTypeContext.getStart(), reg, generics); } - public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.TypeTypeContext typeContext, - JavaClassRegistry reg, GenericsRegistry genericsRegistry) { + public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.TypeTypeContext typeContext, JavaClassRegistry reg, GenericsRegistry genericsRegistry) { if (typeContext.primitiveType() != null) { if (typeContext.primitiveType().getText().equals("boolean")) { 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 // System.out.println(unannTypeContext.getText()); 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, - JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) { + public static GenericDeclarationList convert(Java17Parser.GenericDeclarationListContext typeParametersContext, JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) { Token endOffset = typeParametersContext.getStop(); List typeVars = new ArrayList<>(); for (Java17Parser.GenericTypeVarContext typeParameter : typeParametersContext.genericTypeVar()) { @@ -131,8 +123,7 @@ public class TypeGenerator { return new GenericDeclarationList(typeVars, endOffset); } - public static GenericTypeVar convert(Java17Parser.GenericTypeVarContext typeVar, JavaClassName parentClass, - String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) { + public static GenericTypeVar convert(Java17Parser.GenericTypeVarContext typeVar, JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) { String name = typeVar.identifier().getText(); // TODO: Es müssen erst alle GenericTypeVars generiert werden, dann können die // bounds dieser Generics ermittelt werden @@ -144,8 +135,7 @@ public class TypeGenerator { return ret; } - public static List convert(Java17Parser.TypeBoundContext typeBoundContext, - JavaClassRegistry reg, GenericsRegistry generics) { + public static List convert(Java17Parser.TypeBoundContext typeBoundContext, JavaClassRegistry reg, GenericsRegistry generics) { List ret = new ArrayList<>(); if (Objects.isNull(typeBoundContext)) { ret.add(ASTFactory.createObjectType()); @@ -160,29 +150,23 @@ public class TypeGenerator { throw new NotImplementedException(); } - public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.WildcardTypeContext wildcardContext, - JavaClassRegistry reg, GenericsRegistry generics) { + public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.WildcardTypeContext wildcardContext, JavaClassRegistry reg, GenericsRegistry generics) { if (wildcardContext.getChildCount() < 3) { if (!Objects.isNull(wildcardContext.extendsWildcardType())) { - return new ExtendsWildcardType(convert(wildcardContext.extendsWildcardType().typeType(), reg, generics), - wildcardContext.getStart()); + return new ExtendsWildcardType(convert(wildcardContext.extendsWildcardType().typeType(), reg, generics), wildcardContext.getStart()); } else { - return new SuperWildcardType(convert(wildcardContext.superWildcardType().typeType(), reg, generics), - wildcardContext.getStart()); + return new SuperWildcardType(convert(wildcardContext.superWildcardType().typeType(), reg, generics), wildcardContext.getStart()); } } else { throw new NotImplementedException(); // Wildcard ohne Bound } } - public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(String name, Token offset, JavaClassRegistry reg, - GenericsRegistry generics) { + public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(String name, Token offset, JavaClassRegistry reg, GenericsRegistry generics) { return convertTypeName(name, (Java17Parser.TypeArgumentsContext) null, offset, reg, generics); } - public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName( - String name, Java17Parser.TypeArgumentsContext typeArguments, Token offset, JavaClassRegistry reg, - GenericsRegistry generics) { + public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(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 (generics.contains(name)) { return new GenericRefType(name, offset); @@ -207,10 +191,7 @@ public class TypeGenerator { } } - public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName( - String name, Java17Parser.NonWildcardTypeArgumentsContext typeArguments, Token offset, - JavaClassRegistry reg, - GenericsRegistry generics) { + public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(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 (generics.contains(name)) { return new GenericRefType(name, offset); @@ -235,8 +216,7 @@ public class TypeGenerator { } } - public static List convert(Java17Parser.TypeArgumentsContext typeArguments, - JavaClassRegistry reg, GenericsRegistry generics) { + public static List convert(Java17Parser.TypeArgumentsContext typeArguments, JavaClassRegistry reg, GenericsRegistry generics) { List ret = new ArrayList<>(); for (Java17Parser.TypeArgumentContext arg : typeArguments.typeArgument()) { WildcardTypeContext wc = arg.wildcardType(); @@ -249,9 +229,7 @@ public class TypeGenerator { return ret; } - public static List convert( - Java17Parser.NonWildcardTypeArgumentsContext typeArguments, - JavaClassRegistry reg, GenericsRegistry generics) { + public static List convert(Java17Parser.NonWildcardTypeArgumentsContext typeArguments, JavaClassRegistry reg, GenericsRegistry generics) { List ret = new ArrayList<>(); for (Java17Parser.TypeTypeContext arg : typeArguments.typeList().typeType()) { ret.add(convert(arg, reg, generics)); diff --git a/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java b/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java index da84a068..0938653e 100644 --- a/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java +++ b/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java @@ -10,8 +10,7 @@ import de.dhbwstuttgart.parser.antlr.Java17Parser; public class GatherNames { - public static Map getNames(SrcfileContext ctx, PackageCrawler packages, - ClassLoader classLoader) throws ClassNotFoundException { + public static Map getNames(SrcfileContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException { Map ret = new HashMap<>(); String pkgName = getPackageName(ctx); String nameString = ""; @@ -22,27 +21,20 @@ public class GatherNames { ClassorinterfacedeclContext clsoif = (ClassorinterfacedeclContext) member; if (clsoif.interfaceDeclaration() != null) { if (pkgName != "") { - nameString = pkgName + "." - + clsoif.interfaceDeclaration().identifier().getText(); + nameString = pkgName + "." + clsoif.interfaceDeclaration().identifier().getText(); } else { nameString = clsoif.interfaceDeclaration().identifier().getText(); } - int numGenerics = clsoif.interfaceDeclaration().genericDeclarationList() != null - ? clsoif.interfaceDeclaration().genericDeclarationList().genericTypeVar().size() - : 0; + int numGenerics = clsoif.interfaceDeclaration().genericDeclarationList() != null ? clsoif.interfaceDeclaration().genericDeclarationList().genericTypeVar().size() : 0; // Die Generic TypeParameter Definitionen Nicht! an die JavaClassName-Registry // anfügen: /* * //Diese gelängen dadurch in den globalen Scope, was sie schließlich nicht - * sind - * if(clsoif.classDeclaration().normalClassDeclaration().typeParameters() != - * null){ - * for(Java17Parser.TypeParameterContext tp : + * sind if(clsoif.classDeclaration().normalClassDeclaration().typeParameters() + * != null){ for(Java17Parser.TypeParameterContext tp : * clsoif.classDeclaration().normalClassDeclaration().typeParameters(). * typeParameterList().typeParameter()){ - * //this.reg.add(tp.Identifier().toString()); - * } - * } + * //this.reg.add(tp.Identifier().toString()); } } */ ret.put(nameString, numGenerics); } else { @@ -55,19 +47,13 @@ public class GatherNames { // anfügen: /* * //Diese gelängen dadurch in den globalen Scope, was sie schließlich nicht - * sind - * if(clsoif.classDeclaration().normalClassDeclaration().typeParameters() != - * null){ - * for(Java17Parser.TypeParameterContext tp : + * sind if(clsoif.classDeclaration().normalClassDeclaration().typeParameters() + * != null){ for(Java17Parser.TypeParameterContext tp : * clsoif.classDeclaration().normalClassDeclaration().typeParameters(). * typeParameterList().typeParameter()){ - * this.reg.add(tp.Identifier().toString()); - * } - * } + * this.reg.add(tp.Identifier().toString()); } } */ - int numGenerics = clsoif.classDeclaration().genericDeclarationList() != null - ? clsoif.classDeclaration().genericDeclarationList().genericTypeVar().size() - : 0; + int numGenerics = clsoif.classDeclaration().genericDeclarationList() != null ? clsoif.classDeclaration().genericDeclarationList().genericTypeVar().size() : 0; ret.put(nameString, numGenerics); } @@ -76,8 +62,7 @@ public class GatherNames { return ret; } - public static Map getImports(Java17Parser.SrcfileContext ctx, PackageCrawler packages, - ClassLoader classLoader) throws ClassNotFoundException { + public static Map getImports(Java17Parser.SrcfileContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException { Map ret = new HashMap<>(); // ret.putAll(packages.getClassNames("java.lang")); for (Java17Parser.ImportDeclarationContext importDeclCtx : ctx.importDeclaration()) { diff --git a/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java b/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java index 534d0916..867973f9 100644 --- a/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java +++ b/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java @@ -1,12 +1,12 @@ package de.dhbwstuttgart.parser.scope; - import java.util.ArrayList; import java.util.List; /** - * Stellt den Namen einer Java Klasse dar. - * Dieser kann auch den Packagenamen mit beinhalten: de.dhbwstuttgart.typeinference.Menge + * Stellt den Namen einer Java Klasse dar. + * Dieser kann auch den Packagenamen mit beinhalten: + * de.dhbwstuttgart.typeinference.Menge * * @author Andreas Stadelmeier */ @@ -16,22 +16,23 @@ public class JavaClassName { private String name; private PackageName packageName; - public JavaClassName(String name){ - if(name == null)throw new NullPointerException(); - + public JavaClassName(String name) { + if (name == null) + throw new NullPointerException(); + String[] names = name.split("[.]"); boolean match = true; - if(names.length == 1){ - //packageName = new PackageName(); + if (names.length == 1) { + // packageName = new PackageName(); this.name = name; - }else { - name = names[names.length-1]; + } else { + name = names[names.length - 1]; List packageNames = new ArrayList(); - for(int i = 0; i names = new ArrayList<>(); - + public PackageName(List packageNames) { names = packageNames; } public PackageName() { - //Do nothing + // Do nothing } @Override @@ -132,12 +139,14 @@ class PackageName{ return false; return true; } - + @Override public String toString() { String ret = ""; - if(names == null)return ""; - for(String n : names)ret+=n+"."; + if (names == null) + return ""; + for (String n : names) + ret += n + "."; if (ret != null && ret.length() > 0 && ret.charAt(ret.length() - 1) == '.') { ret = ret.substring(0, ret.length() - 1); } diff --git a/src/test/java/packages/LoadDefaultPackageClassesTest.java b/src/test/java/packages/LoadDefaultPackageClassesTest.java index 49f33385..c8bd3205 100644 --- a/src/test/java/packages/LoadDefaultPackageClassesTest.java +++ b/src/test/java/packages/LoadDefaultPackageClassesTest.java @@ -13,16 +13,13 @@ import java.net.URLClassLoader; 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 { /* - Generate ToImport class in rootDirectory and in output-Directory + * Generate ToImport class in rootDirectory and in output-Directory */ - JavaTXCompiler compiler = new JavaTXCompiler( - Lists.newArrayList(new File(rootDirectory+"Gen.jav")), - Lists.newArrayList(new File(rootDirectory+"/de/test/output/"))); + JavaTXCompiler compiler = new JavaTXCompiler(Lists.newArrayList(new File(rootDirectory + "Gen.jav")), Lists.newArrayList(new File(rootDirectory + "/de/test/output/"))); compiler.typeInference(); compiler.generateBytecode(); File f = new File(rootDirectory + "Gen.class"); @@ -30,26 +27,22 @@ public class LoadDefaultPackageClassesTest extends TestCase { } 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 { - 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"); } -/* - public void testE2E() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"OL.jav")); - compiler.typeInference(); - compiler.generateBytecode(); - File f = new File(rootDirectory + "OL.class"); - assertTrue(f.exists()); - - compiler = new JavaTXCompiler(new File(rootDirectory+"OLMain.jav")); - compiler.typeInference(); - compiler.generateBytecode(); - f = new File(rootDirectory + "OLMain.class"); - assertTrue(f.exists()); - } - */ + /* + * public void testE2E() throws IOException, ClassNotFoundException { + * JavaTXCompiler compiler = new JavaTXCompiler(new + * File(rootDirectory+"OL.jav")); compiler.typeInference(); + * compiler.generateBytecode(); File f = new File(rootDirectory + "OL.class"); + * assertTrue(f.exists()); + * + * compiler = new JavaTXCompiler(new File(rootDirectory+"OLMain.jav")); + * compiler.typeInference(); compiler.generateBytecode(); f = new + * File(rootDirectory + "OLMain.class"); assertTrue(f.exists()); } + */ } diff --git a/src/test/java/parser/ExtendsTest.jav b/src/test/java/parser/ExtendsTest.jav index 9103f463..43441756 100644 --- a/src/test/java/parser/ExtendsTest.jav +++ b/src/test/java/parser/ExtendsTest.jav @@ -1,3 +1,5 @@ +import java.lang.Object; + class C1 extends Object { m(para) { return para; } diff --git a/src/test/java/parser/GeneralParserTest.java b/src/test/java/parser/GeneralParserTest.java index 7c819d7e..262f7406 100644 --- a/src/test/java/parser/GeneralParserTest.java +++ b/src/test/java/parser/GeneralParserTest.java @@ -33,7 +33,6 @@ public class GeneralParserTest { filenames.add("StatementsTest.jav"); // filenames.add("Methods.jav"); filenames.add("ImportTestGeneric.jav"); - filenames.add("CastTest.jav"); // filenames.add("BoundedParameter.jav"); // filenames.add("GenericFieldVarTest.jav"); filenames.add("FieldVarTest.jav"); diff --git a/src/test/java/parser/Java17Rules.jav b/src/test/java/parser/Java17Rules.jav index b824ed49..4fe344ef 100644 --- a/src/test/java/parser/Java17Rules.jav +++ b/src/test/java/parser/Java17Rules.jav @@ -353,7 +353,7 @@ class Records { } - final record R1(@Dummy2 @Dummy x) { + final record R1(x) { R1(x) { this.x = x;