2 Commits

Author SHA1 Message Date
Ruben
558fcb5ebb feat: initially check syntax when opening document 2025-09-15 13:50:20 +02:00
Ruben
1e4541b705 feat: update 2025-09-11 12:53:41 +02:00
5 changed files with 69 additions and 100 deletions

View File

@@ -109,6 +109,10 @@ public class JavaTXTextDocumentService implements org.eclipse.lsp4j.services.Tex
public void didOpen(DidOpenTextDocumentParams params) {
cacheService.reset();
typeResolver.reset();
List<Diagnostic> syntaxErrors = parserService.getDiagnosticsOfErrors(params.getTextDocument().getText(), params.getTextDocument().getUri());
if (!syntaxErrors.isEmpty()) {
clientService.publishDiagnostics(params.getTextDocument().getUri(), syntaxErrors);
}
client.refreshDiagnostics();
client.refreshInlayHints();
textDocuments.put(params.getTextDocument().getUri(), params.getTextDocument().getText());

View File

@@ -3,11 +3,11 @@ package de.dhbw.handler;
import com.google.common.base.Stopwatch;
import de.dhbw.helper.ConversionHelper;
import de.dhbw.helper.TypeResolver;
import de.dhbw.model.DiagnosticsAndTypehints;
import de.dhbw.model.DocumentChanges;
import de.dhbw.model.LSPVariable;
import de.dhbw.model.LineCharPosition;
import de.dhbw.model.*;
import de.dhbw.service.*;
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.typeinference.result.PairTPHequalRefTypeOrWildcardType;
import org.eclipse.lsp4j.*;
import java.io.BufferedWriter;
@@ -40,27 +40,32 @@ public class ChangeHandler {
public static String findAddedWord(String str1, String str2) {
String[] words1 = str1.split("\\s+");
String[] words2 = str2.split("\\s+");
int i = 0, j = 0;
while (i < words1.length && j < words2.length) {
if (words1[i].equals(words2[j])) {
i++;
j++;
} else {
return words2[j]; // Unterschied gefunden
}
// Suche den ersten Unterschied
while (i < str1.length() && j < str2.length() && str1.charAt(i) == str2.charAt(j)) {
i++;
j++;
}
// Falls das neue Wort am Ende steht
if (j < words2.length) {
return words2[j];
// Falls alles gleich ist, gibt es nichts Neues
if (i == str1.length() && j == str2.length()) {
return null;
}
return null; // Kein Unterschied gefunden
// Suche ab Ende rückwärts, um den gemeinsamen Suffix zu finden
int iEnd = str1.length() - 1;
int jEnd = str2.length() - 1;
while (iEnd >= i && jEnd >= j && str1.charAt(iEnd) == str2.charAt(jEnd)) {
iEnd--;
jEnd--;
}
// Der Unterschied liegt nun zwischen j und jEnd in str2
return str2.substring(j, jEnd + 1);
}
public void didChange(DidChangeTextDocumentParams params) {
String currentText = textDocumentService.getFileOfUri(params.getTextDocument().getUri());
@@ -70,6 +75,7 @@ public class ChangeHandler {
List<Diagnostic> syntaxErrors = parserService.getDiagnosticsOfErrors(summedUp.get(), params.getTextDocument().getUri());
if (!syntaxErrors.isEmpty()) {
clientService.publishDiagnostics(params.getTextDocument().getUri(), syntaxErrors);
}
@@ -77,41 +83,27 @@ public class ChangeHandler {
if (syntaxErrors.isEmpty()) {
DocumentChanges documentChanges = textDocumentService.calculateDifference(currentText, summedUp.get());
HashMap<LineCharPosition, String> preciseChanges = documentChanges.getPreciseChanges();
HashMap<Integer, List<String>> textChanges;
String type = findAddedWord(currentText, summedUp.get());
logService.log("ADDED TYPE IS: " + type);
//Have to check of old saved Input because the result set and Inlay Hints will be updated according to the old AST which contains the old Positions
if (cacheService.getLastSavedFiles().containsKey(params.getTextDocument().getUri())) {
DocumentChanges changesFromOldSave = textDocumentService.calculateDifference(cacheService.getLastSavedFiles().get(params.getTextDocument().getUri()), summedUp.get());
;
textChanges = changesFromOldSave.getTextChanges();
preciseChanges = changesFromOldSave.getPreciseChanges();
logService.log(textChanges.values().stream().map(el -> String.join(", ", el)).collect(Collectors.joining("\n")));
} else {
textChanges = documentChanges.getTextChanges();
}
String input = summedUp.get();
logService.log("Variables are: " + cacheService.getVariables().size());
boolean shouldCalculate = false;
AtomicBoolean needToCalculate = new AtomicBoolean(false);
cacheService.getVariables().forEach(
el -> el.getPossibleTypes().forEach(pos -> needToCalculate.set(needToCalculate.get() || pos.getType().equalsIgnoreCase(type)))
);
logService.log("Type is here: " + type);
for (LSPVariable variable : cacheService.getVariables()) {
for (Type variableType : variable.getPossibleTypes()) {
logService.log(variableType.getType() + " <> "+ type.replaceAll(" ", "") + ": " + type.replaceAll(" ", "").contains(variableType.getType().replaceAll(" ", "")));
shouldCalculate = shouldCalculate || type.replaceAll(" ", "").contains(variableType.getType().replaceAll(" ", ""));
if (shouldCalculate) {
break;
}
}
}
logService.log("Should Calculate is: " + shouldCalculate);
if (false) {
typeResolver.reduceCurrent(preciseChanges, cacheService.getVariables());
try {
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File tempFile = File.createTempFile("newText", ".tmp", tempDir);
@@ -126,33 +118,20 @@ public class ChangeHandler {
logService.log(e.getMessage());
}
var sWatch = Stopwatch.createUnstarted();
sWatch.start();
try {
String currentInput = textDocumentService.getFileOfUri(params.getTextDocument().getUri());
if (currentInput == null) {
logService.log("[didChange] Input of Text Document is null in TextDocument-Hashmap.", MessageType.Error);
}
ArrayList<LSPVariable> typesOfMethodAndParameters = typeResolver.infereChangeInput();
DiagnosticsAndTypehints diagnosticsAndTypehints = conversionHelper.variablesToDiagnosticsAndTypehints(typesOfMethodAndParameters, params.getTextDocument().getUri());
List<InlayHint> typeHint = diagnosticsAndTypehints.getInlayHints();
List<Diagnostic> diagnostics = diagnosticsAndTypehints.getDiagnostics();
cacheService.updateGlobalMaps(diagnostics, typeHint, params.getTextDocument().getUri());
} catch (Exception e) {
logService.log("[didChange] Error trying to get Inlay-Hints and Diagnostics for Client: " + e.getMessage(), MessageType.Error);
for (var stackTrace : e.getStackTrace()) {
logService.log(stackTrace.toString());
}
@@ -165,54 +144,24 @@ public class ChangeHandler {
logService.log("[didChange] Finished Calculating in [" + sWatch.elapsed().toSeconds() + "s]", MessageType.Info);
}
//updatePositions(params, offsetPerLine);
cacheService.getGlobalInlayHintMap().put(params.getTextDocument().getUri(), cacheService.getGlobalInlayHintMap().get(params.getTextDocument().getUri()).stream().filter(el -> {
//TODO: Hier das Label aufspalten an | weil die Typehints immer mit und getrennt sind und so jeder Typhint für sich durchlaufen werden kann.
logService.log(el.getLabel().getLeft().replaceAll(" ", "") + "<>" + String.join(",", textChanges.get(el.getPosition().getLine())) + ": " + (!textChanges.get(el.getPosition().getLine()).contains(el.getLabel().getLeft().replaceAll(" ", "")) ? "true" : "false"), MessageType.Info);
return !textChanges.get(el.getPosition().getLine()).contains(el.getLabel().getLeft().replaceAll(" ", ""));
}).toList());
cacheService.getGlobalDiagnosticsMap().put(params.getTextDocument().getUri(), cacheService.getGlobalDiagnosticsMap().get(params.getTextDocument().getUri()).stream().filter(el -> {
logService.log(el.getMessage().replaceAll(" ", "") + "<>" + String.join(",", textChanges.get(el.getRange().getStart().getLine())) + ": " + (!textChanges.get(el.getRange().getStart().getLine()).contains(el.getMessage().replaceAll(" ", "")) ? "true" : "false"), MessageType.Info);
return !textChanges.get(el.getRange().getStart().getLine()).contains(el.getMessage().replaceAll(" ", ""));
}).toList());
List<Diagnostic> typeDiagnostics = cacheService.getGlobalDiagnosticsMap().get(params.getTextDocument().getUri());
List<Diagnostic> parserErrors = parserService.getDiagnosticsOfErrors(input, params.getTextDocument().getUri());
ArrayList<Diagnostic> allDiagnostics = new ArrayList<>(typeDiagnostics);
allDiagnostics.addAll(parserErrors);
clientService.publishDiagnostics(params.getTextDocument().getUri(), allDiagnostics);
} else {
logService.log("Calculating again.");
var sWatch = Stopwatch.createUnstarted();
sWatch.start();
try {
String fileInput = input;
logService.log("Input ist:");
logService.log(fileInput);
// cacheService.getLastSavedFiles().put(didSaveTextDocumentParams.getTextDocument().getUri(), fileInput);
// typeResolver.getCompilerInput(didSaveTextDocumentParams.getTextDocument().getUri(), fileInput);
try {
File tempDir2 = new File(System.getProperty("java.io.tmpdir"));
File tempFile2 = File.createTempFile("newText", ".tmp", tempDir2);
FileWriter fileWriter = new FileWriter(tempFile2, true);
BufferedWriter bw = new BufferedWriter(fileWriter);
bw.write(fileInput);
bw.write(input);
bw.close();
if (fileInput == null) {
logService.log("[didSave] Input of Text Document is null in TextDocument-Hashmap.", MessageType.Error);
}
ArrayList<LSPVariable> variables = typeResolver.infereInput(tempFile2.toURI().toString(), fileInput, false);
ArrayList<LSPVariable> variables = typeResolver.infereInput(tempFile2.toURI().toString(), input, false);
cacheService.setVariables(variables);
DiagnosticsAndTypehints diagnosticsAndTypehints = conversionHelper.variablesToDiagnosticsAndTypehintsWithInput(variables, input);
@@ -223,7 +172,7 @@ public class ChangeHandler {
cacheService.updateGlobalMaps(diagnostics, typeHint, params.getTextDocument().getUri());
List<Diagnostic> allDiagnostics = new ArrayList<>(diagnostics);
allDiagnostics.addAll(parserService.getDiagnosticsOfErrors(fileInput, params.getTextDocument().getUri()));
allDiagnostics.addAll(parserService.getDiagnosticsOfErrors(input, params.getTextDocument().getUri()));
clientService.publishDiagnostics(params.getTextDocument().getUri(), allDiagnostics);
@@ -240,7 +189,6 @@ public class ChangeHandler {
} finally {
sWatch.stop();
logService.log("[didSave] Finished Calculating in [" + sWatch.elapsed().toSeconds() + "s]", MessageType.Info);
}
} catch (Exception e) {

View File

@@ -74,7 +74,6 @@ public class SaveHandler {
cacheService.updateGlobalMaps(diagnostics, typeHint, didSaveTextDocumentParams.getTextDocument().getUri());
List<Diagnostic> allDiagnostics = new ArrayList<>(diagnostics);
allDiagnostics.addAll(parserService.getDiagnosticsOfErrors(fileInput, didSaveTextDocumentParams.getTextDocument().getUri()));
clientService.publishDiagnostics(didSaveTextDocumentParams.getTextDocument().getUri(), allDiagnostics);

View File

@@ -115,12 +115,21 @@ public class TypeResolver {
}
}
inserts = insertsOnLines;
ArrayList<LSPVariable> variables = new ArrayList<>(insertsOnLines.entrySet().stream().map(el -> new LSPVariable("test", new ArrayList<>(el.getValue().stream().map(typeinsert -> new Type(typeinsert.getInsertString(), typeinsert.point.isGenericClassInsertPoint())).toList()), el.getValue().getFirst().point.point.getLine(), el.getValue().getFirst().point.point.getCharPositionInLine(), el.getValue().get(0).point.point.getStopIndex(), el.getValue().get(0).getResultPair().getLeft())).toList());
for (var variable : variables) {
Set<Type> set = new HashSet<>(variable.getPossibleTypes().stream().map(el -> new Type(el.getType().replaceAll(" ", ""), el.isGeneric())).toList());
variable.getPossibleTypes().clear();
variable.getPossibleTypes().addAll(set);
HashMap<String, Type> uniqueType = new HashMap<>();
for (var type : variable.getPossibleTypes()) {
if (!uniqueType.containsKey(type.getType().replaceAll(" ", ""))) {
uniqueType.put(type.getType(), type);
}
}
variable.setPossibleTypes(new ArrayList<>(uniqueType.values()));
logger.info(variable.getLine() + ":" + variable.getCharPosition());
for (Type t : variable.getPossibleTypes()) {
logger.info(t.getType());
@@ -139,7 +148,6 @@ public class TypeResolver {
logger.info("Path is for calculation: " + path.toString());
var file = path.toFile();
NameGenerator.resetTo("A");
Files.createDirectories(path.getParent().resolve("out"));
var compiler = new JavaTXCompiler(List.of(file), List.of(path.getParent().toFile()), path.getParent().resolve("out").toFile());
@@ -180,9 +188,20 @@ public class TypeResolver {
inserts = insertsOnLines;
insertsOnLines.forEach((key, value) -> value.forEach(type -> logger.info(type.insert(input))));
logger.info("TYPES ARE:");
insertsOnLines.forEach((key, value) -> value.forEach(type -> logger.info(type.point.getInsertString())));
ArrayList<LSPVariable> variables = new ArrayList<>();
ArrayList<LSPVariable> variables = new ArrayList<>(insertsOnLines.entrySet().stream().map(el -> new LSPVariable("test", new ArrayList<>(el.getValue().stream().map(typeinsert -> new Type(typeinsert.getInsertString(), typeinsert.point.isGenericClassInsertPoint())).toList()), el.getValue().getFirst().point.point.getLine(), el.getValue().getFirst().point.point.getCharPositionInLine(), el.getValue().get(0).point.point.getStopIndex(), el.getValue().get(0).getResultPair().getLeft())).toList());
for(var entrySet : insertsOnLines.entrySet()){
ArrayList<Type> typesOfVariable = new ArrayList<>();
for(PlaceholderVariable typeinsert : entrySet.getValue()){
typesOfVariable.add(new Type(typeinsert.getInsertString(), typeinsert.point.isGenericClassInsertPoint()));
}
variables.add(new LSPVariable("test",typesOfVariable , entrySet.getValue().getFirst().point.point.getLine(), entrySet.getValue().getFirst().point.point.getCharPositionInLine(), entrySet.getValue().get(0).point.point.getStopIndex(), entrySet.getValue().get(0).getResultPair().getLeft()));
}
for (var variable : variables) {

View File

@@ -48,7 +48,6 @@ public class CacheService {
typeResolver = new TypeResolver();
fileRoot = null;
singleFileOpened = false;
variables = new ArrayList<>();
typeInserts = null;
}