From 76a8b074e89e17c7425220888eeec38427261d46 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Thu, 22 Oct 2026 14:42:38 +0100 Subject: [PATCH] feat(pbs): add concrete generic structs and free functions --- ...t-random-handles-and-source-conformance.md | 16 +- .../evidence.json | 8 +- ...-0089-concrete-generic-state-and-bodies.md | 202 ++++++ .../evidence.json | 185 +++++ .../first-class-functions-and-captures.md | 6 + docs/compiler/pbs/specs/generic-contracts.md | 4 +- .../generic-structs-and-free-functions.md | 271 +++++++ .../pbs/specs/runtime-random-integration.md | 8 +- .../typed-arrays-and-optional-execution.md | 5 + .../pbs/11. AST Specification.md | 7 + .../pbs/12. Diagnostics Specification.md | 7 + .../13. Lowering IRBackend Specification.md | 7 + .../pbs/3. Core Syntax Specification.md | 21 +- .../pbs/4. Static Semantics Specification.md | 7 + ...tdlib, and SDK Resolution Specification.md | 7 + .../app/compiler/InstalledKnowledgeProbe.java | 2 + .../backend/irvm/PbsGenericStructsTest.java | 211 ++++++ .../backend/irvm/PbsRuntimeRandomTest.java | 35 +- .../studio/compiler/pbs/PbsContractTypes.java | 40 +- .../compiler/pbs/PbsFrontendCompiler.java | 21 +- .../compiler/pbs/PbsGenericCoherence.java | 120 +++ .../compiler/pbs/PbsGenericDiagnostics.java | 55 ++ .../compiler/pbs/PbsGenericInstantiation.java | 685 ++++++++++++++++++ .../pbs/PbsGenericTemplateValidator.java | 288 ++++++++ .../compiler/pbs/PbsInstantiationBudget.java | 39 + .../p/studio/compiler/pbs/ast/PbsAst.java | 56 +- .../compiler/pbs/ast/PbsAstRewriter.java | 113 +++ .../compiler/pbs/ast/PbsTypeTraversal.java | 3 +- .../linking/PbsModuleVisibilityValidator.java | 62 +- .../pbs/lowering/PbsRuntimeTypes.java | 12 +- .../compiler/pbs/parser/PbsBarrelParser.java | 7 +- .../pbs/parser/PbsDeclarationParser.java | 10 +- .../pbs/parser/PbsExprPrimaryParser.java | 43 +- .../compiler/pbs/parser/PbsTokenCursor.java | 12 + .../pbs/semantics/PbsAstDocumentSymbols.java | 9 +- .../PbsCtorInitializationAnalyzer.java | 144 ++++ .../PbsDeclarationSemanticsValidator.java | 37 +- .../semantics/PbsEditorialSupportService.java | 118 ++- .../pbs/semantics/PbsFlowBodyAnalyzer.java | 7 +- .../semantics/PbsFlowStatementAnalyzer.java | 8 +- .../PbsInlineHintSurfaceFormatter.java | 6 +- .../services/PBSFrontendPhaseService.java | 13 +- .../services/PbsGenericProgramService.java | 52 ++ .../PbsImportedSemanticContextService.java | 13 +- .../examples/game/1/src/generics.pbs | 21 + .../examples/game/1/src/mod.barrel | 1 + .../compiler/pbs/PbsGenericStructsTest.java | 203 ++++++ .../PbsGenericStructsEditorialTest.java | 61 ++ .../CompilerLanguageServiceBridge.java | 3 +- .../CompilerLanguageServiceBridgeTest.java | 26 + tools/pbx-conformance/main.rs | 88 ++- tools/pbx-conformance/run.py | 3 +- 52 files changed, 3285 insertions(+), 103 deletions(-) create mode 100644 discussion/lessons/DSC-0094-pbs-generic-structs/LSN-0089-concrete-generic-state-and-bodies.md create mode 100644 discussion/lessons/DSC-0094-pbs-generic-structs/evidence.json create mode 100644 docs/compiler/pbs/specs/generic-structs-and-free-functions.md create mode 100644 prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericStructsTest.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericCoherence.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericDiagnostics.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericInstantiation.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericTemplateValidator.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsInstantiationBudget.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAstRewriter.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsCtorInitializationAnalyzer.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsGenericProgramService.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/generics.pbs create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsGenericStructsTest.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsGenericStructsEditorialTest.java diff --git a/discussion/lessons/DSC-0082-pbs-runtime-random-integration/LSN-0086-explicit-random-handles-and-source-conformance.md b/discussion/lessons/DSC-0082-pbs-runtime-random-integration/LSN-0086-explicit-random-handles-and-source-conformance.md index 91f3809e..cf57271b 100644 --- a/discussion/lessons/DSC-0082-pbs-runtime-random-integration/LSN-0086-explicit-random-handles-and-source-conformance.md +++ b/discussion/lessons/DSC-0082-pbs-runtime-random-integration/LSN-0086-explicit-random-handles-and-source-conformance.md @@ -82,9 +82,12 @@ it does not replace or introduce a lifecycle feature. The 48 provider oracle rows cover six seeds and eight draws. Projecting both integer and Float outputs, with optimization off/on, produces 192 fixtures. -Another 34 paired fixtures cover aliases, independent objects, mixed/discarded -operations, named/positional effects, storage/captures, limits, faults and GC. -Together with real imports this is **227 mandatory fixtures per runtime profile**. +Another 30 source fixtures cover aliases, independent objects, mixed/discarded +operations, named/positional effects, storage/captures, limits, faults and GC. Four +controlled provider fixtures cover null and typed-null carriers. Together with real +imports this is **223 source fixtures plus four controlled provider fixtures**. +The DEC-0073 follow-up requalified this revised corpus in the dev profile; the +original debug/release evidence below describes the earlier source corpus. Each of the 226 callable fixtures executes with single-step budgets and twice with full budgets to compare exact bits/faults, call charges and total cycles. The runner checks oracle byte equality against the selected runtime. @@ -95,8 +98,11 @@ Random objects are reclaimed, array, field and closure roots still draw the expected shared sequence. The source corpus also exercises a genuine rejected PCG word followed by acceptance, charging range 20 cycles. -PBS has no public null or Dynamic type. A source struct constructor that leaves -a Random field at its runtime default provides a null reference for tests. +PBS has no public null or Dynamic type. Following the explicit DEC-0073 +clarification, every completing constructor path initializes every field. Null +coverage uses a controlled provider fixture: compile a fully initialized Random +field, then suppress its unique field store in test bytecode to exercise the provider +reference default. Storing it in a typed array preserves a present Dynamic tag and exact TypeId; extracting it then drawing traps NULL_REFERENCE. This must not be confused with an empty array slot. Existing global-initializer restrictions are unchanged. diff --git a/discussion/lessons/DSC-0082-pbs-runtime-random-integration/evidence.json b/discussion/lessons/DSC-0082-pbs-runtime-random-integration/evidence.json index 6dce4fcc..745d5d5a 100644 --- a/discussion/lessons/DSC-0082-pbs-runtime-random-integration/evidence.json +++ b/discussion/lessons/DSC-0082-pbs-runtime-random-integration/evidence.json @@ -104,5 +104,11 @@ "macOS arm64 only", "Reference-game and installed-runtime process qualification excluded", "Existing explicit provider schema gaps LifecycleRole and NonFiniteValue retained" - ] + ], + "follow_up_2026_10_22": { + "discussion": "DSC-0094", + "scope": "Explicitly authorized complete PBS constructor field initialization; revise null fixtures to controlled provider injection", + "qualification": "227 Random fixtures passed on macOS arm64 dev; prior release evidence describes the original corpus", + "evidence": "../DSC-0094-pbs-generic-structs/evidence.json" + } } diff --git a/discussion/lessons/DSC-0094-pbs-generic-structs/LSN-0089-concrete-generic-state-and-bodies.md b/discussion/lessons/DSC-0094-pbs-generic-structs/LSN-0089-concrete-generic-state-and-bodies.md new file mode 100644 index 00000000..67f699da --- /dev/null +++ b/discussion/lessons/DSC-0094-pbs-generic-structs/LSN-0089-concrete-generic-state-and-bodies.md @@ -0,0 +1,202 @@ +--- +id: LSN-0089 +ticket: pbs-generic-structs +title: Concrete Generic State and Bodies in PBS +created: 2026-10-22 +tags: [compiler-pbs, generic-structs, generic-functions, nominal-identity, runtime-conformance] +--- + +## Original problem and final result + +Owner: `compiler/pbs`. Studio/LSP receives source projections; the common backend +and runtime continue to execute concrete types and functions. DSC-0094 implemented +accepted DEC-0073 through PLN-0152, covering requirements R1–R14. The disposable +workflow artifacts are removed by housekeeping; specifications remain normative. + +Generic contracts could describe a strategy but could not provide parameterized +state or algorithms. PBS now supports generic structs, owner-dependent methods +and constructors, restricted owner-bound implementations, and named generic free +functions with explicit arguments. SDK and project code use the same frontend +mechanism. No runtime source, opcode, descriptor category or PBX format changed. + +```pbs +declare struct Box(value: T) { + ctor make(value: T) { this.value = value; } + fn get() -> T { return this.value; } +} +declare contract Reader { fn read() -> T; } +implements Reader for Box using box { + fn read() -> T { return box.get(); } +} +fn read(reader: Reader) -> T { return reader.read(); } +fn example() -> int { + let box = new Box.make(42); + let reader: Reader = box; + let invoke: Fn(Reader) -> int = read; + return invoke(reader); +} +``` + +The combined program executes through production PBX and the provider VM. A +separate multi-module variant uses aliases, reexports and private definition-side +helpers while preserving the result 42. + +## Decisions that shape the implementation + +Application identity is source nominal origin plus ordered canonical logical +arguments. It is independent of layout width and presentation. Two homonymous +Enemy declarations must yield distinct Box types; two aliases of the same +declaration share one application. Phantom arguments also remain significant. +Function applications preserve their declaration and argument identity even when +several targets share a compatible structural Fn descriptor. + +Definition scope and argument scope are separate. A parameter is bound by its +declaration/binder and position. Resolve the caller's arguments before constructing +the callee's substitution environment. Private helpers remain in their definition +module. Generated imports connect concrete instances without publishing helpers +as source exports. Explicit barrels retain the template and its ordered parameters. + +Explicit struct construction provides its own arguments. Diamond and omission +require an existing expected application; values do not infer T. Generic functions +always require explicit arguments, including when converted to Fn. Explicit +applications filter generic overloads by type arity; ordinary calls use ordinary +overloads. Renaming binders alone does not create a new overload. + +Concrete specialization increases frontend work and potentially image size, but +reuses the established runtime value model. It avoids requiring a Dynamic generic +argument ABI or adapter objects. Existing Array packing still follows Array rules. +No performance or byte-for-byte image equivalence is promised. + +## Checking and materializing the graph + +`PbsGenericInstantiation` owns the interacting concrete graph. Shared +`PbsContractTypes`, `PbsInstantiationBudget` and application provenance support +contracts, structs and functions. Register anchors before traversing dependencies: +revisiting the same application closes a finite graph, whereas requesting new +applications indefinitely produces a bounded expansion diagnostic. + +The current frontend budget bounds depth at 256, instances at 65,536, work at +1,048,576 visits and accounted specialization storage at 64 MiB. These analysis +ceilings do not enlarge provider admission or execution limits. + +Validation has two distinct purposes. Symbolic capability checking prevents T +from gaining arithmetic, comparison, members or construction from a chosen concrete +argument. Opaque nominal witnesses also run unused template bodies through the +ordinary declaration and flow validators, catching ordinary errors such as wrong +returns and incomplete constructors. Dependency shapes provide their declared +capabilities without recursively executing every unused template family. + +Each required concrete owner then validates fields, constructors and every method, +including uncalled methods. Substitute entire bodies, annotations, nested calls, +constructions, lambdas and captures. Revalidate positions after substitution: +Box can have a T field, but array cannot accept that substitution. +Reject overloads that collapse after substitution; never prefer an int overload +over set(T) merely because T became int. + +Owner-bound implementation rules bind every parameter through distinct direct +owner arguments. Symbolic unification detects generic/generic, generic/closed and +closed/closed overlap before any conflicting application is requested. A closed +rule has no priority over a family. Implementations remain exact and module-owned; +their methods do not enter the struct's direct method namespace. + +Specialized free-function references use ordinary Closure values with empty +environments. Lambdas inside specialized bodies keep explicit snapshot captures +and complete logical groups. Struct values retain reference identity; assignment +does not copy their state. + +## Constructor initialization and Random + +Implementation exposed a conflict: the static semantics required every field +initialized on each completing constructor path, while Random fixtures used an +empty constructor to obtain the provider's null reference default. The user +explicitly chose complete initialization and authorized revising Random's spec +and fixtures. This clarification applies to ordinary and generic structs. + +The flow check intersects assignments across branches and accounts for loop exits +and short-circuit logical operands. +An assignment in a loop that might run zero times is insufficient. Deferred lambda +bodies do not initialize the enclosing constructor's fields. A constructor that +cannot complete has no completing path to check. + +Valid Random source fixtures now initialize their fields explicitly. Four null +and typed-null checks remain controlled provider fixtures: compile valid source, +suppress the unique named-constructor field store in test bytecode, then run the +production verifier/VM. Runtime field defaults, typed Array presence and null +faults are still tested without making incomplete PBS constructors legal. + +## Editor and diagnostic projections + +Keep original declarations and spans alongside the specialized semantic projection. +Navigation and references distinguish symbolic parameters, concrete arguments and +generic origins. Concrete hover/completion/signature help use the applied type; +template bodies retain symbolic field and method presentation. Source formatting, +document/workspace symbols, rename references, inline hints and semantic overlays +continue through the existing frontend/LSP surfaces. + +Pass the current application into declaration and flow diagnostics. Merely replacing +generated names at file scope is insufficient: field-position errors also need +related spans for the original definition and requesting use. Display a short +source chain and canonical application names rather than internal identities. + +## Qualification and requirement coverage + +The final reports contain 1,004 general tests, zero failures/errors and 13 existing +skips, plus two passing installed-knowledge tests. The complete Gradle regression +passed; final affected gates were repeated after improving diagnostic provenance +and finalizing installed spec references. One earlier external-source LSP failure +passed in isolation and in the complete repetition; no unrelated LSP code changed. + +Production qualification used runtime revision +`f7d7c167531bb662a1af9d73fc326bb476bf8aa7`, Rust 1.98.1, macOS arm64, dev profile, +`resource-diagnostics`, default limits and `NONE` capabilities, with explicitly +lowered quota cases. All 16 mandatory generic fixtures passed. The full existing +PBX harness also passed, including 227 Random cases. This evidence does not qualify +another platform, a release runtime profile or the reference game. + +| Requirements | Final evidence | +| --- | --- | +| R1–R2 | Exact arguments, origin/phantom/reference identity, contextual and named construction, complete initialization | +| R3–R5 | Composed multi-slot storage, symbolic capability errors, complete bodies, unused-method and overload failures | +| R6–R7 | Restricted coherent owner rules, overlap before use, anchored recursion and bounded expanding bodies | +| R8 | Production concrete Registry/PBX/VM, implementation zero, retained captures through GC and quota refusals | +| R9–R10 | Explicit free functions, concrete Fn/empty closures, nested captures and ordinary apply | +| R11–R12 | Homonymous binders/origins, definition-side helpers, aliases/reexports, barrels, duplicates and comparisons | +| R13 | Symbolic/concrete navigation and editor tests; diagnostic definition/use spans and readable applications | +| R14 | Shared infrastructure, isolated/combined modules, installed example/specs and complete regressions | + +The 16 fixtures cover basic/manual objects, constructors/Self, phantom applications, +tuple, optional, Array, nominal recursion, combined dispatch, generic/manual Fn, +GC, imports/reexports, installed example, multiple parameters and homonymous origins. +Specialized and handwritten object/Fn fixtures execute under a one-handle limit +and use equal guest heap resources. All observed resources return to zero after +VM disposal. Refused allocation publishes no partial object. Full fixture sizes, +type/implementation counts, hashes, commands and log fingerprints are retained in +[evidence.json](evidence.json). + +## Pitfalls and subsequent work + +- Checking only requested templates or called methods changes source acceptance. +- Rewriting only signatures loses local annotations, construction contexts and captures. +- Using simple names or physical slots as identity merges distinct applications. +- Resolving private helpers at the caller makes imports change template meaning. +- Choosing a closed implementation over a family hides an incoherent program. +- Treating a provider's reference default as a PBS constructor exemption creates + incompatible source rules. +- Maintaining normative chapters in both `docs/specs/compiler-languages/pbs` and + `docs/compiler/pbs/specs` permits contradictions. The canonical owner is the + latter; existing distribution still merges both roots. Consolidating the legacy + chapters and their links/build inputs remains a separate repository migration. + +The next collection discussion is List (DSC-0090 / AGD-0092). Its API, iteration, +logical bounds and private slot-transfer decisions remain open. Completing this +language prerequisite does not approve those collection proposals. + +## References + +- [Generic structs and free functions](../../../docs/compiler/pbs/specs/generic-structs-and-free-functions.md). +- [Generic contracts](../../../docs/compiler/pbs/specs/generic-contracts.md). +- [Arrays and optional](../../../docs/compiler/pbs/specs/typed-arrays-and-optional-execution.md). +- [Functions and captures](../../../docs/compiler/pbs/specs/first-class-functions-and-captures.md). +- [Random integration](../../../docs/compiler/pbs/specs/runtime-random-integration.md). +- [Concrete common Registry/PBX](../../../docs/compiler/general/specs/typed-registry-and-pbx-v0.md). +- Historical execution plan: PLN-0152, completed and removed by discussion housekeeping. diff --git a/discussion/lessons/DSC-0094-pbs-generic-structs/evidence.json b/discussion/lessons/DSC-0094-pbs-generic-structs/evidence.json new file mode 100644 index 00000000..1932e93c --- /dev/null +++ b/discussion/lessons/DSC-0094-pbs-generic-structs/evidence.json @@ -0,0 +1,185 @@ +{ + "date": "2026-10-22", + "owner": "compiler/pbs", + "discussion": "DSC-0094", + "decision": "DEC-0073", + "plan": "PLN-0152", + "runtime_revision": "f7d7c167531bb662a1af9d73fc326bb476bf8aa7", + "runtime_profile": "dev", + "runtime_features": [ + "resource-diagnostics" + ], + "runtime_limits": "default; explicit lower GuestBytes/HandleSlots refusal cases", + "capabilities": "NONE", + "platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O", + "rustc": "rustc 1.98.1 (48a229cea 2026-09-01)", + "java_tests": { + "test": { + "tests": 1004, + "failures": 0, + "errors": 0, + "skipped": 13 + }, + "installedKnowledgeTest": { + "tests": 2, + "failures": 0, + "errors": 0, + "skipped": 0 + } + }, + "generic_fixtures": [ + { + "name": "basic", + "types": 3, + "implementations": 0, + "bytes": 1278, + "sha256": "c6b72687525737aa6626ca5cea47e11498d68df0c6463ab04293062915d80409" + }, + { + "name": "manual", + "types": 3, + "implementations": 0, + "bytes": 1216, + "sha256": "485c560ef569d07e46f2ce90a4b9814f68fc59a76b3a274e9f023985091fcd38" + }, + { + "name": "constructor", + "types": 3, + "implementations": 0, + "bytes": 1329, + "sha256": "9274c106cba055f608e400a3fb033522e9a1e4d485cba85583ad813ddffc54e3" + }, + { + "name": "phantom", + "types": 4, + "implementations": 0, + "bytes": 1094, + "sha256": "ccc6e25213c69e5b6c9c9b0089304d8d168584d5779f5f43e6289f9bf6d67b9f" + }, + { + "name": "tuple", + "types": 4, + "implementations": 0, + "bytes": 2244, + "sha256": "7ee8ffb76df45de6a8824aa2b871763d47fd264e6024f5f6c89f6b1fded865cd" + }, + { + "name": "optional", + "types": 5, + "implementations": 0, + "bytes": 1708, + "sha256": "bd662f86db9f53f882dd74c7728d0f48f98d25b3bbf5cc70111ed1472d6de81f" + }, + { + "name": "array", + "types": 8, + "implementations": 0, + "bytes": 2186, + "sha256": "e5f1815ddca28177bba0af27297b25c039ffcde1402d374dd858c8f59dbe5c9e" + }, + { + "name": "recursive", + "types": 5, + "implementations": 0, + "bytes": 1116, + "sha256": "0527985e60ab6a41f94122b7f88d62e4ffd237f887b0af23c01886f4a818658c" + }, + { + "name": "combined", + "types": 5, + "implementations": 1, + "bytes": 1935, + "sha256": "2d5b9c9a501a66b951a7708523a3c0f02cba9d9f2fd3fcd7444b8359a701d63b" + }, + { + "name": "function", + "types": 3, + "implementations": 0, + "bytes": 806, + "sha256": "32b80c1dc6be78db679d31bb0393362afca01354727aa8ba81dc8f92de6e2280" + }, + { + "name": "function-manual", + "types": 3, + "implementations": 0, + "bytes": 773, + "sha256": "60f8fe92f39e0b5b531cdfefd1cee9d40377253fb6d7db80202ebf4b5becadf3" + }, + { + "name": "gc", + "types": 6, + "implementations": 0, + "bytes": 2169, + "sha256": "9f292f40c4bfb6a6c6f734130d877abf2ce809da1665dd54bbb352d328aaa59e" + }, + { + "name": "imports", + "types": 4, + "implementations": 1, + "bytes": 2493, + "sha256": "3ac928d8feebed5414aebe595c90ce08062903c0e5a9e198ba6365dc0f88c55e" + }, + { + "name": "installed", + "types": 5, + "implementations": 1, + "bytes": 2142, + "sha256": "41af3aaeca0c39267543af3e79bc5f40b0846f66f448aa74afd2adcade3039b1" + }, + { + "name": "multiple", + "types": 3, + "implementations": 0, + "bytes": 1305, + "sha256": "a59365588676083b8d9e078f869828067ed48f881252da4ad5b904f800f7d2b9" + }, + { + "name": "origins", + "types": 5, + "implementations": 0, + "bytes": 2484, + "sha256": "ed3fcfdcab2aabe98ae525c67c688e3d7bec7bc757bb127b82ee652b4322ecb6" + } + ], + "generic_fixtures_passed": 16, + "random_fixtures_passed": 227, + "source_fingerprints": { + "tools/pbx-conformance/main.rs": "322a772b4353c90d6acc54f90a0136eef544f92dd7434c7244762abb0125553e", + "tools/pbx-conformance/run.py": "7d4817b40371847c3debe1524f253354ca919cbda986349770647c3841a3eedb", + "prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericStructsTest.java": "a2ecc312075009e052994a47cf7b52037ef545882865991adbcb328a5a27a665", + "prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java": "ba0b3de2e0aa7177fa71b5a837a56bc262a080717df3276c3a73b67b33dcb384", + "docs/compiler/pbs/specs/generic-structs-and-free-functions.md": "517cf07f7543a6ab261b1fdd177985b047b62fdb624bda40a63f61e28fa11263", + "prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericInstantiation.java": "4047b14f11aca83b62c5247233a941502cdedb462c887ec6032d2d0c5e308ee5", + "prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsCtorInitializationAnalyzer.java": "5a4a134324b2effce4c9e8ed66d1025e393c0fe61959190586d7ea103ad06f47", + "prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsGenericStructsTest.java": "dc21746271b26bf0c7af191eeae70b1308dc322bedbdd0e3bcceda7c734bf14a" + }, + "provider_fingerprints": { + "Cargo.lock": "cffad9ed62f38a591538abd81dd39270d6022397342c8189f4ac6c7baaa8e795", + "docs/vm-arch/INTRINSICS.csv": "0c1bb78a9b81d1e3480ef5713f3d70f0b06772a7dfab2fd00c1f0a6364f98daa", + "docs/vm-arch/BUILTIN_CONSTANTS.csv": "e407e4718127aa7ef7b1097b5b4b67d86dd979235e73a551a7c36b628cddc039", + "crates/console/prometeu-vm/tests/fixtures/numeric-conformance.tsv": "5536ee18cadaf32e3719b0e8d541dfcf1a84a49ea978a702101547c5ccdee3fe", + "crates/console/prometeu-vm/tests/fixtures/random-conformance.tsv": "0bee1cd0366f1716687aee8c7ac39dd495da5fe2908cce37b1443cb04fac542f" + }, + "commands": [ + "./gradlew test :prometeu-app:installedKnowledgeTest --console=plain --continue", + "./gradlew :prometeu-compiler:frontends:prometeu-frontend-pbs:test :prometeu-architecture-tests:test :prometeu-lsp:prometeu-lsp-v1:test :prometeu-app:installedKnowledgeTest --console=plain", + "python3 tools/pbx-conformance/run.py --runtime ../runtime", + "discussion validate", + "git diff --check", + "./gradlew :prometeu-compiler:frontends:prometeu-frontend-pbs:test :prometeu-architecture-tests:test --console=plain" + ], + "logs": { + "dec73-regression-final.log": "2a90cbace3db898da9b445aba9c21be2b4f0c3d22724e1763fc9a0f3e52e7947", + "dec73-vm-regression.log": "159c6e0928a7d69aecb8660221135c1fa166e8e59212c5a3778883796170ea7e", + "dec73-final-provenance.log": "84168ed25ad52a98fbc3de7e0574d2bbbe1ba57cba47c066f09c26e0173d17b9", + "dec73-final-ctor-branches.log": "f32a83cf9084e4def4c1f12c2d3cce43b2254e217d57b9076f1707338afda3a9" + }, + "notes": [ + "One initial external-source LSP failure passed in isolated reproduction and complete regression repetition; no unrelated LSP code changed.", + "Final affected suite repeats include the declaration/use provenance correction and final installed spec cross-references.", + "Null and typed-null Random cases are controlled provider bytecode fixtures; ordinary and generic PBS constructors require complete field initialization.", + "Existing LifecycleRole and NonFiniteValue provider schema gaps remain reported by the common harness.", + "Qualification is local macOS arm64 dev profile, not another platform, release profile or reference-game qualification.", + "Final constructor analysis includes symbolic and/or short-circuit branches; frontend and architecture passed. All 16 regenerated artifact hashes match the production-VM-qualified PBX files." + ] +} diff --git a/docs/compiler/pbs/specs/first-class-functions-and-captures.md b/docs/compiler/pbs/specs/first-class-functions-and-captures.md index 86467e64..c993562d 100644 --- a/docs/compiler/pbs/specs/first-class-functions-and-captures.md +++ b/docs/compiler/pbs/specs/first-class-functions-and-captures.md @@ -81,3 +81,9 @@ See [Runtime Random integration](runtime-random-integration.md) for opaque gener ## Parameterized contract integration [Generic contracts](generic-contracts.md) extend nominal contract declarations with explicit type arguments. Valid Array/Fn/optional/tuple compositions preserve their existing logical and physical rules after substitution. No generic-only Dynamic transport, view wrapper, altered resource limit or new runtime opcode is introduced. + +[Generic structs and free functions](generic-structs-and-free-functions.md) extend +that concrete model to state and bodies. A closed free-function application such +as `identity` supplies an ordinary concrete Fn through an empty-environment +Closure. Lambdas inside specialized bodies preserve explicit captures and complete +logical value groups. The open template never becomes a polymorphic Fn value. diff --git a/docs/compiler/pbs/specs/generic-contracts.md b/docs/compiler/pbs/specs/generic-contracts.md index 79998202..e6c28e6c 100644 --- a/docs/compiler/pbs/specs/generic-contracts.md +++ b/docs/compiler/pbs/specs/generic-contracts.md @@ -17,7 +17,7 @@ declare contract Converter { A parameterized declaration has one or more distinct ordered type parameters. Their scope is the contract's signatures, including nested type references. A type parameter is not the receiver. `Self` retains its existing meaning and validity restrictions. -Applications supply explicit ordered type arguments with exact arity: `Identity` and `Converter`. The declaration's raw name, omitted arguments, `<>`, default arguments and blanket generic implementations are not value types or inference mechanisms. Nonparameterized contracts remain valid. +Applications supply explicit ordered type arguments with exact arity: `Identity` and `Converter`. The declaration's raw name, omitted arguments, `<>`, default arguments and blanket generic implementations are not value types or inference mechanisms. Nonparameterized contracts remain valid. [Generic structs and free functions](generic-structs-and-free-functions.md) add restricted owner-bound implementation families; they do not introduce blanket implementations for arbitrary owners. The same compositional type grammar applies in annotations, nested applications, implementation targets and expression-form `as`. Existing contextual angle closers and expression comparisons retain their meanings. A barrel exports the declaration, for example `pub contract Identity;`, preserving its origin and ordered parameters rather than exporting a particular application. @@ -71,4 +71,4 @@ Navigation reaches generic declarations, parameters and argument declarations. H Compile real PBS through typed IR and production PBX into the production loader, verifier and VM. Cover multiple parameters/applications, several applications on one owner, imports/aliases/reexports, nominal origin, phantom arguments, composed and multi-slot payloads, finite recursion, expanding recursion rejection, service/struct views, typed absence, implementation zero, GC and resource refusal. -A specialized contract and a manually written concrete equivalent must exhibit the same behavior without generic-only adaptation/boxing. Identical image bytes and a performance improvement are not required. Installed knowledge packages this specification and a runnable source example. Generic structs/functions, bounds, variance, inheritance/default methods, generic reflection, runtime instantiation and collection algorithms are outside this extension. +A specialized contract and a manually written concrete equivalent must exhibit the same behavior without generic-only adaptation/boxing. Identical image bytes and a performance improvement are not required. Installed knowledge packages this specification and a runnable source example. Generic structs/functions are defined by the separate [owner specification](generic-structs-and-free-functions.md), sharing canonical identities, provenance and bounded expansion with contracts. Bounds, variance, inheritance/default methods, generic reflection, runtime instantiation and collection algorithms remain outside these extensions. diff --git a/docs/compiler/pbs/specs/generic-structs-and-free-functions.md b/docs/compiler/pbs/specs/generic-structs-and-free-functions.md new file mode 100644 index 00000000..791ea283 --- /dev/null +++ b/docs/compiler/pbs/specs/generic-structs-and-free-functions.md @@ -0,0 +1,271 @@ +# Concrete Generic Structs and Free Functions + +Owner: `compiler/pbs`. This specification adds parameterized state and executable +bodies to the nominal, concrete application model of generic contracts. It applies +uniformly to SDK modules and program sources. Registry, PBX, VM admission, resource +limits and instruction semantics remain governed by the existing provider contracts. + +## Declarations and identity + +Structs and module-level named free functions may declare one or more distinct, +ordered type parameters. Applications have exact arity. Type parameters have +identity by declaration or binder and ordinal position; their spelling is lexical +presentation, not a globally substitutable symbol. + +```pbs +declare struct Box(value: T) { + fn get() -> T { return this.value; } + fn set(value: T) { this.value = value; } +} +declare struct Pair(key: K, value: V); +fn identity(value: T) -> T { return value; } +``` + +An application is identified by its nominal source declaration and ordered, +canonical logical arguments after alias resolution. Aliases and reexports of the +same declaration share applications. Homonymous declarations from different +origins, phantom arguments and logically different types remain distinct even +when fields, signatures or physical carriers coincide. Applications are invariant; +numeric or reference conversions between arguments do not convert their containers. +Struct assignment shares the existing object reference and does not deep-copy it. + +The raw name of a parameterized struct is not a closed type, including inside its +own declaration. Open parameters exist only in the authorized declaration scopes +and must not reach executable metadata. + +## Construction and expected types + +```pbs +let a = new Box(42); +let b: Box = new Box<>(42); +let c: Box = new Box(42); +``` + +Explicit construction supplies its application. Diamond and omitted arguments +require a sufficient, compatible expected application at the existing contextual +Array positions: annotated bindings, assignments, resolved callable parameters, +returns and value expressions with an expected type. Values do not infer type +arguments: `let d = new Box(42);` is invalid. There is no partial inference, default +argument or additional overload search to discover generic arguments. + +Named constructors use the applied owner, for example `new Box.make(42)`. +Substitution preserves existing constructor selection, evaluation order, definite +field initialization, visibility, `this` and completion rules. A parameter has no +implicit constructor or universal default; `new T()` is invalid. + +Every completing constructor path MUST explicitly assign every field, in ordinary +and generic structs, including fields of opaque builtin type Random. Assignment +in only one conditional branch or in a loop that may execute zero times is +insufficient. Runtime reference defaults are provider behavior and do not exempt +PBS constructors from this rule. Controlled null-provider fixtures are described +in [Runtime Random integration](runtime-random-integration.md). + +## Composition and symbolic capabilities + +Arguments and substituted uses compose with valid builtins, nominal values, +applied structs/contracts, Array, Fn, optional, tuples and existing return/result +positions. Each position retains its existing restrictions. Normalize logical +types before deriving physical groups, preserving labels, names, order and every +slot of a multi-slot value. + +Array's element restriction is not a global generic restriction. A T field can +hold `Box`; a field declared `array` makes the application with +T=optional int invalid. Revalidate all concrete positions after substitution. + +Templates are validated symbolically before relying on concrete arguments. An +unconstrained T can be stored, assigned compatibly, passed and returned. It gains +no arithmetic, comparison, members or construction from a particular application. +`value + value` on T is invalid even when the only requested application uses int. +Known operations of declared containers remain available; indexing array, for +example, produces optional T. Additional capabilities require explicit composition: + +```pbs +declare struct ComparedBox(value: T, identity: Identity) { + fn matches(other: T) -> bool { + return this.identity.equals(this.value, other); + } +} +``` + +This does not introduce bounds, implicit equality/hash or opportunistic member +lookup on an argument. + +## Complete substitution, validation and Self + +Substitute fields, constructor/method signatures and complete bodies, including +local annotations, nested applications and constructions, references/calls, +lambdas and capture environments. Rewriting signatures alone is insufficient. +Ordinary methods use their owner's type parameters; they do not declare another +generic parameter list. + +Self denotes the complete applied owner in its existing valid locations. It means +Box inside that application and Box inside the other. Header fields +must still spell recursive types explicitly, such as `optional Node`; the +feature does not expand Self's valid locations. Existing privacy, pub/pub mut, +receiver and direct-versus-contract method rules remain unchanged. + +For every required owner application, validate its fields, constructors and all +methods, including uncalled methods. Dead-code elimination must not change source +acceptance. Method/constructor identities include their source declaration, +applied owner and existing signature identity. Distinct overloads that collapse +after substitution reject the application and identify both declarations. In +particular, set(T) and set(int) collide at T=int without an implicit preference. + +## Owner-bound implementations and coherence + +```pbs +declare contract Reader { fn read() -> T; } +implements Reader for Box using box { + fn read() -> T { return box.get(); } +} +``` + +A parameterized implementation's owner must directly apply a declared generic +struct. Every owner argument is a distinct binder parameter, and all binder +parameters are bound through the owner. Binder names need not match the struct's +parameter names. Arbitrary owners, unbound parameters, narrower patterns such as +Box>, and repeated arguments restricting the family are invalid. + +The rule belongs to the owner's declaration module. Its target resolves to a +contract and may compose the owner-bound parameters under existing type rules. +Implementations are complete with exact substituted signatures. Emitted owners, +targets and methods are concrete. Contract methods are not injected into the +owner's direct namespace. Views preserve receiver, implementation and identity +without a wrapper required by parameterization. + +Uniqueness is by concrete (owner, contract) pair. Two declarations overlap if an +admissible application could produce the same pair. Compare canonical nominal +origins and arguments with symbolically owner-bound parameters. Detect +generic/generic, generic/closed and closed/closed collisions before the conflicting +application is used. Different contract applications for an owner remain valid +when their pairs cannot coincide. Bounded analysis must not enumerate only used +applications, choose file/import order, prefer closed rules or silently succeed +after exhausting its budget. + +## Free functions, overloads and Fn + +References and calls provide explicit type arguments, such as identity(42). +An argument may mention a parameter in an enclosing template but must become +concrete before emission. There is no value, result or expected-Fn inference, +function diamond or default generic argument. `identity<>` and a polymorphic Fn +value for open `identity` are invalid. + +An applied function's identity includes its source declaration and ordered logical +arguments, including phantom arguments. Equivalent uses share the application; +different declarations remain different targets despite identical concrete +signatures. Symbolic validation, definition scope, complete body substitution, +normalization and bounded expansion apply to required function applications too. + +`f` considers generic free functions with matching type arity. A reference +or call without type arguments does not select a generic template. Ordinary +overloads remain subject to existing rules. After explicit binding, use existing +concrete signature resolution. Consistent renaming does not create overloads: +f(value:T) and f(value:U) are duplicates when otherwise signature-equivalent. +Substituted collisions in the filtered generic candidate set are errors. + +```pbs +let transform: Fn(int) -> int = identity; +let answer = transform(42); +``` + +Closed references use the existing Closure mechanism with an empty environment. +Fn stays structural by logical parameters/results, excluding target identity, +names and captures. Distinct targets may share a compatible Fn descriptor. +Lambdas in specialized bodies preserve explicit capture semantics and complete +groups. Bare method extraction remains invalid. Calls preserve canonical apply, +existing named/positional forms, order and single evaluation. + +## Definition scope, imports and barrels + +Each declaration/binder has its own substitution environment. Names in a template +body bind in its definition scope; type argument names bind at the use. Caller +and callee parameters with the same spelling must not capture one another. +Instantiation does not resolve private helpers in the caller or export them. + +```pbs +pub struct Box; +pub struct Pair; +pub fn identity(value: T) -> T; +``` + +Barrels export the parameterized declaration, ordered parameters and signature, +not an enumeration of closed instances. Preserve the original definition through +imports/aliases/reexports and make the necessary body available to the compiler +under existing visibility rules. This does not add an open-template PBX format. + +The application grammar extends the existing ordered type argument syntax to +struct/free-function declarations, barrels, owner-bound implements and named +function reference expressions. Calls continue to use ordinary parentheses/apply. +Nested applications and adjacent closers preserve spans. Complete type-argument +references must remain distinct from ordinary <, > and >= comparisons without +changing their meanings or adding shifts. Malformed source retains localized +diagnostics and recovery. Fields, ordinary Fn values and methods gain no generic +parameter list from this grammar. + +## Expansion, diagnostics and concrete execution + +Share logical identity, substitution environments, provenance and bounded +expansion infrastructure across PBS structs, functions and contracts. Keep each +category's layout/callable rules explicit and keep PBS rules in the frontend. +Register nominal and callable anchors before expanding dependencies. Revisiting +the same application forms a finite graph, including cross-category field/body +dependencies. Families requiring indefinitely new applications are diagnosed, +including growth through uncalled methods of a used owner. + +Analysis, normalization, substitution, coherence and materialization are bounded +in depth, work and storage. Exhaustion must not become a hang, host stack overflow, +misleading missing method or ordinary argument mismatch. Frontend budgets do not +increase provider limits. + +Errors preserve the original declaration and requesting use, with a short chain +such as `main -> wrap -> Box`. Cover unbound/duplicate parameters, +arity, raw/inferred application, invalid positions/capabilities, incomplete +construction, overload collisions, invalid implementation owners/rules, overlap +and expansion. Generated names and Java stacks do not replace source explanation. +Navigation, references/rename, hover, completion, signature help, symbols, +formatting and semantic tokens share compilation resolution/substitution. Distinguish +symbolic parameter, concrete argument and generic origin, including imported code. + +Emit only concrete Struct/Trait/Fn descriptors, callables, fields, signatures, +capture environments and implementation functions. Preserve logical identity +independently of storage width. Existing Struct/Array/Trait/Fn, direct calls, +REF_TO_TRAIT/CALL_TRAIT and Closure execute the result. Preserve receiver, +singletons where applicable, typed absence, valid ImplementationId zero, rooting, +GC, ownership, faults, evaluation and quotas. Genericity must not impose Dynamic, +reboxing or an adapter wrapper as its argument ABI; existing storage packing +retains its own contract. No new opcode, PBX category or runtime instantiation +engine is required. A provider-contract gap requires explicit decision revision. + +## Qualification and boundaries + +Conformance compiles real source through typed IR and production PBX into the +production loader, verifier and VM. Cover multiple arguments/applications, origin, +aliases/reexports/phantom identity, constructors/Self/all methods, composition and +multi-slot groups, free functions/apply/Fn, captures, finite/expanding recursion, +coherence, GC, ownership and quota refusal. Include negative cases for symbolic +operations, unused invalid methods, inferred applications, alpha-equivalent +duplicates and provenance diagnostics. + +A complete multi-module fixture must combine Box, Reader, owner-bound +implements, read, read as Fn and imports/aliases, returning 42. Compare +specialized structs/functions with handwritten concrete equivalents for behavior, +identity/lifetime and absence of adaptation imposed solely by T. Record provider +revision/configuration, complete fixture counts, metadata counts and artifact +sizes. Identical PBX bytes and a performance improvement are not required. + +Ship and verify specifications and executable examples in installed knowledge. +Regress Array, ordinary/applied structs/contracts, Self, constructors, Fn/captures +and lifecycle. No mandatory requirement is deferred to a collection implementation. + +Independent generic methods, generic contract methods/lambdas, polymorphic Fn, +function type inference, bounds, variance, defaults, user specialization and +blanket/narrower implementation patterns are outside this feature. Lifecycle +signatures remain concrete. Collection APIs/algorithms, default equality/hash, +iteration protocols and List logical bounds/slot transfer are separate decisions. + +## Related specifications + +- [Generic contracts](generic-contracts.md). +- [Typed arrays and optional execution](typed-arrays-and-optional-execution.md). +- [First-class functions and captures](first-class-functions-and-captures.md). +- [Concrete Registry and PBX handoff](../../general/specs/typed-registry-and-pbx-v0.md). diff --git a/docs/compiler/pbs/specs/runtime-random-integration.md b/docs/compiler/pbs/specs/runtime-random-integration.md index d71cfc30..7b8ea6a2 100644 --- a/docs/compiler/pbs/specs/runtime-random-integration.md +++ b/docs/compiler/pbs/specs/runtime-random-integration.md @@ -35,7 +35,7 @@ Assignment, parameter passing, returns and capture copy a reference to the same The reference MUST retain identity and ownership in locals, globals, fields, arrays, function parameters/results and captures. Captures use the existing snapshot rules: the copied reference continues to identify the shared generator. Reachable references MUST remain valid across runtime collection. -PBS does not expose a `null` literal or a public `Dynamic` type. Runtime reference defaults remain null, including an uninitialized Random field in an explicitly invoked ordinary struct constructor. Existing global-initializer restrictions remain unchanged; an unsupported arbitrary call in a global initializer does not become legal because it returns Random. +PBS does not expose a `null` literal or a public `Dynamic` type. Runtime reference defaults remain null at the provider boundary. PBS constructors MUST explicitly initialize every field on every completing path, including Random fields; an empty constructor cannot expose that runtime default. Existing global-initializer restrictions remain unchanged; an unsupported arbitrary call in a global initializer does not become legal because it returns Random. Typed arrays use their existing private `Array` representation. Packing Random MUST preserve its exact runtime TypeId and direct reference without cloning state or adding a multi-slot box. A present typed-null Random element MUST remain distinguishable from an empty array position: presence is checked by tag before exact extraction. Consuming that null generator raises the runtime null-reference fault rather than treating the element as absent. @@ -56,11 +56,11 @@ The source corpus MUST run the production PBS → common IR → PBX → runtime - all four signatures, real SDK imports/aliases and incompatible-source diagnostics; - provider vectors for seeds `0`, `1`, `42`, `-1`, Int64 MIN/MAX, integer and Float draws; - aliases, independent equal-seed objects, mixed outputs, discarded draws and positional/named argument effects; -- locals/globals/fields/arrays/parameters/results/captures, private Dynamic, typed null and retained roots across collection; -- unit/extreme intervals, excluded upper bound, invalid bounds, null receiver and real rejection followed by acceptance; +- locals/globals/fields/arrays/parameters/results/captures, private Dynamic and retained roots across collection; +- unit/extreme intervals, excluded upper bound, invalid bounds and real rejection followed by acceptance; - exact intrinsic charges and replay/optimizer agreement. -Rare synthetic rejection paths, cap rollback, malformed carriers and native reference provenance remain separately identified provider evidence. Tests MUST reuse the provider's controlled fixtures without adding injection or alternate algorithms to the public SDK. Record runtime revision, platform, profiles, toolchain, features and source/catalog/oracle/lockfile fingerprints. Local results do not qualify unexecuted platforms or the reference game. +Null receivers and present typed-null Array elements MUST be covered by separately identified controlled provider fixtures. Such fixtures may suppress a fully initialized field store after compilation to exercise provider reference defaults; they MUST NOT depend on accepting incomplete source constructors. Rare synthetic rejection paths, cap rollback, malformed carriers and native reference provenance remain separately identified provider evidence. Tests MUST reuse the provider's controlled fixtures without adding injection or alternate algorithms to the public SDK. Record runtime revision, platform, profiles, toolchain, features and source/catalog/oracle/lockfile fingerprints. Local results do not qualify unexecuted platforms or the reference game. ## References diff --git a/docs/compiler/pbs/specs/typed-arrays-and-optional-execution.md b/docs/compiler/pbs/specs/typed-arrays-and-optional-execution.md index 07fe6832..59faef13 100644 --- a/docs/compiler/pbs/specs/typed-arrays-and-optional-execution.md +++ b/docs/compiler/pbs/specs/typed-arrays-and-optional-execution.md @@ -89,3 +89,8 @@ See [Runtime Random integration](runtime-random-integration.md) for opaque gener ## Parameterized contract integration [Generic contracts](generic-contracts.md) extend nominal contract declarations with explicit type arguments. Valid Array/Fn/optional/tuple compositions preserve their existing logical and physical rules after substitution. No generic-only Dynamic transport, view wrapper, altered resource limit or new runtime opcode is introduced. + +[Generic structs and free functions](generic-structs-and-free-functions.md) reuse +these contextual construction positions and storage rules. A generic T field can +hold an optional value, but substituting an optional value type into array +remains invalid. Array's private packing does not become a generic argument ABI. diff --git a/docs/specs/compiler-languages/pbs/11. AST Specification.md b/docs/specs/compiler-languages/pbs/11. AST Specification.md index e2c66bf3..e882d697 100644 --- a/docs/specs/compiler-languages/pbs/11. AST Specification.md +++ b/docs/specs/compiler-languages/pbs/11. AST Specification.md @@ -189,3 +189,10 @@ Array syntax uses `array` with compositional nesting. Explicit `new array( Contract declarations and barrel items preserve ordered type-parameter names and individual spans. Applied type references preserve ordered child arguments and spans. Implements and as carry a complete target type reference. Semantic imported bindings retain the original declaration and importing lexical scope rather than inventing nominal origins. Existing visitors must traverse type arguments as well as inner/group/Fn/tuple children. See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md). + + +## Concrete generic structs and free functions + +Structs and free functions preserve ordered parameter declarations and spans. Explicit applied function references preserve type arguments and their source span. Implements preserves its binder, full applied owner and target. Substitution rewrites every field, signature, annotation and executable body/capture position with a declaration-local environment. Concrete application provenance retains original declaration, canonical logical arguments and requesting use; it is not an executable runtime template. + +See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md). diff --git a/docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md b/docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md index b19ecf49..dd36c0b9 100644 --- a/docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md +++ b/docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md @@ -313,3 +313,10 @@ Array syntax uses `array` with compositional nesting. Explicit `new array( Parameterized contract diagnostics distinguish exact arity (E_SEM_CONTRACT_ARITY), undeclared/duplicate parameters (E_SEM_CONTRACT_PARAMETER), invalid applications (E_SEM_CONTRACT_ARGUMENT), incompatible or incomplete implementations (E_SEM_CONTRACT_SIGNATURE), duplicate pairs (E_SEM_CONTRACT_DUPLICATE_IMPLEMENTATION), invalid owners/modules (E_SEM_CONTRACT_OWNER / E_SEM_CONTRACT_OWNER_MODULE), invalid coercions (E_SEM_CONTRACT_COERCION), and bounded expansion/resource exhaustion (E_SEM_CONTRACT_EXPANSION). Barrel parameter disagreement uses E_LINK_CONTRACT_PARAMETERS. Existing invalid Array/Fn/optional/Self diagnostics also apply after substitution. See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md). + + +## Concrete generic structs and free functions + +Generic diagnostics distinguish duplicate/unbound parameters, exact arity, raw or improperly inferred application, unjustified symbolic capabilities, invalid substituted positions, constructor errors, collapsed overloads, invalid bound owners, overlap and bounded expansion. Preserve declaration and requesting-use locations with a short instantiation chain. Editor projections retain symbolic parameter, concrete argument and generic origin identities. Generated instance names and host stacks do not replace source explanations. + +See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md). diff --git a/docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md b/docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md index 70771a54..2ea65f72 100644 --- a/docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md +++ b/docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md @@ -255,3 +255,10 @@ Array syntax uses `array` with compositional nesting. Explicit `new array( The frontend substitutes each closed application and emits a concrete nominal Trait descriptor shared by equivalent uses. Distinct logical applications remain distinct despite shared physical carriers. Concrete implementation functions take the receiver first. CALL_TRAIT evaluates and roots the receiver before arguments, evaluates arguments left to right, then places the complete receiver/ImplementationId view after the argument groups as required by the runtime ABI. Preserve exact signatures, absence, ImplementationId zero, ownership, GC and quotas; generic calls do not add a Dynamic ABI or adaptation wrapper. See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md). + + +## Concrete generic structs and free functions + +Instantiate structs, free functions and owner-bound implementations within PBS before publishing executable descriptors. Registry receives concrete fields, signatures, bodies, capture groups and targets. Specialized free-function references use existing empty-environment Closure values; Fn remains structural. Preserve receiver identity, implementation zero, singletons, rooting, GC, ownership, evaluation/fault order and quotas. No generic Dynamic/boxing ABI, opcode, descriptor category or runtime instantiation engine is introduced. + +See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md). diff --git a/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md b/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md index 311b9c40..ae56bf52 100644 --- a/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md +++ b/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md @@ -165,8 +165,8 @@ BarrelItem ::= BarrelFnItem | BarrelConstItem BarrelVisibility ::= 'mod' | 'pub' -BarrelFnItem ::= BarrelVisibility 'fn' Identifier ParamList ReturnAnn? ';' -BarrelStructItem ::= BarrelVisibility 'struct' Identifier ';' +BarrelFnItem ::= BarrelVisibility 'fn' Identifier TypeParameters? ParamList ReturnAnn? ';' +BarrelStructItem ::= BarrelVisibility 'struct' Identifier TypeParameters? ';' BarrelContractItem ::= BarrelVisibility 'contract' Identifier TypeParameters? ';' BarrelHostItem ::= BarrelVisibility 'host' Identifier ';' BarrelErrorItem ::= BarrelVisibility 'error' Identifier ';' @@ -280,7 +280,7 @@ Top-level `let` forms and top-level executable statements are forbidden. ```ebnf TypeDecl ::= StructDecl | ServiceDecl | ContractDecl | HostDecl | BuiltinTypeDecl | ErrorDecl | EnumDecl -StructDecl ::= 'declare' 'struct' Identifier '(' StructFieldList? ')' (StructMethodBody | ';') +StructDecl ::= 'declare' 'struct' Identifier TypeParameters? '(' StructFieldList? ')' (StructMethodBody | ';') ServiceDecl ::= 'declare' 'service' Identifier ServiceBody ContractDecl ::= 'declare' 'contract' Identifier TypeParameters? ContractBody TypeParameters ::= '<' Identifier (',' Identifier)* '>' @@ -390,7 +390,7 @@ Rules: ### 7.4 Functions ```ebnf -FunctionDecl ::= 'fn' Identifier ParamList ReturnAnn? Block +FunctionDecl ::= 'fn' Identifier TypeParameters? ParamList ReturnAnn? Block ParamList ::= '(' (Param (',' Param)*)? ')' Param ::= Identifier ':' TypeRef ReturnAnn ::= '->' ReturnSpec @@ -467,7 +467,7 @@ Rules: - Named tuple arity is 1..6 in v1 core syntax. - Tuple types in PBS core are always named. - Single-slot tuple types are allowed only in type/signature surface, not as tuple literals. -- User-defined parameterized declarations are supported for contracts. General generic structs and functions remain outside PBS core v1. +- User-defined parameterized declarations are supported for contracts. Generic structs and explicit generic free functions follow the concrete generic application extension linked below. - `SimpleType` may denote either a visible nominal type identifier or one of the predeclared builtin simple types. - The predeclared builtin simple types in v1 core are `int`, `float`, `bool`, and `str`. - Builtin simple types are always available in type position and do not require import. @@ -574,10 +574,10 @@ ArgList ::= Expr (',' Expr)* Literal ::= IntLit | FloatLit | StringLit | BoolLit BoolLit ::= 'true' | 'false' -PrimaryExpr ::= Literal | Identifier | ThisExpr | NewExpr | LambdaExpr | SomeExpr | NoneExpr | OkExpr | ErrExpr | UnitExpr | TupleExpr | GroupExpr | Block +PrimaryExpr ::= Literal | Identifier TypeArguments? | ThisExpr | NewExpr | LambdaExpr | SomeExpr | NoneExpr | OkExpr | ErrExpr | UnitExpr | TupleExpr | GroupExpr | Block ThisExpr ::= 'this' NewExpr ::= 'new' NewTarget '(' ArgList? ')' -NewTarget ::= Identifier ('.' Identifier)? +NewTarget ::= Identifier (TypeArguments | '<' '>')? ('.' Identifier)? LambdaExpr ::= 'fn' '[' CaptureNames? ']' ParamList '->' TypeRef Block CaptureNames ::= Identifier (',' Identifier)* FnType ::= 'Fn' '(' (TypeRef (',' TypeRef)*)? ')' '->' TypeRef @@ -1211,3 +1211,10 @@ Array syntax uses `array` with compositional nesting. Explicit `new array( Parameterized contracts use explicit angular arguments in annotations, nested types, implements and as. Barrels export the ordered parameter list. Raw generic uses, empty argument lists and default arguments are invalid; existing contextual closers and Array construction sugars remain unchanged. See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md). + + +## Concrete generic structs and free functions + +Struct and module-level free-function declarations and their barrel items accept ordered type parameters. Explicit function applications are reference expressions; calls use existing parentheses/apply. Generic construction supports explicit arguments and contextual diamond/omission. Owner-bound `implements` accepts its own parameter binder and a full applied owner. Independent method parameters, function diamond/inference and polymorphic Fn remain invalid. The owner specification defines exact arity, comparison disambiguation and recovery. + +See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md). 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 378c394f..776a56a5 100644 --- a/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md +++ b/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md @@ -830,3 +830,10 @@ Array syntax uses `array` with compositional nesting. Explicit `new array( Application identity combines the defining nominal declaration with ordered canonical logical arguments after alias resolution. Applications are invariant. Substitution preserves existing type-position restrictions, names, labels and complete groups across Array, Fn, optional, tuples and nested contracts. A struct/service may implement several applications, with complete unique implementations in its owner module. Finite instance recursion is accepted within resource limits; unbounded expansion receives a bounded diagnostic. See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md). + + +## Concrete generic structs and free functions + +Templates are checked symbolically in definition scope. Required concrete owners validate all methods and constructors, including unused methods. Substitute complete bodies and applied Self; preserve position restrictions, invariant nominal/phantom identity and logical groups. Explicit function applications filter generic overloads by type arity; ordinary calls never infer them. Bound owner implementations require complete exact signatures and symbolic overlap rejection before use. Finite recursive applications are anchored; expanding type/body families are bounded errors. + +See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md). diff --git a/docs/specs/compiler-languages/pbs/5. Manifest, Stdlib, and SDK Resolution Specification.md b/docs/specs/compiler-languages/pbs/5. Manifest, Stdlib, and SDK Resolution Specification.md index e0a0e013..ec3a5e6a 100644 --- a/docs/specs/compiler-languages/pbs/5. Manifest, Stdlib, and SDK Resolution Specification.md +++ b/docs/specs/compiler-languages/pbs/5. Manifest, Stdlib, and SDK Resolution Specification.md @@ -563,3 +563,10 @@ new coverage; existing behavior MUST NOT regress. A barrel exports a parameterized contract declaration with the same ordered parameters as its source declaration. Imported bindings retain the original declaration and lexical source scope, including aliases in signatures of dependencies. A local alias never creates another nominal type. Implementations remain in the declaring module of the concrete struct/service owner. See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md). + + +## Concrete generic structs and free functions + +Generic struct/function barrels export declarations and ordered parameters, including complete function signatures, rather than enumerated specializations. Imports and aliases preserve nominal origins and definition-scoped bodies/private helpers. Specializations are shared across equivalent uses and do not export private dependencies. SDK and program sources use the same language machinery. + +See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md). diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java index 1a783d77..60f2badc 100644 --- a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java +++ b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java @@ -25,6 +25,8 @@ public final class InstalledKnowledgeProbe { var docs = provider.documentation().orElseThrow().references(1, p.studio.AppMode.Game); check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:generic-contracts.md")), "Missing installed generic-contract specification"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/contracts.pbs")), "Missing installed generic-contract example"); + check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:generic-structs-and-free-functions.md")), "Missing installed generic struct/function specification"); + check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/generics.pbs")), "Missing installed generic struct/function example"); for (var reference : docs) { if (reference.id().startsWith("pbs:example:game:1:")) { Path file = root.resolve(reference.id().substring("pbs:example:game:1:".length())); diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericStructsTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericStructsTest.java new file mode 100644 index 00000000..ba48c5c7 --- /dev/null +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGenericStructsTest.java @@ -0,0 +1,211 @@ +package p.studio.compiler.backend.irvm; + +import org.junit.jupiter.api.Test; +import p.studio.compiler.backend.bytecode.*; +import p.studio.compiler.models.*; +import p.studio.compiler.pbs.*; +import p.studio.compiler.pbs.lexer.PbsLexer; +import p.studio.compiler.pbs.parser.PbsParser; +import p.studio.compiler.source.diagnostics.DiagnosticSink; +import p.studio.compiler.source.identifiers.*; +import p.studio.utilities.structures.ReadOnlyList; +import java.nio.file.*; +import static org.junit.jupiter.api.Assertions.*; + +class PbsGenericStructsTest { + private static final String BOX = """ + declare struct Box(value: T) { + fn get() -> T { return this.value; } + fn set(value: T) { this.value = value; } + } + """; + private static Path directory() { return Path.of(System.getProperty("pbs.registryConformanceDirectory")); } + private static BytecodeModule compile(String name, String source) throws Exception { + var diagnostics = DiagnosticSink.empty(); var id = new FileId(0); + var ast = PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics, PbsParser.ParseMode.ORDINARY); + var file = new PbsFrontendCompiler().compileParsedFile(id, ast, diagnostics, SourceKind.PROJECT, new ModuleId(0), + ReadOnlyList.empty(), p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(), + p.studio.compiler.messages.FESurfaceContext.empty(), new p.studio.compiler.source.tables.NameTable()); + assertFalse(diagnostics.hasErrors(), () -> name+": "+diagnostics.stream().map(d -> d.getCode()+":"+d.getMessage()).toList()); + var backend = IRBackend.builder().entryPointCallableName("Probe.main").entryPointModuleId(new ModuleId(0)) + .executableFunctions(file.executableFunctions()).globals(file.globals()).registry(file.registry()) + .intrinsicPool(file.intrinsicPool()).callableSignatures(file.callableSignatures()).build(); + var program = new LowerToIRVMService().lower(backend); + var module = new BytecodeEmitter().emit(program.coherentEmissionPlan()); + if (name.equals("gc")) module = PbsStructuredValuesTest.withTestSafepoint(module); + new BytecodePreloadVerifierService().verify(module); + Files.createDirectories(directory()); + Files.write(directory().resolve("pbs-generic-struct-"+name+".pbx"), module.serialize()); + return module; + } + @Test void genericAndHandwrittenObjectsPreserveReferenceIdentity() throws Exception { + compile("basic", BOX+""" + declare service Probe { fn main() -> int { + let box = new Box(40); let alias = box; + alias.set(42); return box.get(); + } } + """); + compile("manual", """ + declare struct IntBox(value: int) { + fn get() -> int { return this.value; } + fn set(value: int) { this.value = value; } + } + declare service Probe { fn main() -> int { + let box = new IntBox(40); let alias = box; + alias.set(42); return box.get(); + } } + """); + } + @Test void constructorsSelfAndPhantomApplicationsAreConcrete() throws Exception { + compile("constructor", """ + declare struct Box(value: T) { + ctor make(value: T) { this.value = value; } + fn same() -> Self { return this; } + fn get() -> T { return this.value; } + } + declare service Probe { fn main() -> int { + let box = new Box.make(42); return box.same().get(); + } } + """); + compile("phantom", """ + declare struct Marker() { fn answer() -> int { return 21; } } + declare service Probe { fn main() -> int { + let a = new Marker(); let b = new Marker(); return a.answer() + b.answer(); + } } + """); + } + @Test void composedStorageAndCompleteGroupsExecute() throws Exception { + compile("multiple", """ + declare struct Pair(key: K, value: V) { + fn first() -> K { return this.key; } + fn second() -> V { return this.value; } + } + declare service Probe { fn main() -> int { + let pair = new Pair(20, 22); return pair.first() + pair.second(); + } } + """); + compile("tuple", BOX+""" + declare service Probe { fn main() -> int { + let box = new Box<(left: int, right: int)>((left: 20, right: 22)); + let pair = box.get(); return pair.left + pair.right; + } } + """); + compile("optional", BOX+""" + declare service Probe { fn main() -> int { + let box = new Box(none); box.set(some(42)); return box.get() else 0; + } } + """); + compile("array", BOX+""" + declare service Probe { fn main() -> int { + let box = new Box>([42]); return box.get()[0] else 0; + } } + """); + compile("recursive", """ + declare struct Node(value: T, next: optional Node) { fn get() -> T { return this.value; } } + declare service Probe { fn main() -> int { let node = new Node(42, none); return node.get(); } } + """); + } + @Test void freeFunctionsFnAndOwnerBoundDispatchInteract() throws Exception { + compile("combined", BOX+""" + declare contract Reader { fn read() -> T; } + implements Reader for Box using box { fn read() -> T { return box.get(); } } + fn read(reader: Reader) -> T { return reader.read(); } + declare service Probe { fn main() -> int { + let box = new Box(42); let reader: Reader = box; + let invoke: Fn(Reader) -> int = read; return invoke(reader); + } } + """); + compile("function", """ + fn identity(value: T) -> T { return value; } + declare service Probe { fn main() -> int { let f: Fn(int) -> int = identity; return f(42); } } + """); + compile("function-manual", """ + fn identity(value: int) -> int { return value; } + declare service Probe { fn main() -> int { let f: Fn(int) -> int = identity; return f(42); } } + """); + } + @Test void specializedCapturesRemainRootedAcrossCollection() throws Exception { + compile("gc", BOX+""" + fn capture(value: T) -> Fn() -> T { + let box = new Box(value); return fn [box]() -> T { return box.get(); }; + } + declare service Probe { + fn garbage() { let discarded: array = new array(1); } + fn collect() { let marker = 314159; } + fn main() -> int { + let read = capture(42); + for i: int from 0 until 1100 { Probe.garbage(); } + Probe.collect(); return read(); + } + } + """); + } + @Test void installedGenericExampleUsesTheSameProductionPipeline() throws Exception { + try (var stream = PbsFrontendCompiler.class.getResourceAsStream("/pbs-knowledge/examples/game/1/src/generics.pbs")) { + assertNotNull(stream); + compile("installed", new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8) + + "\ndeclare service Probe { fn main() -> int { return genericsExample(); } }"); + } + } + @Test void importsAliasesReexportsAndDefinitionScopedHelpersExecute(@org.junit.jupiter.api.io.TempDir Path root) throws Exception { + Files.createDirectories(root.resolve("src/policy")); Files.createDirectories(root.resolve("src/facade")); + Files.writeString(root.resolve("prometeu.json"), """ + {"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]} + """); + Files.writeString(root.resolve("src/mod.barrel"), "pub fn frame() -> void;"); + var exports = "pub struct Box; pub contract Reader; pub fn read(reader: Reader) -> T; pub fn wrap(value: U) -> Box;"; + Files.writeString(root.resolve("src/policy/mod.barrel"), exports); + Files.writeString(root.resolve("src/facade/mod.barrel"), exports); + Files.writeString(root.resolve("src/facade/main.pbs"), "import { Box, Reader, read, wrap } from @app:policy;"); + Files.writeString(root.resolve("src/policy/main.pbs"), BOX+""" + declare contract Reader { fn read() -> T; } + implements Reader for Box using box { fn read() -> T { return box.get(); } } + fn helper(value: T) -> T { return value; } + fn wrap(value: U) -> Box { return new Box(helper(value)); } + fn read(reader: Reader) -> T { return reader.read(); } + """); + Files.writeString(root.resolve("src/main.pbs"), """ + import { Box as B, Reader as R, read as invoke, wrap as make } from @app:facade; + fn helper(value: int) -> int { return 0; } + [Frame] fn frame() -> void { + let box: B = make(42); let reader: R = box; + let f: Fn(R) -> int = invoke; + if f(reader) != 42 { let fail = 1 / 0; } + } + """); + var result = p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile( + p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false, root.toString())), + p.studio.utilities.logs.LogAggregator.stdout()); + assertFalse(result.diagnostics().stream().anyMatch(d -> d.isError()), result.diagnostics().toString()); + assertTrue(result.bytecodeBytes().length > 0); + Files.createDirectories(directory()); Files.write(directory().resolve("pbs-generic-struct-imports.pbx"), result.bytecodeBytes()); + } + @Test void homonymousArgumentsFromDifferentModulesRemainNominallyDistinct(@org.junit.jupiter.api.io.TempDir Path root) throws Exception { + for (var module : new String[]{"policy", "left", "right"}) Files.createDirectories(root.resolve("src/"+module)); + Files.writeString(root.resolve("prometeu.json"), """ + {"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]} + """); + Files.writeString(root.resolve("src/mod.barrel"), "pub fn frame() -> void;"); + Files.writeString(root.resolve("src/policy/mod.barrel"), "pub struct Box;"); + Files.writeString(root.resolve("src/policy/main.pbs"), BOX); + for (var module : new String[]{"left", "right"}) { + Files.writeString(root.resolve("src/"+module+"/mod.barrel"), "pub struct Enemy;"); + Files.writeString(root.resolve("src/"+module+"/main.pbs"), "declare struct Enemy(pub hp: int);"); + } + Files.writeString(root.resolve("src/main.pbs"), """ + import { Box } from @app:policy; + import { Enemy as Left } from @app:left; + import { Enemy as Right } from @app:right; + [Frame] fn frame() -> void { + let a = new Box(new Left(20)); + let b = new Box(new Right(22)); + if a.get().hp + b.get().hp != 42 { let fail = 1 / 0; } + } + """); + var result = p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile( + p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false, root.toString())), + p.studio.utilities.logs.LogAggregator.stdout()); + assertFalse(result.diagnostics().stream().anyMatch(d -> d.isError()), result.diagnostics().toString()); + Files.createDirectories(directory()); Files.write(directory().resolve("pbs-generic-struct-origins.pbx"), result.bytecodeBytes()); + } +} diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java index 2207a79d..266b9a69 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java @@ -87,10 +87,33 @@ class PbsRuntimeRandomTest { var program = new LowerToIRVMService().lower(backend); if(name.endsWith("-optimized")) program = new OptimizeIRVMService().optimize(program); var module = new p.studio.compiler.backend.bytecode.BytecodeEmitter().emit(program.coherentEmissionPlan()); + if (name.startsWith("random-null") || name.startsWith("random-typed-null")) module = withInjectedNull(module); if (name.startsWith("random-gc")) module = PbsStructuredValuesTest.withTestSafepoint(module); new p.studio.compiler.backend.bytecode.BytecodePreloadVerifierService().verify(module); java.nio.file.Files.write(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory"),"pbs-"+name+".pbx"),module.serialize()); } + // Controlled provider fixture: compile valid, fully initialized source, then + // suppress its unique one-slot field store. Allocation, field defaults, typed + // Array access and Random consumption still use the production provider. + private static p.studio.compiler.backend.bytecode.BytecodeModule withInjectedNull( + p.studio.compiler.backend.bytecode.BytecodeModule module) { + byte[] code = module.code().clone(); + var entry = module.debugInfo().functionNames().stream().filter(f -> f.name().contains("Empty.$ctor.create")).findFirst().orElseThrow(); + var function = module.functions().get(entry.funcIdx()); + int replaced = 0; + for (int pc = function.codeOffset(); pc + 10 <= function.codeOffset() + function.codeLen(); pc += 2) { + if (code[pc] == (byte) 0xa2 && code[pc + 1] == 0 + && java.nio.ByteBuffer.wrap(code, pc + 6, 4).order(java.nio.ByteOrder.LITTLE_ENDIAN).getInt() == 0) { + java.util.Arrays.fill(code, pc, pc + 10, (byte) 0); + code[pc] = 0x11; code[pc + 2] = 0x11; // discard field value and receiver + replaced++; + } + } + assertEquals(1, replaced, "unique controlled provider field store"); + return new p.studio.compiler.backend.bytecode.BytecodeModule(module.version(), module.constPool(), + module.functions(), code, module.debugInfo(), module.exports(), module.syscalls(), + module.registry(), module.intrinsicSignatures()); + } @Test void providerSeedVectors() throws Exception { String corpus; try (var stream = PbsRuntimeRandomTest.class.getResourceAsStream("/random/random-conformance.tsv")) { @@ -118,7 +141,7 @@ class PbsRuntimeRandomTest { } @Test void storageAndIndependentStreams() throws Exception { pair("storage", """ - declare struct Empty(pub value: Random) { ctor create() {} } declare global saved: Random = new Empty.create().value; + declare struct Empty(pub value: Random) { ctor create() { this.value = random.new(9223372036854775807); } } declare global saved: Random = new Empty.create().value; declare struct Box(pub value: Random); fn echo(rng: Random) -> Random { return rng; } fn capture(rng: Random) -> Fn() -> long { return fn [rng]() -> long { return random.next(rng); }; } @@ -144,7 +167,7 @@ class PbsRuntimeRandomTest { """); pair("named", """ declare global trace: int = 0; - declare struct Empty(pub value: Random) { ctor create() {} } declare global rng: Random = new Empty.create().value; + declare struct Empty(pub value: Random) { ctor create() { this.value = random.new(9223372036854775807); } } declare global rng: Random = new Empty.create().value; declare service Probe { fn receiver() -> Random { trace = trace * 10 + 1; return rng; } fn low() -> long { trace = trace * 10 + 2; random.next(rng); return -7; } @@ -158,7 +181,7 @@ class PbsRuntimeRandomTest { """); pair("positional", """ declare global trace: int = 0; - declare struct Empty(pub value: Random) { ctor create() {} } declare global rng: Random = new Empty.create().value; + declare struct Empty(pub value: Random) { ctor create() { this.value = random.new(9223372036854775807); } } declare global rng: Random = new Empty.create().value; declare service Probe { fn receiver() -> Random { trace = trace * 10 + 1; return rng; } fn low() -> long { trace = trace * 10 + 2; random.next(rng); return -7; } @@ -171,7 +194,7 @@ class PbsRuntimeRandomTest { } """); } - @Test void rangeBoundsAndNullDefaults() throws Exception { + @Test void rangeBoundsAndControlledProviderNulls() throws Exception { String[][] bounds = {{"0","1"},{"-10","-3"},{"-10","10"},{"0","16"}, {"-9223372036854775808","0"},{"-1","9223372036854775807"},{"-9223372036854775808","9223372036854775807"}, {"5","5"},{"6","5"}}; @@ -184,9 +207,9 @@ class PbsRuntimeRandomTest { return (value: value, next: random.next(rng)); } } """); - pair("null", "declare struct Empty(pub value: Random) { ctor create() {} } declare global empty: Random = new Empty.create().value; declare service Probe { fn main() -> long { return random.next(empty); } }"); + pair("null", "declare struct Empty(pub value: Random) { ctor create() { this.value = random.new(9223372036854775807); } } declare global empty: Random = new Empty.create().value; declare service Probe { fn main() -> long { return random.next(empty); } }"); pair("typed-null", """ - declare struct Empty(pub value: Random) { ctor create() {} } declare global empty: Random = new Empty.create().value; + declare struct Empty(pub value: Random) { ctor create() { this.value = random.new(9223372036854775807); } } declare global empty: Random = new Empty.create().value; declare service Probe { fn main() -> long { let values: array = [empty]; if let value = values[0] { return random.next(value); } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsContractTypes.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsContractTypes.java index c836f996..2a9f177c 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsContractTypes.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsContractTypes.java @@ -29,12 +29,20 @@ public final class PbsContractTypes { private final List implementations = new ArrayList<>(); private final Set reported = new HashSet<>(); private final DiagnosticSink diagnostics; + private final PbsInstantiationBudget sharedBudget; private long keyChars; private int work; private boolean failed; + private PbsAst.TopDecl activeDeclaration; public PbsContractTypes(PbsAst.File ast, ReadOnlyList supplemental, DiagnosticSink diagnostics) { + this(ast, supplemental, diagnostics, new PbsInstantiationBudget(diagnostics)); + } + + public PbsContractTypes(PbsAst.File ast, ReadOnlyList supplemental, DiagnosticSink diagnostics, + PbsInstantiationBudget sharedBudget) { this.diagnostics = diagnostics; + this.sharedBudget = sharedBudget; supplemental.forEach(this::index); ast.topDecls().forEach(this::index); for (var imported : ast.imports()) for (var item : imported.items()) { @@ -45,7 +53,7 @@ public final class PbsContractTypes { } } - private void index(PbsAst.TopDecl declaration) { + public void index(PbsAst.TopDecl declaration) { if (declaration instanceof PbsAst.TypeBindingDecl binding) { index(binding.declaration()); declarations.put(binding.name(), binding.declaration()); @@ -77,6 +85,8 @@ public final class PbsContractTypes { if (type == null) return "void"; if (type.kind() == PbsAst.TypeRefKind.SIMPLE) { var declaration = declaration(type); + var origin = applicationOrigin(declaration); + if (origin != null) return origin.display(); var name = switch (declaration) { case PbsAst.ContractDecl c -> c.name(); case PbsAst.StructDecl s -> s.name(); @@ -127,6 +137,8 @@ public final class PbsContractTypes { case GROUP -> { return key(type.inner(), depth + 1); } case SIMPLE -> { var declaration = declaration(type); + var origin = applicationOrigin(declaration); + if (origin != null && type.arguments().isEmpty()) return origin.key(); head = declaration == null ? type.name() : nominal(declaration); for (var argument : type.arguments()) children.add(key(argument, depth + 1)); } @@ -150,13 +162,25 @@ public final class PbsContractTypes { // Length framing prevents ambiguity between nested constructors and nominal names. var result = head + "[" + children.stream().map(s -> s.length() + ":" + s).collect(Collectors.joining()) + "]"; keyChars += result.length(); keys.put(type, result); + sharedBudget.store(type.span(), result.length()); return result; } - private static String nominal(PbsAst.TopDecl declaration) { + public static String nominal(PbsAst.TopDecl declaration) { + var origin = applicationOrigin(declaration); + if (origin != null) return origin.key(); return "pbs:" + declaration.getClass().getSimpleName() + ":" + declaration.span().getFileId().getId() + ":" + declaration.span().getStart(); } + public static PbsAst.ApplicationOrigin applicationOrigin(PbsAst.TopDecl declaration) { + return switch (declaration) { + case PbsAst.StructDecl s -> s.applicationOrigin(); + case PbsAst.ContractDecl c -> c.applicationOrigin(); + case PbsAst.FunctionDecl f -> f.applicationOrigin(); + case null, default -> null; + }; + } + public Instance resolve(PbsAst.TypeRef type) { if (failed) return null; var template = template(type); @@ -169,6 +193,7 @@ public final class PbsContractTypes { var cached = instances.get(key); if (cached != null) return cached; if (instances.size() >= MAX_INSTANCES) throw expansion(type.span(), "Contract instance graph exceeds Registry type limit"); + sharedBudget.instance(type.span()); var bindings = new LinkedHashMap(); for (int i = 0; i < template.typeParameters().size(); i++) bindings.put(template.typeParameters().get(i).name(), type.arguments().get(i)); var signatures = ReadOnlyList.wrap(template.signatures().stream().map(s -> PbsTypeSubstitution.substitute(s, bindings)).toList()); @@ -186,6 +211,7 @@ public final class PbsContractTypes { public void validate(PbsAst.File ast) { try { for (var declaration : ast.topDecls()) { + activeDeclaration = declaration; if (declaration instanceof PbsAst.ContractDecl contract) { var parameters = new HashSet(); for (var parameter : contract.typeParameters()) if (!parameters.add(parameter.name())) @@ -199,6 +225,10 @@ public final class PbsContractTypes { } expand(); validateImplementations(ast); + } catch (PbsInstantiationBudget.Exhausted failure) { + failed = true; + pending.clear(); + error("E_SEM_CONTRACT_EXPANSION", "Contract expansion exceeds bounded generic analysis", ast.span()); } catch (ExpansionFailure failure) { failed = true; pending.clear(); @@ -284,6 +314,8 @@ public final class PbsContractTypes { return returnKey(type, 0); } + public String resultKey(PbsAst.TypeRef type) { return returnKey(type); } + private String returnKey(PbsAst.TypeRef type, int depth) { type = unwrap(type); if (type != null && type.kind() == PbsAst.TypeRefKind.NAMED_TUPLE && type.fields().size() == 1) type = type.fields().getFirst().typeRef(); @@ -304,6 +336,7 @@ public final class PbsContractTypes { public List instances() { return List.copyOf(instances.values()); } private void budget(Span span, int depth) { + sharedBudget.visit(span, depth); if (depth > MAX_DEPTH || ++work > MAX_WORK) throw expansion(span, "Contract expansion exceeds bounded type analysis; recursive applications may expand indefinitely"); } @@ -313,7 +346,8 @@ public final class PbsContractTypes { } private void error(String code, String message, Span span) { - if (reported.add(code + ":" + span + ":" + message)) Diagnostics.error(diagnostics, code, message, span); + if (reported.add(code + ":" + span + ":" + message)) Diagnostics.error( + activeDeclaration == null ? diagnostics : PbsGenericDiagnostics.forDeclaration(activeDeclaration, diagnostics), code, message, span); } private static PbsAst.TypeRef unwrap(PbsAst.TypeRef type) { diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsFrontendCompiler.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsFrontendCompiler.java index 4ece62dd..8aab1b55 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsFrontendCompiler.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsFrontendCompiler.java @@ -127,7 +127,7 @@ public final class PbsFrontendCompiler { public IRBackendFile compileParsedFile( final FileId fileId, - final PbsAst.File ast, + final PbsAst.File sourceAst, final DiagnosticSink diagnostics, final SourceKind sourceKind, final ModuleId moduleId, @@ -140,6 +140,14 @@ public final class PbsFrontendCompiler { final ReadOnlyList importedGlobals, final IRReservedMetadata importedReservedMetadata, final Map declaredGlobalVisibilityByName) { + final PbsAst.File ast; + if (PbsGenericInstantiation.needed(sourceAst)) { + var before = diagnostics.errorCount(); + var prepared = new PbsGenericInstantiation(java.util.List.of(new PbsGenericInstantiation.Source(sourceAst, + supplementalTopDecls == null ? ReadOnlyList.empty() : supplementalTopDecls)), diagnostics, feSurfaceContext).prepare(); + if (diagnostics.errorCount() > before) return IRBackendFile.empty(fileId); + ast = prepared.files().get(fileId); + } else ast = sourceAst; final var effectiveModuleId = moduleId == null ? ModuleId.none() : moduleId; final var effectiveModulePool = modulePool == null ? ReadOnlyList.empty() : modulePool; final var effectiveNameTable = nameTable == null ? new NameTable() : nameTable; @@ -161,15 +169,16 @@ public final class PbsFrontendCompiler { final var effectiveDeclaredGlobalVisibilityByName = declaredGlobalVisibilityByName == null ? Map.of() : Map.copyOf(declaredGlobalVisibilityByName); + final var diagnosticView = PbsGenericDiagnostics.forFile(ast, effectiveSupplementalTopDecls, diagnostics); final var semanticsErrorBaseline = diagnostics.errorCount(); new PbsDeclarationSemanticsValidator(effectiveNameTable).validate( ast, sourceKind, effectiveModuleId, effectiveImportedGlobals, - diagnostics); - flowSemanticsValidator.validate(ast, effectiveSupplementalTopDecls, effectiveFESurfaceContext, diagnostics); - lifecycleSemanticsValidator.validate(ast, effectiveSupplementalTopDecls, diagnostics); + diagnosticView); + flowSemanticsValidator.validate(ast, effectiveSupplementalTopDecls, effectiveFESurfaceContext, diagnosticView); + lifecycleSemanticsValidator.validate(ast, effectiveSupplementalTopDecls, diagnosticView); if (diagnostics.errorCount() > semanticsErrorBaseline) { return IRBackendFile.empty(fileId); } @@ -178,7 +187,7 @@ public final class PbsFrontendCompiler { ast, sourceKind, hostAdmissionContext, - diagnostics); + diagnosticView); if (reservedMetadata == null) { return IRBackendFile.empty(fileId); } @@ -200,7 +209,7 @@ public final class PbsFrontendCompiler { mergeReservedMetadata(reservedMetadata, effectiveImportedReservedMetadata), effectiveNameTable, effectiveFESurfaceContext, - diagnostics, + diagnosticView, effectiveImportedCallables); if (diagnostics.errorCount() > loweringErrorBaseline) { return IRBackendFile.empty(fileId); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericCoherence.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericCoherence.java new file mode 100644 index 00000000..ba6e6b22 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericCoherence.java @@ -0,0 +1,120 @@ +package p.studio.compiler.pbs; + +import p.studio.compiler.pbs.ast.PbsAst; +import p.studio.compiler.source.Span; +import p.studio.compiler.source.diagnostics.DiagnosticSink; +import java.util.*; + +/** First-order symbolic overlap checking; never enumerates only the used applications. */ +final class PbsGenericCoherence { + private record Term(String head, List children, boolean variable) {} + private final PbsGenericInstantiation context; + PbsGenericCoherence(PbsGenericInstantiation context, DiagnosticSink diagnostics) { this.context = context; } + + void validate(List rules) { + var valid = new ArrayList(); + for (var rule : rules) { + context.budget().visit(rule.span(), 0); + var owner = context.declaration(rule.ownerType()); + var target = context.declaration(rule.contractType()); + if (!(target instanceof PbsAst.ContractDecl contract)) { + context.error("IMPLEMENTATION", "Implementation target must resolve to a contract", rule.contractType().span()); + continue; + } + if (!rule.typeParameters().isEmpty()) { + var names = new HashSet<>(rule.typeParameters().stream().map(PbsAst.TypeParameter::name).toList()); + var arguments = rule.ownerType().arguments(); + var bound = new HashSet(); + boolean ownerValid = owner instanceof PbsAst.StructDecl s && !s.typeParameters().isEmpty() + && s.typeParameters().size() == arguments.size(); + for (var argument : arguments) ownerValid &= argument.kind() == PbsAst.TypeRefKind.SIMPLE && + argument.arguments().isEmpty() && names.contains(argument.name()) && bound.add(argument.name()); + ownerValid &= bound.equals(names) && names.size() == rule.typeParameters().size(); + if (!ownerValid) { + context.error("OWNER", "Generic implements must bind each parameter exactly once through a direct generic struct owner", rule.ownerType().span()); + continue; + } + if (!context.sameModule(rule.span(), owner.span())) { + context.error("OWNER_MODULE", "Generic implements must belong to the module declaring its owner", rule.span()); + continue; + } + } + if (contract.typeParameters().size() != rule.contractType().arguments().size()) { + context.error("ARITY", "Implementation target has incorrect contract arity", rule.contractType().span()); + continue; + } + var bindings = new HashMap(); + for (int i = 0; i < contract.typeParameters().size(); i++) bindings.put(contract.typeParameters().get(i).name(), rule.contractType().arguments().get(i)); + for (var signature : contract.signatures()) { + var expected = PbsTypeSubstitution.substitute(signature, bindings); + var count = rule.methods().stream().filter(m -> matches(m, expected)).count(); + if (count != 1) context.error("SIGNATURE", "Implementation must supply exactly one matching "+signature.name(), rule.span()); + } + if (rule.methods().size() != contract.signatures().size()) context.error("SIGNATURE", "Implementation must be complete with no extra methods", rule.span()); + valid.add(rule); + } + for (int i = 0; i < valid.size(); i++) for (int j = 0; j < i; j++) { + var left = valid.get(i); var right = valid.get(j); + context.budget().visit(left.span(), 0); + var substitutions = new HashMap(); + if (unify(term(left.ownerType(), left, 0), term(right.ownerType(), right, 0), substitutions, left.span(), 0) + && unify(term(left.contractType(), left, 0), term(right.contractType(), right, 0), substitutions, left.span(), 0)) + context.error("OVERLAP", "Overlapping implementations can produce the same concrete owner/contract pair; conflicting declaration at "+right.span(), left.span()); + } + } + + private boolean matches(PbsAst.FunctionDecl method, PbsAst.FunctionSignature expected) { + if (!method.name().equals(expected.name()) || method.parameters().size() != expected.parameters().size() + || (method.returnKind() == PbsAst.ReturnKind.RESULT) != (expected.returnKind() == PbsAst.ReturnKind.RESULT) + || !context.resultKey(method.returnType()).equals(context.resultKey(expected.returnType())) + || !context.key(method.resultErrorType()).equals(context.key(expected.resultErrorType()))) return false; + for (int i = 0; i < method.parameters().size(); i++) + if (!context.key(method.parameters().get(i).typeRef()).equals(context.key(expected.parameters().get(i).typeRef()))) return false; + return true; + } + + private Term term(PbsAst.TypeRef type, PbsAst.ImplementsDecl rule, int depth) { + if (type == null) return new Term("void", List.of(), false); + context.budget().visit(type.span(), depth); + if (type.kind() == PbsAst.TypeRefKind.GROUP) return term(type.inner(), rule, depth+1); + if (type.kind() == PbsAst.TypeRefKind.SIMPLE) { + for (int i = 0; i < rule.typeParameters().size(); i++) if (rule.typeParameters().get(i).name().equals(type.name())) + return new Term(PbsContractTypes.nominal(rule)+":"+i, List.of(), true); + } + var children = new ArrayList(); + for (var argument : type.arguments()) children.add(term(argument, rule, depth+1)); + for (var field : type.fields()) children.add(term(field.typeRef(), rule, depth+1)); + if (type.inner() != null) children.add(term(type.inner(), rule, depth+1)); + var declaration = context.declaration(type); + var head = type.kind() == PbsAst.TypeRefKind.SIMPLE ? declaration == null ? type.name() : PbsContractTypes.nominal(declaration) : type.kind().name(); + context.budget().store(type.span(), 32L + head.length()); + return new Term(head, List.copyOf(children), false); + } + + private Term dereference(Term term, Map substitutions, Span site) { + while (term.variable() && substitutions.containsKey(term.head())) { + context.budget().visit(site, 0); term = substitutions.get(term.head()); + } + return term; + } + private boolean occurs(String variable, Term term, Map substitutions, Span site, int depth) { + context.budget().visit(site, depth); + term = dereference(term, substitutions, site); + if (term.variable()) return variable.equals(term.head()); + for (var child : term.children()) if (occurs(variable, child, substitutions, site, depth+1)) return true; + return false; + } + private boolean unify(Term a, Term b, Map substitutions, Span site, int depth) { + context.budget().visit(site, depth); + a = dereference(a, substitutions, site); b = dereference(b, substitutions, site); + if (a.variable() && b.variable() && a.head().equals(b.head())) return true; + if (a.variable()) { + if (occurs(a.head(), b, substitutions, site, depth+1)) return false; + substitutions.put(a.head(), b); return true; + } + if (b.variable()) return unify(b, a, substitutions, site, depth+1); + if (!a.head().equals(b.head()) || a.children().size() != b.children().size()) return false; + for (int i = 0; i < a.children().size(); i++) if (!unify(a.children().get(i), b.children().get(i), substitutions, site, depth+1)) return false; + return true; + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericDiagnostics.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericDiagnostics.java new file mode 100644 index 00000000..3435d42f --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericDiagnostics.java @@ -0,0 +1,55 @@ +package p.studio.compiler.pbs; + +import p.studio.compiler.pbs.ast.PbsAst; +import p.studio.compiler.source.diagnostics.*; +import p.studio.utilities.structures.ReadOnlyList; +import java.util.*; + +/** Presents source applications and retains both ends of specialization diagnostics. */ +public final class PbsGenericDiagnostics extends DiagnosticSink { + private final DiagnosticSink delegate; + private final PbsAst.ApplicationOrigin origin; + private final Map names; + + private PbsGenericDiagnostics(DiagnosticSink delegate, PbsAst.ApplicationOrigin origin, Map names) { + this.delegate = delegate; this.origin = origin; this.names = names; + } + public static DiagnosticSink forDeclaration(PbsAst.TopDecl declaration, DiagnosticSink sink) { + var origin = PbsContractTypes.applicationOrigin(declaration); + return forOrigin(origin, sink); + } + public static DiagnosticSink forOrigin(PbsAst.ApplicationOrigin origin, DiagnosticSink sink) { + return origin == null ? sink : new PbsGenericDiagnostics(sink, origin, Map.of()); + } + public static DiagnosticSink forFile(PbsAst.File file, ReadOnlyList supplemental, DiagnosticSink sink) { + var names = new LinkedHashMap(); + var declarations = new ArrayList<>(file.topDecls().asList()); + if (supplemental != null) declarations.addAll(supplemental.asList()); + for (var declaration : declarations) { + if (declaration instanceof PbsAst.TypeBindingDecl b) declaration = b.declaration(); + var origin = PbsContractTypes.applicationOrigin(declaration); + if (origin != null) names.put(PbsGenericInstantiation.name(declaration), origin.display()); + } + return names.isEmpty() ? sink : new PbsGenericDiagnostics(sink, null, names); + } + @Override public DiagnosticSink report(Diagnostic diagnostic) { + var message = diagnostic.getMessage(); + for (var entry : names.entrySet()) message = message.replace(entry.getKey(), entry.getValue()); + var related = new ArrayList<>(diagnostic.getRelated().asList()); + if (origin != null) { + var chain = origin.chain().stream().limit(4).collect(java.util.stream.Collectors.joining(" -> ")); + if (origin.chain().size() > 4) chain += " -> ... -> "+origin.display(); + message += " (instantiating "+chain+")"; + related.add(new RelatedSpan("Generic declaration "+origin.display(), origin.declaration().span())); + related.add(new RelatedSpan("Application requested here", origin.requestedAt())); + } + delegate.report(new Diagnostic(diagnostic.getSeverity(), diagnostic.getCode(), diagnostic.getPhase(), + diagnostic.getTemplateId(), diagnostic.getPlaceholders(), message, diagnostic.getSpan(), related)); + return this; + } + @Override public Collection asCollection() { return delegate.asCollection(); } + @Override public int errorCount() { return delegate.errorCount(); } + @Override public int warningCount() { return delegate.warningCount(); } + @Override public boolean hasErrors() { return delegate.hasErrors(); } + @Override public boolean hasWarnings() { return delegate.hasWarnings(); } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericInstantiation.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericInstantiation.java new file mode 100644 index 00000000..b6bd2f5e --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericInstantiation.java @@ -0,0 +1,685 @@ +package p.studio.compiler.pbs; + +import p.studio.compiler.pbs.ast.PbsAst; +import p.studio.compiler.pbs.ast.PbsAstRewriter; +import p.studio.compiler.source.Span; +import p.studio.compiler.source.diagnostics.DiagnosticSink; +import p.studio.compiler.source.diagnostics.Diagnostics; +import p.studio.compiler.source.identifiers.FileId; +import p.studio.utilities.structures.ReadOnlyList; + +import java.util.*; +import java.util.stream.Collectors; + +/** Definition-scoped, anchored specialization. All output is ordinary concrete PBS AST. */ +public final class PbsGenericInstantiation { + public record Source(PbsAst.File ast, ReadOnlyList visible, Object module) { + public Source(PbsAst.File ast, ReadOnlyList visible) { this(ast, visible, ast.span().getFileId()); } + } + public record Prepared(Map files, Map> dependencies, Map resolutions) {} + private record Request(PbsAst.TopDecl template, ReadOnlyList arguments, String name, + PbsAst.ApplicationOrigin origin, List chain) {} + + private final DiagnosticSink diagnostics; + private final PbsInstantiationBudget budget; + private final PbsContractTypes types; + private final Map>> scopes = new HashMap<>(); + private final Map modules = new HashMap<>(); + private final Map> concrete = new LinkedHashMap<>(); + private final Map> dependencies = new HashMap<>(); + private final Map resolutions = new HashMap<>(); + private final Map> argumentBindings = new HashMap<>(); + private final Map instances = new LinkedHashMap<>(); + private final ArrayDeque pending = new ArrayDeque<>(); + private final List rules = new ArrayList<>(); + private final List sources; + private final Map anchors = new LinkedHashMap<>(); + private final Set requiredShapes = new LinkedHashSet<>(); + private boolean symbolicProbe; + private final p.studio.compiler.messages.FESurfaceContext surface; + + public PbsGenericInstantiation(List sources, DiagnosticSink diagnostics) { + this(sources, diagnostics, p.studio.compiler.messages.FESurfaceContext.empty()); + } + public PbsGenericInstantiation(List sources, DiagnosticSink diagnostics, p.studio.compiler.messages.FESurfaceContext surface) { + this(sources, diagnostics, surface, null); + } + private PbsGenericInstantiation(List sources, DiagnosticSink diagnostics, + p.studio.compiler.messages.FESurfaceContext surface, PbsInstantiationBudget sharedBudget) { + this.sources = sources; + this.surface = surface == null ? p.studio.compiler.messages.FESurfaceContext.empty() : surface; + this.diagnostics = diagnostics; + budget = sharedBudget == null ? new PbsInstantiationBudget(diagnostics) : sharedBudget; + var declarations = new ArrayList(); + for (var source : sources) { + var file = source.ast().span().getFileId(); + modules.put(file, source.module()); + scopes.put(file, new HashMap<>()); + concrete.put(file, new ArrayList<>()); + for (var d : source.visible()) { declarations.add(d); bind(file, name(d), d); } + for (var d : source.ast().topDecls()) { declarations.add(d); bind(file, name(d), d); } + } + var first = sources.getFirst().ast(); + types = new PbsContractTypes(new PbsAst.File(ReadOnlyList.empty(), ReadOnlyList.wrap(declarations), first.span()), + ReadOnlyList.empty(), diagnostics, budget); + for (var source : sources) for (var d : source.visible()) if (d instanceof PbsAst.TypeBindingDecl b) types.index(b); + for (var source : sources) for (var d : source.ast().topDecls()) { + if (d instanceof PbsAst.ImplementsDecl rule && rules.stream().noneMatch(r -> r.span().equals(rule.span()))) rules.add(rule); + } + } + + public static boolean needed(PbsAst.File file) { + return file.topDecls().stream().anyMatch(d -> !(d instanceof PbsAst.ContractDecl) && !parameters(d).isEmpty()); + } + + private void bind(FileId file, String name, PbsAst.TopDecl declaration) { + if (declaration instanceof PbsAst.TypeBindingDecl b) { name = b.name(); declaration = b.declaration(); } + if (name == null) return; + var list = scopes.computeIfAbsent(file, ignored -> new HashMap<>()).computeIfAbsent(name, ignored -> new ArrayList<>()); + var bound = declaration; + if (list.stream().noneMatch(d -> d == bound || d.span().equals(bound.span()))) list.add(declaration); + } + + public List lookup(String name, Span site) { + return scopes.getOrDefault(site.getFileId(), Map.of()).getOrDefault(name, List.of()); + } + + public PbsAst.TopDecl declaration(PbsAst.TypeRef type) { return types.declaration(type); } + public String key(PbsAst.TypeRef type) { return types.key(type); } + public String resultKey(PbsAst.TypeRef type) { return types.resultKey(type); } + private String signatureKey(PbsAst.FunctionDecl f) { + return f.parameters().stream().map(p -> key(p.typeRef())).collect(Collectors.joining(",")) + "->" + + resultKey(f.returnType()) + (f.returnKind() == PbsAst.ReturnKind.RESULT ? "!"+key(f.resultErrorType()) : ""); + } + public PbsInstantiationBudget budget() { return budget; } + public boolean sameModule(Span a, Span b) { return Objects.equals(modules.get(a.getFileId()), modules.get(b.getFileId())); } + + public Prepared prepare() { + try { + validateDeclarations(); + for (var source : sources) { + var output = concrete.get(source.ast().span().getFileId()); + var rewrite = new ConcreteRewriter(Map.of(), null, List.of()); + for (var d : source.ast().topDecls()) { + if (!parameters(d).isEmpty()) continue; + output.add(rewrite.declaration(d)); + } + } + while (!pending.isEmpty()) { + var request = pending.removeFirst(); budget.origin(request.origin()); + try { materialize(request); } finally { budget.origin(null); } + } + } catch (PbsInstantiationBudget.Exhausted exhausted) { + pending.clear(); + } + var files = new LinkedHashMap(); + for (var source : sources) { + var file = source.ast().span().getFileId(); + for (var binding : argumentBindings.getOrDefault(file, Map.of()).entrySet()) { + var original = binding.getValue(); + var resolved = concrete.getOrDefault(original.span().getFileId(), List.of()).stream() + .filter(d -> d.getClass() == original.getClass() && d.span().equals(original.span()) + && PbsContractTypes.applicationOrigin(d) == null).findFirst().orElse(original); + concrete.get(file).add(new PbsAst.TypeBindingDecl(binding.getKey(), resolved, source.ast().span())); + } + files.put(file, new PbsAst.File(source.ast().imports(), ReadOnlyList.wrap(concrete.get(file)), source.ast().span())); + } + return new Prepared(Map.copyOf(files), dependencies, Map.copyOf(resolutions)); + } + + private void validateDeclarations() { + for (var source : sources) { + var duplicates = new HashMap(); + for (var d : source.ast().topDecls()) { + validateSelfPositions(d); + var names = new HashSet(); + for (var p : parameters(d)) if (!names.add(p.name())) error("PARAMETER", "Duplicate type parameter " + p.name(), p.span()); + if (d instanceof PbsAst.FunctionDecl f && !f.typeParameters().isEmpty()) { + if (f.lifecycleMarker() != PbsAst.LifecycleMarker.NONE) error("LIFECYCLE", "Lifecycle functions cannot declare type parameters", f.span()); + var env = new HashMap(); + for (int i = 0; i < f.typeParameters().size(); i++) env.put(f.typeParameters().get(i).name(), PbsAst.TypeRef.simple("$parameter"+i, f.span())); + var signature = new PbsAstRewriter() { + @Override public PbsAst.TypeRef type(PbsAst.TypeRef t) { + return t != null && t.kind() == PbsAst.TypeRefKind.SIMPLE && env.containsKey(t.name()) ? env.get(t.name()) : super.type(t); + } + }.function(f); + var duplicateKey = f.name()+"#"+f.typeParameters().size()+"#"+signatureKey(signature); + if (duplicates.putIfAbsent(duplicateKey, f) != null) error("DUPLICATE", "Generic overloads differ only by parameter renaming: " + f.name(), f.span()); + } + if (d instanceof PbsAst.StructDecl s) for (var m : s.methods()) rejectMethodParameters(m); + if (d instanceof PbsAst.ServiceDecl s) for (var m : s.methods()) rejectMethodParameters(m); + if (d instanceof PbsAst.ImplementsDecl i) for (var m : i.methods()) rejectMethodParameters(m); + } + } + validateRules(); + // Symbolic checking is independent of which concrete applications are requested. + new PbsGenericTemplateValidator(this, diagnostics).validate(sources); + if (!diagnostics.hasErrors()) validateSymbolicBodies(); + } + + private void rejectMethodParameters(PbsAst.FunctionDecl method) { + if (!method.typeParameters().isEmpty()) error("METHOD", "Methods cannot declare their own type parameters", method.span()); + } + + private void validateSelfPositions(PbsAst.TopDecl declaration) { + new PbsAstRewriter() { + private boolean allowed; + private boolean owner; + @Override public PbsAst.TopDecl declaration(PbsAst.TopDecl d) { + boolean previous = owner; + owner = d instanceof PbsAst.StructDecl || d instanceof PbsAst.ServiceDecl; + try { return super.declaration(d); } finally { owner = previous; } + } + @Override public PbsAst.FunctionDecl function(PbsAst.FunctionDecl f) { + boolean previous = allowed; allowed = owner; + try { return super.function(f); } finally { allowed = previous; } + } + @Override public PbsAst.CtorDecl constructor(PbsAst.CtorDecl c) { + boolean previous = allowed; allowed = owner; + try { return super.constructor(c); } finally { allowed = previous; } + } + @Override public PbsAst.TypeRef type(PbsAst.TypeRef t) { + if (t != null && t.kind() == PbsAst.TypeRefKind.SELF && !allowed) + Diagnostics.error(diagnostics, "E_SEM_INVALID_SELF_CONTEXT", "Self requires a struct/service method or constructor", t.span()); + return super.type(t); + } + }.declaration(declaration); + } + + public static ReadOnlyList parameters(PbsAst.TopDecl d) { + return switch (d) { + case PbsAst.StructDecl s -> s.typeParameters(); + case PbsAst.ContractDecl c -> c.typeParameters(); + case PbsAst.FunctionDecl f -> f.typeParameters(); + case PbsAst.ImplementsDecl i -> i.typeParameters(); + case null, default -> ReadOnlyList.empty(); + }; + } + + public static String name(PbsAst.TopDecl d) { + return switch (d) { + case PbsAst.StructDecl s -> s.name(); + case PbsAst.ContractDecl c -> c.name(); + case PbsAst.FunctionDecl f -> f.name(); + case PbsAst.ServiceDecl s -> s.name(); + case PbsAst.BuiltinTypeDecl b -> b.name(); + case PbsAst.HostDecl h -> h.name(); + case PbsAst.EnumDecl e -> e.name(); + case PbsAst.ErrorDecl e -> e.name(); + case PbsAst.GlobalDecl g -> g.name(); + case PbsAst.ConstDecl c -> c.name(); + case PbsAst.TypeBindingDecl b -> b.name(); + default -> null; + }; + } + + public static String nominalBinding(PbsAst.TopDecl declaration) { return "$nominal$"+PbsContractTypes.nominal(declaration); } + + private PbsAst.TypeRef canonicalArgument(PbsAst.TypeRef argument, Span definition) { + return new PbsAstRewriter() { + @Override public PbsAst.TypeRef type(PbsAst.TypeRef t) { + if (t == null) return null; + var rewritten = super.type(t); + var d = types.declaration(t); + if (t.kind() != PbsAst.TypeRefKind.SIMPLE || d == null || PbsContractTypes.applicationOrigin(d) != null) return rewritten; + var alias = nominalBinding(d); + types.index(new PbsAst.TypeBindingDecl(alias, d, definition)); + var file = concrete.containsKey(definition.getFileId()) ? definition.getFileId() : sources.getFirst().ast().span().getFileId(); + argumentBindings.computeIfAbsent(file, ignored -> new LinkedHashMap<>()).put(alias, d); + dependency(definition, d); + return PbsAst.TypeRef.simple(alias, t.span()); + } + }.type(argument); + } + + private Request request(PbsAst.TopDecl template, ReadOnlyList arguments, Span site, List chain, String callableName) { + if (parameters(template).size() != arguments.size()) { + error("ARITY", name(template)+" requires "+parameters(template).size()+" explicit type argument(s)", site); + return null; + } + var application = PbsAst.TypeRef.applied(name(template), arguments, template.span()); + var applicationKey = template instanceof PbsAst.FunctionDecl ? PbsContractTypes.nominal(template)+"["+ + arguments.stream().map(types::key).map(k -> k.length()+":"+k).collect(Collectors.joining())+"]" : types.key(application); + var existing = instances.get(applicationKey); + if (existing != null) { dependency(site, template); resolutions.put(site, existing.name()); return existing; } + budget.visit(site, chain.size()); budget.instance(site); budget.store(site, applicationKey.length()); + var display = name(template)+"<"+arguments.stream().map(types::display).collect(Collectors.joining(", "))+">"; + arguments = PbsAstRewriter.map(arguments, a -> canonicalArgument(a, template.span())); + var instanceName = callableName == null ? "$generic$"+applicationKey : callableName; + var path = new ArrayList<>(chain); path.add(display); + var origin = new PbsAst.ApplicationOrigin(template, arguments, applicationKey, display, site, ReadOnlyList.wrap(path)); + var request = new Request(template, arguments, instanceName, origin, List.copyOf(path)); + instances.put(applicationKey, request); // Anchor before any field, signature or body is traversed. + resolutions.put(site, instanceName); + PbsAst.TopDecl anchor = switch (template) { + case PbsAst.StructDecl s -> new PbsAst.StructDecl(instanceName, ReadOnlyList.empty(), ReadOnlyList.empty(), ReadOnlyList.empty(), ReadOnlyList.empty(), s.hasBody(), s.attributes(), origin, s.span()); + case PbsAst.ContractDecl c -> new PbsAst.ContractDecl(instanceName, ReadOnlyList.empty(), ReadOnlyList.empty(), c.attributes(), origin, c.span()); + default -> null; + }; + if (anchor != null) { types.index(anchor); scopes.values().forEach(scope -> scope.put(instanceName, List.of(anchor))); } + if (anchor != null) anchors.put(instanceName, anchor); + pending.addLast(request); + dependency(site, template); + return request; + } + + private void dependency(Span use, PbsAst.TopDecl template) { + dependencies.computeIfAbsent(use.getFileId(), ignored -> new LinkedHashSet<>()).add(template); + } + + private Map environment(PbsAst.TopDecl template, ReadOnlyList arguments) { + var result = new LinkedHashMap(); + for (int i = 0; i < parameters(template).size(); i++) result.put(parameters(template).get(i).name(), arguments.get(i)); + return Map.copyOf(result); + } + + private void materialize(Request request) { + var template = request.template(); + var rewrite = new ConcreteRewriter(environment(template, request.arguments()), + template instanceof PbsAst.StructDecl ? PbsAst.TypeRef.simple(request.name(), template.span()) : null, request.chain()); + var instance = concreteDeclaration(request, rewrite); + concrete.getOrDefault(template.span().getFileId(), concrete.values().iterator().next()).add(instance); + types.index(instance); + anchors.put(request.name(), instance); + scopes.values().forEach(scope -> scope.put(request.name(), List.of(instance))); + if (instance instanceof PbsAst.StructDecl s) { + checkCollisions(s.methods(), request); + checkCollisions(PbsAstRewriter.map(s.ctors(), c -> new PbsAst.FunctionDecl(c.name(), c.parameters(), + PbsAst.ReturnKind.EXPLICIT_UNIT, PbsAst.TypeRef.unit(c.span()), null, ReadOnlyList.empty(), + PbsAst.LifecycleMarker.NONE, c.body(), c.span())), request); + if (symbolicProbe) return; + for (var rule : rules) if (!rule.typeParameters().isEmpty() && types.declaration(rule.ownerType()) == template) { + var bindings = new LinkedHashMap(); + for (int i = 0; i < rule.ownerType().arguments().size(); i++) bindings.put(rule.ownerType().arguments().get(i).name(), request.arguments().get(i)); + var ruleRewrite = new ConcreteRewriter(bindings, PbsAst.TypeRef.simple(request.name(), rule.span()), request.chain()); + ruleRewrite.implicitLocals = Map.of(rule.binderName(), PbsAst.TypeRef.simple(request.name(), rule.span())); + var implementation = new PbsAst.ImplementsDecl(ReadOnlyList.empty(), ruleRewrite.type(rule.contractType()), + PbsAst.TypeRef.simple(request.name(), rule.ownerType().span()), rule.binderName(), + PbsAstRewriter.map(rule.methods(), ruleRewrite::function), rule.span()); + concrete.getOrDefault(rule.span().getFileId(), concrete.values().iterator().next()).add(implementation); + } + } + } + + private PbsAst.TopDecl concreteDeclaration(Request request, ConcreteRewriter rewrite) { + var d = rewrite.declaration(request.template()); + return switch (d) { + case PbsAst.StructDecl s -> new PbsAst.StructDecl(request.name(), ReadOnlyList.empty(), s.fields(), s.methods(), s.ctors(), s.hasBody(), s.attributes(), request.origin(), s.span()); + case PbsAst.ContractDecl c -> new PbsAst.ContractDecl(request.name(), ReadOnlyList.empty(), c.signatures(), c.attributes(), request.origin(), c.span()); + case PbsAst.FunctionDecl f -> new PbsAst.FunctionDecl(request.name(), ReadOnlyList.empty(), f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.lifecycleMarker(), f.body(), request.origin(), f.span()); + default -> throw new IllegalStateException("Unexpected generic declaration"); + }; + } + + /** Validate control flow, constructors and ordinary operations with opaque symbolic witnesses. + * Dependencies contribute shapes only: expanding families remain an application-time concern. */ + private void validateSymbolicBodies() { + for (var source : sources) for (var template : source.ast().topDecls()) { + if (!(template instanceof PbsAst.StructDecl || template instanceof PbsAst.FunctionDecl || template instanceof PbsAst.ImplementsDecl) + || parameters(template).isEmpty()) continue; + budget.visit(template.span(), 0); + var symbolicDiagnostics = DiagnosticSink.empty(); + var probe = new PbsGenericInstantiation(sources, symbolicDiagnostics, surface, budget); + probe.symbolicProbe = true; + var witnesses = new ArrayList(); + var arguments = new ArrayList(); + var presentation = new LinkedHashMap(); + for (int i = 0; i < parameters(template).size(); i++) { + var parameter = parameters(template).get(i); + var name = "$symbol$"+PbsContractTypes.nominal(template)+":"+i; + var witness = new PbsAst.StructDecl(name, ReadOnlyList.empty(), ReadOnlyList.empty(), ReadOnlyList.empty(), false, ReadOnlyList.empty(), parameter.span()); + witnesses.add(witness); probe.types.index(witness); + arguments.add(PbsAst.TypeRef.simple(name, parameter.span())); + presentation.put(name, parameter.name()); presentation.put(nominalBinding(witness), parameter.name()); + } + String callableName = null; + if (template instanceof PbsAst.FunctionDecl f) { + var candidates = probe.lookup(f.name(), f.span()).stream().filter(d -> d instanceof PbsAst.FunctionDecl && parameters(d).size() == f.typeParameters().size()).toList(); + callableName = probe.functionGroup(candidates, ReadOnlyList.wrap(arguments)); + } + Request request = null; + List current; + if (template instanceof PbsAst.ImplementsDecl rule) { + var env = probe.environment(rule, ReadOnlyList.wrap(arguments)); + var rewrite = probe.new ConcreteRewriter(env, null, List.of()); + var owner = rewrite.type(rule.ownerType()); + rewrite = probe.new ConcreteRewriter(env, owner, List.of()); + rewrite.implicitLocals = Map.of(rule.binderName(), owner); + var target = rewrite.type(rule.contractType()); + probe.requiredShapes.add(target.name()); + var methods = PbsAstRewriter.map(rule.methods(), rewrite::function); + current = List.of(new PbsAst.ImplementsDecl(ReadOnlyList.empty(), target, owner, rule.binderName(), methods, rule.span())); + } else { + request = probe.request(template, ReadOnlyList.wrap(arguments), template.span(), List.of(), callableName); + if (request == null) continue; + probe.pending.remove(request); + probe.materialize(request); + current = probe.concrete.values().stream().flatMap(Collection::stream).toList(); + } + var supplemental = new ArrayList(witnesses); + var visible = new ArrayList(source.visible().asList()); + visible.addAll(source.ast().topDecls().asList()); + var shapeKeys = new HashSet(); + for (var declaration : visible) { + String alias = null; + if (declaration instanceof PbsAst.TypeBindingDecl b) { alias = b.name(); declaration = b.declaration(); } + if (!parameters(declaration).isEmpty() || declaration instanceof PbsAst.ImplementsDecl) continue; + var shape = probe.shapeRewriter(Map.of(), declaration instanceof PbsAst.StructDecl || declaration instanceof PbsAst.ServiceDecl + ? PbsAst.TypeRef.simple(name(declaration), declaration.span()) : null).declaration(declaration); + if (shape instanceof PbsAst.FunctionDecl f && alias != null) shape = new PbsAst.FunctionDecl(alias, f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.lifecycleMarker(), f.body(), f.span()); + else if (alias != null) shape = new PbsAst.TypeBindingDecl(alias, shape, declaration.span()); + var shapeKey = name(shape)+":"+shape.span(); + if (shapeKeys.add(shapeKey)) supplemental.add(shape); + } + while (!probe.pending.isEmpty()) { + var dependency = probe.pending.removeFirst(); + if (dependency == request) continue; + var fullShape = dependency.template() instanceof PbsAst.FunctionDecl || probe.requiredShapes.contains(dependency.name()); + var shape = fullShape ? probe.concreteDeclaration(dependency, probe.shapeRewriter( + probe.environment(dependency.template(), dependency.arguments()), PbsAst.TypeRef.simple(dependency.name(), dependency.template().span()))) + : probe.anchors.get(dependency.name()); + if (shape != null) { supplemental.add(shape); probe.types.index(shape); } + } + for (var bindings : probe.argumentBindings.values()) for (var binding : bindings.entrySet()) + supplemental.add(new PbsAst.TypeBindingDecl(binding.getKey(), binding.getValue(), template.span())); + var ast = new PbsAst.File(source.ast().imports(), ReadOnlyList.wrap(current), source.ast().span()); + var supplementalList = ReadOnlyList.wrap(supplemental); + new p.studio.compiler.pbs.semantics.PbsDeclarationSemanticsValidator(new p.studio.compiler.source.tables.NameTable()).validate(ast, symbolicDiagnostics); + new p.studio.compiler.pbs.semantics.PbsFlowSemanticsValidator().validate(ast, supplementalList, surface, symbolicDiagnostics); + for (var diagnostic : symbolicDiagnostics) if (diagnostic.getSeverity().isError()) { + var message = diagnostic.getMessage(); + for (var entry : presentation.entrySet()) message = message.replace(entry.getKey(), entry.getValue()); + Diagnostics.error(diagnostics, diagnostic.getCode(), message, diagnostic.getSpan()); + } + } + } + + private ConcreteRewriter shapeRewriter(Map bindings, PbsAst.TypeRef owner) { + return new ConcreteRewriter(bindings, owner, List.of()) { + @Override public PbsAst.FunctionDecl function(PbsAst.FunctionDecl f) { + return new PbsAst.FunctionDecl(f.name(), f.typeParameters(), map(f.parameters(), this::parameter), f.returnKind(), type(f.returnType()), + type(f.resultErrorType()), f.attributes(), f.lifecycleMarker(), new PbsAst.Block(ReadOnlyList.empty(), null, f.body().span()), f.applicationOrigin(), f.span()); + } + @Override public PbsAst.CtorDecl constructor(PbsAst.CtorDecl c) { + return new PbsAst.CtorDecl(c.name(), map(c.parameters(), this::parameter), new PbsAst.Block(ReadOnlyList.empty(), null, c.body().span()), c.span()); + } + }; + } + + private String functionGroup(List candidates, ReadOnlyList arguments) { + return "$generic$fn$"+candidates.stream().map(PbsContractTypes::nominal).sorted().collect(Collectors.joining("$"))+ + "["+arguments.stream().map(types::key).map(k -> k.length()+":"+k).collect(Collectors.joining())+"]"; + } + + private void checkCollisions(ReadOnlyList methods, Request request) { + var signatures = new HashMap(); + for (var method : methods) { + var shape = method.name()+":"+signatureKey(method); + var previous = signatures.putIfAbsent(shape, method); + if (previous != null) error("COLLISION", "Overloads collapse in "+request.origin().display()+": "+method.name()+ + "; declarations at "+previous.span()+" and "+method.span(), request.origin().requestedAt()); + } + } + + private void validateRules() { + // Implemented below using bounded symbolic owner/target unification, independent of requested applications. + new PbsGenericCoherence(this, diagnostics).validate(rules); + } + + private class ConcreteRewriter extends PbsAstRewriter { + private final Map bindings; + private final PbsAst.TypeRef self; + private final List chain; + private Map locals = new HashMap<>(); + private Map implicitLocals = Map.of(); + private PbsAst.TypeRef result; + private PbsAst.TypeRef blockExpected; + + private ConcreteRewriter(Map bindings, PbsAst.TypeRef self, List chain) { + this.bindings = Map.copyOf(bindings); this.self = self; this.chain = chain; + } + + @Override public PbsAst.TopDecl declaration(PbsAst.TopDecl d) { + if (self == null && (d instanceof PbsAst.StructDecl || d instanceof PbsAst.ServiceDecl)) + return new ConcreteRewriter(bindings, PbsAst.TypeRef.simple(name(d), d.span()), chain).declaration(d); + return super.declaration(d); + } + + @Override public PbsAst.TypeRef type(PbsAst.TypeRef t) { + if (t == null) return null; + budget.visit(t.span(), chain.size()); + budget.store(t.span(), 64); + if (t.kind() == PbsAst.TypeRefKind.SELF && self != null) return self; + if (t.kind() == PbsAst.TypeRefKind.SIMPLE && bindings.containsKey(t.name())) { + if (!t.arguments().isEmpty()) error("PARAMETER", "Type parameter cannot be applied", t.span()); + return bindings.get(t.name()); + } + var rewritten = super.type(t); + var declaration = types.declaration(rewritten); + if (rewritten.kind() == PbsAst.TypeRefKind.SIMPLE && declaration != null && !parameters(declaration).isEmpty()) { + var request = request(declaration, rewritten.arguments(), t.span(), chain, null); + return request == null ? PbsAst.TypeRef.error(t.span()) : PbsAst.TypeRef.simple(request.name(), t.span()); + } + return rewritten; + } + + @Override public PbsAst.FunctionDecl function(PbsAst.FunctionDecl f) { + var previousLocals = locals; var previousResult = result; + locals = new HashMap<>(implicitLocals); + f.parameters().forEach(p -> locals.put(p.name(), type(p.typeRef()))); + result = type(f.returnType()); + try { return super.function(f); } + finally { locals = previousLocals; result = previousResult; } + } + + @Override public PbsAst.CtorDecl constructor(PbsAst.CtorDecl c) { + var previous = locals; var oldResult = result; + locals = new HashMap<>(); + c.parameters().forEach(p -> locals.put(p.name(), type(p.typeRef()))); + result = null; + try { return super.constructor(c); } + finally { locals = previous; result = oldResult; } + } + + @Override public PbsAst.Block block(PbsAst.Block b) { + if (b == null) return null; + var previous = locals; locals = new HashMap<>(locals); + try { return new PbsAst.Block(map(b.statements(), this::statement), expression(b.tailExpression(), blockExpected), b.span()); } + finally { locals = previous; } + } + + @Override public PbsAst.Statement statement(PbsAst.Statement s) { + budget.visit(s.span(), chain.size()); budget.store(s.span(), 64); + if (s instanceof PbsAst.LetStatement l) { + var expected = type(l.explicitType()); + var value = expression(l.initializer(), expected); + locals.put(l.name(), expected == null ? infer(value) : expected); + return new PbsAst.LetStatement(l.isConst(), l.name(), l.nameSpan(), expected, value, l.span()); + } + if (s instanceof PbsAst.ReturnStatement r) return new PbsAst.ReturnStatement(expression(r.value(), result), r.span()); + if (s instanceof PbsAst.AssignStatement a) { + var target = a.target().expression(); + var expected = target == null ? locals.get(a.target().rootName()) : infer(target); + return new PbsAst.AssignStatement(a.target(), a.operator(), expression(a.value(), expected), a.span()); + } + return super.statement(s); + } + + @Override public PbsAst.Expression expression(PbsAst.Expression e, PbsAst.TypeRef expected) { + if (e != null) { budget.visit(e.span(), chain.size()); budget.store(e.span(), 64); } + if (e instanceof PbsAst.CallExpr c) { + var callee = expression(c.callee()); + var signatures = callableSignatures(callee); + var candidates = signatures.stream().filter(s -> s.parameters().size() == c.arguments().size()).toList(); + var arguments = new ArrayList(); + for (int i = 0; i < c.arguments().size(); i++) arguments.add(expression(c.arguments().get(i), + candidates.size() == 1 ? candidates.getFirst().parameters().get(i).typeRef() : null)); + return new PbsAst.CallExpr(callee, ReadOnlyList.wrap(arguments), c.span()); + } + if (e instanceof PbsAst.ApplyExpr a) { + var callee = expression(a.callee()); + var signatures = callableSignatures(callee); + PbsAst.TypeRef argumentType = null; + if (signatures.size() == 1) { + var parameters = signatures.getFirst().parameters(); + argumentType = parameters.size() == 1 ? parameters.getFirst().typeRef() + : PbsAst.TypeRef.namedTuple(map(parameters, p -> new PbsAst.NamedTypeField(p.name(), p.typeRef(), p.span())), a.span()); + } + return new PbsAst.ApplyExpr(callee, expression(a.argument(), argumentType), a.span()); + } + if (e instanceof PbsAst.LambdaExpr l) { + var previous = locals; var oldResult = result; + locals = new HashMap<>(locals); + for (var p : l.parameters()) locals.put(p.name(), type(p.typeRef())); + result = type(l.returnType()); + try { return super.expression(e, expected); } + finally { locals = previous; result = oldResult; } + } + if (e instanceof PbsAst.SomeExpr s) return new PbsAst.SomeExpr(expression(s.value(), + expected != null && expected.kind() == PbsAst.TypeRefKind.OPTIONAL ? expected.inner() : null), s.span()); + if (e instanceof PbsAst.OkExpr o) return new PbsAst.OkExpr(expression(o.value(), expected), o.span()); + if (e instanceof PbsAst.TupleExpr t && expected != null && expected.kind() == PbsAst.TypeRefKind.NAMED_TUPLE + && t.items().size() == expected.fields().size()) { + var items = new ArrayList(); + for (int i = 0; i < t.items().size(); i++) { var item = t.items().get(i); + items.add(new PbsAst.TupleItem(item.label(), expression(item.expression(), expected.fields().get(i).typeRef()), item.span())); } + return new PbsAst.TupleExpr(ReadOnlyList.wrap(items), t.span()); + } + if (e instanceof PbsAst.BlockExpr || e instanceof PbsAst.IfExpr || e instanceof PbsAst.SwitchExpr || e instanceof PbsAst.HandleExpr) { + var previous = blockExpected; blockExpected = expected; + try { return super.expression(e, expected); } finally { blockExpected = previous; } + } + if (e instanceof PbsAst.IdentifierExpr i && i.applied()) { + if (locals.containsKey(i.name())) { + error("FUNCTION_ARGUMENTS", "Type arguments apply only to named generic free functions", i.span()); + return i; + } + var arguments = map(i.typeArguments(), this::type); + var candidates = lookup(i.name(), i.span()).stream().filter(d -> d instanceof PbsAst.FunctionDecl && + !parameters(d).isEmpty() && parameters(d).size() == arguments.size()).toList(); + if (candidates.isEmpty()) { error("FUNCTION_ARITY", "No generic free function "+i.name()+" accepts "+arguments.size()+" type argument(s)", i.span()); return i; } + var group = functionGroup(candidates, arguments); + var signatures = new HashSet(); + for (var candidate : candidates) { + var request = request(candidate, arguments, i.span(), chain, group); + if (request == null) continue; + var original = (PbsAst.FunctionDecl) candidate; + var env = environment(candidate, arguments); + var substituted = new PbsAst.FunctionDecl(original.name(), map(original.parameters(), p -> + new PbsAst.Parameter(p.name(), PbsTypeSubstitution.substitute(p.typeRef(), env), p.span())), original.returnKind(), + PbsTypeSubstitution.substitute(original.returnType(), env), PbsTypeSubstitution.substitute(original.resultErrorType(), env), + original.attributes(), original.lifecycleMarker(), original.body(), original.span()); + var signature = signatureKey(substituted); + if (!signatures.add(signature)) error("COLLISION", "Generic overload signatures collapse in "+i.name(), i.span()); + } + return new PbsAst.IdentifierExpr(group, i.span()); + } + if (e instanceof PbsAst.IdentifierExpr i && !i.applied() && !locals.containsKey(i.name())) { + var functions = lookup(i.name(), i.span()).stream().filter(d -> d instanceof PbsAst.FunctionDecl).toList(); + if (!functions.isEmpty() && functions.stream().allMatch(d -> !parameters(d).isEmpty())) + error("FUNCTION_ARGUMENTS", "Generic function "+i.name()+" requires explicit type arguments", i.span()); + } + if (e instanceof PbsAst.NewExpr n && !n.typeName().equals("array")) { + var raw = PbsAst.TypeRef.simple(n.typeName(), n.span()); + var declaration = types.declaration(raw); + if (bindings.containsKey(n.typeName())) { error("CONSTRUCTION", "A type parameter has no implicit constructor", n.span()); return n; } + if (declaration instanceof PbsAst.StructDecl s && !s.typeParameters().isEmpty()) { + var applied = n.explicitType(); + if (applied == null) { + var context = expected; + while (context != null && context.kind() == PbsAst.TypeRefKind.GROUP) context = context.inner(); + var target = context == null ? null : types.declaration(context); + var origin = PbsContractTypes.applicationOrigin(target); + if (origin != null && origin.declaration() == declaration) applied = PbsAst.TypeRef.applied(n.typeName(), origin.arguments(), n.span()); + else if (context != null && target == declaration && !context.arguments().isEmpty()) applied = context; + else { error("CONTEXT", "Construction of "+n.typeName()+" requires explicit arguments or an expected application", n.span()); return n; } + } + var concreteType = type(applied); + if (symbolicProbe) requiredShapes.add(concreteType.name()); + var fields = constructorParameters(concreteType, n.ctorName()); + var arguments = new ArrayList(); + for (int i = 0; i < n.arguments().size(); i++) arguments.add(expression(n.arguments().get(i), + fields.size() == n.arguments().size() ? fields.get(i).typeRef() : null)); + return new PbsAst.NewExpr(concreteType.name(), n.ctorName(), ReadOnlyList.wrap(arguments), null, false, n.span()); + } + } + return super.expression(e, expected); + } + + private PbsAst.TypeRef infer(PbsAst.Expression e) { + return switch (e) { + case PbsAst.IdentifierExpr i -> locals.get(i.name()); + case PbsAst.ThisExpr t -> self; + case PbsAst.NewExpr n -> n.explicitType() != null ? n.explicitType() : PbsAst.TypeRef.simple(n.typeName(), n.span()); + case PbsAst.GroupExpr g -> infer(g.expression()); + case PbsAst.CallExpr c -> { var callables = callableSignatures(c.callee()); yield callables.size() == 1 ? callables.getFirst().returnType() : null; } + case PbsAst.MemberExpr m -> { + var receiver = infer(m.receiver()); + if (symbolicProbe && receiver != null) requiredShapes.add(receiver.name()); + var declaration = types.declaration(receiver); + var origin = PbsContractTypes.applicationOrigin(declaration); + if (origin != null) declaration = origin.declaration(); + if (declaration instanceof PbsAst.StructDecl s) { + var field = s.fields().stream().filter(f -> f.name().equals(m.memberName())).findFirst(); + yield field.isEmpty() ? null : origin == null ? field.get().typeRef() + : new ConcreteRewriter(environment(s, origin.arguments()), receiver, chain).type(field.get().typeRef()); + } + yield null; + } + case null, default -> null; + }; + } + + private List callableSignatures(PbsAst.Expression expression) { + if (expression instanceof PbsAst.IdentifierExpr i) { + var local = locals.get(i.name()); + if (local != null && local.kind() == PbsAst.TypeRefKind.FN) return List.of(new PbsAst.FunctionSignature(i.name(), + map(local.fields(), f -> new PbsAst.Parameter(f.label(), f.typeRef(), f.span())), PbsAst.ReturnKind.PLAIN, + local.inner(), null, ReadOnlyList.empty(), i.span())); + var requests = instances.values().stream().filter(r -> r.name().equals(i.name()) && r.template() instanceof PbsAst.FunctionDecl).toList(); + if (!requests.isEmpty()) return requests.stream().map(r -> { + var f = (PbsAst.FunctionDecl)r.template(); + return new ConcreteRewriter(environment(f, r.arguments()), null, r.chain()).signature(signature(f)); + }).toList(); + return lookup(i.name(), i.span()).stream().filter(d -> d instanceof PbsAst.FunctionDecl && parameters(d).isEmpty()) + .map(d -> signature((PbsAst.FunctionDecl)d)).toList(); + } + if (expression instanceof PbsAst.MemberExpr member) { + var receiver = infer(member.receiver()); + if (symbolicProbe && receiver != null) requiredShapes.add(receiver.name()); + var d = types.declaration(receiver); + if (d == null && member.receiver() instanceof PbsAst.IdentifierExpr i) + d = lookup(i.name(), i.span()).stream().findFirst().orElse(null); + var origin = PbsContractTypes.applicationOrigin(d); + if (origin != null) d = origin.declaration(); + var signatures = switch (d) { + case PbsAst.StructDecl s -> s.methods().stream().map(this::signature).toList(); + case PbsAst.ServiceDecl s -> s.methods().stream().map(this::signature).toList(); + case PbsAst.ContractDecl c -> c.signatures().asList(); + case PbsAst.HostDecl h -> h.signatures().asList(); + case PbsAst.BuiltinTypeDecl b -> b.signatures().asList(); + case null, default -> List.of(); + }; + var rewrite = origin == null ? this : new ConcreteRewriter(environment(d, origin.arguments()), receiver, chain); + return signatures.stream().filter(s -> s.name().equals(member.memberName())).map(rewrite::signature).toList(); + } + return List.of(); + } + + private PbsAst.FunctionSignature signature(PbsAst.FunctionDecl f) { + return new PbsAst.FunctionSignature(f.name(), f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.span()); + } + private ReadOnlyList constructorParameters(PbsAst.TypeRef owner, String constructor) { + var d = types.declaration(owner); + var origin = PbsContractTypes.applicationOrigin(d); + if (origin != null) d = origin.declaration(); + if (!(d instanceof PbsAst.StructDecl s)) return ReadOnlyList.empty(); + var rewrite = origin == null ? this : new ConcreteRewriter(environment(s, origin.arguments()), owner, chain); + if (constructor == null) return map(s.fields(), f -> new PbsAst.Parameter(f.name(), rewrite.type(f.typeRef()), f.span())); + var candidates = s.ctors().stream().filter(c -> c.name().equals(constructor)).toList(); + return candidates.size() == 1 ? map(candidates.getFirst().parameters(), rewrite::parameter) : ReadOnlyList.empty(); + } + } + + void error(String suffix, String message, Span span) { Diagnostics.error(diagnostics, "E_SEM_GENERIC_"+suffix, message, span); } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericTemplateValidator.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericTemplateValidator.java new file mode 100644 index 00000000..0499d609 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericTemplateValidator.java @@ -0,0 +1,288 @@ +package p.studio.compiler.pbs; + +import p.studio.compiler.pbs.ast.PbsAst; +import p.studio.compiler.pbs.ast.PbsAstRewriter; +import p.studio.compiler.source.Span; +import p.studio.compiler.source.diagnostics.DiagnosticSink; +import p.studio.utilities.structures.ReadOnlyList; +import java.util.*; + +/** Checks template capabilities in their definition environment, before concrete specialization. */ +final class PbsGenericTemplateValidator { + private static final Set BUILTINS = Set.of("int", "long", "float", "bool", "str", "Addressable"); + private record Callable(ReadOnlyList parameters, PbsAst.TypeRef result) {} + private final PbsGenericInstantiation context; + PbsGenericTemplateValidator(PbsGenericInstantiation context, DiagnosticSink diagnostics) { this.context = context; } + + void validate(List sources) { + for (var source : sources) for (var d : source.ast().topDecls()) { + if (PbsGenericInstantiation.parameters(d).isEmpty()) continue; + var body = new SymbolicBody(d); + body.declaration(d); + } + } + + private final class SymbolicBody extends PbsAstRewriter { + private final Set parameters; + private final PbsAst.TypeRef owner; + private Map locals = new HashMap<>(); + private final IdentityHashMap inferred = new IdentityHashMap<>(); + private PbsAst.TypeRef result; + private boolean selfAllowed; + + SymbolicBody(PbsAst.TopDecl template) { + parameters = new HashSet<>(PbsGenericInstantiation.parameters(template).stream().map(PbsAst.TypeParameter::name).toList()); + owner = switch (template) { + case PbsAst.StructDecl s -> PbsAst.TypeRef.applied(s.name(), map(s.typeParameters(), p -> PbsAst.TypeRef.simple(p.name(), p.span())), s.span()); + case PbsAst.ImplementsDecl i -> i.ownerType(); + default -> null; + }; + if (template instanceof PbsAst.ImplementsDecl i) locals.put(i.binderName(), i.ownerType()); + } + + @Override public PbsAst.TypeRef type(PbsAst.TypeRef t) { + if (t == null) return null; + context.budget().visit(t.span(), 0); + if (t.kind() == PbsAst.TypeRefKind.SELF && !selfAllowed) + context.error("SELF", "Self is only valid in existing owner method/constructor scopes", t.span()); + if (t.kind() == PbsAst.TypeRefKind.ARRAY && t.inner() != null && + (t.inner().kind() == PbsAst.TypeRefKind.OPTIONAL || t.inner().kind() == PbsAst.TypeRefKind.UNIT)) + context.error("POSITION", "Array elements must be non-optional value types", t.span()); + if (t.kind() == PbsAst.TypeRefKind.SIMPLE) { + if (parameters.contains(t.name())) { + if (!t.arguments().isEmpty()) context.error("PARAMETER", "Type parameter cannot be applied", t.span()); + } else { + var declaration = context.declaration(t); + if (declaration == null && !BUILTINS.contains(t.name())) context.error("PARAMETER", "Unresolved type or undeclared parameter "+t.name(), t.span()); + else if (declaration != null && PbsGenericInstantiation.parameters(declaration).size() != t.arguments().size()) + context.error("ARITY", "Type application requires the declaration's exact explicit arity", t.span()); + } + } + return super.type(t); + } + + @Override public PbsAst.FunctionDecl function(PbsAst.FunctionDecl f) { + var previous = locals; var oldResult = result; + var previousSelf = selfAllowed; selfAllowed = owner != null; + locals = new HashMap<>(locals); + for (var p : f.parameters()) locals.put(p.name(), p.typeRef()); + result = f.returnType(); + try { return super.function(f); } + finally { locals = previous; result = oldResult; selfAllowed = previousSelf; } + } + + @Override public PbsAst.CtorDecl constructor(PbsAst.CtorDecl c) { + var previous = locals; + var previousSelf = selfAllowed; selfAllowed = owner != null; + locals = new HashMap<>(locals); + for (var p : c.parameters()) locals.put(p.name(), p.typeRef()); + try { return super.constructor(c); } + finally { locals = previous; selfAllowed = previousSelf; } + } + + @Override public PbsAst.Block block(PbsAst.Block b) { + var previous = locals; locals = new HashMap<>(locals); + try { return super.block(b); } finally { locals = previous; } + } + + @Override public PbsAst.Statement statement(PbsAst.Statement s) { + if (s instanceof PbsAst.LetStatement l) { + var actual = infer(l.initializer(), l.explicitType()); + checkCompatible(actual, l.explicitType(), l.span()); + locals.put(l.name(), l.explicitType() == null ? actual : l.explicitType()); + } else if (s instanceof PbsAst.ReturnStatement r) checkCompatible(infer(r.value(), result), result, r.span()); + else if (s instanceof PbsAst.AssignStatement a) { + var target = a.target().expression() == null ? locals.get(a.target().rootName()) : infer(a.target().expression(), null); + checkCompatible(infer(a.value(), target), target, a.span()); + if (a.operator() != PbsAst.AssignOperator.ASSIGN && symbolic(target)) capability(a.span()); + } + return super.statement(s); + } + + @Override public PbsAst.Expression expression(PbsAst.Expression e, PbsAst.TypeRef expected) { + if (e == null) return null; + infer(e, expected); + if (e instanceof PbsAst.LambdaExpr l) { + var previous = locals; var oldResult = result; + locals = new HashMap<>(locals); + for (var p : l.parameters()) locals.put(p.name(), p.typeRef()); + result = l.returnType(); + try { return super.expression(e, expected); } + finally { locals = previous; result = oldResult; } + } + return super.expression(e, expected); + } + + private PbsAst.TypeRef infer(PbsAst.Expression e, PbsAst.TypeRef expected) { + if (e == null) return null; + if (inferred.containsKey(e)) return inferred.get(e); + context.budget().visit(e.span(), 0); + var type = inferBody(e, expected); + inferred.put(e, type); + return type; + } + + private PbsAst.TypeRef inferBody(PbsAst.Expression e, PbsAst.TypeRef expected) { + return switch (e) { + case PbsAst.IdentifierExpr i -> { + if (locals.containsKey(i.name())) { + if (i.applied()) context.error("FUNCTION", "Only a generic free function accepts type arguments", i.span()); + yield locals.get(i.name()); + } + var candidates = functions(i); + if (candidates.size() == 1) { + var callable = candidates.getFirst(); + yield PbsAst.TypeRef.function(map(callable.parameters(), p -> new PbsAst.NamedTypeField(null, p.typeRef(), p.span())), callable.result(), i.span()); + } + yield null; + } + case PbsAst.ThisExpr t -> owner; + case PbsAst.IntLiteralExpr i -> PbsAst.TypeRef.simple("int", e.span()); + case PbsAst.FloatLiteralExpr f -> PbsAst.TypeRef.simple("float", e.span()); + case PbsAst.BoolLiteralExpr b -> PbsAst.TypeRef.simple("bool", e.span()); + case PbsAst.StringLiteralExpr s -> PbsAst.TypeRef.simple("str", e.span()); + case PbsAst.BoundedLiteralExpr b -> PbsAst.TypeRef.simple("int", e.span()); + case PbsAst.NewExpr n -> { + if (parameters.contains(n.typeName())) capability(n.span()); + var result = n.explicitType() == null ? expected == null ? PbsAst.TypeRef.simple(n.typeName(), n.span()) : expected : n.explicitType(); + var d = context.declaration(result); + if (d != null && !PbsGenericInstantiation.parameters(d).isEmpty() && result.arguments().isEmpty()) + context.error("CONTEXT", "Generic construction requires an expected application or explicit type arguments", n.span()); + if (d instanceof PbsAst.StructDecl s) { + var env = bindings(s, result); + var expectedParameters = n.ctorName() == null ? map(s.fields(), f -> new PbsAst.Parameter(f.name(), PbsTypeSubstitution.substitute(f.typeRef(), env), f.span())) + : s.ctors().stream().filter(c -> c.name().equals(n.ctorName())).findFirst().map(c -> + map(c.parameters(), p -> new PbsAst.Parameter(p.name(), PbsTypeSubstitution.substitute(p.typeRef(), env), p.span()))).orElse(ReadOnlyList.empty()); + checkArguments(n.arguments(), List.of(new Callable(expectedParameters, result)), n.span()); + } + yield result; + } + case PbsAst.MemberExpr m -> { + var receiver = infer(m.receiver(), null); + if (symbolic(receiver)) { capability(m.span()); yield null; } + var d = context.declaration(receiver); + if (d instanceof PbsAst.StructDecl s) { + var env = bindings(s, receiver); + var field = s.fields().stream().filter(f -> f.name().equals(m.memberName())).findFirst(); + if (field.isPresent()) yield PbsTypeSubstitution.substitute(field.get().typeRef(), env); + } + if (receiver != null && receiver.kind() == PbsAst.TypeRefKind.ARRAY && m.memberName().equals("length")) yield PbsAst.TypeRef.simple("long", m.span()); + yield null; + } + case PbsAst.CallExpr c -> { + var candidates = callables(c.callee()); + yield checkArguments(c.arguments(), candidates, c.span()); + } + case PbsAst.ApplyExpr a -> { + var candidates = callables(a.callee()); + var args = a.argument() instanceof PbsAst.TupleExpr t ? map(t.items(), PbsAst.TupleItem::expression) + : a.argument() instanceof PbsAst.UnitExpr ? ReadOnlyList.empty() : ReadOnlyList.wrap(List.of(a.argument())); + yield checkArguments(args, candidates, a.span()); + } + case PbsAst.BinaryExpr b -> { + var left = infer(b.left(), null); var right = infer(b.right(), null); + if (containsParameter(left) || containsParameter(right)) capability(b.span()); + yield Set.of("==", "!=", "<", ">", "<=", ">=", "and", "or", "&&", "||").contains(b.operator()) + ? PbsAst.TypeRef.simple("bool", b.span()) : left; + } + case PbsAst.UnaryExpr u -> { var value = infer(u.expression(), null); if (containsParameter(value)) capability(u.span()); yield value; } + case PbsAst.IndexExpr i -> { + var receiver = infer(i.receiver(), null); + yield receiver != null && receiver.kind() == PbsAst.TypeRefKind.ARRAY ? PbsAst.TypeRef.optional(receiver.inner(), i.span()) : null; + } + case PbsAst.GroupExpr g -> infer(g.expression(), expected); + case PbsAst.SomeExpr s -> { var value = infer(s.value(), expected == null ? null : expected.inner()); yield value == null ? null : PbsAst.TypeRef.optional(value, s.span()); } + case PbsAst.NoneExpr n -> expected; + case PbsAst.ElseExpr x -> { var optional = infer(x.optionalExpression(), null); yield optional == null ? infer(x.fallbackExpression(), expected) : optional.inner(); } + case PbsAst.AsExpr a -> { if (symbolic(infer(a.expression(), null))) capability(a.span()); yield a.contractType(); } + case PbsAst.TupleExpr t -> PbsAst.TypeRef.namedTuple(map(t.items(), i -> new PbsAst.NamedTypeField(i.label(), infer(i.expression(), null), i.span())), t.span()); + case PbsAst.LambdaExpr l -> l.functionType(); + case PbsAst.ArrayLiteralExpr a -> a.elements().isEmpty() ? expected : PbsAst.TypeRef.array(infer(a.elements().getFirst(), null), a.span()); + case PbsAst.BlockExpr b -> b.block().tailExpression() == null ? expected : infer(b.block().tailExpression(), expected); + case PbsAst.IfExpr i -> expected; + case PbsAst.SwitchExpr s -> expected; + case PbsAst.HandleExpr h -> expected; + case PbsAst.PropagateExpr p -> { var value = infer(p.expression(), null); yield value == null ? null : value.inner(); } + case PbsAst.OkExpr o -> infer(o.value(), expected); + case PbsAst.ErrExpr x -> expected; + case PbsAst.UnitExpr u -> PbsAst.TypeRef.unit(u.span()); + }; + } + + private List functions(PbsAst.IdentifierExpr identifier) { + var result = new ArrayList(); + boolean genericSeen = false; + for (var d : context.lookup(identifier.name(), identifier.span())) { + if (!(d instanceof PbsAst.FunctionDecl f)) continue; + genericSeen |= !f.typeParameters().isEmpty(); + if (identifier.applied() == f.typeParameters().isEmpty()) continue; + if (identifier.applied() && f.typeParameters().size() != identifier.typeArguments().size()) continue; + var env = new HashMap(); + for (int i = 0; i < f.typeParameters().size(); i++) env.put(f.typeParameters().get(i).name(), identifier.typeArguments().get(i)); + result.add(new Callable(map(f.parameters(), p -> new PbsAst.Parameter(p.name(), PbsTypeSubstitution.substitute(p.typeRef(), env), p.span())), + PbsTypeSubstitution.substitute(f.returnType(), env))); + } + if (result.isEmpty() && (genericSeen || identifier.applied())) context.error("FUNCTION_ARITY", "Generic free-function references require explicit arguments of exact arity", identifier.span()); + return result; + } + + private List callables(PbsAst.Expression callee) { + if (callee instanceof PbsAst.IdentifierExpr i && !locals.containsKey(i.name())) return functions(i); + if (callee instanceof PbsAst.MemberExpr m) { + var receiver = infer(m.receiver(), null); + if (symbolic(receiver)) { capability(m.span()); return List.of(); } + var d = context.declaration(receiver); + if (d == null && m.receiver() instanceof PbsAst.IdentifierExpr i) d = context.lookup(i.name(), i.span()).stream().findFirst().orElse(null); + var signatures = new ArrayList(); + if (d instanceof PbsAst.ContractDecl c) signatures.addAll(c.signatures().asList()); + if (d instanceof PbsAst.StructDecl s) for (var f : s.methods()) signatures.add(signature(f)); + if (d instanceof PbsAst.ServiceDecl s) for (var f : s.methods()) signatures.add(signature(f)); + if (d instanceof PbsAst.HostDecl h) signatures.addAll(h.signatures().asList()); + if (d instanceof PbsAst.BuiltinTypeDecl b) signatures.addAll(b.signatures().asList()); + var env = bindings(d, receiver); + var methods = signatures.stream().filter(s -> s.name().equals(m.memberName())).map(s -> { + var substituted = PbsTypeSubstitution.substitute(s, env); return new Callable(substituted.parameters(), substituted.returnType()); + }).toList(); + if (!methods.isEmpty()) return methods; + } + var type = infer(callee, null); + if (type != null && type.kind() == PbsAst.TypeRefKind.FN) return List.of(new Callable(map(type.fields(), f -> new PbsAst.Parameter(f.label(), f.typeRef(), f.span())), type.inner())); + return List.of(); + } + private PbsAst.FunctionSignature signature(PbsAst.FunctionDecl f) { + return new PbsAst.FunctionSignature(f.name(), f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.span()); + } + private Map bindings(PbsAst.TopDecl declaration, PbsAst.TypeRef applied) { + var result = new HashMap(); + if (applied != null && PbsGenericInstantiation.parameters(declaration).size() == applied.arguments().size()) + for (int i = 0; i < applied.arguments().size(); i++) result.put(PbsGenericInstantiation.parameters(declaration).get(i).name(), applied.arguments().get(i)); + return result; + } + private PbsAst.TypeRef checkArguments(ReadOnlyList arguments, List candidates, Span site) { + var actual = arguments.stream().map(a -> infer(a, null)).toList(); + var arity = candidates.stream().filter(c -> c.parameters().size() == actual.size()).toList(); + var matches = arity.stream().filter(c -> { + for (int i = 0; i < actual.size(); i++) if (!compatible(actual.get(i), c.parameters().get(i).typeRef())) return false; + return true; + }).toList(); + if (matches.isEmpty() && actual.stream().anyMatch(this::containsParameter)) context.error("SYMBOLIC_CALL", "No callable accepts these symbolic arguments in the definition scope", site); + return matches.size() == 1 ? matches.getFirst().result() : null; + } + private boolean compatible(PbsAst.TypeRef actual, PbsAst.TypeRef expected) { + if (actual != null && actual.kind() == PbsAst.TypeRefKind.SELF) actual = owner; + if (expected != null && expected.kind() == PbsAst.TypeRefKind.SELF) expected = owner; + if (actual == null || expected == null || (!containsParameter(actual) && !containsParameter(expected))) return true; + return context.key(actual).equals(context.key(expected)); + } + private void checkCompatible(PbsAst.TypeRef actual, PbsAst.TypeRef expected, Span site) { + if (!compatible(actual, expected)) context.error("SYMBOLIC_TYPE", "Value does not match the declared symbolic type", site); + } + private boolean symbolic(PbsAst.TypeRef t) { return t != null && t.kind() == PbsAst.TypeRefKind.SIMPLE && parameters.contains(t.name()); } + private boolean containsParameter(PbsAst.TypeRef t) { + if (t == null) return false; + if (symbolic(t) || containsParameter(t.inner())) return true; + return t.arguments().stream().anyMatch(this::containsParameter) || t.fields().stream().anyMatch(f -> containsParameter(f.typeRef())); + } + private void capability(Span site) { context.error("CAPABILITY", "This operation is not justified for an unconstrained type parameter", site); } + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsInstantiationBudget.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsInstantiationBudget.java new file mode 100644 index 00000000..e3831dbe --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsInstantiationBudget.java @@ -0,0 +1,39 @@ +package p.studio.compiler.pbs; + +import p.studio.compiler.source.Span; +import p.studio.compiler.source.diagnostics.DiagnosticSink; +import p.studio.compiler.source.diagnostics.Diagnostics; + +/** One budget for the interacting type, callable and coherence graphs. Provider limits remain unchanged. */ +public final class PbsInstantiationBudget { + public static final int MAX_DEPTH = 256; + public static final int MAX_INSTANCES = 65_536; + private static final int MAX_WORK = 1_048_576; + private static final long MAX_STORAGE = 64L * 1024 * 1024; + private final DiagnosticSink diagnostics; + private long storage; + private int work; + private int instances; + private p.studio.compiler.pbs.ast.PbsAst.ApplicationOrigin origin; + + public PbsInstantiationBudget(DiagnosticSink diagnostics) { this.diagnostics = diagnostics; } + public void origin(p.studio.compiler.pbs.ast.PbsAst.ApplicationOrigin origin) { this.origin = origin; } + public void visit(Span span, int depth) { + if (depth > MAX_DEPTH || ++work > MAX_WORK) fail(span, "Generic expansion exceeds bounded analysis depth/work"); + } + public void instance(Span span) { + visit(span, 0); + if (++instances > MAX_INSTANCES) fail(span, "Generic application graph exceeds the type/callable budget"); + } + public void store(Span span, long size) { + if (size < 0 || size > MAX_STORAGE - storage) fail(span, "Generic identity/substitution storage budget exceeded"); + storage += size; + } + private void fail(Span span, String message) { + Diagnostics.error(PbsGenericDiagnostics.forOrigin(origin, diagnostics), "E_SEM_GENERIC_EXPANSION", message, span); + throw new Exhausted(); + } + public static final class Exhausted extends RuntimeException { + public Exhausted() { super(null, null, false, false); } + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java index cb7be39b..d6135f99 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java @@ -136,6 +136,7 @@ public final class PbsAst { public record FunctionDecl( String name, + ReadOnlyList typeParameters, ReadOnlyList parameters, ReturnKind returnKind, TypeRef returnType, @@ -143,17 +144,39 @@ public final class PbsAst { ReadOnlyList attributes, LifecycleMarker lifecycleMarker, Block body, + ApplicationOrigin applicationOrigin, Span span) implements TopDecl { + public FunctionDecl(String name, ReadOnlyList typeParameters, ReadOnlyList parameters, + ReturnKind returnKind, TypeRef returnType, TypeRef resultErrorType, ReadOnlyList attributes, + LifecycleMarker lifecycleMarker, Block body, Span span) { + this(name, typeParameters, parameters, returnKind, returnType, resultErrorType, attributes, lifecycleMarker, body, null, span); + } + public FunctionDecl(String name, ReadOnlyList parameters, ReturnKind returnKind, + TypeRef returnType, TypeRef resultErrorType, ReadOnlyList attributes, + LifecycleMarker lifecycleMarker, Block body, Span span) { + this(name, ReadOnlyList.empty(), parameters, returnKind, returnType, resultErrorType, attributes, lifecycleMarker, body, span); + } } public record StructDecl( String name, + ReadOnlyList typeParameters, ReadOnlyList fields, ReadOnlyList methods, ReadOnlyList ctors, boolean hasBody, ReadOnlyList attributes, + ApplicationOrigin applicationOrigin, Span span) implements TopDecl { + public StructDecl(String name, ReadOnlyList typeParameters, ReadOnlyList fields, + ReadOnlyList methods, ReadOnlyList ctors, boolean hasBody, + ReadOnlyList attributes, Span span) { + this(name, typeParameters, fields, methods, ctors, hasBody, attributes, null, span); + } + public StructDecl(String name, ReadOnlyList fields, ReadOnlyList methods, + ReadOnlyList ctors, boolean hasBody, ReadOnlyList attributes, Span span) { + this(name, ReadOnlyList.empty(), fields, methods, ctors, hasBody, attributes, span); + } } public record ContractDecl( @@ -161,7 +184,12 @@ public final class PbsAst { ReadOnlyList typeParameters, ReadOnlyList signatures, ReadOnlyList attributes, + ApplicationOrigin applicationOrigin, Span span) implements TopDecl { + public ContractDecl(String name, ReadOnlyList typeParameters, ReadOnlyList signatures, + ReadOnlyList attributes, Span span) { + this(name, typeParameters, signatures, attributes, null, span); + } public ContractDecl(String name, ReadOnlyList signatures, ReadOnlyList attributes, Span span) { this(name, ReadOnlyList.empty(), signatures, attributes, span); @@ -170,6 +198,14 @@ public final class PbsAst { public record TypeParameter(String name, Span span) {} + /** Logical application identity and source provenance; never a runtime template descriptor. */ + public record ApplicationOrigin(TopDecl declaration, ReadOnlyList arguments, String key, + String display, Span requestedAt, ReadOnlyList chain) { + public ApplicationOrigin(TopDecl declaration, ReadOnlyList arguments, String key, String display, Span requestedAt) { + this(declaration, arguments, key, display, requestedAt, ReadOnlyList.wrap(java.util.List.of(display))); + } + } + /** Imported lexical binding; retains the original declaration and the importing source scope. */ public record TypeBindingDecl(String name, TopDecl declaration, Span span) implements TopDecl {} @@ -232,16 +268,22 @@ public final class PbsAst { } public record ImplementsDecl( + ReadOnlyList typeParameters, TypeRef contractType, - String ownerName, + TypeRef ownerType, String binderName, ReadOnlyList methods, Span span) implements TopDecl { + public ImplementsDecl(TypeRef contractType, String ownerName, String binderName, + ReadOnlyList methods, Span span) { + this(ReadOnlyList.empty(), contractType, TypeRef.simple(ownerName, span), binderName, methods, span); + } public ImplementsDecl(String contractName, String ownerName, String binderName, ReadOnlyList methods, Span span) { this(TypeRef.simple(contractName, span), ownerName, binderName, methods, span); } public String contractName() { return contractType.surface(); } + public String ownerName() { return ownerType.surface(); } } public record InvalidDecl( @@ -498,7 +540,10 @@ public final class PbsAst { public record IdentifierExpr( String name, + ReadOnlyList typeArguments, + boolean applied, Span span) implements Expression { + public IdentifierExpr(String name, Span span) { this(name, ReadOnlyList.empty(), false, span); } } public record IntLiteralExpr( @@ -754,17 +799,26 @@ public final class PbsAst { public record BarrelFunctionItem( Visibility visibility, String name, + ReadOnlyList typeParameters, ReadOnlyList parameterTypes, ReturnKind returnKind, TypeRef returnType, TypeRef resultErrorType, Span span) implements BarrelItem { + public BarrelFunctionItem(Visibility visibility, String name, ReadOnlyList parameterTypes, + ReturnKind returnKind, TypeRef returnType, TypeRef resultErrorType, Span span) { + this(visibility, name, ReadOnlyList.empty(), parameterTypes, returnKind, returnType, resultErrorType, span); + } } public record BarrelStructItem( Visibility visibility, String name, + ReadOnlyList typeParameters, Span span) implements BarrelItem { + public BarrelStructItem(Visibility visibility, String name, Span span) { + this(visibility, name, ReadOnlyList.empty(), span); + } } public record BarrelContractItem( diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAstRewriter.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAstRewriter.java new file mode 100644 index 00000000..e7756c7d --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAstRewriter.java @@ -0,0 +1,113 @@ +package p.studio.compiler.pbs.ast; + +import p.studio.utilities.structures.ReadOnlyList; +import java.util.function.Function; + +/** Exhaustive, source-preserving structural rewrite of all executable type positions. */ +public class PbsAstRewriter { + public static ReadOnlyList map(ReadOnlyList values, Function transform) { + return ReadOnlyList.wrap(values.stream().map(transform).toList()); + } + + public PbsAst.TypeRef type(PbsAst.TypeRef t) { + if (t == null) return null; + return new PbsAst.TypeRef(t.kind(), t.name(), map(t.fields(), f -> + new PbsAst.NamedTypeField(f.label(), type(f.typeRef()), f.span())), type(t.inner()), map(t.arguments(), this::type), t.span()); + } + + public PbsAst.Parameter parameter(PbsAst.Parameter p) { return new PbsAst.Parameter(p.name(), type(p.typeRef()), p.span()); } + public PbsAst.FunctionSignature signature(PbsAst.FunctionSignature s) { + return new PbsAst.FunctionSignature(s.name(), map(s.parameters(), this::parameter), s.returnKind(), type(s.returnType()), + type(s.resultErrorType()), s.attributes(), s.span()); + } + public PbsAst.FunctionDecl function(PbsAst.FunctionDecl f) { + return new PbsAst.FunctionDecl(f.name(), f.typeParameters(), map(f.parameters(), this::parameter), f.returnKind(), type(f.returnType()), + type(f.resultErrorType()), f.attributes(), f.lifecycleMarker(), block(f.body()), f.applicationOrigin(), f.span()); + } + public PbsAst.CtorDecl constructor(PbsAst.CtorDecl c) { + return new PbsAst.CtorDecl(c.name(), map(c.parameters(), this::parameter), block(c.body()), c.span()); + } + public PbsAst.TopDecl declaration(PbsAst.TopDecl d) { + return switch (d) { + case PbsAst.FunctionDecl f -> function(f); + case PbsAst.StructDecl s -> new PbsAst.StructDecl(s.name(), s.typeParameters(), map(s.fields(), f -> + new PbsAst.StructField(f.name(), type(f.typeRef()), f.isPublic(), f.isMutable(), f.span())), + map(s.methods(), this::function), map(s.ctors(), this::constructor), s.hasBody(), s.attributes(), s.applicationOrigin(), s.span()); + case PbsAst.ContractDecl c -> new PbsAst.ContractDecl(c.name(), c.typeParameters(), map(c.signatures(), this::signature), c.attributes(), c.applicationOrigin(), c.span()); + case PbsAst.ImplementsDecl i -> new PbsAst.ImplementsDecl(i.typeParameters(), type(i.contractType()), type(i.ownerType()), + i.binderName(), map(i.methods(), this::function), i.span()); + case PbsAst.ServiceDecl s -> new PbsAst.ServiceDecl(s.name(), map(s.methods(), this::function), + map(s.constants(), c -> (PbsAst.ConstDecl) declaration(c)), s.attributes(), s.span()); + case PbsAst.HostDecl h -> new PbsAst.HostDecl(h.name(), map(h.signatures(), this::signature), h.attributes(), h.span()); + case PbsAst.BuiltinTypeDecl b -> new PbsAst.BuiltinTypeDecl(b.name(), map(b.fields(), f -> + new PbsAst.BuiltinFieldDecl(f.name(), type(f.typeRef()), f.isPublic(), f.attributes(), f.span())), + map(b.signatures(), this::signature), b.attributes(), b.span()); + case PbsAst.GlobalDecl g -> new PbsAst.GlobalDecl(g.name(), type(g.explicitType()), expression(g.initializer(), type(g.explicitType())), g.span()); + case PbsAst.ConstDecl c -> new PbsAst.ConstDecl(c.name(), type(c.explicitType()), expression(c.initializer(), type(c.explicitType())), c.attributes(), c.span()); + case PbsAst.TypeBindingDecl b -> new PbsAst.TypeBindingDecl(b.name(), declaration(b.declaration()), b.span()); + case PbsAst.EnumDecl e -> e; + case PbsAst.ErrorDecl e -> e; + case PbsAst.InvalidDecl i -> i; + }; + } + public PbsAst.File file(PbsAst.File f) { return new PbsAst.File(f.imports(), map(f.topDecls(), this::declaration), f.span()); } + public PbsAst.Block block(PbsAst.Block b) { + return b == null ? null : new PbsAst.Block(map(b.statements(), this::statement), expression(b.tailExpression()), b.span()); + } + public PbsAst.Statement statement(PbsAst.Statement s) { + return switch (s) { + case PbsAst.LetStatement l -> new PbsAst.LetStatement(l.isConst(), l.name(), l.nameSpan(), type(l.explicitType()), + expression(l.initializer(), type(l.explicitType())), l.span()); + case PbsAst.AssignStatement a -> new PbsAst.AssignStatement(new PbsAst.LValue(a.target().rootName(), a.target().pathSegments(), + a.target().span(), expression(a.target().expression())), a.operator(), expression(a.value()), a.span()); + case PbsAst.ReturnStatement r -> new PbsAst.ReturnStatement(expression(r.value()), r.span()); + case PbsAst.IfStatement i -> new PbsAst.IfStatement(expression(i.condition()), block(i.thenBlock()), + i.elseIf() == null ? null : (PbsAst.IfStatement) statement(i.elseIf()), block(i.elseBlock()), i.span(), i.bindingName(), i.bindingSpan()); + case PbsAst.ForStatement f -> new PbsAst.ForStatement(f.iteratorName(), type(f.iteratorType()), expression(f.fromExpression()), + expression(f.untilExpression()), expression(f.stepExpression()), block(f.body()), f.span()); + case PbsAst.WhileStatement w -> new PbsAst.WhileStatement(expression(w.condition()), block(w.body()), w.span()); + case PbsAst.ExpressionStatement e -> new PbsAst.ExpressionStatement(expression(e.expression()), e.span()); + case PbsAst.BreakStatement b -> b; + case PbsAst.ContinueStatement c -> c; + }; + } + public PbsAst.Expression expression(PbsAst.Expression e) { return expression(e, null); } + public PbsAst.Expression expression(PbsAst.Expression e, PbsAst.TypeRef expected) { + if (e == null) return null; + return switch (e) { + case PbsAst.IdentifierExpr i -> new PbsAst.IdentifierExpr(i.name(), map(i.typeArguments(), this::type), i.applied(), i.span()); + case PbsAst.NewExpr n -> new PbsAst.NewExpr(n.typeName(), n.ctorName(), map(n.arguments(), this::expression), type(n.explicitType()), n.diamond(), n.span()); + case PbsAst.LambdaExpr l -> new PbsAst.LambdaExpr(l.captures(), map(l.parameters(), this::parameter), type(l.returnType()), block(l.body()), l.span()); + case PbsAst.UnaryExpr u -> new PbsAst.UnaryExpr(u.operator(), expression(u.expression()), u.span()); + case PbsAst.BinaryExpr b -> new PbsAst.BinaryExpr(b.operator(), expression(b.left()), expression(b.right()), b.span()); + case PbsAst.ApplyExpr a -> new PbsAst.ApplyExpr(expression(a.callee()), expression(a.argument()), a.span()); + case PbsAst.CallExpr c -> new PbsAst.CallExpr(expression(c.callee()), map(c.arguments(), this::expression), c.span()); + case PbsAst.MemberExpr m -> new PbsAst.MemberExpr(expression(m.receiver()), m.memberName(), m.span()); + case PbsAst.IndexExpr i -> new PbsAst.IndexExpr(expression(i.receiver()), expression(i.index()), i.span()); + case PbsAst.ArrayLiteralExpr a -> new PbsAst.ArrayLiteralExpr(map(a.elements(), this::expression), a.span()); + case PbsAst.GroupExpr g -> new PbsAst.GroupExpr(expression(g.expression(), expected), g.span()); + case PbsAst.ElseExpr x -> new PbsAst.ElseExpr(expression(x.optionalExpression()), expression(x.fallbackExpression(), expected), x.span()); + case PbsAst.IfExpr i -> new PbsAst.IfExpr(expression(i.condition()), block(i.thenBlock()), expression(i.elseExpression(), expected), i.span()); + case PbsAst.SwitchExpr s -> new PbsAst.SwitchExpr(expression(s.selector()), map(s.arms(), a -> new PbsAst.SwitchArm( + a.pattern() instanceof PbsAst.LiteralSwitchPattern l ? new PbsAst.LiteralSwitchPattern(expression(l.literal()), l.span()) : a.pattern(), + block(a.block()), a.span())), s.span()); + case PbsAst.HandleExpr h -> new PbsAst.HandleExpr(expression(h.value()), map(h.arms(), a -> + new PbsAst.HandleArm(a.pattern(), a.remapTarget(), block(a.block()), a.span())), h.span()); + case PbsAst.AsExpr a -> new PbsAst.AsExpr(expression(a.expression()), type(a.contractType()), a.span()); + case PbsAst.PropagateExpr p -> new PbsAst.PropagateExpr(expression(p.expression()), p.span()); + case PbsAst.SomeExpr s -> new PbsAst.SomeExpr(expression(s.value()), s.span()); + case PbsAst.OkExpr o -> new PbsAst.OkExpr(expression(o.value()), o.span()); + case PbsAst.TupleExpr t -> new PbsAst.TupleExpr(map(t.items(), i -> new PbsAst.TupleItem(i.label(), expression(i.expression()), i.span())), t.span()); + case PbsAst.BlockExpr b -> new PbsAst.BlockExpr(block(b.block()), b.span()); + case PbsAst.IntLiteralExpr i -> i; + case PbsAst.FloatLiteralExpr f -> f; + case PbsAst.BoundedLiteralExpr b -> b; + case PbsAst.StringLiteralExpr s -> s; + case PbsAst.BoolLiteralExpr b -> b; + case PbsAst.ThisExpr t -> t; + case PbsAst.NoneExpr n -> n; + case PbsAst.ErrExpr x -> x; + case PbsAst.UnitExpr u -> u; + }; + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsTypeTraversal.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsTypeTraversal.java index f01e24ff..9474aef4 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsTypeTraversal.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsTypeTraversal.java @@ -24,7 +24,7 @@ public final class PbsTypeTraversal { b.fields().forEach(f -> type(f.typeRef(), visitor)); b.signatures().forEach(s -> signature(s, visitor)); } - case PbsAst.ImplementsDecl i -> { type(i.contractType(), visitor); i.methods().forEach(f -> function(f, visitor)); } + case PbsAst.ImplementsDecl i -> { type(i.contractType(), visitor); type(i.ownerType(), visitor); i.methods().forEach(f -> function(f, visitor)); } case PbsAst.GlobalDecl g -> { type(g.explicitType(), visitor); expression(g.initializer(), visitor); } case PbsAst.ConstDecl c -> { type(c.explicitType(), visitor); expression(c.initializer(), visitor); } default -> { } @@ -67,6 +67,7 @@ public final class PbsTypeTraversal { private static void expression(PbsAst.Expression e, Consumer visitor) { if (e == null) return; switch (e) { + case PbsAst.IdentifierExpr i -> i.typeArguments().forEach(t -> type(t, visitor)); case PbsAst.AsExpr a -> { type(a.contractType(), visitor); expression(a.expression(), visitor); } case PbsAst.NewExpr n -> { type(n.explicitType(), visitor); n.arguments().forEach(a -> expression(a, visitor)); } case PbsAst.LambdaExpr l -> { l.parameters().forEach(p -> type(p.typeRef(), visitor)); type(l.returnType(), visitor); block(l.body(), visitor); } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/linking/PbsModuleVisibilityValidator.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/linking/PbsModuleVisibilityValidator.java index e6d3cfbb..11d6174f 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/linking/PbsModuleVisibilityValidator.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/linking/PbsModuleVisibilityValidator.java @@ -99,11 +99,12 @@ public final class PbsModuleVisibilityValidator { for (final var item : barrel.ast().items()) { if (item instanceof PbsAst.BarrelFunctionItem( - PbsAst.Visibility visibility, String name, ReadOnlyList parameterTypes, + PbsAst.Visibility visibility, String name, ReadOnlyList typeParameters, ReadOnlyList parameterTypes, PbsAst.ReturnKind returnKind, PbsAst.TypeRef returnType, PbsAst.TypeRef resultErrorType, Span span )) { final var functionKey = functionKey( name, + typeParameters.size(), parameterTypes.asList(), returnKind, returnType, @@ -122,7 +123,12 @@ public final class PbsModuleVisibilityValidator { continue; } - final var matches = declarations.functionsBySignature.getOrDefault(functionKey, List.of()); + var matches = declarations.functionsBySignature.getOrDefault(functionKey, List.of()); + if (matches.isEmpty() || !typeParameters.isEmpty()) matches = resolveFunctionExport(module, name, unitsByModule, new HashSet<>()).stream() + .filter(f -> f.typeParameters().stream().map(PbsAst.TypeParameter::name).toList().equals(typeParameters.stream().map(PbsAst.TypeParameter::name).toList())) + .filter(f -> functionKey.equals(functionKey(name, f.typeParameters().size(), f.parameters().stream().map(PbsAst.Parameter::typeRef).toList(), + f.returnKind(), f.returnType(), f.resultErrorType(), nameTable, signatureInterning))) + .map(PbsAst.FunctionDecl::span).distinct().toList(); if (matches.isEmpty()) { p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics, PbsLinkErrors.E_LINK_UNRESOLVED_BARREL_ENTRY.name(), @@ -170,7 +176,10 @@ public final class PbsModuleVisibilityValidator { var matches = declarations.nonFunctionsByKindAndName.getOrDefault(symbolKey, List.of()); var resolvedContract = item instanceof PbsAst.BarrelContractItem contractItem ? resolveContractExport(module, contractItem.name(), unitsByModule, new HashSet<>()) : null; + var resolvedStruct = item instanceof PbsAst.BarrelStructItem structItem + ? resolveStructExport(module, structItem.name(), unitsByModule, new HashSet<>()) : null; if (matches.isEmpty() && resolvedContract != null) matches = List.of(resolvedContract.span()); + if (matches.isEmpty() && resolvedStruct != null) matches = List.of(resolvedStruct.span()); if (matches.isEmpty()) { p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics, PbsLinkErrors.E_LINK_UNRESOLVED_BARREL_ENTRY.name(), @@ -200,6 +209,13 @@ public final class PbsModuleVisibilityValidator { continue; } } + if (item instanceof PbsAst.BarrelStructItem structItem && resolvedStruct != null && + !resolvedStruct.typeParameters().stream().map(PbsAst.TypeParameter::name).toList().equals( + structItem.typeParameters().stream().map(PbsAst.TypeParameter::name).toList())) { + p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics, "E_LINK_STRUCT_PARAMETERS", + "Barrel struct parameters must preserve the declaration's ordered parameters", structItem.span()); + continue; + } if (nonFunctionVisibility(item) == PbsAst.Visibility.PUB) { exports.publicNameIds.add(symbolKey.nameId()); } @@ -208,6 +224,39 @@ public final class PbsModuleVisibilityValidator { return exports; } + private PbsAst.StructDecl resolveStructExport(ModuleUnit module, String name, + Map units, Set visited) { + if (!visited.add(module.coordinates()+":"+name)) return null; + for (var source : module.sourceFiles()) for (var declaration : source.ast().topDecls()) + if (declaration instanceof PbsAst.StructDecl struct && struct.name().equals(name)) return struct; + for (var source : module.sourceFiles()) for (var imported : source.ast().imports()) for (var item : imported.items()) { + if (!(item.alias() == null ? item.name() : item.alias()).equals(name)) continue; + var target = units.get(new ModuleRefKey(imported.moduleRef().project(), imported.moduleRef().pathSegments())); + if (target != null && target.barrelFiles().stream().anyMatch(b -> b.ast().items().stream().anyMatch(i -> + i instanceof PbsAst.BarrelStructItem s && s.visibility() == PbsAst.Visibility.PUB && s.name().equals(item.name())))) { + var resolved = resolveStructExport(target, item.name(), units, visited); if (resolved != null) return resolved; + } + } + return null; + } + + private List resolveFunctionExport(ModuleUnit module, String name, + Map units, Set visited) { + if (!visited.add(module.coordinates()+":"+name)) return List.of(); + var result = new ArrayList(); + for (var source : module.sourceFiles()) for (var declaration : source.ast().topDecls()) + if (declaration instanceof PbsAst.FunctionDecl function && function.name().equals(name)) result.add(function); + if (!result.isEmpty()) return result; + for (var source : module.sourceFiles()) for (var imported : source.ast().imports()) for (var item : imported.items()) { + if (!(item.alias() == null ? item.name() : item.alias()).equals(name)) continue; + var target = units.get(new ModuleRefKey(imported.moduleRef().project(), imported.moduleRef().pathSegments())); + if (target != null && target.barrelFiles().stream().anyMatch(b -> b.ast().items().stream().anyMatch(i -> + i instanceof PbsAst.BarrelFunctionItem f && f.visibility() == PbsAst.Visibility.PUB && f.name().equals(item.name())))) + result.addAll(resolveFunctionExport(target, item.name(), units, visited)); + } + return result; + } + private void validateImplementationOwners(ModuleUnit module, DiagnosticSink diagnostics) { var localOwners = new HashSet(); for (var source : module.sourceFiles()) for (var declaration : source.ast().topDecls()) { @@ -215,7 +264,7 @@ public final class PbsModuleVisibilityValidator { if (declaration instanceof PbsAst.ServiceDecl s) localOwners.add(s.name()); } for (var source : module.sourceFiles()) for (var declaration : source.ast().topDecls()) - if (declaration instanceof PbsAst.ImplementsDecl i && !localOwners.contains(i.ownerName())) + if (declaration instanceof PbsAst.ImplementsDecl i && !localOwners.contains(i.ownerType().name())) p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics, "E_SEM_CONTRACT_OWNER_MODULE", "Contract implementations must be declared in the owner's module", i.span()); } @@ -300,6 +349,7 @@ public final class PbsModuleVisibilityValidator { if (topDecl instanceof PbsAst.FunctionDecl functionDecl) { final var key = functionKey( functionDecl.name(), + functionDecl.typeParameters().size(), functionDecl.parameters().stream().map(PbsAst.Parameter::typeRef).toList(), functionDecl.returnKind(), functionDecl.returnType(), @@ -353,6 +403,7 @@ public final class PbsModuleVisibilityValidator { private FunctionSymbolKey functionKey( final String name, + final int typeArity, final List parameterTypes, final PbsAst.ReturnKind returnKind, final PbsAst.TypeRef returnType, @@ -361,7 +412,7 @@ public final class PbsModuleVisibilityValidator { final SignatureInterning signatureInterning) { return new FunctionSymbolKey( nameTable.register(name), - callableShapeId(parameterTypes, returnKind, returnType, resultErrorType, signatureInterning)); + callableShapeId(parameterTypes, returnKind, returnType, resultErrorType, signatureInterning), typeArity); } private CallableShapeId callableShapeId( @@ -536,7 +587,8 @@ public final class PbsModuleVisibilityValidator { private record FunctionSymbolKey( NameId nameId, - CallableShapeId callableShapeId) { + CallableShapeId callableShapeId, + int typeArity) { } private record SignatureInterning( diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java index af755d63..6ddf2fd0 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java @@ -66,7 +66,8 @@ final class PbsRuntimeTypes { if (services.containsKey(item.name())) services.put(item.alias(), services.get(item.name())); if (contracts.containsKey(item.name())) contracts.put(item.alias(), contracts.get(item.name())); } - for (var declaration : supplemental) if (declaration instanceof PbsAst.TypeBindingDecl binding) { + for (var declaration : declarations) if (declaration instanceof PbsAst.TypeBindingDecl binding) { + aliases.put(binding.name(), p.studio.compiler.pbs.PbsGenericInstantiation.name(binding.declaration())); if (binding.declaration() instanceof PbsAst.StructDecl s) structs.put(binding.name(), s); if (binding.declaration() instanceof PbsAst.ServiceDecl s) services.put(binding.name(), s); if (binding.declaration() instanceof PbsAst.ContractDecl c) contracts.put(binding.name(), c); @@ -108,10 +109,13 @@ final class PbsRuntimeTypes { if (t.kind() == PbsAst.TypeRefKind.ARRAY) return "array("+key(t.inner())+")"; if (t.kind() == PbsAst.TypeRefKind.OPTIONAL) return "optional("+key(t.inner())+")"; if (t.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) return "tuple("+t.fields().stream().map(f->key(f.typeRef())).reduce((a,b)->a+","+b).orElse("")+")"; - if (contractTypes.declaration(t) instanceof PbsAst.StructDecl s) return nominalKey("struct", s.span()); + if (contractTypes.declaration(t) instanceof PbsAst.StructDecl s) return nominalKey("struct", s.span()) + + (s.applicationOrigin() == null ? "" : ":" + s.applicationOrigin().key()); if (contractTypes.declaration(t) instanceof PbsAst.ServiceDecl s) return nominalKey("struct", s.span()); if (isContract(t)) { var nominal = nominalKey("contract", contractTypes.template(t).span()); + var origin = contractTypes.template(t).applicationOrigin(); + if (origin != null) return nominal + ":" + origin.key(); return t.arguments().isEmpty() ? nominal : nominal + ":" + contractTypes.key(t); } return canonical(t); @@ -170,11 +174,11 @@ final class PbsRuntimeTypes { if (contractTypes.declaration(t) instanceof PbsAst.StructDecl || contractTypes.declaration(t) instanceof PbsAst.ServiceDecl) { var ref = new IRRegistry.TypeRef(key(t)); if (!used.containsKey(ref.declarationKey())) { - used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,canonical(t),new IRRegistry.Struct(null))); + used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,contractTypes.display(t),new IRRegistry.Struct(null))); var fields = new ArrayList(); if (contractTypes.declaration(t) instanceof PbsAst.StructDecl s) for(var field : s.fields()) fields.add(new IRRegistry.NamedType(registryType(field.typeRef()),field.name())); - used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,canonical(t),new IRRegistry.Struct(ReadOnlyList.wrap(fields)))); + used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,contractTypes.display(t),new IRRegistry.Struct(ReadOnlyList.wrap(fields)))); } return ref; } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsBarrelParser.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsBarrelParser.java index 76f4ee3c..90beef28 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsBarrelParser.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsBarrelParser.java @@ -115,7 +115,7 @@ public final class PbsBarrelParser { final PbsToken visibilityToken, final PbsTokenKind kind) { final var name = consume(PbsTokenKind.IDENTIFIER, "Expected declaration name in barrel item"); - final var typeParameters = kind == PbsTokenKind.CONTRACT + final var typeParameters = kind == PbsTokenKind.CONTRACT || kind == PbsTokenKind.STRUCT ? new PbsTypeParser(new PbsParserContext(cursor, fileId, diagnostics, PbsParser.ParseMode.ORDINARY)).parseTypeParameters() : ReadOnlyList.empty(); @@ -123,7 +123,7 @@ public final class PbsBarrelParser { final var itemSpan = span(visibilityToken.start(), semicolon.end()); return switch (kind) { - case STRUCT -> new PbsAst.BarrelStructItem(visibility, name.lexeme(), itemSpan); + case STRUCT -> new PbsAst.BarrelStructItem(visibility, name.lexeme(), typeParameters, itemSpan); case CONTRACT -> new PbsAst.BarrelContractItem(visibility, name.lexeme(), typeParameters, itemSpan); case HOST -> new PbsAst.BarrelHostItem(visibility, name.lexeme(), itemSpan); case ERROR -> new PbsAst.BarrelErrorItem(visibility, name.lexeme(), itemSpan); @@ -140,6 +140,8 @@ public final class PbsBarrelParser { final PbsAst.Visibility visibility, final PbsToken visibilityToken) { final var name = consume(PbsTokenKind.IDENTIFIER, "Expected function name in barrel item"); + final var typeParameters = new PbsTypeParser(new PbsParserContext(cursor, fileId, diagnostics, + PbsParser.ParseMode.ORDINARY)).parseTypeParameters(); consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after function name"); final var parameterTypes = new ArrayList(); @@ -157,6 +159,7 @@ public final class PbsBarrelParser { return new PbsAst.BarrelFunctionItem( visibility, name.lexeme(), + typeParameters, ReadOnlyList.wrap(parameterTypes), returnSpec.kind(), returnSpec.returnType(), diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java index ced41ead..c38e9562 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java @@ -174,9 +174,10 @@ final class PbsDeclarationParser { } PbsAst.ImplementsDecl parseImplementsDeclaration(final PbsToken implementsToken) { + final var typeParameters = typeParser.parseTypeParameters(); final var contractType = typeParser.parseTypeRef(); consume(PbsTokenKind.FOR, "Expected 'for' in 'implements' declaration"); - final var ownerName = consume(PbsTokenKind.IDENTIFIER, "Expected owner name after 'for'"); + final var ownerType = typeParser.parseTypeRef(); consume(PbsTokenKind.USING, "Expected 'using' in 'implements' declaration"); final var binderName = consume(PbsTokenKind.IDENTIFIER, "Expected binder name after 'using'"); @@ -201,8 +202,9 @@ final class PbsDeclarationParser { } return new PbsAst.ImplementsDecl( + typeParameters, contractType, - ownerName.lexeme(), + ownerType, binderName.lexeme(), ReadOnlyList.wrap(methods), span(implementsToken.start(), end)); @@ -312,6 +314,7 @@ final class PbsDeclarationParser { final PbsToken declareToken, final ReadOnlyList attributes) { final var name = consume(PbsTokenKind.IDENTIFIER, "Expected struct name"); + final var typeParameters = typeParser.parseTypeParameters(); consume(PbsTokenKind.LEFT_PAREN, "Expected '(' in struct declaration"); final var fields = parseStructFields(); consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after struct fields"); @@ -338,6 +341,7 @@ final class PbsDeclarationParser { return new PbsAst.StructDecl( name.lexeme(), + typeParameters, ReadOnlyList.wrap(fields), ReadOnlyList.wrap(methods), ReadOnlyList.wrap(ctors), @@ -568,6 +572,7 @@ final class PbsDeclarationParser { final ReadOnlyList pendingAttributes) { final var lifecycleMarker = validateAndResolveLifecycleMarker(pendingAttributes); final var name = consumeCallableName(); + final var typeParameters = typeParser.parseTypeParameters(); consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after function name"); final var parameters = typeParser.parseParametersUntilRightParen(); final var rightParen = consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after parameter list"); @@ -577,6 +582,7 @@ final class PbsDeclarationParser { final var body = parseBlock(); return new PbsAst.FunctionDecl( name.lexeme(), + typeParameters, ReadOnlyList.wrap(parameters), returnSpec.kind(), returnSpec.returnType(), diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsExprPrimaryParser.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsExprPrimaryParser.java index 005efd0d..6144a5b0 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsExprPrimaryParser.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsExprPrimaryParser.java @@ -41,6 +41,11 @@ final class PbsExprPrimaryParser { var expression = parsePrimary(); while (true) { + if (expression instanceof PbsAst.IdentifierExpr identifier && !identifier.applied() + && cursor.check(PbsTokenKind.LESS)) { + var applied = parseFunctionApplication(identifier); + if (applied != null) { expression = applied; continue; } + } if (cursor.match(PbsTokenKind.LEFT_PAREN)) { final var arguments = new ArrayList(); if (!cursor.check(PbsTokenKind.RIGHT_PAREN)) { @@ -234,18 +239,21 @@ final class PbsExprPrimaryParser { PbsAst.TypeRef explicitType = null; boolean diamond = false; if (cursor.match(PbsTokenKind.LESS)) { - if (!typeName.lexeme().equals("array")) { - context.report(typeName, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE, - "Type arguments in construction are currently supported only for array"); - } var types = context.typeParser(); if (cursor.check(PbsTokenKind.GREATER)) { diamond = true; types.consumeTypeClose(); } else { - var element = types.parseArrayElementType(); + var arguments = new ArrayList(); + do { arguments.add(typeName.lexeme().equals("array") ? types.parseArrayElementType() : types.parseTypeRef()); } + while (cursor.match(PbsTokenKind.COMMA)); var closeType = types.consumeTypeClose(); - explicitType = PbsAst.TypeRef.array(element, context.span(typeName.start(), closeType.end())); + var typeSpan = context.span(typeName.start(), closeType.end()); + if (typeName.lexeme().equals("array")) { + if (arguments.size() != 1) context.report(typeName, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE, + "Array construction requires exactly one type argument"); + explicitType = PbsAst.TypeRef.array(arguments.getFirst(), typeSpan); + } else explicitType = PbsAst.TypeRef.applied(typeName.lexeme(), ReadOnlyList.wrap(arguments), typeSpan); } } String ctorName = null; @@ -270,6 +278,29 @@ final class PbsExprPrimaryParser { context.span(newToken.start(), close.end())); } + /** A complete type-argument expression is recognized without consuming comparison tokens on failure. */ + private PbsAst.IdentifierExpr parseFunctionApplication(PbsAst.IdentifierExpr identifier) { + var trial = cursor.fork(); + var diagnostics = p.studio.compiler.source.diagnostics.DiagnosticSink.empty(); + var types = new PbsTypeParser(new PbsParserContext(trial, identifier.span().getFileId(), diagnostics, + PbsParser.ParseMode.ORDINARY)); + trial.advance(); + var arguments = new ArrayList(); + if (!trial.check(PbsTokenKind.GREATER)) { + do { arguments.add(types.parseTypeRef()); } while (trial.match(PbsTokenKind.COMMA)); + } + var close = types.consumeTypeClose(); + if (diagnostics.hasErrors() || close.lexeme().isEmpty()) return null; + // A following primary continues an ordinary comparison, rather than a type application. + if (switch (trial.peek().kind()) { + case IDENTIFIER, INT_LITERAL, FLOAT_LITERAL, STRING_LITERAL, TRUE, FALSE -> true; + default -> false; + }) return null; + cursor.commit(trial); + return new PbsAst.IdentifierExpr(identifier.name(), ReadOnlyList.wrap(arguments), true, + context.span(identifier.span().getStart(), close.end())); + } + private PbsAst.Expression parseLambda(PbsToken start) { context.consume(PbsTokenKind.LEFT_BRACKET, "Lambda requires explicit capture list, including []"); var captures = new ArrayList(); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsTokenCursor.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsTokenCursor.java index f985d16e..3443e839 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsTokenCursor.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsTokenCursor.java @@ -25,6 +25,18 @@ final class PbsTokenCursor { } } + PbsTokenCursor fork() { + var copy = new PbsTokenCursor(ReadOnlyList.wrap(tokens)); + copy.current = current; + return copy; + } + + void commit(PbsTokenCursor copy) { + tokens.clear(); + tokens.addAll(copy.tokens); + current = copy.current; + } + /** Peel one type closer without changing expression tokenization. */ PbsToken consumeTypeClose() { var token = peek(); 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 bc5e6a5b..96f99033 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 @@ -25,6 +25,9 @@ final class PbsAstDocumentSymbols { private static Optional symbolFor(final PbsAst.TopDecl topDecl) { if (topDecl instanceof PbsAst.FunctionDecl functionDecl) { + if (!functionDecl.typeParameters().isEmpty()) return namedSymbol(functionDecl.name(), PbsEditorialSymbolKind.FUNCTION, + parameterDetail(functionDecl.typeParameters())+callableDetail(functionDecl.parameters(), functionDecl.returnKind(), + functionDecl.returnType(), functionDecl.resultErrorType()), functionDecl.span(), List.of()); return callableSymbol( functionDecl.name(), PbsEditorialSymbolKind.FUNCTION, @@ -122,11 +125,15 @@ final class PbsAstDocumentSymbols { return namedSymbol( structDecl.name(), PbsEditorialSymbolKind.STRUCT, - "", + parameterDetail(structDecl.typeParameters()), structDecl.span(), children); } + private static String parameterDetail(ReadOnlyList parameters) { + return parameters.isEmpty() ? "" : "<"+parameters.stream().map(PbsAst.TypeParameter::name).collect(java.util.stream.Collectors.joining(", "))+">"; + } + private static Optional builtinTypeSymbol(final PbsAst.BuiltinTypeDecl builtinTypeDecl) { final ArrayList children = new ArrayList<>(); for (final PbsAst.BuiltinFieldDecl field : builtinTypeDecl.fields()) { diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsCtorInitializationAnalyzer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsCtorInitializationAnalyzer.java new file mode 100644 index 00000000..c41a250b --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsCtorInitializationAnalyzer.java @@ -0,0 +1,144 @@ +package p.studio.compiler.pbs.semantics; + +import p.studio.compiler.pbs.ast.PbsAst; +import p.studio.compiler.source.diagnostics.DiagnosticSink; +import p.studio.compiler.source.diagnostics.Diagnostics; + +import java.util.HashSet; +import java.util.Set; + +/** Definite field assignment on completing paths; null denotes an unreachable exit. */ +final class PbsCtorInitializationAnalyzer { + private final PbsFlowSemanticSupport.Model model; + + PbsCtorInitializationAnalyzer(PbsFlowSemanticSupport.Model model) { this.model = model; } + + void validate(PbsAst.StructDecl owner, PbsAst.CtorDecl ctor, DiagnosticSink diagnostics) { + var assigned = block(ctor.body(), Set.of()).normal(); + if (assigned == null) return; + var missing = owner.fields().stream().map(PbsAst.StructField::name).filter(n -> !assigned.contains(n)).toList(); + if (!missing.isEmpty()) Diagnostics.error(diagnostics, "E_SEM_CTOR_FIELD_UNINITIALIZED", + "Every completing constructor path must assign fields: " + String.join(", ", missing), ctor.span()); + } + + private record Paths(Set normal, Set breaks, Set continues) { + static Paths normal(Set fields) { return new Paths(fields, null, null); } + Paths merge(Paths other) { + return new Paths(meet(normal, other.normal), meet(breaks, other.breaks), meet(continues, other.continues)); + } + Paths then(java.util.function.Function, Paths> next) { + if (normal == null) return this; + var result = next.apply(normal); + return new Paths(result.normal, meet(breaks, result.breaks), meet(continues, result.continues)); + } + } + + private static Set meet(Set left, Set right) { + if (left == null) return right; + if (right == null) return left; + var result = new HashSet<>(left); result.retainAll(right); return Set.copyOf(result); + } + + private Paths block(PbsAst.Block block, Set fields) { + var result = Paths.normal(fields); + if (block == null) return result; + for (var statement : block.statements()) result = result.then(f -> statement(statement, f)); + return result.then(f -> expression(block.tailExpression(), f)); + } + + private Paths statement(PbsAst.Statement statement, Set fields) { + return switch (statement) { + case PbsAst.LetStatement l -> expression(l.initializer(), fields); + case PbsAst.ExpressionStatement e -> expression(e.expression(), fields); + case PbsAst.ReturnStatement r -> new Paths(null, null, null); // rejected separately in constructors + case PbsAst.BreakStatement b -> new Paths(null, fields, null); + case PbsAst.ContinueStatement c -> new Paths(null, null, fields); + case PbsAst.AssignStatement a -> expression(a.target().expression(), fields).then(f -> expression(a.value(), f)).then(f -> { + var assigned = new HashSet<>(f); + if (a.operator() == PbsAst.AssignOperator.ASSIGN && a.target().rootName().equals("this") + && a.target().pathSegments().size() == 1) assigned.add(a.target().pathSegments().getFirst()); + return Paths.normal(Set.copyOf(assigned)); + }); + case PbsAst.IfStatement i -> expression(i.condition(), fields).then(f -> { + var yes = block(i.thenBlock(), f); + var no = i.elseIf() == null ? block(i.elseBlock(), f) : statement(i.elseIf(), f); + return yes.merge(no); + }); + case PbsAst.ForStatement loop -> expression(loop.fromExpression(), fields) + .then(f -> expression(loop.untilExpression(), f)).then(f -> expression(loop.stepExpression(), f)) + .then(f -> Paths.normal(meet(f, block(loop.body(), f).breaks()))); + case PbsAst.WhileStatement loop -> expression(loop.condition(), fields).then(f -> { + var body = block(loop.body(), f); + boolean always = unwrap(loop.condition()) instanceof PbsAst.BoolLiteralExpr b && b.value(); + return Paths.normal(always ? body.breaks() : meet(f, body.breaks())); + }); + }; + } + + private Paths expression(PbsAst.Expression expression, Set fields) { + return switch (expression) { + case null -> Paths.normal(fields); + case PbsAst.GroupExpr g -> expression(g.expression(), fields); + case PbsAst.BlockExpr b -> block(b.block(), fields); + case PbsAst.IfExpr i -> expression(i.condition(), fields).then(f -> + block(i.thenBlock(), f).merge(expression(i.elseExpression(), f))); + case PbsAst.SwitchExpr s -> expression(s.selector(), fields).then(f -> { + var result = new Paths(null, null, null); + for (var arm : s.arms()) result = result.merge(block(arm.block(), f)); + if (!exhaustive(s)) result = result.merge(Paths.normal(f)); + return result; + }); + case PbsAst.HandleExpr h -> expression(h.value(), fields).then(f -> { + // The successful value bypasses every handler arm. + var result = Paths.normal(f); + for (var arm : h.arms()) if (arm.remapTarget() == null) result = result.merge(block(arm.block(), f)); + return result; + }); + case PbsAst.ElseExpr e -> expression(e.optionalExpression(), fields).then(f -> + Paths.normal(f).merge(expression(e.fallbackExpression(), f))); + case PbsAst.BinaryExpr b -> expression(b.left(), fields).then(f -> { + var right = expression(b.right(), f); + return Set.of("&&", "||", "and", "or").contains(b.operator()) ? Paths.normal(f).merge(right) : right; + }); + case PbsAst.UnaryExpr u -> expression(u.expression(), fields); + case PbsAst.AsExpr a -> expression(a.expression(), fields); + case PbsAst.PropagateExpr p -> expression(p.expression(), fields); + case PbsAst.SomeExpr s -> expression(s.value(), fields); + case PbsAst.OkExpr o -> expression(o.value(), fields); + case PbsAst.MemberExpr m -> expression(m.receiver(), fields); + case PbsAst.IndexExpr i -> expression(i.receiver(), fields).then(f -> expression(i.index(), f)); + case PbsAst.ApplyExpr a -> expression(a.callee(), fields).then(f -> expression(a.argument(), f)); + case PbsAst.CallExpr c -> expressions(c.arguments(), expression(c.callee(), fields)); + case PbsAst.NewExpr n -> expressions(n.arguments(), Paths.normal(fields)); + case PbsAst.ArrayLiteralExpr a -> expressions(a.elements(), Paths.normal(fields)); + case PbsAst.TupleExpr t -> { + var result = Paths.normal(fields); + for (var item : t.items()) result = result.then(f -> expression(item.expression(), f)); + yield result; + } + default -> Paths.normal(fields); // literals, identifiers and deferred lambda bodies do not assign fields + }; + } + + private Paths expressions(Iterable expressions, Paths result) { + for (var expression : expressions) result = result.then(f -> expression(expression, f)); + return result; + } + + private boolean exhaustive(PbsAst.SwitchExpr expression) { + String enumName = null; + var cases = new HashSet(); + for (var arm : expression.arms()) { + if (arm.pattern() instanceof PbsAst.WildcardSwitchPattern) return true; + if (!(arm.pattern() instanceof PbsAst.EnumCaseSwitchPattern e) || e.path().segments().size() != 2) return false; + var name = e.path().segments().getFirst(); + if (enumName != null && !enumName.equals(name)) return false; + enumName = name; cases.add(e.path().segments().get(1)); + } + return enumName != null && model.enums.containsKey(enumName) && cases.containsAll(model.enums.get(enumName)); + } + + private PbsAst.Expression unwrap(PbsAst.Expression expression) { + return expression instanceof PbsAst.GroupExpr g ? unwrap(g.expression()) : expression; + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java index 5a7ebce2..64d58af9 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java @@ -58,17 +58,18 @@ public final class PbsDeclarationSemanticsValidator { final ReadOnlyList importedGlobals, final DiagnosticSink diagnostics) { final var binder = new PbsNamespaceBinder(nameTable, diagnostics); - final var rules = new PbsDeclarationRuleValidator(nameTable, diagnostics); final var interfaceModule = sourceKind == SourceKind.SDK_INTERFACE; for (final var topDecl : ast.topDecls()) { + final var declarationDiagnostics = p.studio.compiler.pbs.PbsGenericDiagnostics.forDeclaration(topDecl, diagnostics); + final var rules = new PbsDeclarationRuleValidator(nameTable, declarationDiagnostics); if (topDecl instanceof PbsAst.FunctionDecl functionDecl) { - validateDocAttributes(functionDecl.attributes(), "function declarations", diagnostics); + validateDocAttributes(functionDecl.attributes(), "function declarations", declarationDiagnostics); if (interfaceModule) { reportInterfaceNonDeclarativeDecl( functionDecl.span(), "Top-level functions are not allowed in interface modules", - diagnostics); + declarationDiagnostics); } validateCallable( PbsCallableScope.topLevelFunctions(), @@ -86,34 +87,34 @@ public final class PbsDeclarationSemanticsValidator { } if (topDecl instanceof PbsAst.StructDecl structDecl) { - validateDocAttributes(structDecl.attributes(), "struct declarations", diagnostics); + validateDocAttributes(structDecl.attributes(), "struct declarations", declarationDiagnostics); binder.registerType(structDecl.name(), structDecl.span(), "struct"); if (interfaceModule && (structDecl.hasBody() || !structDecl.methods().isEmpty() || !structDecl.ctors().isEmpty())) { reportInterfaceNonDeclarativeDecl( structDecl.span(), "Interface modules must not declare executable struct bodies", - diagnostics); + declarationDiagnostics); } - validateStructDeclaration(structDecl, binder, rules, diagnostics); + validateStructDeclaration(structDecl, binder, rules, declarationDiagnostics); continue; } if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) { - validateDocAttributes(serviceDecl.attributes(), "service declarations", diagnostics); + validateDocAttributes(serviceDecl.attributes(), "service declarations", declarationDiagnostics); binder.registerType(serviceDecl.name(), serviceDecl.span(), "service"); binder.registerValue(serviceDecl.name(), serviceDecl.span(), "service singleton"); binder.registerVisibleTopLevelSurface(serviceDecl.name(), serviceDecl.span(), "service"); - validateServiceDeclaration(serviceDecl, binder, rules, interfaceModule, diagnostics); + validateServiceDeclaration(serviceDecl, binder, rules, interfaceModule, declarationDiagnostics); continue; } if (topDecl instanceof PbsAst.ContractDecl contractDecl) { - validateDocAttributes(contractDecl.attributes(), "contract declarations", diagnostics); + validateDocAttributes(contractDecl.attributes(), "contract declarations", declarationDiagnostics); binder.registerType(contractDecl.name(), contractDecl.span(), "contract"); if (interfaceModule) { for (final var signature : contractDecl.signatures()) { - validateDocAttributes(signature.attributes(), "contract signatures", diagnostics); - validateReservedAttributeTargetExceptDoc(signature.attributes(), "contract signature", diagnostics); + validateDocAttributes(signature.attributes(), "contract signatures", declarationDiagnostics); + validateReservedAttributeTargetExceptDoc(signature.attributes(), "contract signature", declarationDiagnostics); } } validateContractDeclaration(contractDecl, binder, rules); @@ -121,27 +122,27 @@ public final class PbsDeclarationSemanticsValidator { } if (topDecl instanceof PbsAst.HostDecl hostDecl) { - validateDocAttributes(hostDecl.attributes(), "host declarations", diagnostics); + validateDocAttributes(hostDecl.attributes(), "host declarations", declarationDiagnostics); binder.registerHostOwner(hostDecl.name(), hostDecl.span(), "host owner"); - validateHostDeclaration(hostDecl, binder, rules, interfaceModule, diagnostics); + validateHostDeclaration(hostDecl, binder, rules, interfaceModule, declarationDiagnostics); continue; } if (topDecl instanceof PbsAst.BuiltinTypeDecl builtinTypeDecl) { binder.registerType(builtinTypeDecl.name(), builtinTypeDecl.span(), "builtin type"); - validateBuiltinTypeDeclaration(builtinTypeDecl, binder, rules, interfaceModule, diagnostics); + validateBuiltinTypeDeclaration(builtinTypeDecl, binder, rules, interfaceModule, declarationDiagnostics); continue; } if (topDecl instanceof PbsAst.ErrorDecl errorDecl) { - validateDocAttributes(errorDecl.attributes(), "error declarations", diagnostics); + validateDocAttributes(errorDecl.attributes(), "error declarations", declarationDiagnostics); binder.registerType(errorDecl.name(), errorDecl.span(), "error"); rules.validateErrorDeclaration(errorDecl); continue; } if (topDecl instanceof PbsAst.EnumDecl enumDecl) { - validateDocAttributes(enumDecl.attributes(), "enum declarations", diagnostics); + validateDocAttributes(enumDecl.attributes(), "enum declarations", declarationDiagnostics); binder.registerType(enumDecl.name(), enumDecl.span(), "enum"); rules.validateEnumDeclaration(enumDecl); continue; @@ -159,7 +160,7 @@ public final class PbsDeclarationSemanticsValidator { if (topDecl instanceof PbsAst.ConstDecl constDecl) { binder.registerValue(constDecl.name(), constDecl.span(), "const"); binder.registerVisibleTopLevelSurface(constDecl.name(), constDecl.span(), "const"); - final var allowMissingInitializer = validateConstDeclarationAttributes(constDecl, interfaceModule, diagnostics); + final var allowMissingInitializer = validateConstDeclarationAttributes(constDecl, interfaceModule, declarationDiagnostics); rules.validateConstDeclaration(constDecl, !allowMissingInitializer); continue; } @@ -169,7 +170,7 @@ public final class PbsDeclarationSemanticsValidator { reportInterfaceNonDeclarativeDecl( implementsDecl.span(), "Interface modules must not declare executable 'implements' blocks", - diagnostics); + declarationDiagnostics); } validateImplementsDeclaration(implementsDecl, binder, rules); } 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 08815a76..8175e28d 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 @@ -362,12 +362,15 @@ public final class PbsEditorialSupportService { private static final class DocumentContext { private final String sourceText; private final PbsAst.File ast; + private final PbsAst.File semanticAst; + private final Map genericResolutions; + private final Map concreteSymbols; private final ReadOnlyList editorialSupplementalTopDecls; private final ReadOnlyList tokens; private final Model model; private final PbsFlowTypeOps typeOps = new PbsFlowTypeOps(); private final PbsFlowExpressionAnalyzer expressionAnalyzer = new PbsFlowExpressionAnalyzer(typeOps); - private final PbsInlineHintSurfaceFormatter typeFormatter = new PbsInlineHintSurfaceFormatter(); + private final PbsInlineHintSurfaceFormatter typeFormatter; private final Map topLevelSymbols; private final Map importedSymbols; private final Map supplementalSymbols; @@ -386,11 +389,28 @@ public final class PbsEditorialSupportService { this.importedSymbols = buildImportedSymbols(expandedSupplementals); this.editorialSupplementalTopDecls = ReadOnlyList.wrap(expandedSupplementals); this.tokens = PbsLexer.lex(this.sourceText, FileId.none(), DiagnosticSink.empty()); + var projection = p.studio.compiler.pbs.PbsGenericInstantiation.needed(ast) + || expandedSupplementals.stream().anyMatch(d -> !p.studio.compiler.pbs.PbsGenericInstantiation.parameters( + d instanceof PbsAst.TypeBindingDecl b ? b.declaration() : d).isEmpty() + && !(d instanceof PbsAst.ContractDecl)); + var concrete = new LinkedHashMap(); + if (projection) { + var prepared = new p.studio.compiler.pbs.PbsGenericInstantiation(List.of( + new p.studio.compiler.pbs.PbsGenericInstantiation.Source(ast, editorialSupplementalTopDecls)), DiagnosticSink.empty(), feSurfaceContext).prepare(); + semanticAst = prepared.files().get(ast.span().getFileId()); + genericResolutions = prepared.resolutions(); + for (var d : semanticAst.topDecls()) if (p.studio.compiler.pbs.PbsContractTypes.applicationOrigin(d) != null) + concrete.put(p.studio.compiler.pbs.PbsGenericInstantiation.name(d), d); + } else { semanticAst = ast; genericResolutions = Map.of(); } + concreteSymbols = Map.copyOf(concrete); + var modelSupplemental = ReadOnlyList.wrap(editorialSupplementalTopDecls.stream().filter(d -> + !projection || p.studio.compiler.pbs.PbsGenericInstantiation.parameters(d instanceof PbsAst.TypeBindingDecl b ? b.declaration() : d).isEmpty()).toList()); this.model = Model.from( - ast, - editorialSupplementalTopDecls, + semanticAst, + modelSupplemental, feSurfaceContext == null ? FESurfaceContext.empty() : feSurfaceContext, DiagnosticSink.empty()); + this.typeFormatter = new PbsInlineHintSurfaceFormatter(model.contractTypes); this.topLevelSymbols = buildTopLevelSymbols(); this.supplementalSymbols = buildSupplementalSymbols(); this.aliasedTypeRefs = buildAliasedTypeRefs(); @@ -633,7 +653,10 @@ public final class PbsEditorialSupportService { } private CallableFrame callableFrameAt(final int offset) { - for (final var topDecl : ast.topDecls()) { + var declarations = new ArrayList(); + for (var d : ast.topDecls()) if (!p.studio.compiler.pbs.PbsGenericInstantiation.parameters(d).isEmpty()) declarations.add(d); + declarations.addAll(semanticAst.topDecls().asList()); + for (final var topDecl : declarations) { if (topDecl instanceof PbsAst.FunctionDecl functionDecl && functionDecl.span().contains(offset)) { return new CallableFrame( functionDecl.parameters(), @@ -734,6 +757,15 @@ public final class PbsEditorialSupportService { return List.of(); } final Map completions = new LinkedHashMap<>(); + var symbolic = symbolicStruct(receiverType); + if (symbolic != null) { + for (var field : symbolic.fields()) completions.put(field.name(), new PbsEditorialCompletionCandidate( + field.name(), PbsEditorialSymbolKind.FIELD, field.typeRef().surface(), symbolic.name())); + for (var method : symbolic.methods()) completions.put(method.name(), new PbsEditorialCompletionCandidate( + method.name(), PbsEditorialSymbolKind.METHOD, signatureFromFunction(method.name(), method.parameters(), + method.returnKind(), method.returnType(), method.resultErrorType()).label(), symbolic.name())); + return List.copyOf(completions.values()); + } if (receiverType.kind() == Kind.ARRAY) { return List.of(new PbsEditorialCompletionCandidate("length", PbsEditorialSymbolKind.FIELD, "long", "array"), new PbsEditorialCompletionCandidate("clear", PbsEditorialSymbolKind.METHOD, "clear(index: int | long) -> unit", "array")); @@ -783,6 +815,13 @@ public final class PbsEditorialSupportService { return List.copyOf(completions.values()); } + private PbsAst.StructDecl symbolicStruct(TypeView receiver) { + if (receiver == null || receiver.kind() != Kind.STRUCT) return null; + return ast.topDecls().stream().filter(d -> d instanceof PbsAst.StructDecl s + && !s.typeParameters().isEmpty() && s.name().equals(receiver.name())) + .map(d -> (PbsAst.StructDecl) d).findFirst().orElse(null); + } + private Optional resolveSymbolHover( final String symbolName, final int tokenIndex, @@ -844,6 +883,15 @@ public final class PbsEditorialSupportService { if (receiverType == null) { return Optional.empty(); } + var symbolic = symbolicStruct(receiverType); + if (symbolic != null) { + var field = symbolic.fields().stream().filter(f -> f.name().equals(memberName)).findFirst(); + if (field.isPresent()) return Optional.of(new PbsEditorialResolvedSymbol(memberName, + PbsEditorialSymbolKind.FIELD, field.get().typeRef().surface(), symbolic.name(), List.of(), "")); + var methods = signaturesForTopDecl(symbolic).stream().filter(s -> s.label().startsWith(memberName + "(")).toList(); + if (!methods.isEmpty()) return Optional.of(new PbsEditorialResolvedSymbol(memberName, + PbsEditorialSymbolKind.METHOD, methods.getFirst().label(), symbolic.name(), methods, "")); + } if (receiverType.kind() == Kind.ARRAY || receiverType.kind() == Kind.OPTIONAL) { return memberCompletions(receiverType).stream().filter(item -> item.label().equals(memberName)) .findFirst().map(item -> new PbsEditorialResolvedSymbol(item.label(), item.kind(), item.detail(), item.origin(), List.of(), "")); @@ -915,11 +963,11 @@ public final class PbsEditorialSupportService { } private PbsAst.TypeParameter typeParameterAt(String name, long offset) { - for (var declaration : ast.topDecls()) if (declaration instanceof PbsAst.ContractDecl contract && contract.span().contains(offset)) { - for (var parameter : contract.typeParameters()) if (parameter.name().equals(name)) { + for (var declaration : ast.topDecls()) if (declaration.span().contains(offset)) { + for (var parameter : p.studio.compiler.pbs.PbsGenericInstantiation.parameters(declaration)) if (parameter.name().equals(name)) { if (parameter.span().contains(offset)) return parameter; var found = new boolean[1]; - p.studio.compiler.pbs.ast.PbsTypeTraversal.visit(contract, t -> findTypeAt(t, name, offset, found)); + p.studio.compiler.pbs.ast.PbsTypeTraversal.visit(declaration, t -> findTypeAt(t, name, offset, found)); if (found[0]) return parameter; } } @@ -938,7 +986,20 @@ public final class PbsEditorialSupportService { private Optional genericHover(String name, long offset) { var parameter = typeParameterAt(name, offset); if (parameter != null) return Optional.of(new PbsEditorialResolvedSymbol(name, PbsEditorialSymbolKind.PARAMETER, - "type parameter " + name, "contract", List.of(), "")); + "type parameter " + name, "generic declaration", List.of(), "")); + boolean symbolicScope = ast.topDecls().stream().anyMatch(d -> !p.studio.compiler.pbs.PbsGenericInstantiation.parameters(d).isEmpty() && d.span().contains(offset)); + for (var resolution : genericResolutions.entrySet()) { + if (symbolicScope) break; + if (!resolution.getKey().contains(offset) || resolution.getKey().getFileId() == null + || !resolution.getKey().getFileId().equals(ast.span().getFileId()) + || offset >= resolution.getKey().getStart()+name.length()) continue; + var declaration = concreteSymbols.get(resolution.getValue()); + if (declaration == null) continue; + var origin = p.studio.compiler.pbs.PbsContractTypes.applicationOrigin(declaration); + return Optional.of(new PbsEditorialResolvedSymbol(origin.display(), symbolKind(declaration), + symbolKind(declaration).name().toLowerCase(Locale.ROOT)+" "+origin.display(), "generic application", + signaturesForTopDecl(declaration), documentationFromTopDecl(declaration))); + } var references = new ArrayList(); for (var declaration : ast.topDecls()) p.studio.compiler.pbs.ast.PbsTypeTraversal.visit(declaration, references::add); var pending = new ArrayDeque<>(references); @@ -1222,6 +1283,8 @@ public final class PbsEditorialSupportService { private List resolveCallableSignatures( final String callableName, final ScopeState scopeState) { + var applied = concreteSymbols.get(callableName); + if (applied != null) return signaturesForTopDecl(applied); final TopDeclSymbol importedSymbol = importedSymbols.get(callableName); if (importedSymbol != null) { return signaturesForTopDecl(importedSymbol.decl()); @@ -1246,6 +1309,8 @@ public final class PbsEditorialSupportService { } private List resolveConstructorSignatures(final String typeName) { + var applied = concreteSymbols.get(typeName); + if (applied != null) return constructorSignaturesForTopDecl(applied); final TopDeclSymbol importedSymbol = importedSymbols.get(typeName); if (importedSymbol != null) { return constructorSignaturesForTopDecl(importedSymbol.decl()); @@ -1366,8 +1431,11 @@ public final class PbsEditorialSupportService { private List signaturesForTopDecl(final PbsAst.TopDecl topDecl) { if (topDecl instanceof PbsAst.FunctionDecl functionDecl) { - return List.of(signatureFromFunction(functionDecl.name(), functionDecl.parameters(), functionDecl.returnKind(), functionDecl.returnType(), functionDecl.resultErrorType())); + var name = functionDecl.applicationOrigin() == null ? functionDecl.name() : functionDecl.applicationOrigin().display(); + return List.of(signatureFromFunction(name, functionDecl.parameters(), functionDecl.returnKind(), functionDecl.returnType(), functionDecl.resultErrorType())); } + if (topDecl instanceof PbsAst.StructDecl structDecl) return structDecl.methods().stream() + .map(method -> signatureFromFunction(method.name(), method.parameters(), method.returnKind(), method.returnType(), method.resultErrorType())).toList(); if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) { return serviceDecl.methods().stream() @@ -1475,7 +1543,7 @@ public final class PbsEditorialSupportService { return switch (typeRef.kind()) { case UNIT -> "unit"; case SELF -> "Self"; - case SIMPLE -> typeRef.surface(); + 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()) + "?"; @@ -1522,6 +1590,19 @@ public final class PbsEditorialSupportService { } private PbsAst.Expression receiverExpressionBefore(final int dotTokenIndex) { + var receivers = new ArrayList(); + var before = previousSignificantTokenIndex(dotTokenIndex); + if (before != null) { + var endingAt = token(before).end(); + var visitor = new p.studio.compiler.pbs.ast.PbsAstRewriter() { + @Override public PbsAst.Expression expression(PbsAst.Expression e, PbsAst.TypeRef expected) { + if (e instanceof PbsAst.MemberExpr m && m.receiver().span().getEnd() == endingAt) receivers.add(m.receiver()); + return super.expression(e, expected); + } + }; + visitor.file(semanticAst); + if (!receivers.isEmpty()) return receivers.getFirst(); + } // Locate only the fragment boundary here; grammar and overload selection // remain in the existing PBS parser and flow expression analyzer. int start = dotTokenIndex; @@ -1645,11 +1726,22 @@ public final class PbsEditorialSupportService { return null; } final PbsToken calleeToken = token(calleeIndex); + if (calleeToken.kind() == PbsTokenKind.GREATER || calleeToken.kind() == PbsTokenKind.GREATER_EQUAL) { + for (var resolution : genericResolutions.entrySet()) if (resolution.getKey().getEnd() == calleeToken.end()) { + var declaration = concreteSymbols.get(resolution.getValue()); + if (declaration != null) return new CallSite(declaration instanceof PbsAst.StructDecl ? CallSiteKind.CONSTRUCTOR : CallSiteKind.FUNCTION, + resolution.getValue(), activeParameter, -1); + } + } if (calleeToken.kind() != PbsTokenKind.IDENTIFIER) { return null; } final Integer maybeDotIndex = previousSignificantTokenIndex(calleeIndex); if (maybeDotIndex != null && token(maybeDotIndex).kind() == PbsTokenKind.DOT) { + var ownerIndex = previousSignificantTokenIndex(maybeDotIndex); + if (ownerIndex != null) for (var resolution : genericResolutions.entrySet()) + if (resolution.getKey().getEnd() == token(ownerIndex).end() && concreteSymbols.get(resolution.getValue()) instanceof PbsAst.StructDecl) + return new CallSite(CallSiteKind.CONSTRUCTOR, resolution.getValue(), activeParameter, -1); return new CallSite(CallSiteKind.MEMBER, calleeToken.lexeme(), activeParameter, maybeDotIndex); } if (maybeDotIndex != null && token(maybeDotIndex).kind() == PbsTokenKind.NEW) { @@ -2191,6 +2283,7 @@ public final class PbsEditorialSupportService { if (topDecl instanceof PbsAst.FunctionDecl functionDecl) { return new PbsAst.FunctionDecl( newName, + functionDecl.typeParameters(), functionDecl.parameters(), functionDecl.returnKind(), functionDecl.returnType(), @@ -2198,16 +2291,19 @@ public final class PbsEditorialSupportService { functionDecl.attributes(), functionDecl.lifecycleMarker(), functionDecl.body(), + functionDecl.applicationOrigin(), functionDecl.span()); } if (topDecl instanceof PbsAst.StructDecl structDecl) { return new PbsAst.StructDecl( newName, + structDecl.typeParameters(), structDecl.fields(), structDecl.methods(), structDecl.ctors(), structDecl.hasBody(), structDecl.attributes(), + structDecl.applicationOrigin(), structDecl.span()); } if (topDecl instanceof PbsAst.BuiltinTypeDecl builtinTypeDecl) { @@ -2244,6 +2340,8 @@ public final class PbsEditorialSupportService { } private TopDeclSymbol resolveTopDeclSymbol(final String symbolName) { + var concrete = concreteSymbols.get(symbolName); + if (concrete != null) return new TopDeclSymbol(symbolName, concrete, "generic application"); final TopDeclSymbol importedSymbol = importedSymbols.get(symbolName); if (importedSymbol != null) { return importedSymbol; 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 f4794005..d175be05 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 @@ -36,7 +36,7 @@ final class PbsFlowBodyAnalyzer { final var model = Model.from(ast, supplementalTopDecls, feSurfaceContext, diagnostics); for (final var topDecl : ast.topDecls()) { - validateTopDecl(topDecl, model, diagnostics); + validateTopDecl(topDecl, model, p.studio.compiler.pbs.PbsGenericDiagnostics.forDeclaration(topDecl, diagnostics)); } } finally { inlineHintCollector = previousCollector; @@ -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); 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 final PbsInlineHintSurfaceFormatter formatter = new PbsInlineHintSurfaceFormatter(); + private PbsInlineHintSurfaceFormatter formatter = new PbsInlineHintSurfaceFormatter(); @Override public void collect(final PbsAst.LetStatement letStatement, final TypeView inferredType) { @@ -167,6 +167,7 @@ final class PbsFlowBodyAnalyzer { diagnostics); } for (final var ctor : structDecl.ctors()) { + new PbsCtorInitializationAnalyzer(model).validate(structDecl, ctor, diagnostics); validateCallableBody( ctor.parameters(), ctor.body(), diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStatementAnalyzer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStatementAnalyzer.java index 2db72ea9..0e310e45 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStatementAnalyzer.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStatementAnalyzer.java @@ -318,7 +318,7 @@ final class PbsFlowStatementAnalyzer { analyzeReturnErr(errExpr, context); return; } - expressionAnalyzer.analyzeExpression( + final var actual = expressionAnalyzer.analyzeExpression( value, context.scope(), context.returnType(), @@ -329,7 +329,11 @@ final class PbsFlowStatementAnalyzer { context.diagnostics(), ExprUse.VALUE, true, - this::analyzeNestedBlock); + this::analyzeNestedBlock).type(); + if (!typeOps.compatible(actual, context.returnType())) { + Diagnostics.error(context.diagnostics(), "E_SEM_RETURN_TYPE_MISMATCH", + "Returned value does not match the declared result type", value.span()); + } } private void analyzeReturnOk( 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 index 88ac5eae..2e498228 100644 --- 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 @@ -4,6 +4,9 @@ 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; @@ -18,7 +21,8 @@ final class PbsInlineHintSurfaceFormatter { ENUM, ERROR, TYPE_REF, - ADDRESSABLE -> type.name(); + 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 -> { diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PBSFrontendPhaseService.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PBSFrontendPhaseService.java index 7175fe2c..5989889a 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PBSFrontendPhaseService.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PBSFrontendPhaseService.java @@ -58,7 +58,9 @@ public class PBSFrontendPhaseService implements FrontendPhaseService { final var nameTable = ctx.nameTable(); final var feSurfaceContext = ctx.feSurfaceContext(); final var assembly = moduleAssemblyService.assemble(ctx, nameTable, diagnostics, issues); - final var parsedSourceFiles = assembly.parsedSourceFiles(); + final var sourceContexts = importedSemanticContextService.build(assembly.parsedSourceFiles(), assembly.moduleTable()); + final var parsedSourceFiles = new PbsGenericProgramService().prepare(assembly.parsedSourceFiles(), sourceContexts, + assembly.moduleTable(), diagnostics, feSurfaceContext); final var importedSemanticContexts = importedSemanticContextService.build(parsedSourceFiles, assembly.moduleTable()); projectLifecycleSemanticsValidator.validate(parsedSourceFiles.asList(), diagnostics); final var failedModuleIds = assembly.mutableFailedModuleIds(); @@ -127,6 +129,11 @@ public class PBSFrontendPhaseService implements FrontendPhaseService { final var importedSemanticContexts = service.importedSemanticContextService.build( assembly.parsedSourceFiles(), assembly.moduleTable()); + final var semanticFiles = new PbsGenericProgramService().prepare(assembly.parsedSourceFiles(), importedSemanticContexts, + assembly.moduleTable(), diagnostics, ctx.feSurfaceContext()); + final var semanticContexts = service.importedSemanticContextService.build(semanticFiles, assembly.moduleTable()); + final var semanticAstByFile = new HashMap(); + semanticFiles.forEach(f -> semanticAstByFile.put(f.fileId(), f.ast())); final var flowSemanticsValidator = new PbsFlowSemanticsValidator(); final Map astByFile = new LinkedHashMap<>(); final Map> supplementalTopDeclsByFile = new LinkedHashMap<>(); @@ -149,8 +156,8 @@ public class PBSFrontendPhaseService implements FrontendPhaseService { parsedSourceFile.fileId(), PbsImportedSemanticContext.empty()); final var inlineHints = flowSemanticsValidator.collectInlineHints( - parsedSourceFile.ast(), - importedSemanticContext.supplementalTopDecls(), + semanticAstByFile.get(parsedSourceFile.fileId()), + semanticContexts.getOrDefault(parsedSourceFile.fileId(), PbsImportedSemanticContext.empty()).supplementalTopDecls(), ctx.feSurfaceContext(), diagnostics); if (!inlineHints.isEmpty()) { diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsGenericProgramService.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsGenericProgramService.java new file mode 100644 index 00000000..db43d850 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsGenericProgramService.java @@ -0,0 +1,52 @@ +package p.studio.compiler.services; + +import p.studio.compiler.pbs.PbsContractTypes; +import p.studio.compiler.pbs.PbsGenericInstantiation; +import p.studio.compiler.pbs.ast.PbsAst; +import p.studio.compiler.source.diagnostics.DiagnosticSink; +import p.studio.compiler.source.identifiers.FileId; +import p.studio.compiler.source.tables.ModuleTable; +import p.studio.utilities.structures.ReadOnlyList; +import java.util.*; + +/** Instantiates once per program and emits bodies in their definition modules. */ +final class PbsGenericProgramService { + ReadOnlyList prepare(ReadOnlyList files, + Map contexts, ModuleTable modules, DiagnosticSink diagnostics, + p.studio.compiler.messages.FESurfaceContext surface) { + if (files.stream().noneMatch(f -> PbsGenericInstantiation.needed(f.ast()))) return files; + var sources = files.stream().map(f -> new PbsGenericInstantiation.Source(f.ast(), + contexts.getOrDefault(f.fileId(), PbsImportedSemanticContext.empty()).supplementalTopDecls(), f.moduleId())).toList(); + var prepared = new PbsGenericInstantiation(sources, diagnostics, surface).prepare(); + var sourceByFile = new HashMap(); + files.forEach(f -> sourceByFile.put(f.fileId(), f)); + var output = new ArrayList(); + for (var file : files) { + var ast = prepared.files().get(file.fileId()); + var imports = new ArrayList<>(ast.imports().asList()); + var requested = prepared.dependencies().getOrDefault(file.fileId(), Set.of()); + var generatedImports = new HashMap>(); + for (var provider : prepared.files().entrySet()) { + if (file.moduleId().equals(sourceByFile.get(provider.getKey()).moduleId())) continue; + for (var declaration : provider.getValue().topDecls()) { + var origin = PbsContractTypes.applicationOrigin(declaration); + if (origin != null && requested.contains(origin.declaration())) + generatedImports.computeIfAbsent(provider.getKey(), ignored -> new LinkedHashMap<>()).put(PbsGenericInstantiation.name(declaration), null); + else if (origin == null && requested.stream().anyMatch(d -> d.getClass() == declaration.getClass() + && d.span().equals(declaration.span())) && PbsGenericInstantiation.name(declaration) != null) + generatedImports.computeIfAbsent(provider.getKey(), ignored -> new LinkedHashMap<>()).put( + PbsGenericInstantiation.name(declaration), PbsGenericInstantiation.nominalBinding(declaration)); + } + } + for (var imported : generatedImports.entrySet()) { + var provider = sourceByFile.get(imported.getKey()); + var module = modules.get(provider.moduleId()); + imports.add(new PbsAst.ImportDecl(ReadOnlyList.wrap(imported.getValue().entrySet().stream().map(entry -> + new PbsAst.ImportItem(entry.getKey(), entry.getValue(), ast.span())).toList()), + new PbsAst.ModuleRef(module.project(), module.pathSegments(), ast.span()), ast.span())); + } + output.add(new PbsParsedSourceFile(file.fileId(), new PbsAst.File(ReadOnlyList.wrap(imports), ast.topDecls(), ast.span()), file.moduleId(), file.sourceKind())); + } + return ReadOnlyList.wrap(output); + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java index 317bd387..b6c3ae52 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java @@ -58,7 +58,8 @@ final class PbsImportedSemanticContextService { var importedIndex = topDeclsByNameByModule.getOrDefault(target, Map.of()); var localIndex = topDeclsByNameByModule.get(source.moduleId()); for (var item : imported.items()) for (var declaration : new ArrayList<>(importedIndex.getOrDefault(item.name(), new ArrayList<>()))) - if (declaration instanceof PbsAst.ContractDecl) { + if (declaration instanceof PbsAst.ContractDecl || declaration instanceof PbsAst.StructDecl + || declaration instanceof PbsAst.FunctionDecl) { var candidates = localIndex.computeIfAbsent(importItemLocalName(item), ignored -> new ArrayList<>()); if (candidates.stream().noneMatch(d -> d.span().equals(declaration.span()))) { candidates.add(declaration); exportedContractsChanged = true; @@ -82,7 +83,7 @@ final class PbsImportedSemanticContextService { for (var sibling : sourcesByModule.getOrDefault(parsedSource.moduleId(), new ArrayList<>())) { if (sibling.fileId().equals(parsedSource.fileId())) continue; for (var declaration : sibling.ast().topDecls()) { - if (isTypeDecl(declaration)) appendSupplementalTopDecl( + if (isTypeDecl(declaration) || declaration instanceof PbsAst.FunctionDecl f && !f.typeParameters().isEmpty()) appendSupplementalTopDecl( new PbsAst.TypeBindingDecl(topDeclName(declaration), declaration, parsedSource.ast().span()), supplementalTopDecls, supplementalKeys); if (declaration instanceof PbsAst.ImplementsDecl) appendSupplementalTopDecl(declaration, supplementalTopDecls, supplementalKeys); } @@ -110,12 +111,12 @@ final class PbsImportedSemanticContextService { final var directDecls = importedTopDeclsByName.getOrDefault(importName, new ArrayList<>()); for (final var topDecl : directDecls) { appendSupplementalTopDecl(topDecl, supplementalTopDecls, supplementalKeys); - if (isTypeDecl(topDecl)) appendSupplementalTopDecl(new PbsAst.TypeBindingDecl(localName, topDecl, importItem.span()), supplementalTopDecls, supplementalKeys); + if (isTypeDecl(topDecl) || topDecl instanceof PbsAst.FunctionDecl f && !f.typeParameters().isEmpty()) appendSupplementalTopDecl(new PbsAst.TypeBindingDecl(localName, topDecl, importItem.span()), supplementalTopDecls, supplementalKeys); var definingModule = moduleBySource.getOrDefault(topDecl.span().getFileId(), importedModuleId); appendTypeDependencyDecls(topDecl, topDeclsByNameByModule.getOrDefault(definingModule, importedTopDeclsByName), supplementalTopDecls, supplementalKeys); if (topDecl instanceof PbsAst.StructDecl || topDecl instanceof PbsAst.ServiceDecl) { for (var ownerSource : importedSources) for (var declaration : ownerSource.ast().topDecls()) - if (declaration instanceof PbsAst.ImplementsDecl implementation && implementation.ownerName().equals(importName)) { + if (declaration instanceof PbsAst.ImplementsDecl implementation && implementation.ownerType().name().equals(importName)) { appendSupplementalTopDecl(implementation, supplementalTopDecls, supplementalKeys); appendTypeDependencyDecls(implementation, importedTopDeclsByName, supplementalTopDecls, supplementalKeys); } @@ -235,6 +236,10 @@ final class PbsImportedSemanticContextService { final Map> index = new HashMap<>(); for (final var source : moduleSources) { for (final var topDecl : source.ast().topDecls()) { + if (topDecl instanceof PbsAst.TypeBindingDecl binding) { + index.computeIfAbsent(binding.name(), ignored -> new ArrayList<>()).add(binding.declaration()); + continue; + } final var declName = topDeclName(topDecl); if (declName == null || declName.isBlank()) { continue; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/generics.pbs b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/generics.pbs new file mode 100644 index 00000000..924d97fa --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/generics.pbs @@ -0,0 +1,21 @@ +declare struct Box(value: T) { + fn get() -> T { return this.value; } + fn set(value: T) { this.value = value; } +} + +declare contract Reader { fn read() -> T; } + +implements Reader for Box using box { + fn read() -> T { return box.get(); } +} + +fn read(reader: Reader) -> T { return reader.read(); } + +fn genericsExample() -> int { + let box: Box = new Box<>(40); + let alias = box; + alias.set(42); + let reader: Reader = box; + let invoke: Fn(Reader) -> int = read; + return invoke(reader); +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel index a64c3c44..789f346d 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel @@ -1,3 +1,4 @@ pub fn init() -> void; pub fn frame() -> void; pub fn contractExample() -> int; +pub fn genericsExample() -> int; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsGenericStructsTest.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsGenericStructsTest.java new file mode 100644 index 00000000..3cd784d0 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsGenericStructsTest.java @@ -0,0 +1,203 @@ +package p.studio.compiler.pbs; + +import org.junit.jupiter.api.Test; +import p.studio.compiler.source.diagnostics.DiagnosticSink; +import p.studio.compiler.source.identifiers.FileId; +import static org.junit.jupiter.api.Assertions.*; + +class PbsGenericStructsTest { + private static final String BOX = """ + declare struct Box(value: T) { + fn get() -> T { return this.value; } + fn set(value: T) { this.value = value; } + } + """; + private DiagnosticSink compile(String source) { + var diagnostics = DiagnosticSink.empty(); + new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics); + return diagnostics; + } + private void accepts(String source) { + var diagnostics = compile(source); + assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+": "+d.getMessage()).toList().toString()); + } + private void rejects(String source, String code) { + var diagnostics = compile(source); + assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals(code)), () -> diagnostics.stream().map(d -> d.getCode()+": "+d.getMessage()).toList().toString()); + } + @Test void specializesStateMethodsAndContextualConstructions() { + accepts(BOX+""" + fn main() -> int { + let a = new Box(40); + let b: Box = new Box<>(41); + let c: Box = new Box(42); + a.set(c.get()); return a.get(); + } + """); + } + @Test void explicitFreeFunctionsBecomeFnValuesAndComposeWithGenericDispatch() { + accepts(BOX+""" + declare contract Reader { fn read() -> T; } + implements Reader for Box using box { fn read() -> T { return box.get(); } } + fn read(reader: Reader) -> T { return reader.read(); } + fn main() -> int { + let box = new Box(42); + let reader: Reader = box; + let invoke: Fn(Reader) -> int = read; + return invoke(reader); + } + """); + } + @Test void rejectsUnjustifiedCapabilitiesEvenWhenTemplateIsUnused() { + rejects("fn double(value: T) -> T { return value + value; }", "E_SEM_GENERIC_CAPABILITY"); + rejects(BOX+"fn main() { let x = new Box(42); }", "E_SEM_GENERIC_CONTEXT"); + rejects("fn identity(value: T) -> T { return value; } fn main() { let x = identity(42); }", "E_SEM_GENERIC_FUNCTION_ARGUMENTS"); + } + @Test void rejectsOverlappingRulesWithoutRequestingTheConflictingApplication() { + rejects(BOX+""" + declare contract Reader { fn read() -> T; } + implements Reader for Box using box { fn read() -> T { return box.get(); } } + implements Reader for Box using box { fn read() -> int { return box.get(); } } + """, "E_SEM_GENERIC_OVERLAP"); + } + + @Test void substitutesNestedBodiesAndSnapshotCaptures() { + accepts(BOX+""" + fn box(value: U) -> Box { return new Box(value); } + fn wrap(value: T) -> Fn() -> T { + let owner: Box = box(value); + return fn [owner]() -> T { return owner.get(); }; + } + fn main() -> int { let read = wrap(42); return read(); } + """); + } + @Test void composesOptionalTupleArrayAndFunctionFields() { + accepts(BOX+""" + fn add(value: int) -> int { return value + 2; } + fn main() -> int { + let option = new Box(some(40)); + let pair = new Box<(left: int, right: int)>((left: 20, right: 22)); + let array = new Box>([40]); + let function = new Box int>(add); + let values = pair.get(); + let call = function.get(); + return call(array.get()[0] else 0); + } + """); + } + @Test void checksUnusedMethodsAndRejectsCollapsingOverloads() { + rejects(""" + declare struct Container(value: T) { + fn unused() { let values: array = new array(1); } + } + fn main() { let c = new Container(none); } + """, "E_SEM_ARRAY_ELEMENT_TYPE"); + rejects(""" + declare struct Overload(value: T) { + fn set(value: T) { this.value = value; } + fn set(value: int) { } + } + fn main() { let c = new Overload(42); } + """, "E_SEM_GENERIC_COLLISION"); + } + @Test void supportsNominalRecursionAndBoundsExpansionThroughUnusedBodies() { + accepts(""" + declare struct Node(value: T, next: optional Node) { + fn get() -> T { return this.value; } + } + fn main() -> int { let node = new Node(42, none); return node.get(); } + """); + rejects(""" + declare struct Growing(value: T) { + fn unused() { let larger = new Growing>([this.value]); } + } + fn main() { let c = new Growing(42); } + """, "E_SEM_GENERIC_EXPANSION"); + } + @Test void acceptsNamedConstructorsAppliedSelfAndDifferentContractTargets() { + accepts(""" + declare struct Box(value: T) { + ctor make(value: T) { this.value = value; } + fn same() -> Self { return this; } + fn get() -> T { return this.value; } + } + fn main() -> int { let b = new Box.make(42); return b.same().get(); } + """); + } + @Test void preservesNominalArgumentsAndResolvesEveryExpectedConstructionPosition() { + accepts(BOX+""" + declare struct Enemy(pub hp: int); + fn take(value: Box) -> Box { return value; } + fn make() -> Box { return new Box(new Enemy(42)); } + fn main() -> int { + let box = make(); + box = new Box<>(new Enemy(42)); + let selected = take(new Box(new Enemy(42))); + return selected.get().hp; + } + """); + } + @Test void unusedTemplatesStillObeyOrdinaryFlowAndConstructorRules() { + rejects("fn unfinished(value: T) -> T {}", "E_SEM_POSSIBLE_FALLTHROUGH_NON_UNIT"); + rejects("fn wrong(value: T) -> int { return true; }", "E_SEM_RETURN_TYPE_MISMATCH"); + var diagnostics = compile("declare struct Uninitialized(value: T) { ctor make() {} }"); + assertTrue(diagnostics.hasErrors(), "An unused generic constructor must initialize its fields"); + } + @Test void constructorsRequireInitializationAcrossBranchesAndLoopExits() { + accepts(""" + declare struct Box(value: T) { + ctor choose(flag: bool, a: T, b: T) { + if flag { this.value = a; } else { this.value = b; } + } + ctor once(value: T) { while true { this.value = value; break; } } + } + fn main() { let value = new Box.choose(true, 40, 42); } + """); + rejects("declare struct Box(value: int) { ctor choose(flag: bool) { if flag { this.value = 42; } } }", + "E_SEM_CTOR_FIELD_UNINITIALIZED"); + rejects("declare struct Box(value: T) { ctor loop(value: T) { for i: int from 0 until 1 { this.value = value; } } }", + "E_SEM_CTOR_FIELD_UNINITIALIZED"); + rejects("declare struct Box(value: int) { ctor loop(flag: bool) { while true { if flag { break; } this.value = 42; break; } } }", + "E_SEM_CTOR_FIELD_UNINITIALIZED"); + rejects("declare struct Box(value: int) { ctor choose(flag: bool) { let ignored = flag and { this.value = 42; true }; } }", + "E_SEM_CTOR_FIELD_UNINITIALIZED"); + } + @Test void preservesCallableFieldsAndLexicalApplicationScope() { + accepts(""" + declare struct Callback(transform: Fn(T) -> T) { + fn invoke(value: T) -> T { return this.transform(value); } + } + fn identity(value: T) -> T { return value; } + fn main() -> int { let transform = new Callback(identity); return transform.invoke(42); } + """); + rejects("fn id(value: T) -> T { return value; } fn main() { let id = id; id(42); }", + "E_SEM_GENERIC_FUNCTION_ARGUMENTS"); + rejects("declare struct Marker(); fn main() { let marker = new Marker(); }", "E_SEM_INVALID_SELF_CONTEXT"); + } + @Test void filtersExplicitOverloadsAndPreservesComparisonsAndNestedClosers() { + accepts(""" + declare struct Box(value: T); + fn identity(value: bool) -> bool { return value; } + fn identity(value: T) -> T { return value; } + fn main() -> int { + let nested = identity>>(new Box>([42])); + let a = 1; let b = 2; let c = 3; + if a < b && c >= b && identity(true) { return 42; } + return identity(0); + } + """); + rejects("fn duplicate(value: T) -> T { return value; } fn duplicate(value: U) -> U { return value; }", + "E_SEM_GENERIC_DUPLICATE"); + accepts("fn recurse(value: T, stop: bool) -> T { if stop { return value; } return recurse(value, true); } fn main() -> int { return recurse(42, false); }"); + rejects("fn grow(value: T) { grow>([value]); } fn main() { grow(42); }", "E_SEM_GENERIC_EXPANSION"); + } + @Test void concreteErrorsRetainDefinitionAndRequestingUse() { + String source = "declare struct Storage(values: array); fn main() { let value = new Storage([]); }"; + var diagnostics = compile(source); + var error = diagnostics.stream().filter(d -> d.getCode().equals("E_SEM_ARRAY_ELEMENT_TYPE")).findFirst().orElseThrow(); + assertTrue(error.getMessage().contains("Storage"), error.getMessage()); + assertFalse(error.getMessage().contains("$generic$"), error.getMessage()); + assertTrue(error.getRelated().stream().anyMatch(r -> r.getSpan().getStart() == 0)); + assertTrue(error.getRelated().stream().anyMatch(r -> r.getSpan().getStart() >= source.indexOf("new Storage"))); + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsGenericStructsEditorialTest.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsGenericStructsEditorialTest.java new file mode 100644 index 00000000..22bb97e1 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsGenericStructsEditorialTest.java @@ -0,0 +1,61 @@ +package p.studio.compiler.pbs.semantics; + +import org.junit.jupiter.api.Test; +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.diagnostics.DiagnosticSink; +import p.studio.compiler.source.identifiers.FileId; +import p.studio.utilities.structures.ReadOnlyList; +import static org.junit.jupiter.api.Assertions.*; + +class PbsGenericStructsEditorialTest { + private PbsAst.File parse(String source, int id) { + var diagnostics = DiagnosticSink.empty(); var file = new FileId(id); + var ast = PbsParser.parse(PbsLexer.lex(source, file, diagnostics), file, diagnostics, PbsParser.ParseMode.ORDINARY); + assertFalse(diagnostics.hasErrors(), diagnostics.toString()); return ast; + } + @Test void symbolicNavigationAndConcreteSignaturesShareSourceOrigins() { + var source = """ + declare struct Box(value: T) { fn get() -> T { return this.value; } } + fn identity(value: U) -> U { return value; } + fn demo() -> int { + let box: Box = new Box(42); + let copy = identity(42); + return box.get(); + } + """; + var ast = parse(source, 0); var service = new PbsEditorialSupportService(); + var empty = ReadOnlyList.empty(); + var parameter = service.definition(source, ast, empty, source.indexOf("value: T")+7); + assertEquals(source.indexOf("")+1, parameter.getFirst().span().getStart()); + assertTrue(service.hover(source, ast, empty, source.indexOf("value: T")+7).orElseThrow().detail().contains("type parameter")); + var hover = service.hover(source, ast, empty, source.indexOf("Box")); + assertEquals("Box", hover.orElseThrow().displayName()); + assertEquals("get() -> int", hover.orElseThrow().signatures().getFirst().label()); + int member = source.indexOf("box.get")+4; + assertTrue(service.completion(source, ast, empty, member).stream().anyMatch(c -> c.label().equals("get") && c.detail().contains("int"))); + assertFalse(service.definition(source, ast, empty, member).isEmpty()); + assertEquals("identity(value: int) -> int", service.signatureHelp(source, ast, empty, + source.indexOf("identity(42")+14).orElseThrow().signatures().getFirst().label()); + var usages = service.references(source, ast, empty, source.indexOf("")+1); + assertTrue(usages.size() >= 3); + int symbolicMember = source.indexOf("this.value") + 5; + assertTrue(service.completion(source, ast, empty, symbolicMember).stream() + .anyMatch(c -> c.label().equals("value") && c.detail().equals("T"))); + assertEquals("T", service.hover(source, ast, empty, symbolicMember).orElseThrow().detail()); + var formatted = p.studio.compiler.pbs.PbsDocumentFormatter.format(source); + parse(formatted, 0); + assertEquals(formatted, p.studio.compiler.pbs.PbsDocumentFormatter.format(formatted)); + } + @Test void importedGenericAliasesKeepCanonicalPresentationAndDefinitionSpans() { + var remote = parse("declare struct Box(value: T) { fn get() -> T { return this.value; } }", 1); + var source = "import { Box as Package } from @sdk:boxes; fn demo(box: Package) -> int { return box.get(); }"; + var ast = parse(source, 2); + var supplemental = ReadOnlyList.wrap(java.util.List.of(new PbsAst.TypeBindingDecl("Package", remote.topDecls().getFirst(), ast.span()))); + var service = new PbsEditorialSupportService(); + assertEquals(remote.topDecls().getFirst().span(), service.definition(source, ast, supplemental, source.indexOf("Package")).getFirst().span()); + assertEquals("Box", service.hover(source, ast, supplemental, source.indexOf("Package")).orElseThrow().displayName()); + assertEquals("get() -> int", service.hover(source, ast, supplemental, source.indexOf("box.get")+4).orElseThrow().signatures().getFirst().label()); + } +} diff --git a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridge.java b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridge.java index 9ed2680f..682dda12 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridge.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridge.java @@ -1310,7 +1310,8 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg final List signatures = symbol.signatures(); if (!signatures.isEmpty()) { markdown.append("```pbs\n"); - if (symbol.kind() == p.studio.compiler.services.FrontendSymbolKind.CONTRACT) + if (symbol.kind() == p.studio.compiler.services.FrontendSymbolKind.CONTRACT + || symbol.kind() == p.studio.compiler.services.FrontendSymbolKind.STRUCT) markdown.append(symbol.displayName()).append('\n'); for (int index = 0; index < signatures.size(); index += 1) { if (index > 0) { 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 b291ec95..94d6b902 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,32 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class CompilerLanguageServiceBridgeTest { + @Test void genericStructsAndFreeFunctionsExposeConcreteSourceSignatures(@TempDir Path root) throws Exception { + Files.createDirectories(root.resolve("src")); + Files.writeString(root.resolve("prometeu.json"), """ + {"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]} + """); + String text = """ + declare struct Box(value: T) { fn get() -> T { return this.value; } } + fn identity(value: U) -> U { return value; } + fn demo() -> int { let box = new Box(42); let value = identity(42); return box.get(); } + """; + Path file = Files.writeString(root.resolve("src/main.pbs"), text).toRealPath(); + Files.writeString(root.resolve("src/mod.barrel"), "pub struct Box; pub fn identity(value: U) -> U; pub fn demo() -> int;"); + var bridge = new CompilerLanguageServiceBridge(); var context = new LspProjectContext("app", "pbs", root.toRealPath()); + var mapper = new DocumentPositionMapper(text); + var applied = mapper.positionOf(text.indexOf("Box")); + var hover = bridge.hover(context, file.toUri().toString(), text, applied.line(), applied.character()); + assertTrue(hover.markdown().contains("Box"), hover.markdown()); + assertTrue(hover.markdown().contains("get() -> int"), hover.markdown()); + var argument = mapper.positionOf(text.indexOf("identity(42")+14); + var help = bridge.signatureHelp(context, file.toUri().toString(), text, argument.line(), argument.character()); + assertEquals("identity(value: int) -> int", help.signatures().getFirst().label()); + var parameter = mapper.positionOf(text.indexOf("value: T")+7); + var definition = bridge.definition(context, file.toUri().toString(), text, parameter.line(), parameter.character()); + assertEquals(text.indexOf("")+1, definition.locations().getFirst().startCharacter()); + } + @Test void genericContractsKeepSubstitutedSignaturesAcrossTheBridge(@TempDir Path root) throws Exception { Files.createDirectories(root.resolve("src")); Files.writeString(root.resolve("prometeu.json"), """ diff --git a/tools/pbx-conformance/main.rs b/tools/pbx-conformance/main.rs index 152a8176..bd70350c 100644 --- a/tools/pbx-conformance/main.rs +++ b/tools/pbx-conformance/main.rs @@ -37,6 +37,7 @@ impl NativeInterface for NoNative { fn main() { let root = std::path::PathBuf::from(std::env::args().nth(1).expect("fixture directory")); if std::env::args().any(|arg| arg == "--generic-contracts-only") { verify_pbs_generic_contract_fixtures(&root); return; } + if std::env::args().any(|arg| arg == "--generic-structs-only") { verify_pbs_generic_struct_fixtures(&root); return; } if std::env::args().any(|arg| arg == "--random-only") { verify_pbs_random_fixtures(&root); return; } verify_pbs_math_fixtures(&root); if std::env::args().any(|arg| arg == "--math-only") { return; } @@ -45,6 +46,7 @@ fn main() { verify_pbs_fixtures(&root); verify_pbs_structured_fixtures(&root); verify_pbs_generic_contract_fixtures(&root); + verify_pbs_generic_struct_fixtures(&root); verify_pbs_resource_refusals(&root); verify_pbs_closure_frames(&root); for name in [ @@ -481,7 +483,7 @@ fn verify_pbs_fixtures(root: &std::path::Path) { for entry in std::fs::read_dir(root).unwrap() { let path = entry.unwrap().path(); let name = path.file_stem().unwrap().to_str().unwrap(); - if name.starts_with("pbs-random-") || name.starts_with("pbs-math-") || name.starts_with("pbs-structured-") || name.starts_with("pbs-generic-contract-") || !name.starts_with("pbs-") || path.extension().and_then(|v| v.to_str()) != Some("pbx") { continue; } + if name.starts_with("pbs-random-") || name.starts_with("pbs-math-") || name.starts_with("pbs-structured-") || name.starts_with("pbs-generic-contract-") || name.starts_with("pbs-generic-struct-") || !name.starts_with("pbs-") || path.extension().and_then(|v| v.to_str()) != Some("pbx") { continue; } count += 1; let bytes = std::fs::read(&path).unwrap(); let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) @@ -592,6 +594,84 @@ fn verify_pbs_structured_fixtures(root: &std::path::Path) { } } +fn verify_pbs_generic_struct_fixtures(root: &std::path::Path) { + use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits, RuntimeResource}}; + use prometeu_bytecode::registry::TypeKind; + let mut object_heap = None; + let mut function_heap = None; + for name in ["basic", "manual", "constructor", "phantom", "tuple", "optional", "array", "recursive", + "combined", "function", "function-manual", "gc", "imports", "installed", "multiple", "origins"] { + let bytes = std::fs::read(root.join(format!("pbs-generic-struct-{name}.pbx"))) + .unwrap_or_else(|error| panic!("missing mandatory generic struct/function fixture {name}: {error}")); + let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) + .unwrap_or_else(|error| panic!("generic struct/function {name}: {error:?}")); + let declarations = image.registry().declarations(); + if name == "phantom" { + let structs = declarations.types.iter().filter(|t| matches!(t.kind, TypeKind::Struct(_)) + && t.name.as_deref().is_some_and(|name| name.starts_with("Marker<"))).count(); + assert_eq!(structs, 2, "phantom arguments preserve distinct nominal applications"); + } + if name == "origins" { + assert_eq!(declarations.types.iter().filter(|t| t.name.as_deref() == Some("Enemy")).count(), 2); + assert_eq!(declarations.types.iter().filter(|t| t.name.as_deref() == Some("Box")).count(), 2); + } + if name == "combined" || name == "imports" { + assert_eq!(declarations.implementations.len(), 1, "one concrete owner/contract pair, shared across aliases"); + let first = &declarations.implementations[0]; + assert_eq!(image.registry().implementation(first.owner, first.trait_id).unwrap().0, 0); + } + println!("PBS GENERIC STRUCT METADATA {name}: types={} implementations={} bytes={}", declarations.types.len(), declarations.implementations.len(), bytes.len()); + let limits = if ["basic", "manual", "function", "function-manual"].contains(&name) { + RuntimeLimits::default().lowered(RuntimeResource::HandleSlots, 1).unwrap() + } else { RuntimeLimits::default() }; + let mut vm = VirtualMachine::from_image(image, limits); + let observer = vm.resource_observer(); + vm.prepare_boot_call().unwrap(); + let mut report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); + if name == "gc" { + assert!(matches!(report.reason, End::FrameSync), "{name}: {report:?}"); + let gc = vm.resource_snapshot().gc; + assert!(gc.collections >= 1 && gc.reclaimed >= 1100, "{gc:?}"); + report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); + } + assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}"); + if name != "imports" && name != "origins" { assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(42)], "{name}"); } + if name == "basic" || name == "manual" { + assert_eq!(vm.heap().len(), 1, "one object, without a generic wrapper"); + let heap = observer.used(RuntimeResource::GuestBytes); + if let Some(reference) = object_heap { assert_eq!(heap, reference); } + object_heap = Some(heap); + } + if name == "function" || name == "function-manual" { + let heap = observer.used(RuntimeResource::GuestBytes); + if let Some(reference) = function_heap { assert_eq!(heap, reference); } + function_heap = Some(heap); + } + drop(vm); + for resource in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots, RuntimeResource::AuxiliaryBytes, + RuntimeResource::TemporaryBytes, RuntimeResource::StringBytes, RuntimeResource::StringAllocations] { + assert_eq!(observer.used(resource), 0, "{name}: release {resource:?}"); + } + if name == "basic" || name == "combined" { + for (resource, limit) in [(RuntimeResource::GuestBytes, 0), (RuntimeResource::HandleSlots, 0)] { + let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); + let mut refused = VirtualMachine::from_image(image, RuntimeLimits::default().lowered(resource, limit).unwrap()); + let observed = refused.resource_observer(); + refused.prepare_boot_call().unwrap(); + let report = refused.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); + assert!(matches!(report.reason, End::Trap(ref fault) if fault.code == prometeu_bytecode::TRAP_RESOURCE_LIMIT), "{name}/{resource:?}: {report:?}"); + assert_eq!(refused.heap().len(), 0); + assert!(observed.used(resource) <= limit); + drop(refused); + for domain in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots, RuntimeResource::AuxiliaryBytes, RuntimeResource::TemporaryBytes] { + assert_eq!(observed.used(domain), 0); + } + } + } + println!("PBS GENERIC STRUCT SOURCE/LOAD/EXEC PASS {name}"); + } +} + fn verify_pbs_generic_contract_fixtures(root: &std::path::Path) { use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits, RuntimeResource}}; use prometeu_bytecode::{registry::{TypeId, TypeKind}, isa::core::CoreOpCode}; @@ -862,9 +942,9 @@ fn verify_pbs_random_fixtures(root: &std::path::Path) { } }; add("mixed", vec![long(words[3]), "l:-7".into(), "f:3fb304aa46c98538".into()], vec![32,8,12,12,8], None); - add("storage", vec![long(words[0]),long(words[3]),long(words[2]),long(words[1]),long(words[0])], vec![32,8,8,8,8,32,8], None); + add("storage", vec![long(words[0]),long(words[3]),long(words[2]),long(words[1]),long(words[0])], vec![32,32,8,8,8,8,32,8], None); for (name, trace) in [("named",312),("positional",123)] { - add(name,vec![long(words[3]),"l:-7".into(),format!("i:{trace}")],vec![32,8,8,12,8],None); + add(name,vec![long(words[3]),"l:-7".into(),format!("i:{trace}")],vec![32,32,8,8,12,8],None); } let bounds = [(0,1),(-10,-3),(-10,10),(0,16),(i64::MIN,0),(-1,i64::MAX),(i64::MIN,i64::MAX)]; for (index,(min,max)) in bounds.into_iter().enumerate() { @@ -877,7 +957,7 @@ fn verify_pbs_random_fixtures(root: &std::path::Path) { for index in [7,8] { add(&format!("range-{index}"),vec![],vec![32,4],Some(prometeu_bytecode::TRAP_NUMERIC_DOMAIN)); } let rejected_then_accepted = i128::from(i64::MIN)+i128::from(words[2]%((1u64<<63)+1)); add("rejection",vec![long(words[3]),format!("l:{rejected_then_accepted}")],vec![32,8,20,8],None); - for name in ["null","typed-null"] { add(name,vec![],vec![8],Some(prometeu_bytecode::TRAP_NULL_REFERENCE)); } + for name in ["null","typed-null"] { add(name,vec![],vec![32,8],Some(prometeu_bytecode::TRAP_NULL_REFERENCE)); } let mut gc_costs=vec![32;1101]; gc_costs.extend([8,8,8]); add("gc",vec![long(words[2]),long(words[1]),long(words[0])],gc_costs,None); let mut cycles_by_name = std::collections::BTreeMap::new(); diff --git a/tools/pbx-conformance/run.py b/tools/pbx-conformance/run.py index 16ef54de..dd798244 100644 --- a/tools/pbx-conformance/run.py +++ b/tools/pbx-conformance/run.py @@ -15,6 +15,7 @@ parser.add_argument("--release", action="store_true", help="Execute an optimized parser.add_argument("--math-only", action="store_true", help="Run the complete PBS math corpus only") parser.add_argument("--random-only", action="store_true", help="Run the complete PBS Random corpus only") parser.add_argument("--generic-contracts-only", action="store_true", help="Run the mandatory generic-contract source corpus only") +parser.add_argument("--generic-structs-only", action="store_true", help="Run the mandatory generic-struct/function source corpus only") args = parser.parse_args() runtime = args.runtime.resolve() if not args.math_only: @@ -43,4 +44,4 @@ with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory: (root / "Cargo.lock").write_text((runtime / "Cargo.lock").read_text()) (root / "src").mkdir() (root / "src/main.rs").write_text(pathlib.Path(__file__).with_name("main.rs").read_text()) - subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else [])], check=True) + subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else []), *(["--generic-structs-only"] if args.generic_structs_only else [])], check=True)