2 Commits

Author SHA1 Message Date
Ruben
c8fa373972 refactor: rename package 2025-07-07 16:28:17 +02:00
Ruben
f1f0fb8bf3 refactor: Handle Save with Services 2025-07-07 16:27:31 +02:00
10 changed files with 448 additions and 76 deletions

View File

@@ -20,6 +20,11 @@
<artifactId>antlr4</artifactId> <artifactId>antlr4</artifactId>
<version>4.11.1</version> <version>4.11.1</version>
</dependency> </dependency>
<dependency>
<groupId>io.github.java-diff-utils</groupId>
<artifactId>java-diff-utils</artifactId>
<version>4.12</version>
</dependency>
<dependency> <dependency>
<groupId>log4j</groupId> <groupId>log4j</groupId>
<artifactId>log4j</artifactId> <artifactId>log4j</artifactId>
@@ -75,6 +80,12 @@
<version>0.1</version> <version>0.1</version>
</dependency> </dependency>
</dependencies> </dependencies>
<properties>
<!-- Setzt Java 21 als globale Version -->
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.release>21</maven.compiler.release>
</properties>
<build> <build>
<plugins> <plugins>
@@ -96,6 +107,7 @@
<configuration> <configuration>
<source>21</source> <source>21</source>
<target>21</target> <target>21</target>
<release>21</release>
</configuration> </configuration>
</plugin> </plugin>

View File

@@ -1,35 +1,32 @@
package de.dhbw; package de.dhbw;
import com.google.common.base.Stopwatch; import com.google.common.base.Stopwatch;
import de.dhbw.service.CacheService;
import de.dhbw.service.ClientService;
import de.dhbw.service.LogService;
import de.dhbw.handler.SaveHandler;
import de.dhbw.helper.CodeSnippetOptions; import de.dhbw.helper.CodeSnippetOptions;
import de.dhbw.helper.ConversionHelper;
import de.dhbw.helper.TextHelper; import de.dhbw.helper.TextHelper;
import de.dhbw.helper.TypeResolver; import de.dhbw.helper.TypeResolver;
import de.dhbw.model.LSPVariable; import de.dhbw.model.LSPVariable;
import de.dhbw.model.LineCharPosition; import de.dhbw.model.LineCharPosition;
import de.dhbw.model.SnippetWithName; import de.dhbw.model.SnippetWithName;
import de.dhbw.model.Type; import de.dhbw.model.Type;
import de.dhbwstuttgart.languageServerInterface.LanguageServerInterface;
import de.dhbwstuttgart.languageServerInterface.ParserInterface; import de.dhbwstuttgart.languageServerInterface.ParserInterface;
import de.dhbwstuttgart.languageServerInterface.model.ParserError; import de.dhbwstuttgart.languageServerInterface.model.ParserError;
import org.apache.log4j.LogManager; import org.apache.log4j.LogManager;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.eclipse.lsp4j.*; import org.eclipse.lsp4j.*;
import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.eclipse.lsp4j.jsonrpc.messages.Message;
import org.eclipse.lsp4j.services.LanguageClient; import org.eclipse.lsp4j.services.LanguageClient;
import org.eclipse.lsp4j.services.TextDocumentService; import org.eclipse.lsp4j.services.TextDocumentService;
import java.io.File;
import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** /**
* Handles Actions in Documents, such as Autocompletion, Change-Events and Syntax-Checks * Handles Actions in Documents, such as Autocompletion, Change-Events and Syntax-Checks
@@ -37,6 +34,15 @@ import java.util.stream.Stream;
public class JavaTXTextDocumentService implements org.eclipse.lsp4j.services.TextDocumentService { public class JavaTXTextDocumentService implements org.eclipse.lsp4j.services.TextDocumentService {
private final SaveHandler saveHandler;
private final TypeResolver typeResolver;
private final de.dhbw.service.TextDocumentService textDocumentService;
private final LogService logService;
private final ClientService clientService;
private final CacheService cacheService;
private final ConversionHelper conversionHelper;
TextHelper textHelper = new TextHelper();
private static final Logger logger = LogManager.getLogger(JavaTXTextDocumentService.class); private static final Logger logger = LogManager.getLogger(JavaTXTextDocumentService.class);
LanguageClient client; LanguageClient client;
HashMap<String, List<InlayHint>> globalInlayHintMap = new HashMap<>(); HashMap<String, List<InlayHint>> globalInlayHintMap = new HashMap<>();
@@ -44,15 +50,24 @@ public class JavaTXTextDocumentService implements org.eclipse.lsp4j.services.Tex
HashMap<String, List<Diagnostic>> globalDiagnosticsMap = new HashMap<>(); HashMap<String, List<Diagnostic>> globalDiagnosticsMap = new HashMap<>();
HashMap<String, String> textDocuments = new HashMap<>(); HashMap<String, String> textDocuments = new HashMap<>();
CodeSnippetOptions codeSnippetOptions = new CodeSnippetOptions(); CodeSnippetOptions codeSnippetOptions = new CodeSnippetOptions();
TextHelper textHelper = new TextHelper();
Boolean dontShowHints = false; Boolean dontShowHints = false;
TypeResolver typeResolver = new TypeResolver();
Path fileRoot = null; Path fileRoot = null;
Boolean singleFileOpened = false; Boolean singleFileOpened = false;
List<LSPVariable> variables = new ArrayList<>(); List<LSPVariable> variables = new ArrayList<>();
public JavaTXTextDocumentService() {
this.cacheService = new CacheService();
this.clientService = new ClientService(null);
this.typeResolver = new TypeResolver();
this.textDocumentService = new de.dhbw.service.TextDocumentService();
this.conversionHelper = new ConversionHelper(textHelper, textDocumentService);
this.logService = new LogService(clientService);
this.saveHandler = new SaveHandler(typeResolver, textDocumentService, logService, cacheService, conversionHelper, clientService);
}
public void setClient(LanguageClient client) { public void setClient(LanguageClient client) {
this.client = client; this.client = client;
clientService.setClient(client);
} }
public void setFileRoot(List<WorkspaceFolder> root) { public void setFileRoot(List<WorkspaceFolder> root) {
@@ -98,6 +113,7 @@ public class JavaTXTextDocumentService implements org.eclipse.lsp4j.services.Tex
@Override @Override
public void didOpen(DidOpenTextDocumentParams params) { public void didOpen(DidOpenTextDocumentParams params) {
textDocuments.put(params.getTextDocument().getUri(), params.getTextDocument().getText()); textDocuments.put(params.getTextDocument().getUri(), params.getTextDocument().getText());
textDocumentService.saveFileWithUri(params.getTextDocument().getUri(), params.getTextDocument().getText());
} }
@@ -204,6 +220,7 @@ public class JavaTXTextDocumentService implements org.eclipse.lsp4j.services.Tex
AtomicReference<String> summedUp = new AtomicReference<>(""); AtomicReference<String> summedUp = new AtomicReference<>("");
params.getContentChanges().forEach(el -> summedUp.set(summedUp.get() + el.getText())); params.getContentChanges().forEach(el -> summedUp.set(summedUp.get() + el.getText()));
textDocuments.put(params.getTextDocument().getUri(), summedUp.get()); textDocuments.put(params.getTextDocument().getUri(), summedUp.get());
textDocumentService.saveFileWithUri(params.getTextDocument().getUri(), summedUp.get());
String input = summedUp.get(); String input = summedUp.get();
@@ -420,74 +437,11 @@ public class JavaTXTextDocumentService implements org.eclipse.lsp4j.services.Tex
@Override @Override
public void didSave(DidSaveTextDocumentParams didSaveTextDocumentParams) { public void didSave(DidSaveTextDocumentParams didSaveTextDocumentParams) {
log("[didSave] Client triggered didSave-Event.", MessageType.Info); logService.log("[didSave] Client triggered didSave-Event.");
startLoading("compile-task", "Inferring types...", client); startLoading("compile-task", "Inferring types...", client);
saveHandler.handleSave(didSaveTextDocumentParams);
if (!currentlyCalculating) {
currentlyCalculating = true;
ArrayList<Diagnostic> diagnostics = new ArrayList<>();
var sWatch = Stopwatch.createUnstarted();
sWatch.start();
try {
typeResolver.getCompilerInput(didSaveTextDocumentParams.getTextDocument().getUri(), textDocuments.get(didSaveTextDocumentParams.getTextDocument().getUri()));
if (textDocuments.get(didSaveTextDocumentParams.getTextDocument().getUri()) == null) {
log("[didSave] Input of Text Document is null in TextDocument-Hashmap.", MessageType.Error);
}
ArrayList<LSPVariable> typesOfMethodAndParameters = typeResolver.infereInput(textDocuments.get(didSaveTextDocumentParams.getTextDocument().getUri()), didSaveTextDocumentParams.getTextDocument().getUri());
variables = typesOfMethodAndParameters;
List<InlayHint> typeHint = new ArrayList<>();
for (var variable : typesOfMethodAndParameters) {
InlayHint inlayHint = getInlayHint(variable);
typeHint.add(inlayHint);
//Diagnostics of Types
for (var type : variable.getPossibleTypes()) {
Diagnostic diagnostic = getDiagnostic(variable, didSaveTextDocumentParams.getTextDocument().getUri(), type);
diagnostics.add(diagnostic);
}
}
updateGlobalMaps(diagnostics, typeHint, didSaveTextDocumentParams.getTextDocument().getUri());
PublishDiagnosticsParams diagnosticsParams = new PublishDiagnosticsParams(didSaveTextDocumentParams.getTextDocument().getUri(), diagnostics);
client.publishDiagnostics(diagnosticsParams);
} catch (Exception e) {
log("[didSave] Error trying to get Inlay-Hints and Diagnostics for Client: " + e.getMessage(), MessageType.Error);
client.showMessage(new MessageParams(MessageType.Error, e.getMessage()));
updateGlobalMaps(new ArrayList<>(), new ArrayList<>(), didSaveTextDocumentParams.getTextDocument().getUri());
} finally {
currentlyCalculating = false;
sWatch.stop();
log("[didSave] Finished Calculating in [" + sWatch.elapsed().toSeconds() + "s]", MessageType.Info);
}
}
stopLoading("compile-task", "Types successfully inferred", client); stopLoading("compile-task", "Types successfully inferred", client);
clientService.updateClient(client);
dontShowHints = false;
updateClient(client);
ArrayList<File> files = new ArrayList<>();
if (fileRoot != null) {
try (Stream<Path> stream = Files.walk(Paths.get(fileRoot.toUri()))) {
stream.filter(Files::isRegularFile)
.forEach(el -> files.add(el.toFile()));
} catch (IOException e) {
}
}
} }
@Override @Override

View File

@@ -0,0 +1,55 @@
package de.dhbw.handler;
import com.github.difflib.DiffUtils;
import com.github.difflib.patch.AbstractDelta;
import com.github.difflib.patch.DeltaType;
import com.github.difflib.patch.Patch;
import org.eclipse.lsp4j.InlayHint;
import org.eclipse.lsp4j.Position;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class InlayHintAdjusterDiffUtils {
public static List<InlayHint> adjustInlayHintsByLineDiff(String oldText, String newText, List<InlayHint> oldHints) {
List<String> oldLines = Arrays.asList(oldText.split("\n", -1));
List<String> newLines = Arrays.asList(newText.split("\n", -1));
Patch<String> patch = DiffUtils.diff(oldLines, newLines);
List<AbstractDelta<String>> deltas = patch.getDeltas();
List<InlayHint> adjusted = new ArrayList<>();
for (InlayHint hint : oldHints) {
int oldLine = hint.getPosition().getLine();
int lineShift = calculateLineShift(deltas, oldLine);
int newLine = Math.max(0, oldLine + lineShift);
adjusted.add(new InlayHint(new Position(newLine, hint.getPosition().getCharacter()), hint.getLabel()));
}
return adjusted;
}
private static int calculateLineShift(List<AbstractDelta<String>> deltas, int oldLine) {
int shift = 0;
for (AbstractDelta<String> delta : deltas) {
int deltaLine = delta.getSource().getPosition();
int linesRemoved = delta.getSource().size();
int linesAdded = delta.getTarget().size();
if (oldLine > deltaLine) {
if (delta.getType() == DeltaType.INSERT) {
shift += linesAdded;
} else if (delta.getType() == DeltaType.DELETE) {
shift -= linesRemoved;
} else if (delta.getType() == DeltaType.CHANGE) {
shift += linesAdded - linesRemoved;
}
}
}
return shift;
}
}

View File

@@ -0,0 +1,79 @@
package de.dhbw.handler;
import com.google.common.base.Stopwatch;
import de.dhbw.service.CacheService;
import de.dhbw.service.ClientService;
import de.dhbw.service.LogService;
import de.dhbw.service.TextDocumentService;
import de.dhbw.helper.ConversionHelper;
import de.dhbw.helper.TypeResolver;
import de.dhbw.model.LSPVariable;
import org.eclipse.lsp4j.*;
import java.util.ArrayList;
import java.util.List;
public class SaveHandler {
private final TypeResolver typeResolver;
private final TextDocumentService textDocumentService;
private final LogService logService;
private final CacheService cacheService;
private final ConversionHelper conversionHelper;
private final ClientService clientService;
public SaveHandler(TypeResolver typeResolver, TextDocumentService textDocumentService, LogService logService, CacheService cacheService, ConversionHelper conversionHelper, ClientService clientService){
this.typeResolver = typeResolver;
this.textDocumentService = textDocumentService;
this.logService = logService;
this.cacheService = cacheService;
this.conversionHelper = conversionHelper;
this.clientService = clientService;
}
public void handleSave(DidSaveTextDocumentParams didSaveTextDocumentParams){
ArrayList<Diagnostic> diagnostics = new ArrayList<>();
var sWatch = Stopwatch.createUnstarted();
sWatch.start();
try {
String fileInput = textDocumentService.getFileOfUri(didSaveTextDocumentParams.getTextDocument().getUri());
typeResolver.getCompilerInput(didSaveTextDocumentParams.getTextDocument().getUri(), fileInput);
if (fileInput == null) {
logService.log("[didSave] Input of Text Document is null in TextDocument-Hashmap.", MessageType.Error);
}
ArrayList<LSPVariable> variables = typeResolver.infereInput(fileInput, didSaveTextDocumentParams.getTextDocument().getUri());
cacheService.setVariables(variables);
List<InlayHint> typeHint = new ArrayList<>();
for (var variable : variables) {
InlayHint inlayHint = conversionHelper.getInlayHint(variable);
typeHint.add(inlayHint);
for (var type : variable.getPossibleTypes()) {
Diagnostic diagnostic = conversionHelper.getDiagnostic(variable, didSaveTextDocumentParams.getTextDocument().getUri(), type);
diagnostics.add(diagnostic);
}
}
cacheService.updateGlobalMaps(diagnostics, typeHint, didSaveTextDocumentParams.getTextDocument().getUri());
clientService.publishDiagnostics(didSaveTextDocumentParams.getTextDocument().getUri(), diagnostics);
} catch (Exception e) {
logService.log("[didSave] Error trying to get Inlay-Hints and Diagnostics for Client: " + e.getMessage(), MessageType.Error);
clientService.showMessage(MessageType.Error, e.getMessage());
cacheService.updateGlobalMaps(new ArrayList<>(), new ArrayList<>(), didSaveTextDocumentParams.getTextDocument().getUri());
} finally {
sWatch.stop();
logService.log("[didSave] Finished Calculating in [" + sWatch.elapsed().toSeconds() + "s]", MessageType.Info);
}
}
}

View File

@@ -0,0 +1,51 @@
package de.dhbw.helper;
import de.dhbw.service.TextDocumentService;
import de.dhbw.model.LSPVariable;
import de.dhbw.model.Type;
import org.eclipse.lsp4j.*;
public class ConversionHelper {
private final TextHelper textHelper;
private final TextDocumentService textDocumentService;
public ConversionHelper(TextHelper textHelper, TextDocumentService textDocumentService) {
this.textHelper = textHelper;
this.textDocumentService = textDocumentService;
}
public InlayHint getInlayHint(LSPVariable variable) {
InlayHint inlayHint = new InlayHint();
String typeDisplay = "";
for (Type type : variable.getPossibleTypes()) {
typeDisplay += " | " + type.getType().replaceAll("GTV ", "");
}
inlayHint.setLabel(typeDisplay.length() > 2 ? typeDisplay.substring(2) : typeDisplay);
inlayHint.setPosition(new Position(variable.getLine() - 1, variable.getCharPosition()));
inlayHint.setKind(InlayHintKind.Parameter);
inlayHint.setPaddingRight(true);
inlayHint.setPaddingRight(true);
return inlayHint;
}
public Diagnostic getDiagnostic(LSPVariable variable, String fileUri, Type type) {
Range errorRange = new Range(
new Position(variable.getLine() - 1, variable.getCharPosition()), // Startposition
new Position(variable.getLine() - 1, textHelper.getEndingCharOfStartingChar(variable.getLine() - 1, variable.getCharPosition(), textDocumentService.getFileOfUri(fileUri))) // Endposition
);
Diagnostic diagnostic = new Diagnostic(
errorRange,
//TODO: REMOVE! Temporary Fix because GTV, like TPH can be thrown away in the TypeResolver
type.getType().replaceAll("GTV ", ""),
DiagnosticSeverity.Hint,
"JavaTX Language Server"
);
diagnostic.setCode(type.isGeneric() ? "GENERIC" : "TYPE");
return diagnostic;
}
}

View File

@@ -0,0 +1,120 @@
package de.dhbw.service;
import de.dhbw.helper.CodeSnippetOptions;
import de.dhbw.helper.TextHelper;
import de.dhbw.helper.TypeResolver;
import de.dhbw.model.LSPVariable;
import org.eclipse.lsp4j.Diagnostic;
import org.eclipse.lsp4j.InlayHint;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class CacheService {
private HashMap<String, List<InlayHint>> globalInlayHintMap = new HashMap<>();
private Boolean currentlyCalculating = false;
private HashMap<String, List<Diagnostic>> globalDiagnosticsMap = new HashMap<>();
private HashMap<String, String> textDocuments = new HashMap<>();
private CodeSnippetOptions codeSnippetOptions = new CodeSnippetOptions();
private TextHelper textHelper = new TextHelper();
private Boolean dontShowHints = false;
private TypeResolver typeResolver = new TypeResolver();
private Path fileRoot = null;
private Boolean singleFileOpened = false;
private List<LSPVariable> variables = new ArrayList<>();
public void updateGlobalMaps(List<Diagnostic> diagnostics, List<InlayHint> typeHint, String uri) {
globalDiagnosticsMap.put(uri, diagnostics);
globalInlayHintMap.put(uri, typeHint);
}
public Boolean getCurrentlyCalculating() {
return currentlyCalculating;
}
public Boolean getDontShowHints() {
return dontShowHints;
}
public Boolean getSingleFileOpened() {
return singleFileOpened;
}
public CodeSnippetOptions getCodeSnippetOptions() {
return codeSnippetOptions;
}
public HashMap<String, List<Diagnostic>> getGlobalDiagnosticsMap() {
return globalDiagnosticsMap;
}
public HashMap<String, List<InlayHint>> getGlobalInlayHintMap() {
return globalInlayHintMap;
}
public HashMap<String, String> getTextDocuments() {
return textDocuments;
}
public List<LSPVariable> getVariables() {
return variables;
}
public Path getFileRoot() {
return fileRoot;
}
public TextHelper getTextHelper() {
return textHelper;
}
public TypeResolver getTypeResolver() {
return typeResolver;
}
public void setCodeSnippetOptions(CodeSnippetOptions codeSnippetOptions) {
this.codeSnippetOptions = codeSnippetOptions;
}
public void setCurrentlyCalculating(Boolean currentlyCalculating) {
this.currentlyCalculating = currentlyCalculating;
}
public void setDontShowHints(Boolean dontShowHints) {
this.dontShowHints = dontShowHints;
}
public void setFileRoot(Path fileRoot) {
this.fileRoot = fileRoot;
}
public void setGlobalDiagnosticsMap(HashMap<String, List<Diagnostic>> globalDiagnosticsMap) {
this.globalDiagnosticsMap = globalDiagnosticsMap;
}
public void setGlobalInlayHintMap(HashMap<String, List<InlayHint>> globalInlayHintMap) {
this.globalInlayHintMap = globalInlayHintMap;
}
public void setSingleFileOpened(Boolean singleFileOpened) {
this.singleFileOpened = singleFileOpened;
}
public void setTextDocuments(HashMap<String, String> textDocuments) {
this.textDocuments = textDocuments;
}
public void setTextHelper(TextHelper textHelper) {
this.textHelper = textHelper;
}
public void setTypeResolver(TypeResolver typeResolver) {
this.typeResolver = typeResolver;
}
public void setVariables(List<LSPVariable> variables) {
this.variables = variables;
}
}

View File

@@ -0,0 +1,48 @@
package de.dhbw.service;
import org.eclipse.lsp4j.Diagnostic;
import org.eclipse.lsp4j.MessageParams;
import org.eclipse.lsp4j.MessageType;
import org.eclipse.lsp4j.PublishDiagnosticsParams;
import org.eclipse.lsp4j.services.LanguageClient;
import java.util.List;
public class ClientService {
private LanguageClient client;
public ClientService(LanguageClient client) {
this.client = client;
}
public void publishDiagnostics(String uri, List<Diagnostic> diagnostics){
PublishDiagnosticsParams diagnosticsParams = new PublishDiagnosticsParams(uri, diagnostics);
client.publishDiagnostics(diagnosticsParams);
}
public void sendClientLog(MessageType type, String message){
client.logMessage(new MessageParams(type, message));
}
public void sendClientLog(String message){
client.logMessage(new MessageParams(MessageType.Info, message));
}
public void showMessage(MessageType type, String message) {
client.showMessage(new MessageParams(type, message));
}
public void showMessage(String message) {
client.showMessage(new MessageParams(MessageType.Info, message));
}
public void setClient(LanguageClient client) {
this.client = client;
}
public void updateClient(LanguageClient client) {
client.refreshInlayHints();
client.refreshDiagnostics();
}
}

View File

@@ -0,0 +1,31 @@
package de.dhbw.service;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.eclipse.lsp4j.MessageType;
public class LogService {
private final Logger logger = LogManager.getLogger(LogService.class);
private final ClientService clientService;
public LogService(ClientService clientService) {
this.clientService = clientService;
}
public void log(String message, MessageType type) {
clientService.sendClientLog(type, message);
switch (type) {
case Error -> logger.error(message);
case Warning -> logger.warn(message);
case Info -> logger.info(message);
default -> logger.debug(message);
}
}
public void log(String message) {
clientService.sendClientLog(MessageType.Info, message);
logger.info(message);
}
}

View File

@@ -0,0 +1,22 @@
package de.dhbw.service;
import java.util.HashMap;
public class TextDocumentService {
private final HashMap<String, String> files = new HashMap<>();
public TextDocumentService(){
}
public String getFileOfUri(String uri) {
return files.get(uri);
}
public void saveFileWithUri(String uri, String input) {
files.put(uri, input);
}
}