Compare commits
47 Commits
issue363
...
LSP-Interf
Author | SHA1 | Date | |
---|---|---|---|
|
a314013f40 | ||
|
37c58be1f3 | ||
|
24920330c6 | ||
|
bc43ea749d | ||
9160c99cf2 | |||
c72a14cab3 | |||
10bb5d1d11 | |||
2842fc5069 | |||
5c5e0bd1e9 | |||
3d81318e01 | |||
53e2c20608 | |||
86e467fd82 | |||
25b14e9342 | |||
d0de0b31e4 | |||
dd180524b2 | |||
b3744bf5f7 | |||
fda16978c2 | |||
a485cd8fa6 | |||
f8c708f0f4 | |||
28d9946bbb | |||
7b4ca8f177 | |||
b879d7743d | |||
e26a43b400 | |||
5deed725ae | |||
8ae15f9d41 | |||
8c8e088612 | |||
2814c6538e | |||
dcbc29b49b | |||
05033bcb9d | |||
814f5dd5fa | |||
24ca985ccc | |||
|
c479b044b3 | ||
|
9046fb09e5 | ||
|
42e31a3471 | ||
|
d3b3f92193 | ||
|
8208abcaea | ||
|
e4a3939ce9 | ||
|
d903ec0ebb | ||
|
61de81cf92 | ||
|
59888006e0 | ||
|
94034912b4 | ||
|
f303163118 | ||
|
7d99fba044 | ||
|
3740d34954 | ||
|
d8b861ea95 | ||
|
cf45ea68bd | ||
|
be72e4d7fb |
@@ -1,5 +1,8 @@
|
||||
name: Build and Test with Maven
|
||||
on: [push]
|
||||
on:
|
||||
push:
|
||||
branches-ignore:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
Build-and-test-with-Maven:
|
||||
@@ -22,4 +25,4 @@ jobs:
|
||||
mvn compile
|
||||
- name: Run tests
|
||||
run: |
|
||||
mvn test
|
||||
mvn test
|
||||
|
45
.gitea/workflows/sonarqube.yml
Normal file
45
.gitea/workflows/sonarqube.yml
Normal file
@@ -0,0 +1,45 @@
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
name: SonarQube Scan
|
||||
jobs:
|
||||
sonarqube:
|
||||
name: SonarQube Trigger
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checking out
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
# Disabling shallow clone is recommended for improving relevancy of reporting
|
||||
fetch-depth: 0
|
||||
- name: Install maven
|
||||
run: |
|
||||
apt update
|
||||
apt install -y maven
|
||||
- name: Install java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '24'
|
||||
cache: 'maven'
|
||||
- name: Compile project
|
||||
run: |
|
||||
mvn clean dependency:copy-dependencies verify
|
||||
- name: SonarQube Scan
|
||||
uses: SonarSource/sonarqube-scan-action@v5.3.0
|
||||
env:
|
||||
SONAR_HOST_URL: ${{ secrets.SONARQUBE_HOST }}
|
||||
SONAR_TOKEN: ${{ secrets.SONARQUBE_TOKEN }}
|
||||
with:
|
||||
args: >
|
||||
-Dsonar.projectKey=Java-TX
|
||||
-Dsonar.sources=src/main/java
|
||||
-Dsonar.tests=src/test/java
|
||||
-Dsonar.junit.reportPaths=target/test-reports
|
||||
-Dsonar.java.binaries=target/classes
|
||||
-Dsonar.java.libraries=target/dependency/*.jar
|
||||
-Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml
|
7
README.md
Normal file
7
README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
## Java-TX Compiler
|
||||
|
||||
[](https://gitea.hb.dhbw-stuttgart.de/sonarqube/dashboard?id=Java-TX)
|
||||
[](https://gitea.hb.dhbw-stuttgart.de/sonarqube/dashboard?id=Java-TX)
|
||||
[](https://gitea.hb.dhbw-stuttgart.de/sonarqube/dashboard?id=Java-TX)
|
||||
|
||||
Work in Progress Java-TX Compiler repository!
|
25
pom.xml
25
pom.xml
@@ -48,14 +48,33 @@ http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<version>0.8.13</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>report</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.14.0</version>
|
||||
<configuration>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
<source>24</source>
|
||||
<target>24</target>
|
||||
<source>23</source>
|
||||
<target>23</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
@@ -65,7 +84,7 @@ http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<configuration>
|
||||
<redirectTestOutputToFile>true</redirectTestOutputToFile>
|
||||
<reportsDirectory>${project.build.directory}/test-reports</reportsDirectory>
|
||||
<argLine>--enable-preview</argLine>
|
||||
<argLine>${argLine} --enable-preview</argLine>
|
||||
<trimStackTrace>false</trimStackTrace>
|
||||
<excludes>
|
||||
<exclude>**/JavaTXCompilerTest.java</exclude>
|
||||
|
@@ -6,7 +6,7 @@ import java.util.stream.Stream;
|
||||
|
||||
public class Bug325 {
|
||||
public main() {
|
||||
List<Integer> list = new ArrayList<>(List.of(1,2,3,4,5));
|
||||
var list = new ArrayList<>(List.of(1,2,3,4,5));
|
||||
var func = x -> x*2;
|
||||
return list.stream().map(func).toList();
|
||||
}
|
||||
|
17
resources/bytecode/javFiles/Bug373.jav
Normal file
17
resources/bytecode/javFiles/Bug373.jav
Normal file
@@ -0,0 +1,17 @@
|
||||
import java.lang.Boolean;
|
||||
import java.lang.Integer;
|
||||
import java.lang.System;
|
||||
import java.io.PrintStream;
|
||||
import java.lang.Character;
|
||||
|
||||
public class Bug373 {
|
||||
public static main() {
|
||||
System.out.println(true);
|
||||
System.out.println(false);
|
||||
System.out.println(1);
|
||||
System.out.println(1l);
|
||||
System.out.println(1.0);
|
||||
System.out.println(1.0f);
|
||||
System.out.println('a');
|
||||
}
|
||||
}
|
14
resources/bytecode/javFiles/Main.jav
Normal file
14
resources/bytecode/javFiles/Main.jav
Normal file
@@ -0,0 +1,14 @@
|
||||
import java.lang.Object;
|
||||
import java.lang.System;
|
||||
import java.lang.Iterable;
|
||||
import java.io.PrintStream;
|
||||
import java.util.List;
|
||||
import java.lang.String;
|
||||
|
||||
class Main {
|
||||
static main(args) {
|
||||
for (var arg : args) {
|
||||
System.out.println(arg);
|
||||
}
|
||||
}
|
||||
}
|
@@ -232,9 +232,9 @@ public class Codegen {
|
||||
if (source.equals(dest))
|
||||
return;
|
||||
if (source.equals(TargetType.Long)) {
|
||||
if (dest.equals(TargetType.Integer)) {
|
||||
if (dest.equals(TargetType.Integer))
|
||||
mv.visitInsn(L2I);
|
||||
} else if (dest.equals(TargetType.Float))
|
||||
else if (dest.equals(TargetType.Float))
|
||||
mv.visitInsn(L2F);
|
||||
else if (dest.equals(TargetType.Double))
|
||||
mv.visitInsn(L2D);
|
||||
@@ -277,6 +277,8 @@ public class Codegen {
|
||||
mv.visitInsn(I2F);
|
||||
else if (dest.equals(TargetType.Double))
|
||||
mv.visitInsn(I2D);
|
||||
} else if (source.equals(TargetType.Boolean)) {
|
||||
unboxPrimitive(state, dest);
|
||||
} else if (isFunctionalInterface(source) && isFunctionalInterface(dest) &&
|
||||
!(source instanceof TargetFunNType && dest instanceof TargetFunNType)) {
|
||||
boxFunctionalInterface(state, source, dest);
|
||||
@@ -1597,8 +1599,27 @@ public class Codegen {
|
||||
generateMethod(method, null);
|
||||
}
|
||||
|
||||
private void generateMainMethod() {
|
||||
var mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
|
||||
mv.visitCode();
|
||||
mv.visitVarInsn(ALOAD, 0);
|
||||
mv.visitMethodInsn(INVOKESTATIC, "java/util/List", "of", "([Ljava/lang/Object;)Ljava/util/List;", true);
|
||||
mv.visitMethodInsn(INVOKESTATIC, className, "main", "(Ljava/util/List;)V", false);
|
||||
mv.visitInsn(RETURN);
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
}
|
||||
|
||||
private void generateMethod(TargetMethod method, State parent) {
|
||||
var access = method.access();
|
||||
|
||||
var params = method.signature().parameters();
|
||||
if (method.name().equals("main") && method.isStatic() && params.size() == 1 &&
|
||||
params.getFirst().pattern().type().equals(new TargetRefType("java.util.List", List.of(new TargetRefType("java.lang.String"))))) {
|
||||
|
||||
generateMainMethod();
|
||||
}
|
||||
|
||||
if (method.block() == null)
|
||||
access |= ACC_ABSTRACT;
|
||||
if (clazz instanceof TargetInterface)
|
||||
|
@@ -5,6 +5,7 @@ import de.dhbwstuttgart.bytecode.Codegen;
|
||||
import de.dhbwstuttgart.environment.CompilationEnvironment;
|
||||
import de.dhbwstuttgart.environment.DirectoryClassLoader;
|
||||
import de.dhbwstuttgart.exceptions.DebugException;
|
||||
import de.dhbwstuttgart.languageServerInterface.model.LanguageServerTransferObject;
|
||||
import de.dhbwstuttgart.parser.JavaTXParser;
|
||||
import de.dhbwstuttgart.parser.NullToken;
|
||||
import de.dhbwstuttgart.parser.scope.GenericsRegistry;
|
||||
@@ -469,6 +470,85 @@ public class JavaTXCompiler {
|
||||
return results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* TEMPORARY - Only for Language Server Usage
|
||||
*/
|
||||
public LanguageServerTransferObject getResultSetAndAbstractSyntax(File file) throws IOException, ClassNotFoundException {
|
||||
var sf = sourceFiles.get(file);
|
||||
if(sf == null){
|
||||
sf = sourceFiles.values().stream().findFirst().get();
|
||||
}
|
||||
Set<ClassOrInterface> allClasses = new HashSet<>();
|
||||
allClasses.addAll(getAvailableClasses(sf));
|
||||
allClasses.addAll(sf.getClasses());
|
||||
var newClasses = CompilationEnvironment.loadDefaultPackageClasses(sf.getPkgName(), file, this).stream().map(ASTFactory::createClass).collect(Collectors.toSet());
|
||||
for (var clazz : newClasses) {
|
||||
// Don't load classes that get recompiled
|
||||
if (sf.getClasses().stream().anyMatch(nf -> nf.getClassName().equals(clazz.getClassName())))
|
||||
continue;
|
||||
if (allClasses.stream().noneMatch(old -> old.getClassName().equals(clazz.getClassName())))
|
||||
allClasses.add(clazz);
|
||||
}
|
||||
|
||||
final ConstraintSet<Pair> cons = getConstraints(file);
|
||||
Set<Set<UnifyPair>> results = new HashSet<>();
|
||||
try {
|
||||
Writer logFile = new OutputStreamWriter(new NullOutputStream());
|
||||
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses.stream().toList(), logFile, classLoader, this);
|
||||
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(this, cons);
|
||||
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
|
||||
UnifyType lhs, rhs;
|
||||
if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
|
||||
((PlaceholderType) lhs).setInnerType(true);
|
||||
((PlaceholderType) rhs).setInnerType(true);
|
||||
}
|
||||
return x;
|
||||
|
||||
};
|
||||
|
||||
|
||||
unifyCons = unifyCons.map(distributeInnerVars);
|
||||
TypeUnify unify = new TypeUnify();
|
||||
Set<PlaceholderType> varianceTPHold;
|
||||
Set<PlaceholderType> varianceTPH = new HashSet<>();
|
||||
varianceTPH = varianceInheritanceConstraintSet(unifyCons);
|
||||
|
||||
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints();
|
||||
|
||||
if (resultmodel) {
|
||||
/* UnifyResultModel Anfang */
|
||||
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
|
||||
UnifyResultListenerImpl li = new UnifyResultListenerImpl();
|
||||
urm.addUnifyResultListener(li);
|
||||
unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks);
|
||||
generateBytecode(sf, li.getResults());
|
||||
return new LanguageServerTransferObject(li.getResults(), sf, ASTTypePrinter.print(sf), generatedGenerics);
|
||||
}
|
||||
/* UnifyResultModel End */
|
||||
else {
|
||||
Set<Set<UnifyPair>> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks);
|
||||
results.addAll(result);
|
||||
|
||||
results = results.stream().map(x -> {
|
||||
Optional<Set<UnifyPair>> res = new RuleSet().subst(x.stream().map(y -> {
|
||||
if (y.getPairOp() == PairOperator.SMALLERDOTWC)
|
||||
y.setPairOp(PairOperator.EQUALSDOT);
|
||||
return y; // alle Paare a <.? b erden durch a =. b ersetzt
|
||||
}).collect(Collectors.toCollection(HashSet::new)));
|
||||
if (res.isPresent()) {// wenn subst ein Erg liefert wurde was veraendert
|
||||
return new TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure);
|
||||
} else
|
||||
return x; // wenn nichts veraendert wurde wird x zurueckgegeben
|
||||
}).collect(Collectors.toCollection(HashSet::new));
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
}
|
||||
generateBytecode(sf, results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))).collect(Collectors.toList()));
|
||||
return new LanguageServerTransferObject(results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))).collect(Collectors.toList()), sf, ASTTypePrinter.print(sf), generatedGenerics);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine Variance !=0 hat auf alle Typvariablen in Theta.
|
||||
*
|
||||
|
@@ -30,7 +30,7 @@ public class CompilationEnvironment {
|
||||
public final PackageCrawler packageCrawler;
|
||||
|
||||
/**
|
||||
* Imitiert die Environment beim Aufruf des JavaCompilers auf einer Menge von java-Dateien Die Environment enth<EFBFBD>lt automatisch die Java Standard Library
|
||||
* Imitiert die Environment beim Aufruf des JavaCompilers auf einer Menge von java-Dateien Die Environment enthält automatisch die Java Standard Library
|
||||
*
|
||||
* @param sourceFiles die zu kompilierenden Dateien
|
||||
*/
|
||||
|
@@ -0,0 +1,249 @@
|
||||
package de.dhbwstuttgart.languageServerInterface;
|
||||
|
||||
|
||||
import de.dhbwstuttgart.bytecode.Codegen;
|
||||
import de.dhbwstuttgart.core.JavaTXCompiler;
|
||||
import de.dhbwstuttgart.environment.IByteArrayClassLoader;
|
||||
import de.dhbwstuttgart.languageServerInterface.model.LanguageServerTransferObject;
|
||||
import de.dhbwstuttgart.parser.scope.JavaClassName;
|
||||
import de.dhbwstuttgart.syntaxtree.SourceFile;
|
||||
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
|
||||
import de.dhbwstuttgart.target.generate.ASTToTargetAST;
|
||||
import de.dhbwstuttgart.target.generate.GenericsResult;
|
||||
import de.dhbwstuttgart.target.tree.TargetStructure;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Implementation of an Interface for the Language-Server to get the Resultset and abstract Syntax.
|
||||
*/
|
||||
public class LanguageServerInterface {
|
||||
|
||||
|
||||
public LanguageServerTransferObject getResultSetAndAbastractSyntax(String path, String resetNamesTo) throws IOException, URISyntaxException, ClassNotFoundException {
|
||||
NameGenerator.resetTo(resetNamesTo);
|
||||
return getResultSetAndAbstractSyntax(path);
|
||||
|
||||
}
|
||||
|
||||
public SourceFile getAst(String path, String resetNamesTo) throws IOException, URISyntaxException, ClassNotFoundException {
|
||||
NameGenerator.resetTo(resetNamesTo);
|
||||
return getAST(path);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* returns the ResultSets, GenericResultSet and the AST
|
||||
* You have to give the input as well as the path because of potential locks when the File is currently opened in an IDE.
|
||||
* Example: file:///c:/test/main.jav -> file:///c:/test/out/main.class
|
||||
*
|
||||
* @param pathAsString the URI of the File. See Example.
|
||||
* @throws IOException
|
||||
* @throws ClassNotFoundException
|
||||
* @throws URISyntaxException
|
||||
*/
|
||||
public LanguageServerTransferObject getResultSetAndAbstractSyntax(String pathAsString) throws IOException, ClassNotFoundException, URISyntaxException {
|
||||
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
|
||||
|
||||
var uri = new URI(pathAsString);
|
||||
var path = Path.of(uri);
|
||||
var file = path.toFile();
|
||||
Files.createDirectories(path.getParent().resolve("out"));
|
||||
var compiler = new JavaTXCompiler(List.of(file), List.of(path.getParent().toFile()), path.getParent().resolve("out").toFile());
|
||||
|
||||
var parsedSource = compiler.sourceFiles.get(file);
|
||||
var tiResults = compiler.typeInference(file);
|
||||
|
||||
Map<JavaClassName, byte[]> bytecode = compiler.generateBytecode(parsedSource, tiResults);
|
||||
Files.createDirectories(path.getParent().resolve("out"));
|
||||
compiler.writeClassFile(bytecode, path.getParent().resolve("out").toFile(), false);
|
||||
|
||||
return new LanguageServerTransferObject(tiResults, parsedSource, "", compiler.getGeneratedGenerics());
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the AST without calculating the result
|
||||
* You have to give the input as well as the path because of potential locks when the File is currently opened in an IDE.
|
||||
* Example: file:///c:/test/main.jav -> file:///c:/test/out/main.class
|
||||
*
|
||||
* @param path the URI of the File. See Example.
|
||||
* @throws IOException
|
||||
* @throws ClassNotFoundException
|
||||
* @throws URISyntaxException
|
||||
*/
|
||||
public SourceFile getAST(String path) throws IOException, ClassNotFoundException, URISyntaxException {
|
||||
|
||||
|
||||
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
|
||||
|
||||
|
||||
URI uri = new URI(path);
|
||||
ArrayList<String> pathWithoutName = new ArrayList<>(List.of(uri.getPath().split("/")));
|
||||
pathWithoutName.remove(List.of(uri.getPath().split("/")).size() - 1);
|
||||
String stringPathWithoutName = "";
|
||||
|
||||
for (String i : pathWithoutName) {
|
||||
stringPathWithoutName += "/" + i;
|
||||
}
|
||||
|
||||
try {
|
||||
FileUtils.cleanDirectory(new File(stringPathWithoutName + "/out"));
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
try {
|
||||
(new File(stringPathWithoutName + "/out")).mkdirs();
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
var test = getAST(uri.getPath().split("/")[uri.getPath().split("/").length - 1], new File(stringPathWithoutName).getPath());
|
||||
System.setOut(System.out);
|
||||
return test;
|
||||
}
|
||||
|
||||
private static void writeClassFile(String name, byte[] code, Path outputPath) throws IOException {
|
||||
Files.createDirectories(outputPath);
|
||||
Files.write(outputPath.resolve(name + ".class"), code);
|
||||
}
|
||||
|
||||
public static Map<String, ? extends Class<?>> generateClassFiles(IByteArrayClassLoader classLoader, Path path, Path outputPath, String... files) throws IOException, ClassNotFoundException {
|
||||
Files.createDirectories(outputPath);
|
||||
var filenames = Arrays.stream(files).map(filename -> Path.of(path.toString(), filename).toFile()).toList();
|
||||
var compiler = new JavaTXCompiler(filenames, List.of(path.toFile(), outputPath.toFile()), outputPath.toFile());
|
||||
|
||||
var result = new HashMap<String, Class<?>>();
|
||||
for (var file : filenames) {
|
||||
var resultSet = compiler.typeInference(file);
|
||||
|
||||
var sourceFile = compiler.sourceFiles.get(file);
|
||||
var converter = new ASTToTargetAST(compiler, resultSet, sourceFile, classLoader);
|
||||
var classes = compiler.sourceFiles.get(file).getClasses();
|
||||
|
||||
result.putAll(classes.stream().map(cli -> {
|
||||
try {
|
||||
return generateClass(converter.convert(cli), classLoader, converter, outputPath);
|
||||
} catch (IOException exception) {
|
||||
throw new RuntimeException(exception);
|
||||
}
|
||||
}).collect(Collectors.toMap(Class::getName, Function.identity())));
|
||||
|
||||
converter.generateFunNTypes();
|
||||
|
||||
for (var entry : converter.auxiliaries.entrySet()) {
|
||||
writeClassFile(entry.getKey(), entry.getValue(), outputPath);
|
||||
}
|
||||
}
|
||||
|
||||
for (var entry : compiler.loadedClasses.entrySet()) {
|
||||
var name = entry.getKey().toString();
|
||||
result.put(name, classLoader.loadClass(Path.of(entry.getValue().classFile().toURI())));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Class<?> generateClass(TargetStructure clazz, IByteArrayClassLoader classLoader, ASTToTargetAST converter, Path outputPath) throws IOException {
|
||||
Codegen codegen = new Codegen(clazz, converter.compiler, converter);
|
||||
var code = codegen.generate();
|
||||
writeClassFile(clazz.qualifiedName().getClassName(), code, outputPath);
|
||||
return classLoader.loadClass(code);
|
||||
}
|
||||
|
||||
public static Map<String, ? extends Class<?>> generateClassFiles(String filename, IByteArrayClassLoader classLoader, String filePath) throws IOException, ClassNotFoundException {
|
||||
var file = Path.of(filePath, filename).toFile();
|
||||
var compiler = new JavaTXCompiler(List.of(file), List.of(file.getParentFile()), Path.of(filePath + "/out").toFile());
|
||||
var resultSet = compiler.typeInference(file);
|
||||
|
||||
var sourceFile = compiler.sourceFiles.get(file);
|
||||
var converter = new ASTToTargetAST(compiler, resultSet, sourceFile, classLoader);
|
||||
var classes = compiler.sourceFiles.get(file).getClasses();
|
||||
|
||||
var result = classes.stream().map(cli -> {
|
||||
try {
|
||||
return generateClass(converter.convert(cli), classLoader, converter, Path.of(filePath + "/out/"));
|
||||
} catch (IOException exception) {
|
||||
throw new RuntimeException(exception);
|
||||
}
|
||||
}).collect(Collectors.toMap(Class::getName, Function.identity()));
|
||||
|
||||
converter.generateFunNTypes();
|
||||
|
||||
for (var entry : converter.auxiliaries.entrySet()) {
|
||||
writeClassFile(entry.getKey(), entry.getValue(), Path.of(filePath + "/out/"));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static SourceFile getAST(String filename, String filePath) throws IOException, ClassNotFoundException {
|
||||
var file = Path.of(filePath, filename).toFile();
|
||||
var compiler = new JavaTXCompiler(List.of(file), List.of(file.getParentFile()), Path.of(filePath + "/out").toFile());
|
||||
return compiler.sourceFiles.get(file);
|
||||
}
|
||||
|
||||
public static LanguageServerTransferObject getLanguageServerTransferObject(String filename, IByteArrayClassLoader classLoader, String filePath) throws IOException, ClassNotFoundException {
|
||||
var file = Path.of(filePath, filename).toFile();
|
||||
var compiler = new JavaTXCompiler(List.of(file), List.of(file.getParentFile()), Path.of(filePath + "/out").toFile());
|
||||
var resultSet = compiler.typeInference(file);
|
||||
|
||||
var sourceFile = compiler.sourceFiles.get(file);
|
||||
var converter = new ASTToTargetAST(compiler, resultSet, sourceFile, classLoader);
|
||||
compiler.generateBytecode();
|
||||
converter.generateFunNTypes();
|
||||
|
||||
var ta = converter.javaGenerics();
|
||||
var tb = converter.txGenerics();
|
||||
Map<SourceFile, List<GenericsResult>> generics = new HashMap<>();
|
||||
|
||||
ArrayList<GenericsResult> genericsResults = new ArrayList<>();
|
||||
genericsResults.addAll(ta);
|
||||
genericsResults.addAll(tb);
|
||||
generics.put(converter.compiler.sourceFiles.values().stream().findFirst().get(), ta);
|
||||
var test = new LanguageServerTransferObject(resultSet, converter.compiler.sourceFiles.values().stream().findFirst().get(), "", compiler.getGeneratedGenerics());
|
||||
return test;
|
||||
}
|
||||
|
||||
/**
|
||||
* generates Bytecode for the given Path of the File.
|
||||
* The Generated Bytecode can be found in the same place as the path, except the File lies in an /out/ Directory
|
||||
* Example: file:///c:/test/main.jav -> file:///c:/test/out/main.class
|
||||
*
|
||||
* @param uri the URI of the File. See Example.
|
||||
* @throws IOException
|
||||
* @throws ClassNotFoundException
|
||||
* @throws URISyntaxException
|
||||
*/
|
||||
public void generateBytecode(URI uri) throws IOException, ClassNotFoundException, URISyntaxException {
|
||||
|
||||
// System.setOut(new PrintStream(OutputStream.nullOutputStream()));
|
||||
//
|
||||
//
|
||||
// File inputDir = new File(uri.getPath());
|
||||
// File outFile = new File(uri.getPath() + "/out");
|
||||
// FileUtils.cleanDirectory(outFile);
|
||||
// String[] allowedEndings = {".jav"};
|
||||
// ArrayList<File> files = new ArrayList<>();
|
||||
//
|
||||
// try (Stream<Path> stream = Files.walk(Paths.get(inputDir.toURI()))) {
|
||||
// stream.filter(Files::isRegularFile)
|
||||
// .forEach(el -> files.add(el.toFile()));
|
||||
// }
|
||||
//
|
||||
//
|
||||
// List<String> javFiles = files.stream().filter(el -> el.getName().split("\\.").length >= 2 && el.getName().split("\\.")[el.getName().split("\\.").length - 1].contains("jav")).map(el -> el.getPath().replace(inputDir.getPath(), "").substring(1)).toList();
|
||||
// //TODO: Link between Files
|
||||
// generateClassFiles(new ByteArrayClassLoader(), Path.of(inputDir.toURI()), Path.of(outFile.toURI()), javFiles.toArray(new String[0]));
|
||||
// System.setOut(System.out);
|
||||
}
|
||||
}
|
@@ -0,0 +1,40 @@
|
||||
package de.dhbwstuttgart.languageServerInterface;
|
||||
|
||||
|
||||
|
||||
import de.dhbwstuttgart.languageServerInterface.model.CustomParserErrorHandler;
|
||||
import de.dhbwstuttgart.languageServerInterface.model.ParserError;
|
||||
import de.dhbwstuttgart.parser.antlr.Java17Lexer;
|
||||
import de.dhbwstuttgart.parser.antlr.Java17Parser;
|
||||
import de.dhbwstuttgart.parser.antlr.Java17ParserBaseListener;
|
||||
import org.antlr.v4.runtime.CharStream;
|
||||
import org.antlr.v4.runtime.CharStreams;
|
||||
import org.antlr.v4.runtime.CommonTokenStream;
|
||||
import org.antlr.v4.runtime.tree.ParseTree;
|
||||
import org.antlr.v4.runtime.tree.ParseTreeWalker;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ParserInterface {
|
||||
|
||||
public List<ParserError> getParseErrors(String input){
|
||||
|
||||
CustomParserErrorHandler errorListener = new CustomParserErrorHandler();
|
||||
CharStream charStream = CharStreams.fromString(input);
|
||||
|
||||
Java17Lexer lexer = new Java17Lexer(charStream);
|
||||
CommonTokenStream tokens = new CommonTokenStream(lexer);
|
||||
|
||||
Java17Parser parser = new Java17Parser(tokens);
|
||||
parser.removeErrorListeners();
|
||||
parser.addErrorListener(errorListener);
|
||||
|
||||
|
||||
ParseTree tree = parser.sourceFile();
|
||||
ParseTreeWalker walker = new ParseTreeWalker();
|
||||
Java17ParserBaseListener listener = new Java17ParserBaseListener();
|
||||
walker.walk(listener, tree);
|
||||
|
||||
return errorListener.getErrorMessages();
|
||||
}
|
||||
}
|
@@ -0,0 +1,47 @@
|
||||
package de.dhbwstuttgart.languageServerInterface.model;
|
||||
|
||||
|
||||
|
||||
import org.antlr.v4.runtime.*;
|
||||
import org.antlr.v4.runtime.atn.ATNConfigSet;
|
||||
import org.antlr.v4.runtime.dfa.DFA;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.BitSet;
|
||||
import java.util.List;
|
||||
|
||||
public class CustomParserErrorHandler implements ANTLRErrorListener {
|
||||
private final List<ParserError> errorMessages = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
|
||||
int endCharPosition = charPositionInLine;
|
||||
if (offendingSymbol instanceof Token) {
|
||||
Token offendingToken = (Token) offendingSymbol;
|
||||
endCharPosition = charPositionInLine + offendingToken.getText().length();
|
||||
}
|
||||
|
||||
ParserError parserError = new ParserError(line, charPositionInLine, endCharPosition, msg);
|
||||
errorMessages.add(parserError);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reportAmbiguity(Parser parser, DFA dfa, int i, int i1, boolean b, BitSet bitSet, ATNConfigSet atnConfigSet) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reportAttemptingFullContext(Parser parser, DFA dfa, int i, int i1, BitSet bitSet, ATNConfigSet atnConfigSet) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reportContextSensitivity(Parser parser, DFA dfa, int i, int i1, int i2, ATNConfigSet atnConfigSet) {
|
||||
|
||||
}
|
||||
|
||||
public List<ParserError> getErrorMessages() {
|
||||
return errorMessages;
|
||||
}
|
||||
}
|
@@ -0,0 +1,31 @@
|
||||
package de.dhbwstuttgart.languageServerInterface.model;
|
||||
|
||||
|
||||
|
||||
import de.dhbwstuttgart.syntaxtree.SourceFile;
|
||||
import de.dhbwstuttgart.target.generate.GenericsResult;
|
||||
import de.dhbwstuttgart.typeinference.result.ResultSet;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class LanguageServerTransferObject {
|
||||
List<ResultSet> resultSets;
|
||||
SourceFile Ast;
|
||||
String printedAst;
|
||||
Map<SourceFile, List<GenericsResult>> generatedGenerics = new HashMap<>();
|
||||
|
||||
|
||||
public LanguageServerTransferObject(List<ResultSet> resultSets, SourceFile Ast, String printedAst, Map<SourceFile, List<GenericsResult>> generatedGenerics) {
|
||||
this.resultSets = resultSets;
|
||||
this.Ast = Ast;
|
||||
this.printedAst = printedAst;
|
||||
this.generatedGenerics = generatedGenerics;
|
||||
}
|
||||
|
||||
public List<ResultSet> getResultSets() {return resultSets;}
|
||||
public SourceFile getAst() {return Ast;}
|
||||
public String getPrintedAst() {return printedAst;}
|
||||
public Map<SourceFile, List<GenericsResult>> getGeneratedGenerics() {return generatedGenerics;}
|
||||
}
|
@@ -0,0 +1,48 @@
|
||||
package de.dhbwstuttgart.languageServerInterface.model;
|
||||
|
||||
public class ParserError {
|
||||
|
||||
private int line;
|
||||
private int charPositionInLine;
|
||||
private int endCharPosition;
|
||||
String msg;
|
||||
|
||||
public ParserError(int line, int charPositionInLine, int endCharPosition, String msg) {
|
||||
this.line = line;
|
||||
this.charPositionInLine = charPositionInLine;
|
||||
this. endCharPosition = endCharPosition;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public int getEndCharPosition() {
|
||||
return endCharPosition;
|
||||
}
|
||||
|
||||
public void setEndCharPosition(int endCharPosition) {
|
||||
this.endCharPosition = endCharPosition;
|
||||
}
|
||||
|
||||
public void setCharPositionInLine(int charPositionInLine) {
|
||||
this.charPositionInLine = charPositionInLine;
|
||||
}
|
||||
|
||||
public void setLine(int line) {
|
||||
this.line = line;
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public int getCharPositionInLine() {
|
||||
return charPositionInLine;
|
||||
}
|
||||
|
||||
public int getLine() {
|
||||
return line;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
}
|
@@ -0,0 +1,20 @@
|
||||
package de.dhbwstuttgart.languageServerInterface.model;
|
||||
|
||||
|
||||
import com.google.common.reflect.TypeResolver;
|
||||
import de.dhbwstuttgart.typeinference.unify.UnifyResultEvent;
|
||||
import de.dhbwstuttgart.typeinference.unify.UnifyResultListener;
|
||||
|
||||
public class ResultSetListener implements UnifyResultListener {
|
||||
|
||||
TypeResolver typeResolver;
|
||||
|
||||
public ResultSetListener(TypeResolver typeResolver){
|
||||
this.typeResolver = typeResolver;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNewTypeResultFound(UnifyResultEvent evt) {
|
||||
|
||||
}
|
||||
}
|
@@ -41,7 +41,7 @@ public class JavaClassName {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt von einem Klassennamen nur den Namen der Klasse zur<EFBFBD>ck
|
||||
* Gibt von einem Klassennamen nur den Namen der Klasse zurück
|
||||
* Beispiel:
|
||||
* java.lang.Object wird zu: Object
|
||||
*/
|
||||
|
@@ -5,7 +5,7 @@ import de.dhbwstuttgart.exceptions.NotImplementedException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Speichert die Klassen f<EFBFBD>r einen bestimmten Projektscope
|
||||
* Speichert die Klassen für einen bestimmten Projektscope
|
||||
*/
|
||||
public class JavaClassRegistry{
|
||||
final Map<JavaClassName, Integer> existingClasses = new HashMap<>();
|
||||
|
@@ -13,6 +13,10 @@ public class NameGenerator {
|
||||
public static void reset() {
|
||||
strNextName = "A";
|
||||
}
|
||||
|
||||
public static void resetTo(String name) {
|
||||
strNextName = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Berechnet einen neuen, eindeutigen Namen f�r eine neue
|
||||
|
@@ -1,3 +1,4 @@
|
||||
|
||||
package de.dhbwstuttgart.target.generate;
|
||||
|
||||
import de.dhbwstuttgart.bytecode.FunNGenerator;
|
||||
|
@@ -1,6 +1,7 @@
|
||||
package de.dhbwstuttgart.typeinference.typeAlgo;
|
||||
|
||||
import de.dhbwstuttgart.exceptions.DebugException;
|
||||
import de.dhbwstuttgart.parser.NullToken;
|
||||
import de.dhbwstuttgart.parser.SourceLoc;
|
||||
import de.dhbwstuttgart.parser.antlr.Java17Parser;
|
||||
import de.dhbwstuttgart.parser.scope.JavaClassName;
|
||||
@@ -9,15 +10,18 @@ import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
|
||||
import de.dhbwstuttgart.syntaxtree.statement.Statement;
|
||||
import de.dhbwstuttgart.syntaxtree.type.RefType;
|
||||
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
|
||||
import de.dhbwstuttgart.target.tree.type.TargetRefType;
|
||||
import de.dhbwstuttgart.typeinference.assumptions.FieldAssumption;
|
||||
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation;
|
||||
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation;
|
||||
import de.dhbwstuttgart.typeinference.constraints.Constraint;
|
||||
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
|
||||
import de.dhbwstuttgart.typeinference.constraints.Pair;
|
||||
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
|
||||
import de.dhbwstuttgart.util.BiRelation;
|
||||
import org.antlr.v4.runtime.Token;
|
||||
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.*;
|
||||
|
||||
public class TYPE {
|
||||
@@ -87,12 +91,25 @@ public class TYPE {
|
||||
TypeInferenceBlockInformation blockInfo = new TypeInferenceBlockInformation(info.getAvailableClasses(), currentClass, m);
|
||||
TYPEStmt methodScope = new TYPEStmt(blockInfo);
|
||||
ConstraintSet constraintSet = new ConstraintSet();
|
||||
m.getParameterList().getFormalparalist().forEach(el -> {
|
||||
if(el instanceof RecordPattern){
|
||||
constraintSet.addAll(addRecursiveParameterConstraints((RecordPattern) el, blockInfo));
|
||||
|
||||
}
|
||||
});
|
||||
if (m.name.equals("main") && Modifier.isStatic(m.modifier) && m.getParameterList().getFormalparalist().size() == 1) {
|
||||
// Add constraint for main method
|
||||
var firstParam = m.getParameterList().getParameterAt(0);
|
||||
|
||||
constraintSet.addUndConstraint(new Pair(firstParam.getType(),
|
||||
new RefType(new JavaClassName("java.util.List"),
|
||||
List.of(new RefType(new JavaClassName("java.lang.String"), new NullToken())),
|
||||
new NullToken()),
|
||||
PairOperator.EQUALSDOT));
|
||||
} else {
|
||||
m.getParameterList().getFormalparalist().forEach(el -> {
|
||||
if (el instanceof RecordPattern rp){
|
||||
constraintSet.addAll(addRecursiveParameterConstraints(rp, blockInfo));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
m.block.accept(methodScope);
|
||||
constraintSet.addAll(methodScope.getConstraints());
|
||||
return constraintSet;
|
||||
|
@@ -1196,6 +1196,15 @@ public class TestComplete {
|
||||
assertEquals(20, m.invoke(instance));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMain() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "Main.jav");
|
||||
var clazz = classFiles.get("Main");
|
||||
var m = clazz.getDeclaredMethod("main", List.class);
|
||||
m.setAccessible(true);
|
||||
m.invoke(null, List.of("foo", "bar", "baz"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBug122() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "Bug122.jav");
|
||||
@@ -1459,4 +1468,12 @@ public class TestComplete {
|
||||
var m = clazz.getDeclaredMethod("test");
|
||||
assertEquals(true, m.invoke(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBug373() throws Exception {
|
||||
var classFiles = generateClassFiles(createClassLoader(), "Bug373.jav");
|
||||
var clazz = classFiles.get("Bug373");
|
||||
var m = clazz.getDeclaredMethod("main");
|
||||
m.invoke(null);
|
||||
}
|
||||
}
|
||||
|
@@ -0,0 +1,51 @@
|
||||
package languageServerInterfaceTest;
|
||||
|
||||
import de.dhbwstuttgart.core.ConsoleInterface;
|
||||
import de.dhbwstuttgart.core.JavaTXCompiler;
|
||||
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
|
||||
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import de.dhbwstuttgart.languageServerInterface.LanguageServerInterface;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class LangaugeServerInterfaceTest {
|
||||
@Test
|
||||
@Ignore
|
||||
public void consoleInterfaceTest() throws IOException, ClassNotFoundException, URISyntaxException {
|
||||
|
||||
|
||||
LanguageServerInterface languageServerInterface = new LanguageServerInterface();
|
||||
var resp = languageServerInterface.getResultSetAndAbstractSyntax("/home/ruben/code/JavaCompilerCore/src/test/java/languageServerInterfaceTest/test.jav");
|
||||
|
||||
System.out.println("\n-----------------------------------------\n");
|
||||
System.out.println(ASTPrinter.print(resp.getAst()));
|
||||
System.out.println("\n-----------------------------------------\n");
|
||||
|
||||
LanguageServerInterface languageServerInterface2 = new LanguageServerInterface();
|
||||
var ast = languageServerInterface2.getAst("/home/ruben/code/JavaCompilerCore/src/test/java/languageServerInterfaceTest/test.jav", "N");
|
||||
|
||||
System.out.println("\n-----------------------------------------\n");
|
||||
System.out.println(ASTPrinter.print(ast));
|
||||
System.out.println("\n-----------------------------------------\n");
|
||||
System.out.println("");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void testBytecodeGen() throws IOException, ClassNotFoundException, URISyntaxException {
|
||||
|
||||
//TODO: Ordner und Datei löschen wenn sie bereits existieren
|
||||
LanguageServerInterface languageServerInterface = new LanguageServerInterface();
|
||||
languageServerInterface.generateBytecode(new URI("c%3A/Users/ruben/Neuer%20Ordner%20%282%29/LSP-Vortrag/images/"));
|
||||
}
|
||||
}
|
5
src/test/java/languageServerInterfaceTest/test.jav
Normal file
5
src/test/java/languageServerInterfaceTest/test.jav
Normal file
@@ -0,0 +1,5 @@
|
||||
public class t{
|
||||
public mofus(){
|
||||
return 1;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user