feat(studio): improve compiler reliability and AI diagnostics
Preserve structured diagnostics, source attribution, phase outcomes and revision context through compiler, Studio, LSP, MCP and JavaFX. Add project service discovery and resilient VS Code reconnection. Correct all eight reproduced PBS production failures in expression context, sibling executable bindings and nominal owner identity. Consolidate specs, lessons, immutable baseline evidence and the maintained source-to-guest qualification runner. Validation: required Gradle gate recorded 724 tests, with 711 passed and 13 skipped. Full corpus passed 168 compilation observations and 108 guest runs (104 successes and four deliberate faults); supplemental controls passed 42 compilations and 16 guest runs. TypeScript compilation, two Node discovery tests and discussion validation passed.
This commit is contained in:
+4
-1
@@ -4,9 +4,12 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record BaselineDocumentAnalysis(
|
||||
List<BaselineDocumentIssue> issues) {
|
||||
List<BaselineDocumentIssue> issues,
|
||||
java.util.Map<String, Object> details) {
|
||||
public BaselineDocumentAnalysis(List<BaselineDocumentIssue> issues) { this(issues, java.util.Map.of()); }
|
||||
|
||||
public BaselineDocumentAnalysis {
|
||||
issues = List.copyOf(Objects.requireNonNull(issues, "issues"));
|
||||
details = p.studio.utilities.json.ImmutableJson.object(details);
|
||||
}
|
||||
}
|
||||
|
||||
+7
-1
@@ -10,13 +10,19 @@ public record BaselineDocumentIssue(
|
||||
BaselineIssueSeverity severity,
|
||||
String source,
|
||||
String message,
|
||||
String code) {
|
||||
String code,
|
||||
java.util.Map<String, Object> data) {
|
||||
public BaselineDocumentIssue(int startLine, int startCharacter, int endLine, int endCharacter,
|
||||
BaselineIssueSeverity severity, String source, String message, String code) {
|
||||
this(startLine, startCharacter, endLine, endCharacter, severity, source, message, code, java.util.Map.of());
|
||||
}
|
||||
|
||||
public BaselineDocumentIssue {
|
||||
severity = Objects.requireNonNull(severity, "severity");
|
||||
source = requireText(source, "source");
|
||||
message = requireText(message, "message");
|
||||
code = code == null ? "" : code.trim();
|
||||
data = p.studio.utilities.json.ImmutableJson.object(data);
|
||||
}
|
||||
|
||||
private static String requireText(
|
||||
|
||||
+45
-16
@@ -200,13 +200,31 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
|
||||
final String text) {
|
||||
Objects.requireNonNull(context, "context");
|
||||
final Path documentPath = normalizeDocumentPath(documentUri);
|
||||
final String effectiveText = StringUtils.isBlank(text) ? "" : text;
|
||||
final String effectiveText = text == null ? "" : text;
|
||||
final AnalysisSnapshot snapshot = analyzeProject(context, Map.of(documentPath, effectiveText));
|
||||
var analysisId = java.util.UUID.randomUUID().toString();
|
||||
var sources = p.studio.compiler.source.diagnostics.SourceReference.snapshot(snapshot.fileTable());
|
||||
var allIssues = p.studio.compiler.source.diagnostics.CompilerDiagnosticProjection.issues(snapshot.diagnostics(), sources,
|
||||
p.studio.compiler.source.diagnostics.CompilerDiagnosticProjection.capturedText(snapshot.fileTable()), context.projectRoot(), analysisId);
|
||||
var view = p.studio.utilities.json.DiagnosticPayloads.view(allIssues, "project",
|
||||
p.studio.utilities.json.DiagnosticPayloads.evaluate(allIssues), java.util.List.of(
|
||||
p.studio.utilities.json.DiagnosticPayloads.stage("analysis", p.studio.utilities.json.DiagnosticPayloads.evaluate(allIssues))), "partial");
|
||||
String digest;
|
||||
try { digest = java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256")
|
||||
.digest(effectiveText.getBytes(StandardCharsets.UTF_8))); }
|
||||
catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
|
||||
var details = p.studio.utilities.json.ImmutableJson.fields("analysisId", analysisId,
|
||||
"document", p.studio.utilities.json.ImmutableJson.fields("uri", documentUri, "sha256", digest),
|
||||
"issues", view.issues(), "summary", view.summary(),
|
||||
"configuration", p.studio.utilities.json.ImmutableJson.fields("languageId", snapshot.frontendSpec().getLanguageId(),
|
||||
"sdkVersion", snapshot.resolvedWorkspace().stdlib(), "target", snapshot.resolvedWorkspace().target().name(),
|
||||
"vmProfile", "core-v1", "revisionAvailability", "not-recorded"),
|
||||
"inputs", p.studio.compiler.source.diagnostics.CompilerDiagnosticProjection.inputs(sources, context.projectRoot()));
|
||||
return new BaselineDocumentAnalysis(mapDiagnostics(
|
||||
snapshot,
|
||||
documentPath,
|
||||
effectiveText,
|
||||
context.languageId()));
|
||||
context.languageId(), allIssues, view.issues(), analysisId), details);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -975,10 +993,13 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
|
||||
final AnalysisSnapshot snapshot,
|
||||
final Path documentPath,
|
||||
final String text,
|
||||
final String languageId) {
|
||||
final String languageId, final List<Map<String, Object>> allIssues,
|
||||
final List<Map<String, Object>> visibleIssues, final String analysisId) {
|
||||
final ArrayList<BaselineDocumentIssue> issues = new ArrayList<>();
|
||||
final DocumentPositionMapper positionMapper = new DocumentPositionMapper(text);
|
||||
int diagnosticIndex = -1;
|
||||
var visibleIds = visibleIssues.stream().map(i -> (String) i.get("issueId")).collect(java.util.stream.Collectors.toSet());
|
||||
for (final BuildingIssue diagnostic : snapshot.diagnostics()) {
|
||||
diagnosticIndex++;
|
||||
if (diagnostic.getFileId() == null || diagnostic.getFileId() < 0) {
|
||||
continue;
|
||||
}
|
||||
@@ -990,29 +1011,37 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
|
||||
if (!sourceHandle.getCanonPath().toAbsolutePath().normalize().equals(documentPath)) {
|
||||
continue;
|
||||
}
|
||||
issues.add(toBaselineIssue(diagnostic, positionMapper, languageId));
|
||||
if (diagnostic.getStart() == null || diagnostic.getEnd() == null) continue;
|
||||
var projected = allIssues.get(diagnosticIndex);
|
||||
var origin = (Map<?, ?>)projected.get("origin");
|
||||
if (origin == null || !(origin.get("range") instanceof Map<?, ?> recordedRange)) continue;
|
||||
var identity = (String) projected.get("issueId");
|
||||
var data = p.studio.utilities.json.ImmutableJson.fields("prometeu", p.studio.utilities.json.ImmutableJson.fields(
|
||||
"version", 1, "analysisId", analysisId, "issueId", identity,
|
||||
"issue", visibleIds.contains(identity) ? projected : null,
|
||||
"limitations", visibleIds.contains(identity) ? java.util.List.of() : java.util.List.of(
|
||||
p.studio.utilities.json.DiagnosticPayloads.limitation("LIMIT_EXCEEDED", "Issue details omitted by public budget"))));
|
||||
issues.add(toBaselineIssue(diagnostic, recordedRange, languageId, data));
|
||||
}
|
||||
return List.copyOf(issues);
|
||||
}
|
||||
|
||||
private BaselineDocumentIssue toBaselineIssue(
|
||||
final BuildingIssue diagnostic,
|
||||
final DocumentPositionMapper positionMapper,
|
||||
final String languageId) {
|
||||
final int startOffset = diagnostic.getStart() == null ? 0 : diagnostic.getStart();
|
||||
final int endOffset = diagnostic.getEnd() == null ? startOffset : Math.max(startOffset, diagnostic.getEnd());
|
||||
final DocumentPosition start = positionMapper.positionOf(startOffset);
|
||||
final DocumentPosition end = positionMapper.positionOf(endOffset);
|
||||
final Map<?, ?> recordedRange,
|
||||
final String languageId, final Map<String, Object> data) {
|
||||
final var start = (Map<?, ?>)recordedRange.get("start");
|
||||
final var end = (Map<?, ?>)recordedRange.get("end");
|
||||
final String code = diagnostic.getCode() == null ? "" : diagnostic.getCode().trim();
|
||||
return new BaselineDocumentIssue(
|
||||
start.line(),
|
||||
start.character(),
|
||||
end.line(),
|
||||
end.character(),
|
||||
((Number)start.get("line")).intValue(),
|
||||
((Number)start.get("character")).intValue(),
|
||||
((Number)end.get("line")).intValue(),
|
||||
((Number)end.get("character")).intValue(),
|
||||
diagnostic.isError() ? BaselineIssueSeverity.ERROR : BaselineIssueSeverity.WARNING,
|
||||
languageId,
|
||||
diagnostic.getMessage(),
|
||||
code);
|
||||
code, data);
|
||||
}
|
||||
|
||||
private Path normalizeDocumentPath(final String documentUri) {
|
||||
|
||||
+5
@@ -8,6 +8,11 @@ import java.util.concurrent.CompletableFuture;
|
||||
public interface ExternalSourceLanguageServer extends LanguageServer {
|
||||
record Request(String consumerId, String uri) {}
|
||||
record AnimationOriginRequest(String consumerId,String uri,int offset) {}
|
||||
record DiagnosticAnalysisRequest(org.eclipse.lsp4j.VersionedTextDocumentIdentifier textDocument, String contentSha256) {}
|
||||
@JsonRequest("prometeu/documentAnalysis") default CompletableFuture<com.google.gson.JsonObject> documentAnalysis(DiagnosticAnalysisRequest request) {
|
||||
return CompletableFuture.failedFuture(new org.eclipse.lsp4j.jsonrpc.ResponseErrorException(
|
||||
new org.eclipse.lsp4j.jsonrpc.messages.ResponseError(-32601, "Analysis details unavailable", null)));
|
||||
}
|
||||
@JsonRequest("prometeu/openAnimationOrigin") CompletableFuture<Void> openAnimationOrigin(AnimationOriginRequest request);
|
||||
@JsonRequest("prometeu/readExternalSource") CompletableFuture<Content> readExternalSource(Request request);
|
||||
@JsonRequest("prometeu/retainExternalSource") CompletableFuture<Content> retainExternalSource(Request request);
|
||||
|
||||
+20
@@ -23,6 +23,14 @@ public final class PrometeuLanguageServer implements ExternalSourceLanguageServe
|
||||
private final WorkspaceService workspaceService;
|
||||
private volatile LanguageClient client;
|
||||
private volatile boolean shutdownRequested;
|
||||
private boolean diagnosticAnalysisNegotiated;
|
||||
|
||||
@Override public CompletableFuture<com.google.gson.JsonObject> documentAnalysis(DiagnosticAnalysisRequest request) {
|
||||
if (!diagnosticAnalysisNegotiated || !(textDocumentService instanceof PrometeuTextDocumentService service))
|
||||
return CompletableFuture.failedFuture(new org.eclipse.lsp4j.jsonrpc.ResponseErrorException(
|
||||
new org.eclipse.lsp4j.jsonrpc.messages.ResponseError(-32601, "Diagnostic analysis capability was not negotiated", null)));
|
||||
return service.documentAnalysis(request).thenApply(value -> new com.google.gson.Gson().toJsonTree(value).getAsJsonObject());
|
||||
}
|
||||
|
||||
public PrometeuLanguageServer(
|
||||
final LspProjectContext project,
|
||||
@@ -43,6 +51,7 @@ public final class PrometeuLanguageServer implements ExternalSourceLanguageServe
|
||||
|
||||
public void disconnected() {
|
||||
if (externalSources != null && consumerId != null) externalSources.disconnect(consumerId);
|
||||
if (textDocumentService instanceof PrometeuTextDocumentService service) service.clearAnalyses();
|
||||
}
|
||||
|
||||
private void requireConsumer(Request request) {
|
||||
@@ -120,6 +129,17 @@ public final class PrometeuLanguageServer implements ExternalSourceLanguageServe
|
||||
final var result = protocolMessageMapper.mapInitializeResult(languageServiceBridge.describeServer(project));
|
||||
final var gson = new com.google.gson.Gson();
|
||||
final var capability = gson.toJsonTree(params.getCapabilities() == null ? null : params.getCapabilities().getExperimental());
|
||||
if (languageServiceBridge instanceof CompilerLanguageServiceBridge && capability.isJsonObject()
|
||||
&& capability.getAsJsonObject().has("prometeuDiagnosticAnalysis")
|
||||
&& capability.getAsJsonObject().get("prometeuDiagnosticAnalysis").isJsonObject()
|
||||
&& new com.google.gson.JsonPrimitive(1).equals(capability.getAsJsonObject().getAsJsonObject("prometeuDiagnosticAnalysis").get("version"))) {
|
||||
diagnosticAnalysisNegotiated = true;
|
||||
var experimental = gson.toJsonTree(result.getCapabilities().getExperimental());
|
||||
var values = experimental.isJsonObject() ? experimental.getAsJsonObject() : new com.google.gson.JsonObject();
|
||||
values.add("prometeuDiagnosticAnalysis", gson.toJsonTree(java.util.Map.of("version", 1,
|
||||
"method", "prometeu/documentAnalysis", "diagnosticDataVersion", 1)));
|
||||
result.getCapabilities().setExperimental(values);
|
||||
}
|
||||
if (externalSources != null && languageServiceBridge instanceof CompilerLanguageServiceBridge bridge
|
||||
&& bridge.supportsExternalSources(project) && capability.isJsonObject()
|
||||
&& capability.getAsJsonObject().has("prometeuExternalSources")
|
||||
|
||||
+52
-6
@@ -28,6 +28,8 @@ public final class PrometeuTextDocumentService implements TextDocumentService {
|
||||
private final LanguageServiceBridge languageServiceBridge;
|
||||
private final ProtocolMessageMapper protocolMessageMapper;
|
||||
private final ConcurrentMap<String, String> documentTextByUri = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<String, Integer> documentVersionByUri = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<String, CompletableFuture<java.util.Map<String, Object>>> analysisByUri = new ConcurrentHashMap<>();
|
||||
private volatile LanguageClient client;
|
||||
private p.studio.lsp.services.compiler.ExternalSourceRegistry externalSources;
|
||||
private String externalConsumer;
|
||||
@@ -90,6 +92,7 @@ public final class PrometeuTextDocumentService implements TextDocumentService {
|
||||
if (known.isPresent() && known.orElseThrow().readOnly()) text = known.orElseThrow().text();
|
||||
}
|
||||
documentTextByUri.put(uri, text);
|
||||
documentVersionByUri.put(uri, params.getTextDocument().getVersion());
|
||||
publishAnalysis(uri, text);
|
||||
}
|
||||
|
||||
@@ -101,6 +104,7 @@ public final class PrometeuTextDocumentService implements TextDocumentService {
|
||||
? ""
|
||||
: params.getContentChanges().getFirst().getText();
|
||||
documentTextByUri.put(uri, text);
|
||||
documentVersionByUri.put(uri, params.getTextDocument().getVersion());
|
||||
publishAnalysis(uri, text);
|
||||
}
|
||||
|
||||
@@ -110,6 +114,8 @@ public final class PrometeuTextDocumentService implements TextDocumentService {
|
||||
if (externalSources != null) externalSources.release(externalConsumer, params.getTextDocument().getUri()); return;
|
||||
}
|
||||
documentTextByUri.remove(params.getTextDocument().getUri());
|
||||
documentVersionByUri.remove(params.getTextDocument().getUri());
|
||||
analysisByUri.remove(params.getTextDocument().getUri());
|
||||
final LanguageClient currentClient = client;
|
||||
if (currentClient == null) {
|
||||
return;
|
||||
@@ -431,12 +437,52 @@ public final class PrometeuTextDocumentService implements TextDocumentService {
|
||||
private void publishAnalysis(
|
||||
final String uri,
|
||||
final String text) {
|
||||
final LanguageClient currentClient = client;
|
||||
if (currentClient == null) {
|
||||
return;
|
||||
var result = new CompletableFuture<java.util.Map<String, Object>>();
|
||||
analysisByUri.put(uri, result);
|
||||
var version = documentVersionByUri.get(uri);
|
||||
try {
|
||||
var analysis = languageServiceBridge.analyzeDocument(project, uri, text);
|
||||
var envelope = new java.util.LinkedHashMap<>(analysis.details());
|
||||
var document = new java.util.LinkedHashMap<String, Object>();
|
||||
if (envelope.get("document") instanceof java.util.Map<?, ?> captured)
|
||||
captured.forEach((key, value) -> document.put((String) key, value));
|
||||
document.put("uri", uri); document.put("version", version);
|
||||
envelope.put("document", p.studio.utilities.json.ImmutableJson.object(document));
|
||||
result.complete(p.studio.utilities.json.ImmutableJson.object(envelope));
|
||||
var current = client;
|
||||
if (current != null) current.publishDiagnostics(protocolMessageMapper.mapDiagnostics(uri, analysis));
|
||||
} catch (RuntimeException failure) {
|
||||
result.completeExceptionally(new ResponseErrorException(new ResponseError(-32603,
|
||||
"Project analysis failed", java.util.Map.of("reason", "ANALYSIS_INTERNAL_FAILURE"))));
|
||||
var current = client;
|
||||
if (current != null) current.logMessage(protocolMessageMapper.mapErrorMessage("Project analysis failed"));
|
||||
}
|
||||
currentClient.publishDiagnostics(protocolMessageMapper.mapDiagnostics(
|
||||
uri,
|
||||
languageServiceBridge.analyzeDocument(project, uri, text)));
|
||||
}
|
||||
|
||||
CompletableFuture<java.util.Map<String, Object>> documentAnalysis(ExternalSourceLanguageServer.DiagnosticAnalysisRequest request) {
|
||||
if (request == null || request.textDocument() == null || request.contentSha256() == null)
|
||||
return CompletableFuture.failedFuture(new ResponseErrorException(new ResponseError(-32602, "Analysis document and digest are required", null)));
|
||||
var uri = request.textDocument().getUri();
|
||||
var pending = analysisByUri.get(uri);
|
||||
if (pending == null) return CompletableFuture.failedFuture(analysisUnavailable());
|
||||
return pending.thenApply(result -> {
|
||||
if (!documentTextByUri.containsKey(uri)) throw analysisUnavailable();
|
||||
var document = (java.util.Map<?, ?>) result.get("document");
|
||||
if (analysisByUri.get(uri) != pending || !Objects.equals(documentVersionByUri.get(uri), request.textDocument().getVersion())
|
||||
|| document == null || !Objects.equals(document.get("sha256"), request.contentSha256())
|
||||
|| !Objects.equals(document.get("version"), request.textDocument().getVersion()))
|
||||
throw new ResponseErrorException(new ResponseError(-32020, "Analysis revision mismatch",
|
||||
java.util.Map.of("reason", "ANALYSIS_REVISION_MISMATCH")));
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
private ResponseErrorException analysisUnavailable() {
|
||||
return new ResponseErrorException(new ResponseError(-32021, "Analysis result is unavailable",
|
||||
java.util.Map.of("reason", "ANALYSIS_UNAVAILABLE")));
|
||||
}
|
||||
|
||||
void clearAnalyses() {
|
||||
analysisByUri.clear(); documentVersionByUri.clear(); documentTextByUri.clear();
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -493,6 +493,7 @@ public final class Lsp4jProtocolMessageMapper implements ProtocolMessageMapper {
|
||||
diagnostic.setSeverity(mapSeverity(issue.severity()));
|
||||
diagnostic.setSource(issue.source());
|
||||
diagnostic.setMessage(issue.message());
|
||||
if (!issue.data().isEmpty()) diagnostic.setData(issue.data());
|
||||
if (!issue.code().isBlank()) {
|
||||
diagnostic.setCode(Either.forLeft(issue.code()));
|
||||
}
|
||||
|
||||
+35
-2
@@ -38,8 +38,26 @@ class ExternalSourceDevelopmentHostTest {
|
||||
.endpoint(new LspServerEndpoint("127.0.0.1", 0)).build(), new LspProjectContext("dev", "pbs", root),
|
||||
new CompilerLanguageServiceBridge());
|
||||
host.start();
|
||||
final var discoveryWorker = java.util.concurrent.Executors.newSingleThreadExecutor();
|
||||
final Path discovery = Files.createDirectories(root.resolve(".studio")).resolve("lsp.json");
|
||||
final var discoveryTask = discoveryWorker.submit(() -> {
|
||||
try {
|
||||
awaitMarker(root.resolve(".studio/discover-request"));
|
||||
publish(discovery, root, host, "initial");
|
||||
awaitMarker(root.resolve(".studio/restart-request"));
|
||||
Files.delete(discovery);
|
||||
host.close();
|
||||
final var replacement = new TcpLspServerHost(LspServerConfiguration.builder()
|
||||
.endpoint(new LspServerEndpoint("127.0.0.1", 0)).build(), new LspProjectContext("dev", "pbs", root),
|
||||
new CompilerLanguageServiceBridge());
|
||||
replacement.start();
|
||||
try {
|
||||
publish(discovery, root, replacement, "replacement");
|
||||
awaitMarker(root.resolve(".studio/finished"));
|
||||
} finally { replacement.close(); }
|
||||
} catch (Exception failure) { throw new RuntimeException(failure); }
|
||||
});
|
||||
try {
|
||||
Files.writeString(root.resolve(".vscode/settings.json"), "{\"prometeu.studio.port\":" + host.endpoint().orElseThrow().port() + "}");
|
||||
final String executable = System.getenv().getOrDefault("PROMETEU_VSCODE_EXECUTABLE", "/Applications/Visual Studio Code.app/Contents/MacOS/Code");
|
||||
final Path extension = repository.resolve("tools/vscode-extension");
|
||||
final var builder = new ProcessBuilder(executable, "--no-sandbox", "--disable-extensions", "--disable-workspace-trust",
|
||||
@@ -53,11 +71,26 @@ class ExternalSourceDevelopmentHostTest {
|
||||
assertTrue(process.waitFor(90, TimeUnit.SECONDS), "VS Code test timed out: " + log);
|
||||
assertEquals(0, process.exitValue(), () -> read(log));
|
||||
} finally { process.destroyForcibly(); }
|
||||
discoveryTask.get(10, TimeUnit.SECONDS);
|
||||
assertEquals(libraryText, Files.readString(library.resolve("src/shared/main.pbs")));
|
||||
try (var directories = Files.list(root.resolve(".workspace"))) {
|
||||
assertEquals(java.util.List.of("repos"), directories.map(p -> p.getFileName().toString()).toList(), "No editorial SDK cache");
|
||||
}
|
||||
} finally { host.close(); }
|
||||
} finally { discoveryTask.cancel(true); discoveryWorker.shutdownNow(); host.close(); }
|
||||
}
|
||||
private static void awaitMarker(Path marker) throws Exception {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(80);
|
||||
while (!Files.exists(marker)) {
|
||||
if (System.nanoTime() > deadline) throw new IllegalStateException("Marker timed out: " + marker);
|
||||
Thread.sleep(50);
|
||||
}
|
||||
}
|
||||
private static void publish(Path discovery, Path root, TcpLspServerHost host, String session) throws Exception {
|
||||
var temporary = discovery.resolveSibling("lsp.tmp");
|
||||
new com.fasterxml.jackson.databind.ObjectMapper().writeValue(temporary.toFile(), java.util.Map.of(
|
||||
"schemaVersion", 1, "projectRoot", root.toString(), "sessionId", session,
|
||||
"processId", ProcessHandle.current().pid(), "host", "127.0.0.1", "port", host.endpoint().orElseThrow().port()));
|
||||
Files.move(temporary, discovery, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
private static String read(Path path) { try { return Files.readString(path); } catch (Exception e) { return e.toString(); } }
|
||||
}
|
||||
|
||||
+18
-6
@@ -939,12 +939,24 @@ class CompilerLanguageServiceBridgeTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void workspaceSymbolsSearchPhysicalNamedDeclarationsWithoutAnOpenDocument() {
|
||||
final Path projectRoot = findRepoRoot(Path.of("").toAbsolutePath().normalize())
|
||||
.resolve("test-projects")
|
||||
.resolve("main")
|
||||
.toAbsolutePath()
|
||||
.normalize();
|
||||
void workspaceSymbolsSearchPhysicalNamedDeclarationsWithoutAnOpenDocument(@TempDir Path temporary) throws IOException {
|
||||
final Path projectRoot = temporary.toRealPath();
|
||||
Files.createDirectories(projectRoot.resolve("src"));
|
||||
Files.writeString(projectRoot.resolve("prometeu.json"), """
|
||||
{"name":"main","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]}
|
||||
""");
|
||||
Files.writeString(projectRoot.resolve("src/main.pbs"), """
|
||||
import { Log } from @sdk:log;
|
||||
import { Composer } from @sdk:composer;
|
||||
declare struct Bla(a: int) {}
|
||||
[Init] fn init() -> void {}
|
||||
[Frame] fn frame() -> void {}
|
||||
""");
|
||||
Files.writeString(projectRoot.resolve("src/mod.barrel"), """
|
||||
pub struct Bla;
|
||||
pub fn init() -> void;
|
||||
pub fn frame() -> void;
|
||||
""");
|
||||
final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge();
|
||||
final var context = new LspProjectContext("main", "pbs", projectRoot);
|
||||
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package p.studio.lsp.services.protocol;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.eclipse.lsp4j.*;
|
||||
import org.eclipse.lsp4j.jsonrpc.ResponseErrorException;
|
||||
import p.studio.lsp.messages.LspProjectContext;
|
||||
import p.studio.lsp.services.compiler.CompilerLanguageServiceBridge;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class DiagnosticAnalysisProtocolTest {
|
||||
@TempDir Path root;
|
||||
@Test void retainedAnalysisNegotiatesOnceChecksRevisionAndClearsOnClose() throws Exception {
|
||||
root = root.toRealPath(); Files.createDirectories(root.resolve("src"));
|
||||
Files.writeString(root.resolve("prometeu.json"), "{\"name\":\"test\",\"version\":\"1\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}");
|
||||
var source = root.resolve("src/main.pbs"); String text = "// á 😀\r\nfn main() -> int { return 1; }\n"; Files.writeString(source, text);
|
||||
var server = new PrometeuLanguageServer(new LspProjectContext("test", "pbs", root), new CompilerLanguageServiceBridge());
|
||||
var init = new InitializeParams(); init.setRootUri(root.toUri().toString()); init.setCapabilities(new ClientCapabilities());
|
||||
var legacy = server.initialize(init).join();
|
||||
assertFalse(new com.google.gson.Gson().toJsonTree(legacy.getCapabilities().getExperimental()).toString().contains("prometeuDiagnosticAnalysis"));
|
||||
var id = new VersionedTextDocumentIdentifier(source.toUri().toString(), 1);
|
||||
String digest = HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(text.getBytes(java.nio.charset.StandardCharsets.UTF_8)));
|
||||
var request = new ExternalSourceLanguageServer.DiagnosticAnalysisRequest(id, digest);
|
||||
assertCode(-32601, () -> server.documentAnalysis(request).join());
|
||||
init.getCapabilities().setExperimental(Map.of("prometeuDiagnosticAnalysis", Map.of("version", 1)));
|
||||
var rich = server.initialize(init).join(); assertTrue(new com.google.gson.Gson().toJsonTree(rich.getCapabilities().getExperimental()).toString().contains("prometeu/documentAnalysis"));
|
||||
assertCode(-32021, () -> server.documentAnalysis(request).join());
|
||||
server.getTextDocumentService().didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(id.getUri(), "pbs", 1, text)));
|
||||
var first = server.documentAnalysis(request).join();
|
||||
assertEquals(first, server.documentAnalysis(request).join(), "Request returns retained analysis identity");
|
||||
assertEquals(digest, first.getAsJsonObject("document").get("sha256").getAsString());
|
||||
var wrong = new ExternalSourceLanguageServer.DiagnosticAnalysisRequest(id, "different");
|
||||
assertCode(-32020, () -> server.documentAnalysis(wrong).join());
|
||||
var changed = new VersionedTextDocumentIdentifier(id.getUri(), 2);
|
||||
server.getTextDocumentService().didChange(new DidChangeTextDocumentParams(changed, List.of(new TextDocumentContentChangeEvent(text))));
|
||||
assertCode(-32020, () -> server.documentAnalysis(request).join());
|
||||
var second = server.documentAnalysis(new ExternalSourceLanguageServer.DiagnosticAnalysisRequest(changed, digest)).join();
|
||||
assertNotEquals(first.get("analysisId"), second.get("analysisId"));
|
||||
server.getTextDocumentService().didClose(new DidCloseTextDocumentParams(new TextDocumentIdentifier(id.getUri())));
|
||||
assertCode(-32021, () -> server.documentAnalysis(request).join()); server.disconnected();
|
||||
}
|
||||
static void assertCode(int code, Runnable work) {
|
||||
var failure = assertThrows(CompletionException.class, work::run);
|
||||
assertEquals(code, assertInstanceOf(ResponseErrorException.class, failure.getCause()).getResponseError().getCode());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user