From 533c4110f4b58fff4cf357596e77a5d99a83b26f Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Thu, 26 Nov 2026 14:06:09 +0000 Subject: [PATCH] fix(pbs): keep editorial signatures in source syntax Share frontend type and return presentation across hover, completion, signature help, outline and inferred hints. Preserve generic applications, source grouping, nominal origins and navigation. Add parser structure, real module/reexport, LSP mapping and Studio consumer regressions. Document the PBS editorial contract. WRK-0021 / DEC-0001 / PLN-0001. Full make -C tooling verify passed all 11 stages: tooling/build/runs/20261126T135036Z-bed847d1/manifest.json. Commit and push explicitly requested by the user. --- .../pbs/4. Static Semantics Specification.md | 45 +++++++ .../app/lsp/AutomationLspQueriesTest.java | 48 +++++++ .../pbs/semantics/PbsAstDocumentSymbols.java | 37 +----- .../semantics/PbsEditorialSupportService.java | 31 +---- .../pbs/semantics/PbsFlowBodyAnalyzer.java | 4 +- .../PbsInlineHintSurfaceFormatter.java | 71 ----------- .../pbs/semantics/PbsSourceTypeFormatter.java | 104 +++++++++++++++ .../PBSFrontendModuleCompletionTest.java | 79 ++++++++++++ .../PbsEditorialSourceSignatureTest.java | 119 ++++++++++++++++++ .../CompilerLanguageServiceBridgeTest.java | 40 ++++++ 10 files changed, 444 insertions(+), 134 deletions(-) delete mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsInlineHintSurfaceFormatter.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsSourceTypeFormatter.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsEditorialSourceSignatureTest.java diff --git a/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md b/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md index a0aaa63c..d5d3a993 100644 --- a/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md +++ b/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md @@ -219,6 +219,51 @@ Rules: - Generated ordinal placeholders such as `arg0`, `arg1`, or equivalent names are internal implementation fallbacks only and MUST NOT be exposed as public parameter names. - If a user-visible callable lacks a real canonical parameter name, semantic metadata MUST represent that name as missing or unresolved rather than fabricating an ordinal placeholder. +### 3.2.1 Source presentation of callable signatures + +The PBS frontend owns the source presentation shared by hover, completion, +signature help, document symbols and inferred type hints. Consumers transport or +render frontend labels; they MUST NOT reconstruct PBS types, repair type strings +or perform independent generic substitution. + +Complete type and return fragments MUST use accepted PBS source syntax: + +- A result return with no success payload is `result`. +- A result return with a scalar payload is `result T`; a named tuple payload + remains `result (left: T, right: U)` with its labels and order intact. +- Optional values use `optional T`, including inside composed types. +- Ordinary empty returns may be presented as `void`. Internal tuple/result + normalization MUST NOT expose `unit`, `result` or postfix `T?` as a + replacement for these source forms. +- Groups, function inputs/outputs, array elements and generic arguments MUST + preserve their structure, precedence and ordered logical types. + +Presentation MUST preserve nominal error/type identity, parameter names and +order, tuple labels, generic arguments and declaration provenance. Unavailable +parameter names remain unavailable rather than receiving generated ordinal names. +Source recovery may expose an unknown marker or suppress a type hint; it MUST NOT +invent a concrete type or present an unknown result payload as an empty payload. +Recovery markers are not complete source fragments. + +Surfaces may use context-appropriate compact forms rather than identical strings. +Document symbols describe declarations. Hover and signature help for a resolved +application expose its concrete types; symbolic declarations retain their type +parameters. Completion may describe a declaration or known application as +appropriate. This does not add generic argument inference: applications continue +to follow the explicit-argument rules of the generic specifications. + +Imports, aliases and reexports retain the existing canonical-name policy and +nominal origins. Navigation MUST retain access to the original declaration even +when a displayed application is specialized. A canonical name need not match the +consumer's local alias; parseability of a fragment does not by itself establish +name resolution in an arbitrary consumer namespace. + +Conformance checks MUST reparse complete fragments in appropriate grammatical +positions and verify their type structure and resolution/provenance. They MUST +also exercise real module/barrel resolution and frontend-to-consumer transport, +including parameter labels and the active parameter, without treating a compact +label as a self-contained declaration. + ### 3.3 Declaration validity Rules: diff --git a/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java b/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java index e1670b43..cf7e7db2 100644 --- a/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java +++ b/prometeu-app/src/test/java/p/studio/app/lsp/AutomationLspQueriesTest.java @@ -99,6 +99,54 @@ class AutomationLspQueriesTest { assertTrue(symbols.toString().contains("renamed"), symbols.toString()); assertFalse(symbols.toString().contains("helper"), symbols.toString()); } + + @Test void sourceSignaturesReachTheStudioConsumerOverTheActualServer() throws Exception { + final String text = """ + declare error Io { Failed; } + fn load(left: int, right: int) -> result (first: int, second: int) { + return ok((first: left, second: right)); + } + fn maybe(value: optional int) -> optional int { return value; } + fn caller() -> result (first: int, second: int) { + let candidate = maybe(none); + return load(1, 2)!; + } + """; + Files.writeString(source, text); + Files.writeString(source.resolveSibling("mod.barrel"), "pub error Io; " + + "pub fn load(left: int, right: int) -> result (first: int, second: int); " + + "pub fn maybe(value: optional int) -> optional int; " + + "pub fn caller() -> result (first: int, second: int);"); + acquire(); + final String expected = "load(left: int, right: int) -> result (first: int, second: int)"; + final java.util.function.IntFunction> atOffset = offset -> { + final String prefix = text.substring(0, offset); + return at((int) prefix.chars().filter(c -> c == '\n').count(), offset - prefix.lastIndexOf('\n') - 1); + }; + final int call = text.indexOf("load(1, 2)"); + final var help = query("signatureHelp", atOffset.apply(call + 8)).path("result"); + assertEquals(1, help.path("activeParameter").asInt(), help.toString()); + final var signature = help.path("signatures").get(0); + assertNotNull(signature, help.toString()); + assertEquals(expected, signature.path("label").asText()); + assertEquals("left: int", signature.path("parameters").get(0).path("label").asText()); + assertEquals("right: int", signature.path("parameters").get(1).path("label").asText()); + assertTrue(query("hover", atOffset.apply(call + 1)).path("result").toString().contains(expected)); + final var items = query("completion", atOffset.apply(call + 1)).path("result").path("items"); + boolean found = false; + for (var item : items) if (item.path("label").asText().equals("load")) { + assertEquals(expected, item.path("detail").asText()); + found = true; + } + assertTrue(found, items.toString()); + assertTrue(query("documentSymbols", at(0, 0)).path("result").toString() + .contains("(left: int, right: int) -> result (first: int, second: int)")); + final var optional = query("signatureHelp", atOffset.apply(text.indexOf("maybe(none)") + 6)) + .path("result").path("signatures").get(0); + assertNotNull(optional); + assertEquals("maybe(value: optional int) -> optional int", optional.path("label").asText()); + assertFalse(query("definition", atOffset.apply(call + 1)).path("result").isEmpty()); + } @Test void validEmptyDocumentIsSuccessfulEvaluatedAnalysis() throws Exception { Files.writeString(source, ""); Files.writeString(source.resolveSibling("mod.barrel"), "pub fn frame() -> void;\n"); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsAstDocumentSymbols.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsAstDocumentSymbols.java index 96f99033..5d9d8bd3 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsAstDocumentSymbols.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsAstDocumentSymbols.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Optional; final class PbsAstDocumentSymbols { + private static final PbsSourceTypeFormatter SOURCE_TYPES = new PbsSourceTypeFormatter(); private PbsAstDocumentSymbols() { } @@ -282,42 +283,10 @@ final class PbsAstDocumentSymbols { final PbsAst.ReturnKind returnKind, final PbsAst.TypeRef returnType, final PbsAst.TypeRef resultErrorType) { - if (returnKind == null) { - return formatTypeRef(returnType); - } - return switch (returnKind) { - case INFERRED_UNIT, EXPLICIT_UNIT -> "void"; - case PLAIN -> formatTypeRef(returnType); - case RESULT -> { - final String errorType = formatTypeRef(resultErrorType); - if (returnType == null || returnType.kind() == PbsAst.TypeRefKind.UNIT) { - yield "result<" + errorType + ">"; - } - yield "result<" + errorType + "> " + formatTypeRef(returnType); - } - }; + return SOURCE_TYPES.formatReturn(returnKind, returnType, resultErrorType); } private static String formatTypeRef(final PbsAst.TypeRef typeRef) { - if (typeRef == null) { - return "void"; - } - return switch (typeRef.kind()) { - case UNIT -> typeRef.name() == null || typeRef.name().isBlank() ? "void" : typeRef.name(); - case SELF -> "Self"; - case SIMPLE -> typeRef.name() == null ? "void" : typeRef.surface(); - case FN -> "Fn(" + typeRef.fields().stream().map(f -> formatTypeRef(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + formatTypeRef(typeRef.inner()); - case ARRAY -> "array<" + formatTypeRef(typeRef.inner()) + ">"; - case OPTIONAL -> "optional " + formatTypeRef(typeRef.inner()); - case GROUP -> "(" + formatTypeRef(typeRef.inner()) + ")"; - case NAMED_TUPLE -> { - final ArrayList fields = new ArrayList<>(typeRef.fields().size()); - for (final var field : typeRef.fields()) { - fields.add(field.label() + ": " + formatTypeRef(field.typeRef())); - } - yield "(" + String.join(", ", fields) + ")"; - } - case ERROR -> "unknown"; - }; + return SOURCE_TYPES.format(typeRef); } } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java index 80fba737..786ff565 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java @@ -371,7 +371,7 @@ public final class PbsEditorialSupportService { private final Model model; private final PbsFlowTypeOps typeOps = new PbsFlowTypeOps(); private final PbsFlowExpressionAnalyzer expressionAnalyzer = new PbsFlowExpressionAnalyzer(typeOps); - private final PbsInlineHintSurfaceFormatter typeFormatter; + private final PbsSourceTypeFormatter typeFormatter; private final Map topLevelSymbols; private final Map importedSymbols; private final Map supplementalSymbols; @@ -411,7 +411,7 @@ public final class PbsEditorialSupportService { modelSupplemental, feSurfaceContext == null ? FESurfaceContext.empty() : feSurfaceContext, DiagnosticSink.empty()); - this.typeFormatter = new PbsInlineHintSurfaceFormatter(model.contractTypes); + this.typeFormatter = new PbsSourceTypeFormatter(model.contractTypes); this.topLevelSymbols = buildTopLevelSymbols(); this.supplementalSymbols = buildSupplementalSymbols(); this.aliasedTypeRefs = buildAliasedTypeRefs(); @@ -1561,37 +1561,14 @@ public final class PbsEditorialSupportService { } private String formatTypeRef(final PbsAst.TypeRef typeRef) { - if (typeRef == null) { - return "unit"; - } - return switch (typeRef.kind()) { - case UNIT -> "unit"; - case SELF -> "Self"; - case SIMPLE -> typeRef.name().startsWith("$generic$") ? model.contractTypes.display(typeRef) : typeRef.surface(); - case FN -> "Fn(" + typeRef.fields().stream().map(f -> formatTypeRef(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + formatTypeRef(typeRef.inner()); - case ARRAY -> "array<" + formatTypeRef(typeRef.inner()) + ">"; - case OPTIONAL -> formatTypeRef(typeRef.inner()) + "?"; - case GROUP -> formatTypeRef(typeRef.inner()); - case NAMED_TUPLE -> { - final ArrayList fields = new ArrayList<>(typeRef.fields().size()); - for (final var field : typeRef.fields()) { - fields.add(field.label() + ": " + formatTypeRef(field.typeRef())); - } - yield "(" + String.join(", ", fields) + ")"; - } - case ERROR -> "unknown"; - }; + return typeFormatter.format(typeRef); } private String formatReturnType( final PbsAst.ReturnKind returnKind, final PbsAst.TypeRef returnType, final PbsAst.TypeRef resultErrorType) { - return switch (returnKind) { - case INFERRED_UNIT, EXPLICIT_UNIT -> "unit"; - case PLAIN -> formatTypeRef(returnType); - case RESULT -> "result<" + formatTypeRef(resultErrorType) + ", " + formatTypeRef(returnType) + ">"; - }; + return typeFormatter.formatReturn(returnKind, returnType, resultErrorType); } private TypeView resolveReceiverTypeBeforeDot( diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowBodyAnalyzer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowBodyAnalyzer.java index d175be05..524f3915 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowBodyAnalyzer.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowBodyAnalyzer.java @@ -53,7 +53,7 @@ final class PbsFlowBodyAnalyzer { inlineHintCollector = collector; try { final var model = Model.from(ast, supplementalTopDecls, feSurfaceContext, diagnostics); - collector.formatter = new PbsInlineHintSurfaceFormatter(model.contractTypes); + collector.formatter = new PbsSourceTypeFormatter(model.contractTypes); for (final var topDecl : ast.topDecls()) { validateTopDecl(topDecl, model, diagnostics); } @@ -75,7 +75,7 @@ final class PbsFlowBodyAnalyzer { private static final String TYPE_HINT_CATEGORY = "type"; private final ArrayList hints = new ArrayList<>(); - private PbsInlineHintSurfaceFormatter formatter = new PbsInlineHintSurfaceFormatter(); + private PbsSourceTypeFormatter formatter = new PbsSourceTypeFormatter(); @Override public void collect(final PbsAst.LetStatement letStatement, final TypeView inferredType) { diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsInlineHintSurfaceFormatter.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsInlineHintSurfaceFormatter.java deleted file mode 100644 index 2e498228..00000000 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsInlineHintSurfaceFormatter.java +++ /dev/null @@ -1,71 +0,0 @@ -package p.studio.compiler.pbs.semantics; - -import p.studio.compiler.pbs.semantics.PbsFlowSemanticSupport.TupleField; -import p.studio.compiler.pbs.semantics.PbsFlowSemanticSupport.TypeView; - -final class PbsInlineHintSurfaceFormatter { - private final p.studio.compiler.pbs.PbsContractTypes types; - PbsInlineHintSurfaceFormatter() { this(null); } - PbsInlineHintSurfaceFormatter(p.studio.compiler.pbs.PbsContractTypes types) { this.types = types; } - String format(final TypeView type) { - if (type == null) { - return null; - } - return switch (type.kind()) { - case UNKNOWN, ASSET_NAMESPACE -> null; - case UNIT -> "void"; - case INT, LONG, FLOAT, BOOL, STR -> type.name(); - case STRUCT, - SERVICE, - CONTRACT, - ENUM, - ERROR, - TYPE_REF, - ADDRESSABLE -> types == null || type.name() == null || !type.name().startsWith("$generic$") ? type.name() - : types.display(p.studio.compiler.pbs.ast.PbsAst.TypeRef.simple(type.name(), p.studio.compiler.source.Span.none())); - case FN -> "Fn(" + type.functionInputs().stream().map(this::format) - .collect(java.util.stream.Collectors.joining(", ")) + ") -> " + format(type.functionOutput()); - case ARRAY -> { - final var inner = format(type.inner()); - yield inner == null ? null : "array<" + inner + ">"; - } - case OPTIONAL -> { - final var inner = format(type.inner()); - yield inner == null ? null : "optional " + inner; - } - case RESULT -> { - final var errorType = format(type.errorType()); - final var payloadType = format(type.inner()); - if (errorType == null) { - yield null; - } - yield payloadType == null - ? "result<%s>".formatted(errorType) - : "result<%s> %s".formatted(errorType, payloadType); - } - case TUPLE -> formatTuple(type.tupleFields()); - }; - } - - private String formatTuple(final java.util.List fields) { - if (fields.isEmpty()) { - return "()"; - } - final var builder = new StringBuilder("("); - for (int i = 0; i < fields.size(); i++) { - if (i > 0) { - builder.append(", "); - } - final var field = fields.get(i); - final var fieldType = format(field.type()); - if (fieldType == null) { - return null; - } - builder.append(field.label()) - .append(": ") - .append(fieldType); - } - builder.append(')'); - return builder.toString(); - } -} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsSourceTypeFormatter.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsSourceTypeFormatter.java new file mode 100644 index 00000000..f1bbb3d6 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsSourceTypeFormatter.java @@ -0,0 +1,104 @@ +package p.studio.compiler.pbs.semantics; + +import p.studio.compiler.pbs.PbsContractTypes; +import p.studio.compiler.pbs.ast.PbsAst; +import p.studio.compiler.pbs.semantics.PbsFlowSemanticSupport.TypeView; +import p.studio.compiler.source.Span; +import p.studio.utilities.structures.ReadOnlyList; + +import java.util.ArrayList; + +/** Source presentation only: resolution, substitution and nominal identity stay in the model. */ +final class PbsSourceTypeFormatter { + private final PbsContractTypes types; + + PbsSourceTypeFormatter() { + this(null); + } + + PbsSourceTypeFormatter(final PbsContractTypes types) { + this.types = types; + } + + String format(final PbsAst.TypeRef type) { + // Both existing AST projections preserve groups and recursively render type arguments. + return types == null ? (type == null ? "void" : type.surface()) : types.display(type); + } + + String formatReturn(final PbsAst.ReturnKind kind, final PbsAst.TypeRef payload, final PbsAst.TypeRef error) { + if (kind == null) { + return format(payload); + } + return switch (kind) { + case INFERRED_UNIT, EXPLICIT_UNIT -> "void"; + case PLAIN -> format(payload); + case RESULT -> result(error == null ? "unknown" : format(error), payload); + }; + } + + /** Unknown semantic types suppress hints instead of manufacturing a concrete type. */ + String format(final TypeView type) { + if (type == null) { + return null; + } + if (type.kind() == PbsFlowSemanticSupport.Kind.RESULT) { + final var error = sourceType(type.errorType()); + final var payload = sourceType(type.inner()); + return error == null || payload == null ? null : result(format(error), payload); + } + final var source = sourceType(type); + return source == null ? null : format(source); + } + + private String result(final String error, final PbsAst.TypeRef payload) { + var ungrouped = payload; + while (ungrouped != null && ungrouped.kind() == PbsAst.TypeRefKind.GROUP) { + ungrouped = ungrouped.inner(); + } + final boolean empty = ungrouped == null || ungrouped.kind() == PbsAst.TypeRefKind.UNIT + || ungrouped.kind() == PbsAst.TypeRefKind.NAMED_TUPLE && ungrouped.fields().isEmpty(); + return "result<" + error + ">" + (empty ? "" : " " + format(payload)); + } + + private PbsAst.TypeRef sourceType(final TypeView type) { + if (type == null) { + return null; + } + final var span = Span.none(); + return switch (type.kind()) { + case UNKNOWN, ASSET_NAMESPACE, RESULT -> null; + case UNIT -> PbsAst.TypeRef.unit(span); + case INT, LONG, FLOAT, BOOL, STR, STRUCT, SERVICE, CONTRACT, ENUM, ERROR, TYPE_REF, ADDRESSABLE -> + type.sourceType() != null ? type.sourceType() + : type.name() == null ? null : PbsAst.TypeRef.simple(type.name(), span); + case ARRAY, OPTIONAL -> { + final var inner = sourceType(type.inner()); + yield inner == null ? null : type.kind() == PbsFlowSemanticSupport.Kind.ARRAY + ? PbsAst.TypeRef.array(inner, span) : PbsAst.TypeRef.optional(inner, span); + } + case FN -> { + final var inputs = new ArrayList(); + for (final var input : type.functionInputs()) { + final var source = sourceType(input); + if (source == null) { + yield null; + } + inputs.add(new PbsAst.NamedTypeField(null, source, span)); + } + final var output = sourceType(type.functionOutput()); + yield output == null ? null : PbsAst.TypeRef.function(ReadOnlyList.wrap(inputs), output, span); + } + case TUPLE -> { + final var fields = new ArrayList(); + for (final var field : type.tupleFields()) { + final var source = sourceType(field.type()); + if (source == null) { + yield null; + } + fields.add(new PbsAst.NamedTypeField(field.label(), source, span)); + } + yield PbsAst.TypeRef.namedTuple(ReadOnlyList.wrap(fields), span); + } + }; + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/PBSFrontendModuleCompletionTest.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/PBSFrontendModuleCompletionTest.java index e17a32bd..9ef37942 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/PBSFrontendModuleCompletionTest.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/PBSFrontendModuleCompletionTest.java @@ -3,6 +3,7 @@ package p.studio.compiler; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.Test; import p.studio.AppMode; import p.studio.compiler.messages.FrontendPhaseContext; import p.studio.compiler.models.BuildStack; @@ -26,6 +27,7 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class PBSFrontendModuleCompletionTest { @@ -33,6 +35,83 @@ class PBSFrontendModuleCompletionTest { @TempDir Path tempDir; + @Test + void sourceSignaturesPreserveReexportedOriginsAndConcreteApplications() throws IOException { + final Path root = tempDir.resolve("app"); + final Path src = root.resolve("src"); + final Path provider = src.resolve("provider/main.pbs"); + final Path facade = src.resolve("facade/main.pbs"); + Files.createDirectories(provider.getParent()); + Files.createDirectories(facade.getParent()); + final String providerText = """ + declare error Io { Failed; } + fn load(value: T, count: int) -> result T { return ok(value); } + fn find(value: optional int) -> optional int { return value; } + declare contract Reader { fn read(key: int) -> result T; } + declare struct Store() { fn read(key: int) -> result int { return ok(key); } } + """; + final String exports = "pub error Io; pub fn load(value: T, count: int) -> result T; " + + "pub fn find(value: optional int) -> optional int; pub contract Reader; pub struct Store;"; + Files.writeString(provider, providerText); + Files.writeString(provider.resolveSibling("mod.barrel"), exports); + Files.writeString(facade, "import { Io, load, find, Reader, Store } from @app:provider;"); + Files.writeString(facade.resolveSibling("mod.barrel"), exports); + final String caller = """ + import { Io as Fault, load as read, find as maybe, Reader as Policy, Store } from @app:facade; + import { stack } from @sdk:collections; + fn use(reader: Policy, store: Store, values: stack) -> result int { + let value = read(1, 2)!; + let a = reader.read(3)!; + let b = store.read(4)!; + let candidate = maybe(none); + let sdk = values.peek(); + return ok(value); + } + """; + final Path main = Files.writeString(src.resolve("main.pbs"), caller); + Files.writeString(src.resolve("mod.barrel"), "pub fn use(reader: Policy, store: Store, values: stack) -> result int;"); + final var projects = new ProjectTable(); + final var files = new FileTable(1); + final var project = projects.register(ProjectDescriptor.builder().rootPath(root).name("app").version("1.0.0") + .sourceRoots(ReadOnlyList.wrap(List.of(src))).build()); + final var ids = new java.util.HashMap(); + try (var paths = Files.walk(src)) { + for (Path file : paths.filter(Files::isRegularFile).sorted().toList()) ids.put(file, register(project, root, file, files)); + } + final var phase = new FrontendPhaseContext(projects, files, new BuildStack(ReadOnlyList.wrap(List.of(project))), AppMode.Game); + final var service = new PBSFrontendLanguageService(); + final var context = service.prepareEditorialContext(phase, ids.get(main)).orElseThrow(); + final var request = new FrontendDocumentRequest(root, main, caller); + + final int call = caller.indexOf("read(1, 2)"); + final var help = service.signatureHelp(request, context, caller.indexOf("2)!")); + assertEquals("load(value: int, count: int) -> result int", help.signatures().getFirst().label()); + assertEquals(List.of("value: int", "count: int"), help.signatures().getFirst().parameterLabels()); + assertEquals(1, help.activeParameter()); + assertEquals(help.signatures().getFirst().label(), service.hover(request, context, call + 1) + .orElseThrow().signatures().getFirst().label()); + final var definition = service.definition(request, context, call + 1).getFirst(); + assertEquals(provider.toAbsolutePath(), definition.path()); + assertEquals(providerText.indexOf("fn load"), definition.startOffset()); + assertEquals(providerText, definition.source().text()); + final var completion = service.completion(request, context, call + 2).stream() + .filter(c -> c.label().equals("read")).findFirst().orElseThrow(); + assertEquals("read(value: T, count: int) -> result T", completion.detail()); + final int fault = caller.indexOf("result") + 7; + assertEquals(provider.toAbsolutePath(), service.definition(request, context, fault).getFirst().path()); + assertEquals(0, service.definition(request, context, fault).getFirst().startOffset()); + for (String receiver : List.of("reader.read(3)", "store.read(4)")) { + final int start = caller.indexOf(receiver); + final var member = service.signatureHelp(request, context, caller.indexOf('(', start) + 1); + assertEquals("read(key: int) -> result int", member.signatures().getFirst().label()); + assertEquals(provider.toAbsolutePath(), service.definition(request, context, start + receiver.indexOf('.') + 1).getFirst().path()); + } + assertEquals("maybe(value: optional int) -> optional int", service.signatureHelp(request, context, + caller.indexOf("maybe(none)") + 6).signatures().getFirst().label()); + assertEquals("peek() -> optional int", service.signatureHelp(request, context, + caller.indexOf("values.peek()") + "values.peek(".length()).signatures().getFirst().label()); + } + @ParameterizedTest @ValueSource(strings = {"app", "zelda-1", "équipe-1"}) void moduleRefCompletionListsKnownModulesAndMemberCompletionStays(String projectName) throws IOException { diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsEditorialSourceSignatureTest.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsEditorialSourceSignatureTest.java new file mode 100644 index 00000000..0414e698 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsEditorialSourceSignatureTest.java @@ -0,0 +1,119 @@ +package p.studio.compiler.pbs.semantics; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import p.studio.compiler.pbs.ast.PbsAst; +import p.studio.compiler.pbs.lexer.PbsLexer; +import p.studio.compiler.pbs.parser.PbsParser; +import p.studio.compiler.source.Span; +import p.studio.compiler.source.diagnostics.DiagnosticSink; +import p.studio.compiler.source.identifiers.FileId; +import p.studio.utilities.structures.ReadOnlyList; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class PbsEditorialSourceSignatureTest { + private final PbsEditorialSupportService service = new PbsEditorialSupportService(); + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "int | result int", + "int | result", + "int | result (left: int, right: float)", + "optional int | optional int", + "array | void", + "Fn(optional int, array) -> optional int | Fn(int) -> (left: int, right: float)", + "(Fn(int) -> optional int) | (Fn(int) -> optional int)", + "optional (Fn(int) -> int) | optional (Fn(int) -> int)", + "(left: int, right: array) | (left: int, right: float)" + }) + void signaturesRoundTripWithTheSameTypesAcrossFourSurfaces(String input, String output) { + String declarations = "declare error Io { Failed; } "; + String source = declarations + "fn choose(input: " + input + ") -> " + output + " {} " + + "fn caller(input: " + input + ") { choose(input); }"; + var ast = parse(source); + int call = source.lastIndexOf("choose(input)"); + var signature = service.signatureHelp(source, ast, ReadOnlyList.empty(), call + 7) + .orElseThrow().signatures().getFirst(); + assertEquals("choose(input: " + input + ") -> " + output, signature.label()); + assertEquals(List.of("input: " + input), signature.parameterLabels()); + assertEquals(output, signature.returnLabel()); + assertEquals(signature.label(), service.hover(source, ast, ReadOnlyList.empty(), call + 1) + .orElseThrow().signatures().getFirst().label()); + assertEquals(signature.label(), service.completion(source, ast, ReadOnlyList.empty(), call + 2).stream() + .filter(c -> c.label().equals("choose")).findFirst().orElseThrow().detail()); + assertEquals(signature.label().substring("choose".length()), service.documentSymbols(ast).get(1).detail()); + + var original = (PbsAst.FunctionDecl) ast.topDecls().get(1); + var reparsed = (PbsAst.FunctionDecl) parse(declarations + "fn " + signature.label() + " {}").topDecls().get(1); + assertEquals(original.returnKind(), reparsed.returnKind()); + sameType(original.resultErrorType(), reparsed.resultErrorType()); + sameType(original.returnType(), reparsed.returnType()); + sameType(original.parameters().getFirst().typeRef(), reparsed.parameters().getFirst().typeRef()); + if (output.startsWith("result")) { + // A syntactically valid label must still point at the same nominal error declaration. + var originalError = service.definition(source, ast, ReadOnlyList.empty(), source.indexOf("result") + 7); + assertEquals(ast.topDecls().getFirst().span(), originalError.getFirst().span()); + } + } + + @Test + void semanticHintsShareTheSourceProjectionAndDoNotHideUnknownPayloads() { + var formatter = new PbsSourceTypeFormatter(); + var error = PbsFlowSemanticSupport.TypeView.error("Io"); + var integer = PbsFlowSemanticSupport.TypeView.intType(); + assertEquals("result", formatter.format(PbsFlowSemanticSupport.TypeView.result(error, + PbsFlowSemanticSupport.TypeView.unit()))); + assertEquals("result (left: int, right: float)", formatter.format(PbsFlowSemanticSupport.TypeView.result(error, + PbsFlowSemanticSupport.TypeView.tuple(List.of( + new PbsFlowSemanticSupport.TupleField("left", integer), + new PbsFlowSemanticSupport.TupleField("right", PbsFlowSemanticSupport.TypeView.floatType())))))); + assertEquals("Fn(optional int) -> array", formatter.format(PbsFlowSemanticSupport.TypeView.function("Fn", + List.of(PbsFlowSemanticSupport.TypeView.optional(integer)), PbsFlowSemanticSupport.TypeView.array(integer)))); + assertNull(formatter.format(PbsFlowSemanticSupport.TypeView.result(error, PbsFlowSemanticSupport.TypeView.unknown()))); + assertNull(formatter.format(PbsFlowSemanticSupport.TypeView.function("Fn", + List.of(PbsFlowSemanticSupport.TypeView.unknown()), integer))); + assertEquals("?", formatter.format(PbsAst.TypeRef.error(Span.none()))); + } + + @Test + void incompleteCallKeepsKnownSignatureWithoutInventingAType() { + String source = "fn choose(input: optional Missing) -> optional Missing {} fn caller() { choose("; + var id = new FileId(0); + var diagnostics = DiagnosticSink.empty(); + var ast = PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics); + assertTrue(diagnostics.hasErrors()); + var signature = service.signatureHelp(source, ast, ReadOnlyList.empty(), source.length()) + .orElseThrow().signatures().getFirst(); + assertEquals("choose(input: optional Missing) -> optional Missing", signature.label()); + } + + private static PbsAst.File parse(String source) { + var id = new FileId(0); + var diagnostics = DiagnosticSink.empty(); + var ast = PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics); + assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().toList().toString()); + return ast; + } + + private static void sameType(PbsAst.TypeRef expected, PbsAst.TypeRef actual) { + if (expected == null) { + assertNull(actual); + return; + } + assertNotNull(actual); + assertEquals(expected.kind(), actual.kind()); + assertEquals(expected.name(), actual.name()); + sameType(expected.inner(), actual.inner()); + assertEquals(expected.arguments().size(), actual.arguments().size()); + for (int i = 0; i < expected.arguments().size(); i++) sameType(expected.arguments().get(i), actual.arguments().get(i)); + assertEquals(expected.fields().size(), actual.fields().size()); + for (int i = 0; i < expected.fields().size(); i++) { + assertEquals(expected.fields().get(i).label(), actual.fields().get(i).label()); + sameType(expected.fields().get(i).typeRef(), actual.fields().get(i).typeRef()); + } + } +} diff --git a/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridgeTest.java b/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridgeTest.java index 301ca904..8833f28e 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridgeTest.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridgeTest.java @@ -28,6 +28,46 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class CompilerLanguageServiceBridgeTest { + @Test + void sourceReturnShapesReachTheLspMapperWithoutLosingParameters(@TempDir Path temporary) throws Exception { + final var returns = List.of("result", "result int", "result (first: int, second: float)", "optional int"); + for (int i = 0; i < returns.size(); i++) { + final Path root = Files.createDirectories(temporary.resolve("case" + i)).toRealPath(); + Files.createDirectories(root.resolve("src")); + Files.writeString(root.resolve("prometeu.json"), """ + {"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]} + """); + final String output = returns.get(i); + final String input = output.startsWith("optional") ? "optional int" : "int"; + final String text = "declare error Io { Failed; }\nfn load(left: " + input + ", right: int) -> " + output + + " {}\nfn caller() { load(1, 2); }\n"; + final Path file = Files.writeString(root.resolve("src/main.pbs"), text); + Files.writeString(root.resolve("src/mod.barrel"), "pub error Io; pub fn load(left: " + input + + ", right: int) -> " + output + "; pub fn caller() -> void;"); + final String expected = "load(left: " + input + ", right: int) -> " + output; + final var bridge = new CompilerLanguageServiceBridge(); + final var context = new LspProjectContext("app", "pbs", root); + final String uri = file.toUri().toString(); + final var mapper = new DocumentPositionMapper(text); + final var argument = mapper.positionOf(text.indexOf("2);")); + final var help = bridge.signatureHelp(context, uri, text, argument.line(), argument.character()); + assertEquals(1, help.activeParameter()); + assertEquals(expected, help.signatures().getFirst().label()); + assertEquals(List.of("left: " + input, "right: int"), help.signatures().getFirst().parameters()); + final var protocol = new p.studio.lsp.services.protocol.mapping.Lsp4jProtocolMessageMapper().mapSignatureHelp(help); + assertEquals(1, protocol.getActiveParameter()); + assertEquals(expected, protocol.getSignatures().getFirst().getLabel()); + assertEquals(help.signatures().getFirst().parameters(), protocol.getSignatures().getFirst().getParameters() + .stream().map(p -> p.getLabel().getLeft()).toList()); + final var use = mapper.positionOf(text.indexOf("load(1")); + assertTrue(bridge.hover(context, uri, text, use.line(), use.character()).markdown().contains(expected)); + assertEquals(expected, bridge.completion(context, uri, text, use.line(), use.character()).items().stream() + .filter(c -> c.label().equals("load")).findFirst().orElseThrow().detail()); + assertEquals(expected.substring("load".length()), bridge.documentSymbols(context, uri, text).symbols().stream() + .filter(s -> s.name().equals("load")).findFirst().orElseThrow().detail()); + } + } + @Test void genericStructsAndFreeFunctionsExposeConcreteSourceSignatures(@TempDir Path root) throws Exception { Files.createDirectories(root.resolve("src")); Files.writeString(root.resolve("prometeu.json"), """