feat(pbs): add parametric arrays and concrete generic contracts

Support explicit contract type parameters, canonical nominal applications,
recursive substitution, concrete implementations and instantiated editor views.
Complete parametric Array syntax and contextual construction integration.

Preserve type origins across imports and reexports, fix trait argument stack
order, and relocate global slots before lifecycle assembly. Publish specs,
installed examples and consolidated discussion lessons.

Validate frontend, common pipeline, architecture, LSP and installed knowledge
gates, plus the full production VM conformance corpus with 14 generic fixtures.
This commit is contained in:
2026-10-20 11:30:00 +01:00
parent b62db87245
commit 240216170c
70 changed files with 2369 additions and 273 deletions
@@ -19,9 +19,9 @@ The solution separates static source types, optional presence and physical stora
## The resulting source contract
```pbs
let enemies: array Enemy = new array(10);
let groups: array[2] Enemy = new array(3);
let scores: array int = [10, 20, 30];
let enemies: array<Enemy> = new array(10);
let groups: array<array<Enemy>> = new array(3);
let scores: array<int> = [10, 20, 30];
if let enemy = enemies[1] {
enemy.takeDamage(10);
@@ -29,7 +29,7 @@ if let enemy = enemies[1] {
enemies.clear(1);
```
Arrays have fixed length, shared reference identity and invariant element/depth types. Allocation initializes only outer positions to empty; it does not create enemies or nested arrays. Both constructors and every array literal require an expected array type. Depth is a positive literal; compiler structural limits prevent unbounded expansion. Length and indices accept int/long without loss, with the promotion confined to these operations.
Arrays have fixed length, shared reference identity and invariant element/depth types. Allocation initializes only outer positions to empty; it does not create enemies or nested arrays. Following DSC-0088, explicit `new array<T>(n)` supplies its own type; `new array<>(n)`, `new array(n)` and every array literal require an expected array type. Nesting uses `array<array<T>>`; compiler structural limits prevent unbounded expansion. Length and indices accept int/long without loss, with the promotion confined to these operations.
Reads return optional T. A vacant position is none, zero is present, and an invalid index faults. `if let` evaluates once and binds only in the success block. Optional fallback is lazy. Optional values, tuples, fields, parameters and results preserve complete groups. Optional array elements are rejected; an optional array itself is valid. PBS gains neither public Dynamic nor public null.
@@ -47,7 +47,7 @@ fn createCounter() -> Fn() -> int {
```
Each factory call creates independent state. Two closures capturing the same
counter intentionally share state. Arrays use `array (Fn() -> int)` and existing
counter intentionally share state. Arrays use `array<(Fn() -> int)>` and existing
optional-read rules. Methods become function values through explicit lambdas
capturing their receiver. The old `declare callback`, callback barrel exports
and `bind(context, function)` are rejected.
@@ -0,0 +1,80 @@
---
id: LSN-0087
ticket: pbs-array-type-syntax
title: Parametric arrays and contextual construction
status: consolidated
created: 2026-10-19
tags: [compiler-pbs, arrays, type-inference, parsing]
---
# Parametric arrays and contextual construction
Owner: `compiler/pbs`. Worker: Lesson Worker. Discussion: DSC-0088.
## Original problem and consolidated decision
Array already executed through PBS, PBX and the VM, but its `array T` and `array[N] T` syntax did not match the parametrized notation selected for future collections. DEC-0071, explicitly accepted by the user and implemented through PLN-0150, replaced that syntax without changing the storage contract. Those completed workflow artifacts were removed by housekeeping; this lesson and the specs retain their operational content.
Use `array<T>` and composition for nesting. Explicit construction supplies the type; both contextual sugars receive it:
```pbs
let a = new array<Enemy>(10);
let b: array<Enemy> = new array<>(10);
let c: array<Enemy> = new array(10);
let groups: array<array<Enemy>>=new array<>(3);
```
The first binding infers `array<Enemy>`. The next two constructor forms are equivalent and require a sufficient expected array type. Length does not infer the element type. The last allocation creates three empty outer positions, without allocating inner arrays. Old Array spellings are rejected rather than supported in parallel.
All prior execution rules remain: fixed length, reference aliases, invariance, vacancy versus present zero, optional reads, faults for invalid indices, int/long lengths and indices, single evaluation, complete value groups, nominal identity, ownership, quotas and GC. Optional elements remain invalid; optional arrays remain valid. Literal arrays remain contextual. This work does not implement shifts, new collections, generic structs/functions or broader overload inference.
## Implementation and architectural boundaries
`PbsAst.TypeRef` already provides a recursive `inner` node and a span for each type. Reuse that representation for Array's single argument. `NewExpr` now also carries an explicit array TypeRef and a diamond marker; its original total span remains available. An explicit element argument therefore retains its source identity and diagnostics span.
`PbsTypeParser` recognizes angle delimiters and enforces the existing structural nesting limit, including the constructor's outer array node. Barrel types use the same parser. `PbsTokenCursor.consumeTypeClose` peels one closing `>` and preserves the remaining token and byte offsets. For example, a type close taken from `>=` leaves `=` for the binding parser. The mechanism can also peel combined `>>`/`>>=` tokens if tokenization later changes, without adding shifts now. Ordinary expression comparisons remain intact; result and Fn spellings do not change.
Flow analysis resolves explicit constructor types without an expected destination, validates element surfaces and names, and checks invariant compatibility when a destination exists. Contextual construction uses the existing expected-type path for local/global bindings, assignment, arguments with a single resolved signature and returns. Missing context is an error, including unresolved overload contexts; no new overload inference was introduced.
PBS lowering must independently know the explicit constructor type. Local inference already consumes the initializer type, but updating only semantic analysis would leave executable lowering without enough information. Common backend and VM representations remain unchanged. Source type renderers now emit `array<T>`; editorial tests cover constructor-only element references, rename, inferred receiver completion and formatter round trips.
## Pitfalls exposed by execution
- Do not assume that parser acceptance proves execution. New constructor AST fields must feed semantic analysis, lowering and editorial type displays.
- Do not use the enclosing expression's expected return type to match a contextual constructor argument. The integrated test exposed this in lowering: constructor arguments need the selected parameter's type. Statically validated contextual constructors now follow the contextual argument path.
- Do not globally split comparison tokens. Peel type closers only in type context and retain exact remainder spans.
- Do not infer element type from length or silently coerce invariant arrays.
- Do not leave a second type grammar in barrel parsing or obsolete examples in installed knowledge.
- Do not count only the element subtree when checking explicit-constructor nesting limits; the outer array is a node too.
## Validation and final result
On 2026-10-19 the following gates passed without failures or errors:
| Gate | Result |
| --- | --- |
| PBS frontend | 255 tests, none skipped |
| Architecture PBS tests | 64 tests, none skipped |
| LSP v1 | 39 tests, one skipped |
| Installed knowledge | 2 tests, none skipped |
| Production loader/VM harness | Exit 0; new array-parametric fixture and existing structured, optional, alias, group, fault, resource, closure/GC, Random, math and catalog corpora |
| Whitespace review | `git diff --check` passed |
The new runtime fixture checks explicit local inference, diamond/omitted call arguments, global initialization/assignment, return context, nested outer-only allocation, aliases, adjacent closers/assignment and ordinary `>=`; its expected result is 42. Frontend tests separately cover all three constructor forms across expected-type positions, invariant mismatches, unknown/optional/void element types, missing context, malformed/obsolete types, nesting bounds and compound token spans.
Reproduce the Java gates with:
```sh
./gradlew :prometeu-compiler:frontends:prometeu-frontend-pbs:test :prometeu-architecture-tests:test --tests '*Pbs*' :prometeu-lsp:prometeu-lsp-v1:test :prometeu-app:installedKnowledgeTest --console=plain
python3 tools/pbx-conformance/run.py --runtime ../runtime
```
Local run logs were `/tmp/agd90-final-tests.log`, `/tmp/agd90-frontend-final.log` and `/tmp/agd90-vm2.log`; this summary preserves the evidence after temporary logs expire.
## References
- [Normative Array contract](../../../docs/compiler/pbs/specs/typed-arrays-and-optional-execution.md).
- [Function values and captures](../../../docs/compiler/pbs/specs/first-class-functions-and-captures.md).
- [Array storage and optional execution](../DSC-0079-pbs-typed-collections-and-dynamic/LSN-0083-pbs-arrays-optional-and-contract-execution.md).
- [Executable installed example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/arrays.pbs).
- Completed workflow: AGD-0090 → DEC-0071 → PLN-0150 → this lesson. Future collection and contract discussions consume this completed syntax foundation independently.
@@ -0,0 +1,204 @@
---
id: LSN-0088
ticket: pbs-generic-contracts
title: Concrete Generic Contracts from PBS Source to the VM
created: 2026-10-20
tags: [compiler-pbs, generic-contracts, nominal-identity, runtime-conformance]
---
## Original problem and final result
Owner: `compiler/pbs`; cross-domain propagation: `compiler/general` and Studio/LSP.
DSC-0089 implemented accepted DEC-0072 through PLN-0151. Those control artifacts
are removed by housekeeping; the linked specifications are the operational
reference. All twelve decision requirements were implemented together.
PBS already supported nominal contracts and concrete implementation tables. The
missing feature was a frontend path from `Identity<T>` to exact concrete types.
Simple contract names appeared in the AST, imports, validation, lowering and
editor projections. Extending only the parser would have left those consumers
disagreeing about the same program.
The completed path is:
```text
parameterized declaration + explicit application
-> resolve defining declarations and logical arguments
-> memoize nominal application and substitute signatures
-> emit concrete Trait, implementation and function metadata
-> existing PBX loader/verifier and CALL_TRAIT execution
```
There is no runtime generic-instantiation engine or new PBX/ISA category. One
distinct application has one nominal Trait identity per image. Equivalent
applications share it. This delivers user-defined generic contracts; collection
storage and algorithms remain separate work.
## Using a strategy
```pbs
declare contract Identity<T> {
fn hash(e: T) -> int;
fn equals(a: T, b: T) -> bool;
}
declare service IntIdentity {}
implements Identity<int> for IntIdentity using strategy {
fn hash(e: int) -> int { return e; }
fn equals(a: int, b: int) -> bool { return a == b; }
}
fn equalSeven() -> bool {
let identity: Identity<int> = IntIdentity;
return identity.equals(7, 7);
}
```
`IntIdentity` is the receiver; `int` describes the elements. The service keeps
its singleton identity. Structs can instead provide constructed strategy
instances. Contextual assignments, arguments and returns, or explicit `as`,
form a view without allocating an adapter wrapper.
A contract can have several ordered parameters, such as `Converter<A, B>`.
Applications are explicit, exact-arity and invariant. A barrel exports the
declaration (`pub contract Identity<T>;`), not one closed application. There are
no raw types, contract diamond inference, default arguments, blanket generic
implementations or injected direct owner methods.
## Identity is resolved before representation
`PbsContractTypes` is the PBS-owned resolution and substitution boundary. Its
application key contains the defining declaration and ordered canonical logical
argument keys. File/source declaration identity distinguishes unrelated nominal
types; length-framed child keys avoid ambiguous nested encodings. Display names
and image-local numeric TypeIds are not identity keys.
Imports carry a semantic `TypeBindingDecl`: the local spelling, original
declaration and importing scope. The original signature keeps its lexical scope.
Reexports propagate that binding rather than synthesizing a new declaration.
Thus importing `Enemy as Opponent` makes `Identity<Opponent>` the same type as
`Identity<Enemy>`. Two unrelated declarations both named `Enemy` remain distinct.
The production multi-module fixture exercises both properties.
Physical storage must follow logical resolution. `array<int>` and `array<bool>`
can share the internal Array storage carrier while still identifying different
`Marker<array<...>>` applications. A parameter that never occurs in a method
signature still participates in identity. One owner can implement both
applications; implementation function names carry the full application key.
Substitution traverses arguments, arrays, Fn inputs/results, optional payloads,
named tuples and nested contracts. Existing return normalization applies before
signature comparison: for example, a one-field named return payload does not
create a second Fn result identity. Labels and parameter names remain available
for tooling. Existing restrictions still reject invalid substituted positions,
including optional void, void Fn inputs and invalid Array elements. `Self`
keeps its existing scope rules.
## Recursive graphs and bounded processing
Register an application anchor before scanning its substituted signatures. A
reference to an existing key closes a finite nominal graph; self and mutual
recursion therefore terminate. A work queue discovers further instances.
`Growing<T>` returning `Growing<array<T>>` continually creates new applications.
It is diagnosed as `E_SEM_CONTRACT_EXPANSION`, rather than hanging or becoming an
ordinary type mismatch. Analysis has explicit depth, work, instance and key
storage ceilings (256, 1,048,576, 65,536 and 64 Mi characters respectively). These producer
bounds do not increase runtime admission limits or replace loader accounting.
## Integration pitfalls exposed by real execution
**Trait call stack order differs from implementation parameter order.** The
implementation function receives its concrete owner first. At the CALL_TRAIT
instruction, explicit argument groups precede the two-slot view on the operand
stack. Lowering evaluates and roots the receiver, evaluates arguments left to
right, then reloads the complete view immediately before the call. No-argument
contract tests alone did not expose the old ordering error.
**Globals have one image namespace.** Independently compiled files can each
start allocating globals at slot zero. Common IR aggregation now relocates
declarations and GET_GLOBAL/SET_GLOBAL operands together. Lifecycle assembly
preserves those linked slots and places its initialization guard after all
globals. Without this, an imported strategy singleton could collide with the
guard. The fix belongs to the neutral compiler, with no PBS rule in the backend.
**Aliases must cover all consumers.** Imported function emission uses the true
target callable while local resolution uses its alias. Aliased services also
retain their constants. Generic hover uses original declaration names in both
the application heading and substituted signatures; navigation still reaches
the original declaration. A final alias-specific editorial test caught a
heading/signature disagreement that plain `Echo<int>` tests did not reveal.
**Verifier Unknown is not proof of a type error.** A mutated wrong-Trait call
can be rejected statically or admitted with unknown local facts. In the latter
case, execution must trap with the runtime type check. The conformance harness
accepts exactly these valid outcomes rather than weakening runtime checks or
requiring the verifier to infer more than its contract promises.
## Verification evidence
Verified on 2026-10-20 against runtime revision
`f7d7c167531bb662a1af9d73fc326bb476bf8aa7`, macOS/arm64, Rust 1.98.1,
development profile with `resource-diagnostics`. Defaults remain unchanged
except in explicit refusal tests. The harness builds in a temporary directory
and does not modify the provider checkout.
The fourteen mandatory generic fixtures compile actual PBS through the
production frontend, typed IR, PBX emitter, loader, verifier and VM:
| Fixture | Evidence | Types / implementations | PBX bytes |
| --- | --- | --- | --- |
| identity | Contextual/explicit adaptation and dispatch | 5 / 1 | 1,921 |
| manual | Handwritten concrete behavioral reference | 5 / 1 | 1,859 |
| multiple | Same owner, several applications | 6 / 2 | 1,991 |
| tuple | Two parameters, Array input, complete tuple result | 9 / 1 | 2,762 |
| optional | Absence/presence and optional groups | 6 / 1 | 2,267 |
| function | Fn argument and call | 5 / 1 | 1,705 |
| contract | Nested contract argument | 5 / 2 | 2,014 |
| native | Native vec2 payload groups | 5 / 1 | 1,607 |
| recursive | Finite recursive application and chained calls | 4 / 1 | 1,791 |
| phantom | Distinct logical Array arguments, identical signatures | 5 / 2 | 2,036 |
| receiver | Constructed struct receiver state | 4 / 1 | 1,534 |
| gc | Closure retains view/receiver through collection | 7 / 1 | 2,153 |
| installed | Packaged runnable contracts example | 5 / 1 | 2,105 |
| imports | Aliases/reexports, distinct origins, lifecycle globals | 5 / 3 | 2,540 |
The generic and handwritten references both succeed with one heap handle and
equal guest allocation footprint. Typed absence and ImplementationId zero are
checked separately. The GC fixture reclaims at least 1,100 discarded objects
while the captured receiver remains callable. Reduced GuestBytes/HandleSlots
and zero implementation admission test resource refusal, bounded publication
and complete ownership release. These observations do not imply identical PBX
bytes or a performance improvement.
The complete provider harness also passed the existing source/input, structured
value, closure, math, Random, lifecycle, malformed-image and resource corpora.
Its two previously documented upstream schema enum gaps remain explicitly
reported; they are not hidden or counted as schema conformance.
Compiler API (29 tests), PBS frontend (274 tests) and build-pipeline suites
passed, together with 68
affected architecture tests, 22 LSP bridge/protocol tests and both installed
knowledge tests. The build-pipeline suite retains twelve pre-existing disabled
legacy integration cases; production fixtures exercise the required paths.
Additional focused cases cover mutual recursion and imported alias navigation.
Workflow validation and whitespace checks passed before completion.
Reproduce with the gates in the [conformance harness documentation](../../../tools/pbx-conformance/README.md).
The new specification and `contracts.pbs` example are discoverable in installed
knowledge, not only in the source checkout.
## Handoffs and references
AGD92/List is next in the umbrella sequence. SDK data/algorithm specialization
and stable object-identity hashing still require their consumer decisions.
Generic functions/structs, constraints, variance, inheritance/default methods,
associated strategy members and runtime specialization were not introduced.
- [PBS generic contracts specification](../../../docs/compiler/pbs/specs/generic-contracts.md).
- [Typed Registry/PBX and global relocation](../../../docs/compiler/general/specs/typed-registry-and-pbx-v0.md).
- [Arrays, optional and contract execution](../../../docs/compiler/pbs/specs/typed-arrays-and-optional-execution.md).
- [Functions and captures](../../../docs/compiler/pbs/specs/first-class-functions-and-captures.md).
- [Installed source example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/contracts.pbs).
- Historical workflow: AGD-0091, accepted DEC-0072, completed PLN-0151; DSC-0089.
@@ -42,6 +42,12 @@ identities, excluding names. Forward references and recursion through nominal
anchors are valid. Pure Array/Fn cycles are invalid. Every reference must
resolve before emission. Frontends should supply only used imports.
File-local global slots MUST be relocated to unique image-wide slots when common
IR files are merged. Every GET_GLOBAL and SET_GLOBAL operand must use the same
relocation as its declaration. Lifecycle assembly preserves those linked slots
and allocates its initialization guard after all existing image globals. Module
boundaries do not create separate runtime global namespaces.
| BuiltinId | Type | Slots |
| --- | --- | --- |
| `0x0001` | color | 1 |
@@ -19,7 +19,7 @@ fn example() -> int {
}
```
Function-returning functions use `-> Fn(int) -> int`. Function array elements use grouping, for example `array (Fn(int) -> int)`. Existing array vacancy and optional-read rules apply; accessing an empty slot does not fabricate a callable.
Function-returning functions use `-> Fn(int) -> int`. Function array elements use grouping, for example `array<(Fn(int) -> int)>`. Existing array vacancy and optional-read rules apply; accessing an empty slot does not fabricate a callable.
## Lambdas
@@ -76,3 +76,8 @@ Function creation and calls remain subject to existing resource checks and runti
Conformance must compile actual PBS through production PBX and execute it in the production VM. Required cases include signature errors, explicit capture enforcement, snapshots, escaped closures, shared and isolated objects, collection transport, nested closures and function captures, receiver/contract integration, and reachable/unreachable closure behavior across the existing frame lifecycle and GC. Installed knowledge must package this specification and a compilable example.
See [Runtime Random integration](runtime-random-integration.md) for opaque generator aliases in typed storage and captures.
## 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.
@@ -0,0 +1,74 @@
# PBS Generic Contracts
Owner: `compiler/pbs`. This specification extends nominal contracts with explicit type parameters. Registry, PBX, instruction, ownership and resource contracts remain governed by the runtime provider. Collections and object-identity hashing are separate consumers.
## Declaration and application
```pbs
declare contract Identity<T> {
fn hash(e: T) -> int;
fn equals(a: T, b: T) -> bool;
}
declare contract Converter<A, B> {
fn convert(value: A) -> B;
}
```
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<int>` and `Converter<Enemy, str>`. The declaration's raw name, omitted arguments, `<>`, default arguments and blanket generic implementations are not value types or inference mechanisms. Nonparameterized contracts remain valid.
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<T>;`, preserving its origin and ordered parameters rather than exporting a particular application.
## Identity and compatibility
An application's identity is the defining nominal contract declaration plus its ordered canonical logical argument identities. Import aliases resolve before this identity is formed. If `Opponent` aliases the same `Enemy` declaration, `Identity<Opponent>` and `Identity<Enemy>` are identical. Equal names, method shapes or physical layouts do not merge different declarations or applications. Phantom arguments still distinguish applications.
Applications are invariant. A conversion between argument types does not establish a conversion between their contract applications. Existing explicit reference-view conversion can select another implementation actually supplied by the concrete receiver; it does not manufacture variance.
## Substitution and composition
Substitution traverses every type position in each signature, preserving parameter names, tuple labels, order and source provenance. It supports valid composition with existing builtins, nominal values, arrays, other applied contracts, Fn, optional and named tuples. Each resulting position remains subject to the existing type, return, optional/result and storage rules; substitution does not legalize an otherwise invalid position.
Normalize substituted signatures before deriving physical parameter/result groups. One logical parameter can contain several physical values. A shared physical carrier does not erase logical argument identity: distinct `Identity<array<X>>` applications remain nominally distinct even when their arrays share internal storage representation.
## Implementations and values
```pbs
declare service IntIdentity {}
implements Identity<int> for IntIdentity using strategy {
fn hash(e: int) -> int { return e; }
fn equals(a: int, b: int) -> bool { return a == b; }
}
fn equalSeven() -> bool {
let identity: Identity<int> = IntIdentity;
return identity.equals(7, 7);
}
```
Structs and services are the supported owners. An implementation belongs to the owner's declaring module and follows existing visibility rules. Implementations are complete and unique per `(owner, instantiated contract)`. One owner may implement several applications of the same contract. Implementation/callable identities include the full application, preventing collisions between those methods. Contract methods are not injected into the direct method namespace of their owner.
Named service singletons and constructed struct values supply strategies. Contextual assignments, arguments and returns, and explicit `value as Identity<int>`, select the concrete implementation. Conversion preserves the receiver and selected implementation without allocating an adapter wrapper or duplicating a singleton. Associated members such as `Enemy.identity` are not introduced.
## Recursion and bounded analysis
Register a nominal application anchor before expanding its signatures. A recurrence to an existing key forms a finite graph and is valid within existing resource limits. An application family that continually introduces new arguments, such as `Growing<T>` returning `Growing<array<T>>`, must be rejected with a clear expansion diagnostic.
Expansion, substitution and identity processing are bounded in work, storage and depth. Resource exhaustion and nonterminating specialization must not become hangs, host stack overflows, missing-method errors or ordinary argument-mismatch diagnostics.
## Execution and tooling
The frontend emits a concrete nominal Trait descriptor for each distinct required application, sharing the descriptor for equivalent uses across modules. Open type parameters do not reach executable signatures. Implementation functions receive the concrete owner first, followed by complete substituted argument/result groups.
Existing Registry/PBX and `REF_TO_TRAIT`/`CALL_TRAIT` mechanisms execute these records. Preserve typed absence, valid ImplementationId zero, receiver identity, rooting, GC, native ownership and quotas. Generic calls do not introduce a Dynamic argument ABI or boxing merely because an argument was a type parameter. Existing storage-specific packing remains governed by that storage's contract.
Navigation reaches generic declarations, parameters and argument declarations. Hover, completion and signature help show instantiated signatures with canonical source names. Arity, unresolved parameters, invalid applications/coercions, incomplete or duplicate implementations and expansion failures have localized diagnostics. Compilation and editor projections share the same type resolution.
## Conformance
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.
@@ -4,20 +4,28 @@ Owner: `compiler/pbs`. This specification defines the source contract for typed
## Types and construction
`array T` denotes a fixed-length reference to positions holding values of T or no value. `array[N] T` denotes N nested array levels, where N is a positive integer literal. `array[1] T` and `array T` are equivalent. Depth belongs to the type; allocation length belongs to the constructor. The compiler bounds expanded type nesting to 256 nodes and diagnoses excessive depth without expanding an unbounded AST.
`array<T>` denotes a fixed-length reference to positions holding values of T or no value. Nesting is compositional: `array<array<Enemy>>` holds array references. The compiler bounds structural type nesting to 256 nodes and diagnoses excessive depth without expanding an unbounded AST. Allocation length belongs to the constructor, not the type.
```pbs
let enemies: array Enemy = new array(10);
let groups: array[2] Enemy = new array(3);
let scores: array int = [10, 20, 30];
let empty: array Enemy = [];
let enemies = new array<Enemy>(10);
let contextual: array<Enemy> = new array<>(10);
let omitted: array<Enemy> = new array(10);
let groups: array<array<Enemy>> = new array<>(3);
let scores: array<int> = [10, 20, 30];
let empty: array<Enemy> = [];
```
`new array(length)` requires an expected array type. It allocates only the outer array: each position is empty, with no implicit subarray, element construction or callback. Every array literal, including a nonempty literal, requires an expected array type. The compiler must not infer an array type from its elements. Expected types propagate through annotated bindings, assignments, parameters, returns and nested value expressions. Incompatible elements are errors; they do not produce a public Dynamic type.
`new array<T>(length)` supplies its own type, including when the binding has no annotation. T must resolve to a valid element type. `new array<>(length)` and `new array(length)` are equivalent sugars requiring an expected array type. The length never supplies element-type information. All forms allocate only the outer array: each position is empty, with no implicit subarray, element construction or callback.
Arrays are invariant in element type and depth. Assignment and argument passing share the array reference. The runtime's shared storage carrier must not make different PBS array types interchangeable. `array (optional T)` is invalid, including through grouped types. `optional (array T)` remains valid and distinguishes an absent array from a present array whose positions are empty.
Every array literal, including a nonempty literal, requires an expected array type. The compiler must not infer its type from its elements. Expected types propagate through annotated local/global bindings, assignments, arguments with a resolved single callable signature, returns and nested value expressions. This migration does not expand overload resolution; contextual construction without sufficient expected type is an error. Incompatible explicit constructor types and literal elements are errors; they do not produce a public Dynamic type.
`T[]`, `[]T`, `array !! T`, `new T[n]` and `new array[n]` are not alternative spellings. PBS exposes neither a null value nor a Dynamic type.
Arrays are invariant in element type and nesting. Assignment and argument passing share the array reference. The runtime's shared storage carrier must not make different PBS array types interchangeable. `array<optional T>` is invalid, including through grouped types. `optional (array<T>)` remains valid and distinguishes an absent array from a present array whose positions are empty.
Type delimiters can be adjacent to assignment: `let a: array<array<int>>=new array<>(3);` is valid. Parsing consumes type closers contextually while preserving expression comparisons such as `x >= y`. This does not introduce shift operators. Optional, `result<Error>` and `Fn(...) -> ...` retain their existing spellings.
Legacy `array T`, `array[N] T`, and `array<T>[N]` are rejected. `T[]`, `[]T`, `array !! T`, `new T[n]` and `new array[n]` are not alternative spellings. PBS exposes neither a null value nor a Dynamic type.
The frontend AST retains recursive element types and their spans. Constructor nodes distinguish explicit type arguments, diamond and omission; explicit construction types must reach semantic analysis, source tooling and PBS lowering without relying on a destination annotation. Common backend IR and runtime storage do not acquire PBS syntax rules.
## Operations and ordering
@@ -62,7 +70,7 @@ Existing PBS struct and contract rules apply unchanged: structs have reference i
## Diagnostics, tooling and conformance
Diagnostics must reject missing expected array types, invalid depth, optional elements, incompatible invariant arrays, non-integral sizes/indices and non-optional if-let operands. Editor types and hints use PBS array notation. Hover, completion, definitions, references and rename must respect success-only binding scope and source element identity.
Diagnostics must reject missing expected array types for contextual construction, unresolved explicit element types, excessive nesting, removed syntax, optional elements, incompatible invariant arrays, non-integral sizes/indices and non-optional if-let operands. Editor types and hints use PBS array notation. Hover, completion, definitions, references and rename must respect success-only binding scope and source element identity.
Conformance must compile real PBS through typed IR and production PBX into the production loader/VM. Required cases include vacancy versus zero, alias mutation, contextual literals, nested arrays, int/long bounds, lazy and single evaluation, multi-slot groups, constructors and contract dispatch, service identity, resource refusal and GC/ownership. Assembly-only probes are insufficient. Installed knowledge must package this specification and executable examples.
@@ -76,3 +84,8 @@ Conformance must compile real PBS through typed IR and production PBX into the p
List/Set/Map, growth, iteration, equality and hashing policies belong to the separate SDK collections discussion. A future list capacity does not create logical elements; fixed array length does.
See [Runtime Random integration](runtime-random-integration.md) for opaque generator aliases in typed storage and captures.
## 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.
@@ -180,3 +180,12 @@ This document is healthy when:
## Typed arrays and optional execution extension
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(n)` supplies its type; `new array<>(n)` and `new array(n)` use the expected type. The [Array contract](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines contextual closers, spans, invariant validation and lowering; obsolete Array spellings are rejected.
## Parameterized contracts
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).
@@ -304,3 +304,12 @@ The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-a
## Typed arrays and optional execution extension
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(n)` supplies its type; `new array<>(n)` and `new array(n)` use the expected type. The [Array contract](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines contextual closers, spans, invariant validation and lowering; obsolete Array spellings are rejected.
## Parameterized contracts
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).
@@ -246,3 +246,12 @@ The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-a
## Typed arrays and optional execution extension
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(n)` supplies its type; `new array<>(n)` and `new array(n)` use the expected type. The [Array contract](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines contextual closers, spans, invariant validation and lowering; obsolete Array spellings are rejected.
## Parameterized contracts
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).
@@ -167,7 +167,7 @@ BarrelVisibility ::= 'mod' | 'pub'
BarrelFnItem ::= BarrelVisibility 'fn' Identifier ParamList ReturnAnn? ';'
BarrelStructItem ::= BarrelVisibility 'struct' Identifier ';'
BarrelContractItem ::= BarrelVisibility 'contract' Identifier ';'
BarrelContractItem ::= BarrelVisibility 'contract' Identifier TypeParameters? ';'
BarrelHostItem ::= BarrelVisibility 'host' Identifier ';'
BarrelErrorItem ::= BarrelVisibility 'error' Identifier ';'
BarrelEnumItem ::= BarrelVisibility 'enum' Identifier ';'
@@ -282,7 +282,9 @@ Top-level `let` forms and top-level executable statements are forbidden.
TypeDecl ::= StructDecl | ServiceDecl | ContractDecl | HostDecl | BuiltinTypeDecl | ErrorDecl | EnumDecl
StructDecl ::= 'declare' 'struct' Identifier '(' StructFieldList? ')' (StructMethodBody | ';')
ServiceDecl ::= 'declare' 'service' Identifier ServiceBody
ContractDecl ::= 'declare' 'contract' Identifier ContractBody
ContractDecl ::= 'declare' 'contract' Identifier TypeParameters? ContractBody
TypeParameters ::= '<' Identifier (',' Identifier)* '>'
TypeArguments ::= '<' TypeRef (',' TypeRef)* '>'
HostDecl ::= 'declare' 'host' Identifier HostBody
BuiltinTypeDecl ::= AttrList? 'declare' 'builtin' 'type' Identifier '(' BuiltinFieldList? ')' BuiltinTypeBody
ErrorDecl ::= 'declare' 'error' Identifier ErrorBody
@@ -452,7 +454,7 @@ Rules:
TypeRef ::= OptionalType | TypePrimary
TypePrimary ::= FnType | SelfType | SimpleType | NamedTupleType | GroupType | UnitType
SelfType ::= 'Self'
SimpleType ::= Identifier
SimpleType ::= Identifier TypeArguments?
NamedTupleType ::= '(' NamedTupleField (',' NamedTupleField){0,5} ')'
NamedTupleField ::= Identifier ':' TypeRef
GroupType ::= '(' TypeRef ')'
@@ -465,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.
- General user-defined generics are not part of PBS core v1.
- User-defined parameterized declarations are supported for contracts. General generic structs and functions remain outside PBS core v1.
- `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.
@@ -610,7 +612,7 @@ Rules:
- `new Type.ctorName(args...)` is the canonical named-constructor surface.
- Struct construction arguments are positional and follow the declared struct field order.
- `as` is reserved in expressions for explicit contract-view conversion only; it does not denote a general cast surface in v1 core.
- The right operand of expression-form `as` is a simple contract identifier already visible in scope, never a qualified module path.
- A contract-view `as` target is a visible contract type, including explicit arguments such as `Identity<int>`, never a qualified module path. Existing numeric conversions retain their value-alignment rules.
- `this` is an implicit receiver name available only inside struct method, service method, and `ctor` bodies.
- `Self` is valid only inside struct method declarations, service method declarations, and `ctor` declarations.
- `apply` is right-associative: `f1 apply f2 apply x` parses as `f1 apply (f2 apply x)`.
@@ -1200,3 +1202,12 @@ fn test(e: Enum) -> str {
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
Retired `declare callback`, callback exports and `bind(...)` are rejected. They do not provide alternative spellings for Fn or lambdas.
Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(n)` supplies its type; `new array<>(n)` and `new array(n)` use the expected type. The [Array contract](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines contextual closers, spans, invariant validation and lowering; obsolete Array spellings are rejected.
## Parameterized contracts
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).
@@ -388,7 +388,7 @@ Rules:
- Services do not have fields.
- Services do not declare named constructors and are never targets of `new`.
- Contract implementations do not inject their methods into the direct method namespace of the concrete struct or service.
- `implements Contract for Owner using s { ... }` is unique per `(Contract, Owner)` pair, where `Owner` is a declared struct or service.
- `implements Contract for Owner using s { ... }` is unique per `(instantiated Contract, Owner)` pair, where `Owner` is a declared struct or service.
- A contract for a struct or service may be implemented only in the module where that owner itself is declared.
- Contracts may be declared in other modules and implemented for the local struct or service in its owner module.
- An `implements` block has no independent visibility; its observability follows the visibility of the owner declaration, and the contract must also be nameable at the use site.
@@ -396,7 +396,7 @@ Rules:
- A struct value or service singleton value may be coerced to a contract value when exactly one visible `implements Contract for Owner ...` applies.
- Contract coercion may happen by explicit `expr as ContractType` or by contextual typing in assignments, parameter passing, and returns.
- `as` in expression position is reserved for explicit contract coercion only; no other cast semantics exist in v1 core.
- The contract name in `expr as ContractName` must be a simple visible identifier resolved through ordinary scope and import rules.
- The contract in `expr as ContractType` is resolved through ordinary scope/import rules and may carry explicit type arguments. Aliases preserve declaration identity.
- A contract value carries the underlying struct reference or service singleton value together with the selected contract implementation for runtime dispatch.
- Calling `contractValue.method(...)` uses dynamic dispatch through the contract value.
- Calling `structValue.contractMethod(...)` is not valid unless that method is also declared directly on the struct.
@@ -821,3 +821,12 @@ The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-a
## Typed arrays and optional execution extension
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
Array syntax uses `array<T>` with compositional nesting. Explicit `new array<T>(n)` supplies its type; `new array<>(n)` and `new array(n)` use the expected type. The [Array contract](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines contextual closers, spans, invariant validation and lowering; obsolete Array spellings are rejected.
## Parameterized contracts
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).
@@ -556,3 +556,10 @@ dot and signature help during incomplete arguments. An unrelated parse error MUS
NOT invalidate a recoverable receiver. Unknown or ambiguous receivers MUST NOT
invent a type or overload. Indexing/operator-produced receivers are outside the
new coverage; existing behavior MUST NOT regress.
## Parameterized contracts
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).
@@ -139,3 +139,10 @@ That means:
The `@sdk:random` module exports `Random` and `random`. Use an explicit long seed;
copying a generator shares its state. Read `pbs:spec:runtime-random-integration.md`
and `pbs:example:game:1:src/random.pbs` for the exact contract and a small example.
## Parameterized contracts
Parameterized nominal contracts, concrete frontend specialization, implementation/coercion rules, composition, recursion and production conformance are defined by the owner specification.
See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
@@ -23,6 +23,8 @@ public final class InstalledKnowledgeProbe {
if (arguments.length == 1 && arguments[0].equals("--catalog-only")) return;
Path root = Files.createDirectory(Path.of("example")).toRealPath();
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");
for (var reference : docs) {
if (reference.id().startsWith("pbs:example:game:1:")) {
Path file = root.resolve(reference.id().substring("pbs:example:game:1:".length()));
@@ -41,7 +41,7 @@ class PbsClosuresTest {
let counter = new Counter(40);
let increment = fn [counter]() -> void { counter.value += 1; };
let read = fn [counter]() -> int { return counter.value; };
let reads: array (Fn() -> int) = [read];
let reads: array<(Fn() -> int)> = [read];
increment(); increment();
if let f = reads[0] { return f(); }
return 999;
@@ -156,7 +156,7 @@ class PbsClosuresTest {
@Test void closuresSurviveExistingFrameLifecycleAndAreCollectible() throws Exception {
var source = """
declare struct Counter(pub mut value: int);
declare global callbacks: array (Fn() -> int) = new array(1);
declare global callbacks: array<(Fn() -> int)> = new array(1);
declare global frames: int = 0;
[Frame]
fn frame() -> void {
@@ -0,0 +1,234 @@
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.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.*;
import p.studio.utilities.structures.ReadOnlyList;
import java.nio.file.*;
import static org.junit.jupiter.api.Assertions.*;
class PbsGenericContractsTest {
private static final String ECHO = "declare contract Echo<T> { fn echo(value: T) -> T; } declare service Strategy {}\n";
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 supplemental = ReadOnlyList.<PbsAst.TopDecl>empty();
var reserved = IRReservedMetadata.empty();
if (name.equals("native")) {
var nativeId = new FileId(100);
var nativeSource = "[BuiltinType(name = \"vec2\", version = 1)] declare builtin type Vector(pub x: float, pub y: float) {}";
var nativeAst = PbsParser.parse(PbsLexer.lex(nativeSource, nativeId, diagnostics), nativeId, diagnostics, PbsParser.ParseMode.INTERFACE_MODULE);
supplemental = nativeAst.topDecls();
reserved = new PbsReservedMetadataExtractor().extract(nativeAst, SourceKind.SDK_INTERFACE);
}
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(),
supplemental, ReadOnlyList.empty(), ReadOnlyList.empty(), reserved, java.util.Map.of());
assertFalse(diagnostics.hasErrors(), () -> name + ": " + diagnostics.stream().map(d -> d.getCode()+":"+d.getMessage()).toList().toString());
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);
var directory = Path.of(System.getProperty("pbs.registryConformanceDirectory"));
Files.createDirectories(directory);
Files.writeString(directory.resolve("pbs-generic-contract-"+name+".ir.txt"), file.executableFunctions().stream()
.map(f -> f.callableName()+" "+f.metadata()+"\n"+f.instructions().stream().map(Object::toString).collect(java.util.stream.Collectors.joining("\n")))
.collect(java.util.stream.Collectors.joining("\n\n")));
new BytecodePreloadVerifierService().verify(module);
Files.write(directory.resolve("pbs-generic-contract-"+name+".pbx"), module.serialize());
return module;
}
@Test void concreteAndGenericContractsHaveTheSameBehavior() throws Exception {
for (var generic : new boolean[]{true, false}) {
var declaration = generic ? "declare contract Identity<T> { fn hash(e: T) -> int; fn equals(a: T, b: T) -> bool; }" :
"declare contract IntContract { fn hash(e: int) -> int; fn equals(a: int, b: int) -> bool; }";
var application = generic ? "Identity<int>" : "IntContract";
compile(generic ? "identity" : "manual", declaration + "declare service Strategy {} implements " + application + " for Strategy using s {" +
"fn hash(e: int) -> int { return e; } fn equals(a: int, b: int) -> bool { return a == b; } } " +
"declare service Probe { fn main() -> int { let identity: " + application + " = Strategy; if identity.equals(7, 7) { return identity.hash(42); } return 0; } }");
}
}
@Test void oneOwnerDispatchesIndependentApplicationsAndExplicitViews() throws Exception {
compile("multiple", ECHO + """
implements Echo<int> for Strategy using s { fn echo(value: int) -> int { return value; } }
implements Echo<bool> for Strategy using s { fn echo(value: bool) -> bool { return value; } }
declare service Probe { fn main() -> int {
let ints: Echo<int> = Strategy;
let flags = ints as Echo<bool>;
if flags.echo(true) { return ints.echo(42); }
return 0;
} }
""");
}
@Test void composedArgumentsPreserveCompleteGroups() throws Exception {
compile("tuple", """
declare contract Convert<A, B> { fn convert(value: A) -> B; }
declare service Strategy {}
implements Convert<array<int>, (left: int, right: int)> for Strategy using s {
fn convert(value: array<int>) -> (left: int, right: int) { return (left: value[0] else 0, right: 2); }
}
declare service Probe { fn main() -> int {
let c: Convert<array<int>, (left: int, right: int)> = Strategy;
let pair = c.convert([40]); return pair.left + pair.right;
} }
""");
compile("optional", ECHO + """
implements Echo<optional int> for Strategy using s { fn echo(value: optional int) -> optional int { return value; } }
declare service Probe { fn main() -> int {
let c: Echo<optional int> = Strategy;
if let wrong = c.echo(none) { return 0; }
return c.echo(some(42)) else 0;
} }
""");
compile("function", ECHO + """
implements Echo<Fn(int) -> int> for Strategy using s { fn echo(value: Fn(int) -> int) -> Fn(int) -> int { return value; } }
fn add(value: int) -> int { return value + 2; }
declare service Probe { fn main() -> int {
let c: Echo<Fn(int) -> int> = Strategy;
let f = c.echo(add); return f(40);
} }
""");
compile("contract", ECHO + """
declare contract Read<T> { fn read() -> T; }
implements Read<int> for Strategy using s { fn read() -> int { return 42; } }
implements Echo<Read<int>> for Strategy using s { fn echo(value: Read<int>) -> Read<int> { return value; } }
declare service Probe { fn main() -> int {
let reader: Read<int> = Strategy;
let c: Echo<Read<int>> = Strategy;
return c.echo(reader).read();
} }
""");
compile("native", ECHO + """
implements Echo<Vector> for Strategy using s { fn echo(value: Vector) -> Vector { return value; } }
declare service Probe { fn main() -> int {
let c: Echo<Vector> = Strategy;
let value = c.echo(new Vector(20.0, 22.0));
return (value.x + value.y) as int;
} }
""");
}
@Test void finiteRecursionPhantomArgumentsAndReceiverIdentityExecute() throws Exception {
compile("recursive", """
declare contract Node<T> { fn next() -> Node<T>; fn value() -> T; }
declare service Strategy {}
implements Node<int> for Strategy using s {
fn next() -> Node<int> { return Strategy; }
fn value() -> int { return 42; }
}
declare service Probe { fn main() -> int { let node: Node<int> = Strategy; return node.next().value(); } }
""");
compile("phantom", """
declare contract Marker<T> { fn answer() -> int; }
declare service Strategy {}
implements Marker<array<int>> for Strategy using s { fn answer() -> int { return 42; } }
implements Marker<array<bool>> for Strategy using s { fn answer() -> int { return 42; } }
declare service Probe { fn main() -> int {
let first: Marker<array<int>> = Strategy;
let second: Marker<array<bool>> = Strategy;
return first.answer() + second.answer() - 42;
} }
""");
compile("receiver", """
declare contract Read<T> { fn read() -> T; }
declare struct Counter(pub mut value: int) { fn increment() { this.value += 1; } }
implements Read<int> for Counter using counter { fn read() -> int { return counter.value; } }
declare service Probe { fn main() -> int {
let counter = new Counter(41);
let reader: Read<int> = counter;
counter.increment(); return reader.read();
} }
""");
}
@Test void contractCaptureSurvivesARealGcSafepoint() throws Exception {
compile("gc", """
declare contract Read<T> { fn read() -> T; }
declare struct Counter(pub value: int);
implements Read<int> for Counter using counter { fn read() -> int { return counter.value; } }
fn capture() -> Fn() -> int {
let reader: Read<int> = new Counter(42);
return fn [reader]() -> int { return reader.read(); };
}
declare service Probe {
fn garbage() { let discarded: array<int> = new array(1); }
fn collect() { let marker = 314159; }
fn main() -> int {
let read = capture();
for i: int from 0 until 1100 { Probe.garbage(); }
Probe.collect(); return read();
}
}
""");
}
@Test void installedContractExampleExecutes() throws Exception {
try (var stream = PbsFrontendCompiler.class.getResourceAsStream("/pbs-knowledge/examples/game/1/src/contracts.pbs")) {
assertNotNull(stream);
compile("installed", new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)
+ "\ndeclare service Probe { fn main() -> int { return contractExample(); } }");
}
}
@Test void moduleOriginsAliasesAndExportedStrategiesExecute(@org.junit.jupiter.api.io.TempDir Path root) throws Exception {
Files.createDirectories(root.resolve("src/policy"));
Files.createDirectories(root.resolve("src/facade"));
Files.createDirectories(root.resolve("src/left"));
Files.createDirectories(root.resolve("src/right"));
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;");
for (var name : new String[]{"left", "right"}) {
Files.writeString(root.resolve("src/"+name+"/mod.barrel"), "pub struct Enemy;");
Files.writeString(root.resolve("src/"+name+"/main.pbs"), "declare struct Enemy(pub hp: int);");
}
Files.writeString(root.resolve("src/policy/mod.barrel"), "pub contract Identity<T>; pub contract Marker<T>; pub service Strategy;");
Files.writeString(root.resolve("src/facade/mod.barrel"), "pub contract Identity<T>; pub contract Marker<T>;");
Files.writeString(root.resolve("src/facade/main.pbs"), "import { Identity, Marker } from @app:policy;");
Files.writeString(root.resolve("src/policy/main.pbs"), """
import { Enemy as A } from @app:left;
import { Enemy as B } from @app:right;
declare contract Identity<T> { fn hash(value: T) -> int; }
declare contract Marker<T> { fn tag() -> int; }
declare service Strategy {}
implements Identity<int> for Strategy using s { fn hash(value: int) -> int { return value; } }
implements Marker<A> for Strategy using s { fn tag() -> int { return 20; } }
implements Marker<B> for Strategy using s { fn tag() -> int { return 22; } }
""");
Files.writeString(root.resolve("src/main.pbs"), """
import { Identity as Policy, Marker as Tag } from @app:facade;
import { Strategy as Selected } from @app:policy;
import { Enemy as Left } from @app:left;
import { Enemy as Right } from @app:right;
[Frame]
fn frame() -> void {
let identity: Policy<int> = Selected;
let left: Tag<Left> = Selected;
let right: Tag<Right> = Selected;
if identity.hash(42) != 42 { let fail = 1 / 0; }
if left.tag() + right.tag() != 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.write(Path.of(System.getProperty("pbs.registryConformanceDirectory"), "pbs-generic-contract-imports.pbx"), result.bytecodeBytes());
}
}
@@ -127,7 +127,7 @@ class PbsRuntimeRandomTest {
let rng = random.new(42 as long);
saved = echo(rng);
let box = new Box(saved);
let values: array Random = [box.value];
let values: array<Random> = [box.value];
let draw = capture(rng);
let a = random.next(saved);
let b = random.next(box.value);
@@ -188,7 +188,7 @@ class PbsRuntimeRandomTest {
pair("typed-null", """
declare struct Empty(pub value: Random) { ctor create() {} } declare global empty: Random = new Empty.create().value;
declare service Probe { fn main() -> long {
let values: array Random = [empty];
let values: array<Random> = [empty];
if let value = values[0] { return random.next(value); }
return 99;
} }
@@ -232,9 +232,9 @@ class PbsRuntimeRandomTest {
@Test void referencesSurviveCollection() throws Exception {
pair("gc", """
declare struct Box(pub value: Random);
fn make() -> (items: array Random, draw: Fn() -> long, box: Box) {
fn make() -> (items: array<Random>, draw: Fn() -> long, box: Box) {
let rng = random.new(42 as long);
let items: array Random = [rng];
let items: array<Random> = [rng];
let draw = fn [rng]() -> long { return random.next(rng); };
return (items: items, draw: draw, box: new Box(rng));
}
@@ -79,7 +79,7 @@ class PbsStructuredValuesTest {
declare service Probe {
fn main() -> int {
let count: int = 3;
let values: array int = new array(count);
let values: array<int> = new array(count);
let index: int = 1;
values[index] = 42;
let answer = values[index] else 0;
@@ -94,7 +94,7 @@ class PbsStructuredValuesTest {
compile("array-nested", """
declare service Probe {
fn main() -> int {
let groups: array[2] int = new array(3);
let groups: array<array<int>> = new array(3);
groups[0] = [10, 42];
if let group = groups[0] {
if let value = group[1] { return value; }
@@ -128,7 +128,7 @@ class PbsStructuredValuesTest {
implements Target for Enemy using enemy { fn health() -> int { return enemy.health(); } }
declare service Probe {
fn main() -> int {
let enemies: array Enemy = new array(2);
let enemies: array<Enemy> = new array(2);
let enemy = new Enemy.create(50);
enemies[0] = enemy;
if let selected = enemies[0] { selected.damage(8); }
@@ -166,7 +166,7 @@ class PbsStructuredValuesTest {
declare struct Pair(pub mut value: (left: int, right: int)) {}
declare service Probe {
fn main() -> int {
let values: array (left: int, right: int) = [(left: 20, right: 22)];
let values: array<(left: int, right: int)> = [(left: 20, right: 22)];
if let pair = values[0] {
let holder = new Pair(pair);
holder.value = (left: 21, right: 21);
@@ -180,7 +180,7 @@ class PbsStructuredValuesTest {
declare service Probe {
fn absent() -> optional int {}
fn main() -> int {
let values: array int = [0];
let values: array<int> = [0];
if values[0].hasSome() {
if Probe.absent().hasNone() { return 42; }
}
@@ -191,7 +191,7 @@ class PbsStructuredValuesTest {
compile("optional-lazy", """
declare service Probe {
fn forbidden() -> int {
let empty: array int = [];
let empty: array<int> = [];
return empty[0] else 999;
}
fn main() -> int {
@@ -204,10 +204,10 @@ class PbsStructuredValuesTest {
@Test void contextualArraysAndAliasReachProductionPbx() throws Exception {
compile("array-context", """
declare service Probe {
fn make() -> array int { return [20, 22]; }
fn sum(values: array int) -> int { return (values[0] else 0) + (values[1] else 0); }
fn make() -> array<int> { return [20, 22]; }
fn sum(values: array<int>) -> int { return (values[0] else 0) + (values[1] else 0); }
fn main() -> int {
let values: array int = { [1, 2] };
let values: array<int> = { [1, 2] };
let alias = values;
alias[0] = 20;
alias[1] = 22;
@@ -249,7 +249,7 @@ class PbsStructuredValuesTest {
declare service Probe {
fn main() -> int {
let counter = new Counter(0);
let values: array int = new array(2);
let values: array<int> = new array(2);
values[counter.next()] = counter.next();
if counter.count != 2 { return 999; }
if (values[0] else 99) != 1 { return 998; }
@@ -263,16 +263,16 @@ class PbsStructuredValuesTest {
}
@Test void boundsFixturesReachProductionPbx() throws Exception {
for (var entry : java.util.Map.of(
"negative-index", "let a: array int = new array(1); return a[-1] else 42;",
"past-end", "let a: array int = new array(1); return a[1] else 42;",
"negative-length", "let size: int = -1; let a: array int = new array(size); return 42;",
"large-length", "let size: long = 4294967296; let a: array int = new array(size); return 42;"
"negative-index", "let a: array<int> = new array(1); return a[-1] else 42;",
"past-end", "let a: array<int> = new array(1); return a[1] else 42;",
"negative-length", "let size: int = -1; let a: array<int> = new array(size); return 42;",
"large-length", "let size: long = 4294967296; let a: array<int> = new array(size); return 42;"
).entrySet()) compile(entry.getKey(), "declare service Probe { fn main() -> int { " + entry.getValue() + " } }");
compile("long-boundaries", """
declare service Probe {
fn main() -> int {
let size: long = 2;
let a: array int = new array(size);
let a: array<int> = new array(size);
let first: long = 0;
let last: int = 1;
a[first] = 20;
@@ -287,12 +287,12 @@ class PbsStructuredValuesTest {
compile("gc-roots", """
declare struct Enemy(pub hp: int) {}
declare service Probe {
fn garbage() { let discarded: array int = new array(1); }
fn garbage() { let discarded: array<int> = new array(1); }
fn gcCollect() { let marker = 314159; }
fn main() -> int {
let keep: array Enemy = [new Enemy(42)];
let tuples: array (left: int, right: int) = [(left: 20, right: 22)];
let names: array str = new array(2);
let keep: array<Enemy> = [new Enemy(42)];
let tuples: array<(left: int, right: int)> = [(left: 20, right: 22)];
let names: array<str> = new array(2);
names[0] = "enemy";
for i: int from 0 until 1100 { Probe.garbage(); }
Probe.gcCollect();
@@ -314,7 +314,7 @@ class PbsStructuredValuesTest {
declare builtin type Vector(pub x: float, pub y: float) {}
declare service Probe {
fn main() -> int {
let vectors: array Vector = [new Vector(20.0, 22.0)];
let vectors: array<Vector> = [new Vector(20.0, 22.0)];
let vector = vectors[0] else new Vector(0.0, 0.0);
return (vector.x + vector.y) as int;
}
@@ -327,7 +327,7 @@ class PbsStructuredValuesTest {
declare service Probe {
fn main() -> int {
let enemy = new Enemy(42);
let targets: array Target = [enemy as Target];
let targets: array<Target> = [enemy as Target];
if let target = targets[0] { return target.health(); }
return 999;
}
@@ -348,7 +348,7 @@ class PbsStructuredValuesTest {
String clientSource = """
declare service Probe {
fn main() -> int {
let values: array Enemy = [new Enemy.create(42)];
let values: array<Enemy> = [new Enemy.create(42)];
let first = Source;
let second = Source;
if first != second { return 999; }
@@ -398,8 +398,8 @@ class PbsStructuredValuesTest {
}
@Test void globalArraysAreInitializedBeforeUse() throws Exception {
compile("global-array", """
declare global values: array int = [20, 22];
declare global empty: array int = new array(3);
declare global values: array<int> = [20, 22];
declare global empty: array<int> = new array(3);
declare service Probe {
fn main() -> int {
if empty.length != 3 as long { return 999; }
@@ -445,23 +445,59 @@ class PbsStructuredValuesTest {
compile("inline-integers", """
declare service Probe {
fn main() -> int {
let values: array int = [10, 20, 30];
let values: array<int> = [10, 20, 30];
return (values.length as int) + 39;
}
}
""");
}
@Test void parametricConstructorsReachProductionPbx() throws Exception {
compile("array-parametric", """
declare global saved: array<int>=new array<>(1);
declare service Probe {
fn make() -> array<int> { return new array<>(1); }
fn size(values: array<int>) -> int { return values.length as int; }
fn main() -> int {
let inferred = new array<int>(2);
let alias = inferred;
alias[0] = 20;
let nested: array<array<int>>=new array<>(2);
if let unexpected = nested[0] { return 999; }
nested[0] = inferred;
let explicitNested = new array<array<int>>(1);
explicitNested[0] = new array<int>(1);
saved = new array<>(1);
saved[0] = 18;
let fromReturn = Probe.make();
let count = Probe.size(new array<>(1)) + Probe.size(new array(1));
if 2 >= 1 {
return (inferred[0] else 0) + (saved[0] else 0) + count
+ (fromReturn.length as int) + (explicitNested.length as int);
}
return 999;
}
}
""");
}
@Test void invalidArraySurfacesAreRejected() {
for(var body : new String[] {
"let values = new array<>(3);",
"let values = new array<Missing>(3);",
"let values = new array<optional int>(3);",
"let values = new array<void>(3);",
"let values: array<int> = new array<bool>(3);",
"let values: array int = new array(3);", // removed syntax
"let values: array<int>[2] = new array(3);", // removed depth notation
"let values = [1, 2];", "let values = [];", "let values = new array(3);",
"let values: array (optional int) = new array(3);",
"let values: array<(optional int)> = new array(3);",
"let values: array[2147483647] int = new array(3);", "let values: array[0] int = new array(3);", "let values: array[-1] int = new array(3);",
"let values: array int = new array(3); let x = values[true];",
"let values: array int = new array(3); values[0] = true;",
"let values: array<int> = new array(3); let x = values[true];",
"let values: array<int> = new array(3); values[0] = true;",
"if let value = 42 { let x = value; }",
"let value: optional int = some(1); if let found = value {} let bad = found;",
"let value: optional int = some(1); if let found = value {} else { let bad = found; }",
"let values: array int = new array(3); let wrong: array bool = values;"
"let values: array<int> = new array(3); let wrong: array<bool> = values;"
}) {
var diagnostics=DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0),"fn main() { "+body+" }",diagnostics);
@@ -0,0 +1,325 @@
package p.studio.compiler.pbs;
import p.studio.compiler.pbs.ast.PbsAst;
import p.studio.compiler.pbs.ast.PbsTypeTraversal;
import p.studio.compiler.source.Span;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.diagnostics.Diagnostics;
import p.studio.utilities.structures.ReadOnlyList;
import java.util.*;
import java.util.stream.Collectors;
/** PBS-owned nominal applications and recursive signature substitution, shared by all consumers. */
public final class PbsContractTypes {
// Match existing type-depth and Registry graph/storage ceilings; never relax provider limits.
private static final int MAX_DEPTH = 256;
private static final int MAX_INSTANCES = 65_536;
private static final int MAX_WORK = 1_048_576;
private static final long MAX_KEY_CHARS = 64L * 1024 * 1024;
private static final Set<String> BUILTINS = Set.of("int", "long", "float", "bool", "str", "Addressable");
public record Instance(String key, PbsAst.TypeRef type, PbsAst.ContractDecl declaration) {}
private final Map<String, PbsAst.TopDecl> declarations = new LinkedHashMap<>();
private final Map<p.studio.compiler.source.identifiers.FileId, Map<String, PbsAst.TopDecl>> scopes = new HashMap<>();
private final Map<String, Instance> instances = new LinkedHashMap<>();
private final IdentityHashMap<PbsAst.TypeRef, String> keys = new IdentityHashMap<>();
private final ArrayDeque<PbsAst.TypeRef> pending = new ArrayDeque<>();
private final List<PbsAst.ImplementsDecl> implementations = new ArrayList<>();
private final Set<String> reported = new HashSet<>();
private final DiagnosticSink diagnostics;
private long keyChars;
private int work;
private boolean failed;
public PbsContractTypes(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> supplemental, DiagnosticSink diagnostics) {
this.diagnostics = diagnostics;
supplemental.forEach(this::index);
ast.topDecls().forEach(this::index);
for (var imported : ast.imports()) for (var item : imported.items()) {
if (item.alias() != null && !item.alias().isBlank() && !declarations.containsKey(item.alias())) {
var declaration = declarations.get(item.name());
if (declaration != null) declarations.put(item.alias(), declaration);
}
}
}
private void index(PbsAst.TopDecl declaration) {
if (declaration instanceof PbsAst.TypeBindingDecl binding) {
index(binding.declaration());
declarations.put(binding.name(), binding.declaration());
scopes.computeIfAbsent(binding.span().getFileId(), ignored -> new HashMap<>()).put(binding.name(), binding.declaration());
return;
}
String name = switch (declaration) {
case PbsAst.ContractDecl d -> d.name();
case PbsAst.StructDecl d -> d.name();
case PbsAst.ServiceDecl d -> d.name();
case PbsAst.BuiltinTypeDecl d -> d.name();
case PbsAst.EnumDecl d -> d.name();
case PbsAst.ErrorDecl d -> d.name();
default -> null;
};
if (name != null) {
declarations.put(name, declaration);
scopes.computeIfAbsent(declaration.span().getFileId(), ignored -> new HashMap<>()).put(name, declaration);
}
if (declaration instanceof PbsAst.ImplementsDecl implementation && implementations.stream().noneMatch(i -> i.span().equals(implementation.span()))) implementations.add(implementation);
}
public PbsAst.TopDecl declaration(PbsAst.TypeRef type) {
if (type == null) return null;
return scopes.getOrDefault(type.span().getFileId(), Map.of()).getOrDefault(type.name(), declarations.get(type.name()));
}
public String display(PbsAst.TypeRef type) {
if (type == null) return "void";
if (type.kind() == PbsAst.TypeRefKind.SIMPLE) {
var declaration = declaration(type);
var name = switch (declaration) {
case PbsAst.ContractDecl c -> c.name();
case PbsAst.StructDecl s -> s.name();
case PbsAst.ServiceDecl s -> s.name();
case PbsAst.BuiltinTypeDecl b -> b.name();
case PbsAst.EnumDecl e -> e.name();
case PbsAst.ErrorDecl e -> e.name();
case null, default -> type.name();
};
return name + (type.arguments().isEmpty() ? "" : "<" + type.arguments().stream().map(this::display).collect(Collectors.joining(", ")) + ">");
}
return switch (type.kind()) {
case ARRAY -> "array<" + display(type.inner()) + ">";
case OPTIONAL -> "optional " + display(type.inner());
case GROUP -> "(" + display(type.inner()) + ")";
case FN -> "Fn(" + type.fields().stream().map(f -> display(f.typeRef())).collect(Collectors.joining(", ")) + ") -> " + display(type.inner());
case NAMED_TUPLE -> "(" + type.fields().stream().map(f -> f.label() + ": " + display(f.typeRef())).collect(Collectors.joining(", ")) + ")";
default -> type.surface();
};
}
public String implementationCallableName(PbsAst.ImplementsDecl implementation, String method) {
var template = template(implementation.contractType());
var contractKey = "pbs:contract:file" + template.span().getFileId().getId() + ":" + template.span().getStart()
+ (implementation.contractType().arguments().isEmpty() ? "" : ":" + key(implementation.contractType()));
return implementation.ownerName() + ".$impl." + contractKey + "." + method;
}
public boolean isContract(PbsAst.TypeRef type) {
return type != null && type.kind() == PbsAst.TypeRefKind.SIMPLE
&& declaration(type) instanceof PbsAst.ContractDecl;
}
public PbsAst.ContractDecl template(PbsAst.TypeRef type) {
return isContract(type) ? (PbsAst.ContractDecl) declaration(type) : null;
}
public String key(PbsAst.TypeRef type) { return key(type, 0); }
private String key(PbsAst.TypeRef type, int depth) {
if (type == null) return "void";
var cached = keys.get(type);
if (cached != null) return cached;
budget(type.span(), depth);
String head;
var children = new ArrayList<String>();
switch (type.kind()) {
case GROUP -> { return key(type.inner(), depth + 1); }
case SIMPLE -> {
var declaration = declaration(type);
head = declaration == null ? type.name() : nominal(declaration);
for (var argument : type.arguments()) children.add(key(argument, depth + 1));
}
case FN -> {
head = "Fn";
for (var input : type.fields()) children.add(key(input.typeRef(), depth + 1));
children.add("->" + returnKey(type.inner(), depth + 1));
}
case NAMED_TUPLE -> {
head = "tuple";
for (var field : type.fields()) children.add(key(field.typeRef(), depth + 1));
}
default -> {
head = type.kind().name();
if (type.inner() != null) children.add(key(type.inner(), depth + 1));
}
}
long length = head.length() + 2L;
for (var child : children) length += child.length() + 16L;
if (keyChars + length > MAX_KEY_CHARS) throw expansion(type.span(), "Contract type identity storage budget exceeded");
// 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);
return result;
}
private static String nominal(PbsAst.TopDecl declaration) {
return "pbs:" + declaration.getClass().getSimpleName() + ":" + declaration.span().getFileId().getId() + ":" + declaration.span().getStart();
}
public Instance resolve(PbsAst.TypeRef type) {
if (failed) return null;
var template = template(type);
if (template == null) return null;
if (template.typeParameters().size() != type.arguments().size()) {
error("E_SEM_CONTRACT_ARITY", "Contract " + template.name() + " requires " + template.typeParameters().size() + " explicit type argument(s)", type.span());
return null;
}
String key = key(type);
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");
var bindings = new LinkedHashMap<String, PbsAst.TypeRef>();
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());
var concrete = new PbsAst.ContractDecl(display(type), signatures, template.attributes(), template.span());
var instance = new Instance(key, type, concrete);
instances.put(key, instance); // Anchor before discovering recursively referenced applications.
for (var signature : signatures) PbsTypeTraversal.signature(signature, t -> validateType(t, Set.of(), false, 0));
return instance;
}
public void expand() {
while (!pending.isEmpty() && !failed) resolve(pending.removeFirst());
}
public void validate(PbsAst.File ast) {
try {
for (var declaration : ast.topDecls()) {
if (declaration instanceof PbsAst.ContractDecl contract) {
var parameters = new HashSet<String>();
for (var parameter : contract.typeParameters()) if (!parameters.add(parameter.name()))
error("E_SEM_CONTRACT_PARAMETER", "Duplicate contract type parameter " + parameter.name(), parameter.span());
PbsTypeTraversal.visit(declaration, t -> validateType(t, parameters, !parameters.isEmpty(), 0));
} else {
var owner = declaration instanceof PbsAst.StructDecl s ? s.name()
: declaration instanceof PbsAst.ServiceDecl s ? s.name() : null;
PbsTypeTraversal.visit(declaration, t -> validateType(owner == null ? t : PbsTypeSubstitution.replaceSelf(t, owner), Set.of(), false, 0));
}
}
expand();
validateImplementations(ast);
} catch (ExpansionFailure failure) {
failed = true;
pending.clear();
}
}
private void validateType(PbsAst.TypeRef type, Set<String> parameters, boolean templateScope, int depth) {
if (type == null || failed) return;
budget(type.span(), depth);
if (type.kind() == PbsAst.TypeRefKind.SIMPLE) {
var declaration = declaration(type);
if (parameters.contains(type.name())) {
if (!type.arguments().isEmpty()) error("E_SEM_CONTRACT_PARAMETER", "Type parameter cannot be applied", type.span());
} else if (declaration instanceof PbsAst.ContractDecl contract) {
if (contract.typeParameters().size() != type.arguments().size())
error("E_SEM_CONTRACT_ARITY", "Contract " + type.name() + " requires " + contract.typeParameters().size() + " explicit type argument(s)", type.span());
else if (!containsParameter(type, parameters)) pending.add(type);
} else if (!type.arguments().isEmpty()) {
error("E_SEM_CONTRACT_ARGUMENT", "Only a parameterized contract accepts type arguments", type.span());
} else if (templateScope && declaration == null && !BUILTINS.contains(type.name())) {
error("E_SEM_CONTRACT_PARAMETER", "Unresolved type or undeclared type parameter " + type.name(), type.span());
}
}
if (type.kind() == PbsAst.TypeRefKind.ARRAY && type.inner() != null) {
var element = unwrap(type.inner());
if (element.kind() == PbsAst.TypeRefKind.OPTIONAL || element.kind() == PbsAst.TypeRefKind.UNIT)
error("E_SEM_ARRAY_ELEMENT_TYPE", "Array elements must be non-optional values after substitution", type.span());
}
if (type.kind() == PbsAst.TypeRefKind.OPTIONAL && unwrap(type.inner()).kind() == PbsAst.TypeRefKind.UNIT)
error("E_SEM_INVALID_OPTIONAL_VOID_TYPE_SURFACE", "optional void is not a valid substituted type", type.span());
if (type.kind() == PbsAst.TypeRefKind.FN) for (var input : type.fields())
if (unwrap(input.typeRef()).kind() == PbsAst.TypeRefKind.UNIT)
error("E_SEM_FN_PARAMETER", "Fn parameter must remain a value type after substitution", input.span());
for (var argument : type.arguments()) validateType(argument, parameters, true, depth + 1);
for (var field : type.fields()) validateType(field.typeRef(), parameters, templateScope, depth + 1);
validateType(type.inner(), parameters, templateScope, depth + 1);
}
private boolean containsParameter(PbsAst.TypeRef type, Set<String> parameters) {
if (type == null || parameters.isEmpty()) return false;
if (type.kind() == PbsAst.TypeRefKind.SIMPLE && parameters.contains(type.name())) return true;
if (containsParameter(type.inner(), parameters)) return true;
return type.arguments().stream().anyMatch(t -> containsParameter(t, parameters))
|| type.fields().stream().anyMatch(f -> containsParameter(f.typeRef(), parameters));
}
private void validateImplementations(PbsAst.File ast) {
var seen = new HashSet<String>();
for (var implementation : implementations) {
var instance = resolve(implementation.contractType());
if (instance == null) {
error("E_SEM_CONTRACT_IMPLEMENTATION", "Implementation target must be a concrete contract", implementation.contractType().span());
continue;
}
var owner = declaration(PbsAst.TypeRef.simple(implementation.ownerName(), implementation.span()));
if (!(owner instanceof PbsAst.StructDecl) && !(owner instanceof PbsAst.ServiceDecl)) {
error("E_SEM_CONTRACT_OWNER", "Contract owner must be a declared struct or service", implementation.span());
continue;
}
var pair = nominal(owner) + ":" + instance.key();
if (!seen.add(pair)) error("E_SEM_CONTRACT_DUPLICATE_IMPLEMENTATION", "Duplicate implementation of " + implementation.contractName() + " for " + implementation.ownerName(), implementation.span());
var expected = instance.declaration().signatures();
var matched = new HashSet<PbsAst.FunctionDecl>();
for (var signature : expected) {
var methods = implementation.methods().stream().filter(m -> matches(m, signature)).toList();
if (methods.size() != 1) error("E_SEM_CONTRACT_SIGNATURE", "Implementation must supply exactly one matching " + signature.name() + " for " + implementation.contractName(), implementation.span());
else matched.add(methods.getFirst());
}
if (matched.size() != implementation.methods().size()) error("E_SEM_CONTRACT_SIGNATURE", "Implementation contains extra or incompatible contract methods", implementation.span());
}
}
private boolean matches(PbsAst.FunctionDecl method, PbsAst.FunctionSignature signature) {
if (!method.name().equals(signature.name()) || method.parameters().size() != signature.parameters().size()) return false;
if ((method.returnKind() == PbsAst.ReturnKind.RESULT) != (signature.returnKind() == PbsAst.ReturnKind.RESULT)
|| !returnKey(method.returnType()).equals(returnKey(signature.returnType()))) return false;
if (!key(method.resultErrorType()).equals(key(signature.resultErrorType()))) return false;
for (int i = 0; i < method.parameters().size(); i++) if (!key(method.parameters().get(i).typeRef()).equals(key(signature.parameters().get(i).typeRef()))) return false;
return true;
}
private String returnKey(PbsAst.TypeRef type) {
return returnKey(type, 0);
}
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();
return key(type, depth);
}
public Set<String> implementers(PbsAst.TypeRef target) {
var result = new HashSet<String>();
var targetKey = key(target);
for (var implementation : implementations) if (key(implementation.contractType()).equals(targetKey)) {
var owner = declaration(PbsAst.TypeRef.simple(implementation.ownerName(), implementation.span()));
if (owner != null) result.add(key(PbsAst.TypeRef.simple(implementation.ownerName(), implementation.span())));
declarations.forEach((name, d) -> { if (d == owner || (d != null && owner != null && nominal(d).equals(nominal(owner)))) result.add(name); });
}
return Set.copyOf(result);
}
public List<Instance> instances() { return List.copyOf(instances.values()); }
private void budget(Span span, int depth) {
if (depth > MAX_DEPTH || ++work > MAX_WORK) throw expansion(span, "Contract expansion exceeds bounded type analysis; recursive applications may expand indefinitely");
}
private ExpansionFailure expansion(Span span, String message) {
error("E_SEM_CONTRACT_EXPANSION", message, span);
return new ExpansionFailure();
}
private void error(String code, String message, Span span) {
if (reported.add(code + ":" + span + ":" + message)) Diagnostics.error(diagnostics, code, message, span);
}
private static PbsAst.TypeRef unwrap(PbsAst.TypeRef type) {
while (type != null && type.kind() == PbsAst.TypeRefKind.GROUP) type = type.inner();
return type;
}
private static final class ExpansionFailure extends RuntimeException {}
}
@@ -565,7 +565,12 @@ public final class PbsFrontendCompiler {
int returnSlots,
PbsAst.ReturnKind returnKind,
PbsAst.TypeRef returnType,
String shapeSurface) {
String shapeSurface,
String targetName) {
public ImportedCallableSurface(ModuleId moduleId, String callableName, int arity, int returnSlots,
PbsAst.ReturnKind returnKind, PbsAst.TypeRef returnType, String shapeSurface) {
this(moduleId, callableName, arity, returnSlots, returnKind, returnType, shapeSurface, callableName);
}
public ImportedCallableSurface {
moduleId = moduleId == null ? ModuleId.none() : moduleId;
}
@@ -241,7 +241,7 @@ public final class PbsReservedMetadataExtractor {
return "unit";
}
return switch (typeRef.kind()) {
case SIMPLE -> "simple:" + typeRef.name();
case SIMPLE -> "simple:" + typeRef.surface();
case SELF -> "self";
case FN -> "Fn(" + typeRef.fields().stream().map(f -> typeSurfaceKey(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + typeSurfaceKey(typeRef.inner());
case ARRAY -> "array(" + typeSurfaceKey(typeRef.inner()) + ")";
@@ -2,6 +2,7 @@ package p.studio.compiler.pbs;
import p.studio.compiler.pbs.ast.PbsAst;
import p.studio.utilities.structures.ReadOnlyList;
import java.util.Map;
/** Resolves Self consistently in source signatures and executable metadata. */
public final class PbsTypeSubstitution {
@@ -17,11 +18,29 @@ public final class PbsTypeSubstitution {
new PbsAst.NamedTypeField(field.label(), replaceSelf(field.typeRef(), owner), field.span())).toList()), type.span());
}
if (type.inner() != null) {
return new PbsAst.TypeRef(type.kind(), type.name(), type.fields(), replaceSelf(type.inner(), owner), type.span());
return new PbsAst.TypeRef(type.kind(), type.name(), type.fields(), replaceSelf(type.inner(), owner),
ReadOnlyList.wrap(type.arguments().stream().map(t -> replaceSelf(t, owner)).toList()), type.span());
}
if (!type.arguments().isEmpty()) return new PbsAst.TypeRef(type.kind(), type.name(), type.fields(), null,
ReadOnlyList.wrap(type.arguments().stream().map(t -> replaceSelf(t, owner)).toList()), type.span());
return type;
}
public static PbsAst.TypeRef substitute(PbsAst.TypeRef type, Map<String, PbsAst.TypeRef> bindings) {
if (type == null) return null;
if (type.kind() == PbsAst.TypeRefKind.SIMPLE && type.arguments().isEmpty() && bindings.containsKey(type.name()))
return bindings.get(type.name());
return new PbsAst.TypeRef(type.kind(), type.name(), ReadOnlyList.wrap(type.fields().stream().map(f ->
new PbsAst.NamedTypeField(f.label(), substitute(f.typeRef(), bindings), f.span())).toList()),
substitute(type.inner(), bindings), ReadOnlyList.wrap(type.arguments().stream().map(t -> substitute(t, bindings)).toList()), type.span());
}
public static PbsAst.FunctionSignature substitute(PbsAst.FunctionSignature signature, Map<String, PbsAst.TypeRef> bindings) {
return new PbsAst.FunctionSignature(signature.name(), ReadOnlyList.wrap(signature.parameters().stream().map(p ->
new PbsAst.Parameter(p.name(), substitute(p.typeRef(), bindings), p.span())).toList()), signature.returnKind(),
substitute(signature.returnType(), bindings), substitute(signature.resultErrorType(), bindings), signature.attributes(), signature.span());
}
public static PbsAst.FunctionDecl forOwner(PbsAst.FunctionDecl function, String owner) {
var parameters = ReadOnlyList.wrap(function.parameters().stream().map(parameter ->
new PbsAst.Parameter(parameter.name(), replaceSelf(parameter.typeRef(), owner), parameter.span())).toList());
@@ -122,6 +122,7 @@ public final class PbsAst {
EnumDecl,
GlobalDecl,
ConstDecl,
TypeBindingDecl,
ImplementsDecl,
InvalidDecl {
Span span();
@@ -157,11 +158,21 @@ public final class PbsAst {
public record ContractDecl(
String name,
ReadOnlyList<TypeParameter> typeParameters,
ReadOnlyList<FunctionSignature> signatures,
ReadOnlyList<Attribute> attributes,
Span span) implements TopDecl {
public ContractDecl(String name, ReadOnlyList<FunctionSignature> signatures,
ReadOnlyList<Attribute> attributes, Span span) {
this(name, ReadOnlyList.empty(), signatures, attributes, span);
}
}
public record TypeParameter(String name, Span span) {}
/** Imported lexical binding; retains the original declaration and the importing source scope. */
public record TypeBindingDecl(String name, TopDecl declaration, Span span) implements TopDecl {}
public record HostDecl(
String name,
ReadOnlyList<FunctionSignature> signatures,
@@ -221,11 +232,16 @@ public final class PbsAst {
}
public record ImplementsDecl(
String contractName,
TypeRef contractType,
String ownerName,
String binderName,
ReadOnlyList<FunctionDecl> methods,
Span span) implements TopDecl {
public ImplementsDecl(String contractName, String ownerName, String binderName,
ReadOnlyList<FunctionDecl> methods, Span span) {
this(TypeRef.simple(contractName, span), ownerName, binderName, methods, span);
}
public String contractName() { return contractType.surface(); }
}
public record InvalidDecl(
@@ -251,7 +267,27 @@ public final class PbsAst {
String name,
ReadOnlyList<NamedTypeField> fields,
TypeRef inner,
ReadOnlyList<TypeRef> arguments,
Span span) {
public TypeRef(TypeRefKind kind, String name, ReadOnlyList<NamedTypeField> fields, TypeRef inner, Span span) {
this(kind, name, fields, inner, ReadOnlyList.empty(), span);
}
public static TypeRef applied(String name, ReadOnlyList<TypeRef> arguments, Span span) {
return new TypeRef(TypeRefKind.SIMPLE, name, ReadOnlyList.empty(), null, arguments, span);
}
public String surface() {
return switch (kind) {
case SIMPLE -> name + (arguments.isEmpty() ? "" : "<" + arguments.stream().map(TypeRef::surface).collect(java.util.stream.Collectors.joining(", ")) + ">");
case ARRAY -> "array<" + inner.surface() + ">";
case OPTIONAL -> "optional " + inner.surface();
case GROUP -> "(" + inner.surface() + ")";
case FN -> "Fn(" + fields.stream().map(f -> f.typeRef().surface()).collect(java.util.stream.Collectors.joining(", ")) + ") -> " + inner.surface();
case NAMED_TUPLE -> "(" + fields.stream().map(f -> f.label() + ": " + f.typeRef().surface()).collect(java.util.stream.Collectors.joining(", ")) + ")";
case UNIT -> "void";
case SELF -> "Self";
case ERROR -> "?";
};
}
public static TypeRef function(ReadOnlyList<NamedTypeField> inputs, TypeRef output, Span span) {
return new TypeRef(TypeRefKind.FN, "Fn", inputs, output, span);
}
@@ -589,8 +625,12 @@ public final class PbsAst {
public record AsExpr(
Expression expression,
String contractName,
TypeRef contractType,
Span span) implements Expression {
public AsExpr(Expression expression, String contractName, Span span) {
this(expression, TypeRef.simple(contractName, span), span);
}
public String contractName() { return contractType.surface(); }
}
public record CallExpr(
@@ -627,7 +667,12 @@ public final class PbsAst {
String typeName,
String ctorName,
ReadOnlyList<Expression> arguments,
TypeRef explicitType,
boolean diamond,
Span span) implements Expression {
public NewExpr(String typeName, String ctorName, ReadOnlyList<Expression> arguments, Span span) {
this(typeName, ctorName, arguments, null, false, span);
}
}
public record LambdaExpr(
@@ -725,7 +770,11 @@ public final class PbsAst {
public record BarrelContractItem(
Visibility visibility,
String name,
ReadOnlyList<TypeParameter> typeParameters,
Span span) implements BarrelItem {
public BarrelContractItem(Visibility visibility, String name, Span span) {
this(visibility, name, ReadOnlyList.empty(), span);
}
}
public record BarrelHostItem(
@@ -0,0 +1,93 @@
package p.studio.compiler.pbs.ast;
import java.util.function.Consumer;
/** Visits source type roots, including annotations inside executable expressions. */
public final class PbsTypeTraversal {
private PbsTypeTraversal() {}
public static void visit(PbsAst.TopDecl declaration, Consumer<PbsAst.TypeRef> visitor) {
switch (declaration) {
case PbsAst.FunctionDecl f -> function(f, visitor);
case PbsAst.ContractDecl c -> c.signatures().forEach(s -> signature(s, visitor));
case PbsAst.HostDecl h -> h.signatures().forEach(s -> signature(s, visitor));
case PbsAst.StructDecl s -> {
s.fields().forEach(f -> type(f.typeRef(), visitor));
s.methods().forEach(f -> function(f, visitor));
s.ctors().forEach(c -> { c.parameters().forEach(p -> type(p.typeRef(), visitor)); block(c.body(), visitor); });
}
case PbsAst.ServiceDecl s -> {
s.methods().forEach(f -> function(f, visitor));
s.constants().forEach(c -> visit(c, visitor));
}
case PbsAst.BuiltinTypeDecl b -> {
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.GlobalDecl g -> { type(g.explicitType(), visitor); expression(g.initializer(), visitor); }
case PbsAst.ConstDecl c -> { type(c.explicitType(), visitor); expression(c.initializer(), visitor); }
default -> { }
}
}
public static void signature(PbsAst.FunctionSignature s, Consumer<PbsAst.TypeRef> visitor) {
s.parameters().forEach(p -> type(p.typeRef(), visitor)); type(s.returnType(), visitor); type(s.resultErrorType(), visitor);
}
private static void function(PbsAst.FunctionDecl f, Consumer<PbsAst.TypeRef> visitor) {
f.parameters().forEach(p -> type(p.typeRef(), visitor)); type(f.returnType(), visitor); type(f.resultErrorType(), visitor); block(f.body(), visitor);
}
private static void type(PbsAst.TypeRef t, Consumer<PbsAst.TypeRef> visitor) { if (t != null) visitor.accept(t); }
public static void block(PbsAst.Block b, Consumer<PbsAst.TypeRef> visitor) {
if (b == null) return;
for (var statement : b.statements()) switch (statement) {
case PbsAst.LetStatement s -> { type(s.explicitType(), visitor); expression(s.initializer(), visitor); }
case PbsAst.AssignStatement s -> { expression(s.target().expression(), visitor); expression(s.value(), visitor); }
case PbsAst.ReturnStatement s -> expression(s.value(), visitor);
case PbsAst.ExpressionStatement s -> expression(s.expression(), visitor);
case PbsAst.IfStatement s -> conditional(s, visitor);
case PbsAst.WhileStatement s -> { expression(s.condition(), visitor); block(s.body(), visitor); }
case PbsAst.ForStatement s -> {
type(s.iteratorType(), visitor); expression(s.fromExpression(), visitor); expression(s.untilExpression(), visitor);
expression(s.stepExpression(), visitor); block(s.body(), visitor);
}
default -> { }
}
expression(b.tailExpression(), visitor);
}
private static void conditional(PbsAst.IfStatement s, Consumer<PbsAst.TypeRef> visitor) {
if (s == null) return;
expression(s.condition(), visitor); block(s.thenBlock(), visitor); block(s.elseBlock(), visitor); conditional(s.elseIf(), visitor);
}
private static void expression(PbsAst.Expression e, Consumer<PbsAst.TypeRef> visitor) {
if (e == null) return;
switch (e) {
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); }
case PbsAst.CallExpr c -> { expression(c.callee(), visitor); c.arguments().forEach(a -> expression(a, visitor)); }
case PbsAst.ApplyExpr a -> { expression(a.callee(), visitor); expression(a.argument(), visitor); }
case PbsAst.BinaryExpr b -> { expression(b.left(), visitor); expression(b.right(), visitor); }
case PbsAst.UnaryExpr u -> expression(u.expression(), visitor);
case PbsAst.MemberExpr m -> expression(m.receiver(), visitor);
case PbsAst.IndexExpr i -> { expression(i.receiver(), visitor); expression(i.index(), visitor); }
case PbsAst.ArrayLiteralExpr a -> a.elements().forEach(v -> expression(v, visitor));
case PbsAst.TupleExpr t -> t.items().forEach(i -> expression(i.expression(), visitor));
case PbsAst.GroupExpr g -> expression(g.expression(), visitor);
case PbsAst.SomeExpr s -> expression(s.value(), visitor);
case PbsAst.OkExpr o -> expression(o.value(), visitor);
case PbsAst.PropagateExpr p -> expression(p.expression(), visitor);
case PbsAst.ElseExpr f -> { expression(f.optionalExpression(), visitor); expression(f.fallbackExpression(), visitor); }
case PbsAst.BlockExpr b -> block(b.block(), visitor);
case PbsAst.IfExpr i -> { expression(i.condition(), visitor); block(i.thenBlock(), visitor); expression(i.elseExpression(), visitor); }
case PbsAst.SwitchExpr s -> { expression(s.selector(), visitor); s.arms().forEach(a -> block(a.block(), visitor)); }
case PbsAst.HandleExpr h -> { expression(h.value(), visitor); h.arms().forEach(a -> block(a.block(), visitor)); }
default -> { }
}
}
}
@@ -32,13 +32,16 @@ public final class PbsModuleVisibilityValidator {
final DiagnosticSink diagnostics) {
final var signatureInterning = new SignatureInterning(new TypeSurfaceTable(), new CallableShapeTable());
final var exportsByModule = new HashMap<ModuleRefKey, ModuleExports>();
final var unitsByModule = new HashMap<ModuleRefKey, ModuleUnit>();
for (var module : modules) unitsByModule.put(toModuleRef(module.coordinates()), module);
for (final var module : modules) {
final var exports = validateModule(module, nameTable, signatureInterning, diagnostics);
final var exports = validateModule(module, nameTable, signatureInterning, diagnostics, unitsByModule);
exportsByModule.put(toModuleRef(module.coordinates()), exports);
}
for (final var module : modules) {
validateImplementationOwners(module, diagnostics);
validateImports(module, exportsByModule, nameTable, diagnostics);
}
}
@@ -53,7 +56,8 @@ public final class PbsModuleVisibilityValidator {
final ModuleUnit module,
final NameTable nameTable,
final SignatureInterning signatureInterning,
final DiagnosticSink diagnostics) {
final DiagnosticSink diagnostics,
final Map<ModuleRefKey, ModuleUnit> unitsByModule) {
final var exports = new ModuleExports();
if (module.sourceFiles().isEmpty()) {
@@ -163,7 +167,10 @@ public final class PbsModuleVisibilityValidator {
continue;
}
final var matches = declarations.nonFunctionsByKindAndName.getOrDefault(symbolKey, List.of());
var matches = declarations.nonFunctionsByKindAndName.getOrDefault(symbolKey, List.of());
var resolvedContract = item instanceof PbsAst.BarrelContractItem contractItem
? resolveContractExport(module, contractItem.name(), unitsByModule, new HashSet<>()) : null;
if (matches.isEmpty() && resolvedContract != null) matches = List.of(resolvedContract.span());
if (matches.isEmpty()) {
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,
PbsLinkErrors.E_LINK_UNRESOLVED_BARREL_ENTRY.name(),
@@ -184,6 +191,15 @@ public final class PbsModuleVisibilityValidator {
continue;
}
if (item instanceof PbsAst.BarrelContractItem contractItem) {
var expected = resolvedContract;
if (expected != null && !expected.typeParameters().stream().map(PbsAst.TypeParameter::name).toList().equals(
contractItem.typeParameters().stream().map(PbsAst.TypeParameter::name).toList())) {
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics, "E_LINK_CONTRACT_PARAMETERS",
"Barrel contract parameters must preserve the declaration's ordered parameters", contractItem.span());
continue;
}
}
if (nonFunctionVisibility(item) == PbsAst.Visibility.PUB) {
exports.publicNameIds.add(symbolKey.nameId());
}
@@ -192,6 +208,37 @@ public final class PbsModuleVisibilityValidator {
return exports;
}
private void validateImplementationOwners(ModuleUnit module, DiagnosticSink diagnostics) {
var localOwners = new HashSet<String>();
for (var source : module.sourceFiles()) for (var declaration : source.ast().topDecls()) {
if (declaration instanceof PbsAst.StructDecl s) localOwners.add(s.name());
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()))
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());
}
private record ContractExportKey(ModuleRefKey module, String name) {}
private PbsAst.ContractDecl resolveContractExport(ModuleUnit module, String name,
Map<ModuleRefKey, ModuleUnit> units, Set<ContractExportKey> visited) {
if (!visited.add(new ContractExportKey(toModuleRef(module.coordinates()), name))) return null;
for (var source : module.sourceFiles()) for (var declaration : source.ast().topDecls())
if (declaration instanceof PbsAst.ContractDecl contract && contract.name().equals(name)) return contract;
for (var source : module.sourceFiles()) for (var imported : source.ast().imports()) for (var item : imported.items()) {
var local = item.alias() == null || item.alias().isBlank() ? item.name() : item.alias();
if (!local.equals(name)) continue;
var target = units.get(new ModuleRefKey(imported.moduleRef().project(), imported.moduleRef().pathSegments()));
if (target == null || target.barrelFiles().stream().noneMatch(b -> b.ast().items().stream().anyMatch(i ->
i instanceof PbsAst.BarrelContractItem c && c.visibility() == PbsAst.Visibility.PUB && c.name().equals(item.name())))) continue;
var contract = resolveContractExport(target, item.name(), units, visited);
if (contract != null) return contract;
}
return null;
}
private void validateImports(
final ModuleUnit module,
final Map<ModuleRefKey, ModuleExports> exportsByModule,
@@ -68,7 +68,7 @@ final class PbsCallableShapeSurfaceService {
return "unit";
}
return switch (unwrapped.kind()) {
case SIMPLE -> "simple:" + unwrapped.name();
case SIMPLE -> "simple:" + unwrapped.surface();
case SELF -> "self";
case FN -> "Fn(" + unwrapped.fields().stream().map(f -> typeSurfaceKey(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + typeSurfaceKey(unwrapped.inner());
case ARRAY -> "array(" + typeSurfaceKey(unwrapped.inner()) + ")";
@@ -1093,8 +1093,8 @@ final class PbsExecutableBodyLowerer {
try {
var target=PbsRuntimeTypes.unwrap(expected);
var actual=PbsRuntimeTypes.unwrap(expressionType(expression,context));
if(target!=null && actual!=null && context.types().contracts.containsKey(target.name()) && !target.name().equals(actual.name()))
lowerConversion(new PbsAst.AsExpr(expression,target.name(),expression.span()),context);
if(target!=null && actual!=null && context.types().isContract(target) && !context.types().key(target).equals(context.types().key(actual)))
lowerConversion(new PbsAst.AsExpr(expression,target,expression.span()),context);
else lowerExpression(expression, context);
} finally { context.expectedType = previous; }
}
@@ -1141,13 +1141,13 @@ final class PbsExecutableBodyLowerer {
return null;
}
if (e instanceof PbsAst.GroupExpr g) return expressionType(g.expression(), c);
if (e instanceof PbsAst.AsExpr a) return PbsRuntimeTypes.type(a.contractName());
if (e instanceof PbsAst.AsExpr a) return a.contractType();
if (e instanceof PbsAst.UnaryExpr u) return java.util.Set.of("!", "not").contains(u.operator()) ? PbsRuntimeTypes.type("bool") : expressionType(u.expression(), c);
if (e instanceof PbsAst.BinaryExpr b) return java.util.Set.of("==", "!=", "<", "<=", ">", ">=", "&&", "||", "and", "or").contains(b.operator()) ? PbsRuntimeTypes.type("bool") : expressionType(b.left(), c);
if (e instanceof PbsAst.IfExpr branch) return expressionType(branch.thenBlock().tailExpression(), c);
if (e instanceof PbsAst.SwitchExpr branch && !branch.arms().isEmpty()) return expressionType(branch.arms().getFirst().block().tailExpression(), c);
if (e instanceof PbsAst.ApplyExpr apply) return expressionType(applyCall(apply), c);
if (e instanceof PbsAst.NewExpr value) return value.typeName().equals("array") ? c.expectedType : PbsRuntimeTypes.type(value.typeName());
if (e instanceof PbsAst.NewExpr value) return value.typeName().equals("array") ? (value.explicitType() != null ? value.explicitType() : c.expectedType) : PbsRuntimeTypes.type(value.typeName());
if (e instanceof PbsAst.CallExpr call) {
var fn = isDirectFunction(call.callee(), c) ? null : PbsRuntimeTypes.unwrap(expressionType(call.callee(),c));
if (fn != null && fn.kind() == PbsAst.TypeRefKind.FN) return fn.inner();
@@ -1162,9 +1162,13 @@ final class PbsExecutableBodyLowerer {
if(owner!=null) {
if (owner.kind() == PbsAst.TypeRefKind.OPTIONAL
&& (member.memberName().equals("hasSome") || member.memberName().equals("hasNone"))) return PbsRuntimeTypes.type("bool");
var contract=c.types().contracts.get(owner.name());
if(contract!=null) for(var method:contract.signatures()) if(method.name().equals(member.memberName()) && parametersMatch(method.parameters(),call.arguments(),c)
&& returnMatches(method.returnType(),owner.name(),c)) return method.returnType();
var contract=c.types().contract(owner);
if(contract!=null) {
var candidates = contract.signatures().stream().filter(method -> method.name().equals(member.memberName())
&& parametersMatch(method.parameters(),call.arguments(),c)).toList();
if (candidates.size() == 1) return candidates.getFirst().returnType();
for (var method : candidates) if (returnMatches(method.returnType(),owner.name(),c)) return method.returnType();
}
var struct = c.types().structs.get(owner.name());
var service = c.types().services.get(owner.name());
var methods = struct != null ? struct.methods() : service != null ? service.methods() : ReadOnlyList.<PbsAst.FunctionDecl>empty();
@@ -1200,11 +1204,11 @@ final class PbsExecutableBodyLowerer {
var sourceType = expressionType(expr.expression(),c);
var source = c.types().canonical(sourceType);
var target = expr.contractName();
if(c.types().contracts.containsKey(target)) {
if(c.types().isContract(expr.contractType())) {
lowerExpected(expr.expression(),null,c);
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.REGISTRY,
null,"",null,null,null,"","",c.types().slots(sourceType),2,expr.span(),
new IRRegistryInstruction(REF_TO_TRAIT,c.types().registryType(sourceType),c.types().registryType(PbsRuntimeTypes.type(target)),null,0)));
new IRRegistryInstruction(REF_TO_TRAIT,c.types().registryType(sourceType),c.types().registryType(expr.contractType()),null,0)));
return;
}
lowerExpected(expr.expression(), null, c);
@@ -1746,7 +1750,7 @@ final class PbsExecutableBodyLowerer {
}
if(!(call.callee() instanceof PbsAst.MemberExpr member))return false;
var owner=PbsRuntimeTypes.unwrap(expressionType(member.receiver(),c));if(owner==null)return false;
var contract=c.types().contracts.get(owner.name());
var contract=c.types().contract(owner);
if(contract!=null) {
int ordinal=-1;
for(int i=0;i<contract.signatures().size();i++) {
@@ -1755,8 +1759,11 @@ final class PbsExecutableBodyLowerer {
}
if(ordinal<0)return false;
var method=contract.signatures().get(ordinal);lowerExpected(member.receiver(),owner,c);
// Evaluate/root the receiver first, then place its complete view after explicit arguments.
int receiverView = save(2, member.receiver().span(), c);
int pops=2;
for(int i=0;i<call.arguments().size();i++){var type=PbsTypeSubstitution.replaceSelf(method.parameters().get(i).typeRef(),owner.name());lowerExpected(call.arguments().get(i),type,c);pops+=c.types().slots(type);}
emitLoadLocalSlots(receiverView, 2, member.receiver().span(), c);
registry(CALL_TRAIT,c.types().registryType(owner),ordinal,pops,c.types().slots(method.returnType()),call.span(),c);return true;
}
var service=c.types().services.get(owner.name());
@@ -1769,7 +1776,7 @@ final class PbsExecutableBodyLowerer {
}
int pops=0;
for(int i=0;i<call.arguments().size();i++){var type=PbsTypeSubstitution.replaceSelf(method.parameters().get(i).typeRef(),owner.name());lowerExpected(call.arguments().get(i),type,c);pops+=c.types().slots(type);}
emitStructuredFunction(service.name()+"."+method.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),pops,c.types().slots(method.returnType()),call.span(),c);return true;
emitStructuredFunction(owner.name()+"."+method.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),pops,c.types().slots(method.returnType()),call.span(),c);return true;
}
var struct=c.types().structs.get(owner.name());if(struct==null)return false;
var method=struct.methods().stream().filter(m->m.name().equals(member.memberName())&&parametersMatch(m.parameters(),call.arguments(),c) && returnMatches(m.returnType(),owner.name(),c)).findFirst().orElse(null);
@@ -1807,11 +1814,12 @@ final class PbsExecutableBodyLowerer {
if (expected.kind() == PbsAst.TypeRefKind.SELF) continue;
// Contextual expressions have already been disambiguated by static semantics.
if (actual == null || arguments.get(i) instanceof PbsAst.ArrayLiteralExpr
|| arguments.get(i) instanceof PbsAst.NoneExpr) continue;
|| arguments.get(i) instanceof PbsAst.NoneExpr
|| arguments.get(i) instanceof PbsAst.NewExpr allocation
&& allocation.typeName().equals("array") && allocation.explicitType() == null) continue;
if (c.types().shapeKey(actual).equals(c.types().shapeKey(expected))) continue;
if (arguments.get(i) instanceof PbsAst.IntLiteralExpr && "long".equals(c.types().canonical(expected))) continue;
if (c.types().contracts.containsKey(expected.name()) && c.types().implementations.stream().anyMatch(
impl -> impl.ownerName().equals(actual.name()) && impl.contractName().equals(expected.name()))) continue;
if (c.types().isContract(expected) && c.types().contractTypes.implementers(expected).contains(actual.name())) continue;
return false;
}
return true;
@@ -1826,7 +1834,7 @@ final class PbsExecutableBodyLowerer {
}
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
c.callableSignatureByCallableId().get(callableId).moduleId(),
name, callableId, null, null, pops, pushes, span));
c.callableSignatureByCallableId().get(callableId).callableName(), callableId, null, null, pops, pushes, span));
}
private void lowerServiceValue(String name,Span span,PbsExecutableLoweringContext c) {
@@ -24,7 +24,8 @@ public final class PbsExecutableCallableRegistryFactory {
final ModuleId moduleId,
final NameTable nameTable,
final Map<String, String> builtinCanonicalBySourceType,
final ReadOnlyList<PbsFrontendCompiler.ImportedCallableSurface> importedCallables) {
final ReadOnlyList<PbsFrontendCompiler.ImportedCallableSurface> importedCallables,
final PbsRuntimeTypes types) {
final var callableIdTable = new CallableTable();
final var callableIdsByNameAndArity = new HashMap<PbsCallableResolutionKey, List<CallableId>>();
final var callableIdByDeclaration = new HashMap<PbsLowerableCallable, CallableId>();
@@ -33,7 +34,7 @@ public final class PbsExecutableCallableRegistryFactory {
final var tupleProjectionByCallableId = new HashMap<CallableId, PbsTupleProjection>();
final var typeSurfaceTable = new TypeSurfaceTable();
final var callableShapeTable = new CallableShapeTable();
final var localCallables = collectLocalLowerableCallables(ast);
final var localCallables = collectLocalLowerableCallables(ast, types);
registerLocalCallables(
moduleId,
@@ -76,7 +77,7 @@ public final class PbsExecutableCallableRegistryFactory {
ReadOnlyList.wrap(callableSignatures));
}
private ReadOnlyList<PbsLowerableCallable> collectLocalLowerableCallables(final PbsAst.File ast) {
private ReadOnlyList<PbsLowerableCallable> collectLocalLowerableCallables(final PbsAst.File ast, PbsRuntimeTypes types) {
final var callables = new ArrayList<PbsLowerableCallable>();
var globals = new java.util.LinkedHashMap<String, PbsAst.GlobalDecl>();
for (var declaration : ast.topDecls()) if (declaration instanceof PbsAst.GlobalDecl global) globals.put(global.name(),global);
@@ -104,7 +105,7 @@ public final class PbsExecutableCallableRegistryFactory {
}
if (topDecl instanceof PbsAst.ImplementsDecl implementation) {
for (var method : implementation.methods()) callables.add(new PbsLowerableCallable(
implementation.ownerName()+".$impl."+implementation.contractName()+"."+method.name(),
types.implementationCallableName(implementation, method.name()),
withReceiver(method,implementation.ownerName(),implementation.binderName())));
}
if (!(topDecl instanceof PbsAst.ServiceDecl serviceDecl)) {
@@ -200,7 +201,7 @@ public final class PbsExecutableCallableRegistryFactory {
for (final var importedCallable : importedCallables) {
final var callableId = callableIdTable.register(
importedCallable.moduleId(),
importedCallable.callableName(),
importedCallable.targetName(),
importedCallable.arity(),
importedCallable.shapeSurface());
callableIdsByNameAndArity
@@ -111,8 +111,9 @@ final class PbsExecutableLoweringContext {
.collect(java.util.stream.Collectors.joining(",")) + ")->";
var output = returnType == null || returnType.kind() == p.studio.compiler.pbs.ast.PbsAst.TypeRefKind.UNIT
? "unit" : formatter.typeSurfaceKey(returnType);
var importedIds = callableIdsByNameAndArity().getOrDefault(new PbsCallableResolutionKey(nameTable().register(name), parameterTypes.size()), java.util.List.of());
var candidates = callableSignatureByCallableId().entrySet().stream().filter(entry ->
entry.getValue().callableName().equals(name) && entry.getValue().arity() == parameterTypes.size()
importedIds.contains(entry.getKey()) && entry.getValue().arity() == parameterTypes.size()
&& normalizeShape(entry.getValue().typeShape()).equals(normalizeShape(inputs + output))).toList();
if (candidates.size() == 1) return candidates.getFirst().getKey();
return null;
@@ -121,7 +122,7 @@ final class PbsExecutableLoweringContext {
private String normalizeShape(String shape) {
var normalized = shape.replace(" ", "");
for (var alias : types().aliases.entrySet()) normalized = normalized.replaceAll(
"simple:" + java.util.regex.Pattern.quote(alias.getKey()) + "(?=[,()])",
"simple:" + java.util.regex.Pattern.quote(alias.getKey()) + "(?=[<>,()]|$)",
java.util.regex.Matcher.quoteReplacement("simple:" + alias.getValue()));
return normalized;
}
@@ -46,7 +46,7 @@ public final class PbsExecutableLoweringService {
normalizedModuleId,
nameTable,
metadataIndex.builtinCanonicalBySourceType(),
importedCallables);
importedCallables, metadataIndex.types());
for (var entry : callableRegistry.callableSignatureByCallableId().entrySet()) {
var signature = metadataIndex.types().signatures.get(entry.getValue().callableName()+"#"+entry.getValue().arity());
if (signature != null) callableRegistry.returnSlotsByCallableId().put(entry.getKey(), signature.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(signature.returnType()) : 0);
@@ -60,10 +60,10 @@ public final class PbsExecutableLoweringService {
}
for (var implementation : metadataIndex.types().implementations) {
var methods = new ArrayList<p.studio.compiler.source.identifiers.CallableId>();
var contract = metadataIndex.types().contracts.get(implementation.contractName());
var contract = metadataIndex.types().contract(implementation.contractType());
for (var signature : contract.signatures()) {
var candidates = callableRegistry.localCallables().stream().filter(callable ->
callable.callableName().equals(implementation.ownerName()+".$impl."+implementation.contractName()+"."+signature.name())
callable.callableName().equals(metadataIndex.types().implementationCallableName(implementation, signature.name()))
&& callable.functionDecl().parameters().size()==signature.parameters().size()+1
&& metadataIndex.types().shapeKey(callable.functionDecl().returnType()).equals(metadataIndex.types().shapeKey(signature.returnType()))
&& java.util.stream.IntStream.range(0, signature.parameters().size()).allMatch(i ->
@@ -73,9 +73,9 @@ public final class PbsExecutableLoweringService {
methods.add(callableRegistry.callableIdByDeclaration().get(candidates.getFirst()));
}
metadataIndex.types().runtimeImplementations.add(new p.studio.compiler.models.registry.IRRegistry.Implementation(
"pbs:impl:"+metadataIndex.types().key(PbsRuntimeTypes.type(implementation.ownerName()))+":"+metadataIndex.types().key(PbsRuntimeTypes.type(implementation.contractName())),
"pbs:impl:"+metadataIndex.types().key(PbsRuntimeTypes.type(implementation.ownerName()))+":"+metadataIndex.types().key(implementation.contractType()),
metadataIndex.types().registryType(PbsRuntimeTypes.type(implementation.ownerName())),
metadataIndex.types().registryType(PbsRuntimeTypes.type(implementation.contractName())),ReadOnlyList.wrap(methods)));
metadataIndex.types().registryType(implementation.contractType()),ReadOnlyList.wrap(methods)));
}
final var intrinsicIdTable = new IntrinsicTable();
final var executableFunctions = new ArrayList<IRBackendExecutableFunction>(callableRegistry.localCallables().size());
@@ -22,17 +22,20 @@ final class PbsRuntimeTypes {
private final Map<String, IRRegistry.TypeDeclaration> used = new TreeMap<>();
final Map<String, PbsAst.StructDecl> structs = new LinkedHashMap<>();
final Map<String, PbsAst.ContractDecl> contracts = new LinkedHashMap<>();
final p.studio.compiler.pbs.PbsContractTypes contractTypes;
final Map<String, PbsAst.ServiceDecl> services = new LinkedHashMap<>();
final List<PbsAst.ImplementsDecl> implementations = new ArrayList<>();
final List<IRRegistry.Implementation> runtimeImplementations = new ArrayList<>();
PbsRuntimeTypes(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> supplemental, Map<String,String> builtins) {
builtinNames = builtins;
contractTypes = new p.studio.compiler.pbs.PbsContractTypes(ast, supplemental, p.studio.compiler.source.diagnostics.DiagnosticSink.empty());
for (var declaration : ast.topDecls()) if (declaration instanceof PbsAst.ImplementsDecl implementation)
implementations.add(implementation);
var declarations = new ArrayList<>(ast.topDecls().asList());
declarations.addAll(supplemental.asList());
for (var decl : declarations) {
if (decl instanceof PbsAst.TypeBindingDecl binding) decl = binding.declaration();
if (decl instanceof PbsAst.StructDecl s) {
structs.put(s.name(), s);
for (var f : s.methods()) addSignature(s.name()+"."+f.name(), f);
@@ -63,10 +66,23 @@ 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) {
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);
}
}
private void addSignature(String name, PbsAst.FunctionDecl f) {
signatures.put(name+"#"+f.parameters().size(), new PbsAst.FunctionSignature(f.name(), f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.span()));
}
boolean isContract(PbsAst.TypeRef type) { return contractTypes.isContract(unwrap(type)); }
PbsAst.ContractDecl contract(PbsAst.TypeRef type) {
var instance = contractTypes.resolve(unwrap(type));
return instance == null ? null : instance.declaration();
}
String implementationCallableName(PbsAst.ImplementsDecl implementation, String method) {
return contractTypes.implementationCallableName(implementation, method);
}
static PbsAst.TypeRef type(String name) { return PbsAst.TypeRef.simple(name, Span.none()); }
String canonical(PbsAst.TypeRef t) {
if(t==null) return "void";
@@ -78,7 +94,7 @@ final class PbsRuntimeTypes {
if(t==null || t.kind()==PbsAst.TypeRefKind.UNIT) return 0;
if(t.kind()==PbsAst.TypeRefKind.GROUP) return slots(t.inner());
if(t.kind()==PbsAst.TypeRefKind.NAMED_TUPLE) return t.fields().stream().mapToInt(f->slots(f.typeRef())).sum();
if (contracts.containsKey(canonical(t))) return 2;
if (isContract(t)) return 2;
return switch(canonical(t)) { case "vec2" -> 2; case "pixel" -> 3; default -> 1; };
}
static PbsAst.TypeRef unwrap(PbsAst.TypeRef t) {
@@ -92,9 +108,12 @@ 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 (structs.containsKey(t.name())) return nominalKey("struct", structs.get(t.name()).span());
if (services.containsKey(t.name())) return nominalKey("struct", services.get(t.name()).span());
if (contracts.containsKey(t.name())) return nominalKey("contract", contracts.get(t.name()).span());
if (contractTypes.declaration(t) instanceof PbsAst.StructDecl s) return nominalKey("struct", s.span());
if (contractTypes.declaration(t) instanceof PbsAst.ServiceDecl s) return nominalKey("struct", s.span());
if (isContract(t)) {
var nominal = nominalKey("contract", contractTypes.template(t).span());
return t.arguments().isEmpty() ? nominal : nominal + ":" + contractTypes.key(t);
}
return canonical(t);
}
String shapeKey(PbsAst.TypeRef type) {
@@ -148,28 +167,28 @@ final class PbsRuntimeTypes {
}
return ref;
}
if (structs.containsKey(t.name()) || services.containsKey(t.name())) {
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)));
var fields = new ArrayList<IRRegistry.NamedType>();
if (structs.containsKey(t.name())) for(var field : structs.get(t.name()).fields())
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))));
}
return ref;
}
if (contracts.containsKey(t.name())) {
if (isContract(t)) {
var ref = new IRRegistry.TypeRef(key(t));
if (!used.containsKey(ref.declarationKey())) {
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,canonical(t),new IRRegistry.Trait(null)));
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,contractTypes.display(t),new IRRegistry.Trait(null)));
var methods = new ArrayList<IRRegistry.Method>();
for (var method : contracts.get(t.name()).signatures()) {
for (var method : contract(t).signatures()) {
var args = new ArrayList<IRRegistry.NamedType>();
for(var arg : method.parameters()) for(var part : results(arg.typeRef())) args.add(new IRRegistry.NamedType(part,arg.name()));
methods.add(new IRRegistry.Method(method.name(),new IRRegistry.Signature(ReadOnlyList.wrap(args),ReadOnlyList.wrap(results(method.returnType())))));
}
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,canonical(t),new IRRegistry.Trait(ReadOnlyList.wrap(methods))));
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,contractTypes.display(t),new IRRegistry.Trait(ReadOnlyList.wrap(methods))));
}
return ref;
}
@@ -14,8 +14,6 @@ import java.util.ArrayList;
* Parser for `mod.barrel` files.
*/
public final class PbsBarrelParser {
private static final int MAX_NAMED_TUPLE_ARITY = 6;
private final PbsTokenCursor cursor;
private final FileId fileId;
private final DiagnosticSink diagnostics;
@@ -117,12 +115,16 @@ 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
? new PbsTypeParser(new PbsParserContext(cursor, fileId, diagnostics,
PbsParser.ParseMode.ORDINARY)).parseTypeParameters()
: ReadOnlyList.<PbsAst.TypeParameter>empty();
final var semicolon = consume(PbsTokenKind.SEMICOLON, "Expected ';' after barrel item");
final var itemSpan = span(visibilityToken.start(), semicolon.end());
return switch (kind) {
case STRUCT -> new PbsAst.BarrelStructItem(visibility, name.lexeme(), itemSpan);
case CONTRACT -> new PbsAst.BarrelContractItem(visibility, name.lexeme(), 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);
case ENUM -> new PbsAst.BarrelEnumItem(visibility, name.lexeme(), itemSpan);
@@ -185,7 +187,8 @@ public final class PbsBarrelParser {
final var resultToken = cursor.previous();
consume(PbsTokenKind.LESS, "Expected '<' after 'result'");
final var errorType = parseTypeRef();
consume(PbsTokenKind.GREATER, "Expected '>' after result error type");
new PbsTypeParser(new PbsParserContext(cursor, fileId, diagnostics,
PbsParser.ParseMode.INTERFACE_MODULE)).consumeTypeClose();
final PbsAst.TypeRef payloadType;
if (isTypeStart(cursor.peek().kind())) {
@@ -208,65 +211,8 @@ public final class PbsBarrelParser {
}
private PbsAst.TypeRef parseTypeRef() {
if (cursor.match(PbsTokenKind.OPTIONAL)) {
final var optionalToken = cursor.previous();
final var inner = parseTypeRef();
if (inner.kind() == PbsAst.TypeRefKind.UNIT) {
report(optionalToken, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE,
"'optional void' is not a valid type surface");
}
return PbsAst.TypeRef.optional(inner, span(optionalToken.start(), inner.span().getEnd()));
}
if (cursor.match(PbsTokenKind.VOID)) {
final var token = cursor.previous();
return PbsAst.TypeRef.unit(span(token.start(), token.end()));
}
if (cursor.match(PbsTokenKind.SELF)) {
final var token = cursor.previous();
return PbsAst.TypeRef.self(span(token.start(), token.end()));
}
if (cursor.match(PbsTokenKind.IDENTIFIER)) {
final var token = cursor.previous();
return PbsAst.TypeRef.simple(token.lexeme(), span(token.start(), token.end()));
}
if (cursor.match(PbsTokenKind.LEFT_PAREN)) {
final var open = cursor.previous();
if (cursor.match(PbsTokenKind.RIGHT_PAREN)) {
return PbsAst.TypeRef.unit(span(open.start(), cursor.previous().end()));
}
if (cursor.check(PbsTokenKind.IDENTIFIER) && cursor.checkNext(PbsTokenKind.COLON)) {
final var fields = new ArrayList<PbsAst.NamedTypeField>();
do {
final var label = consume(PbsTokenKind.IDENTIFIER, "Expected tuple field label");
consume(PbsTokenKind.COLON, "Expected ':' after tuple field label");
final var type = parseTypeRef();
fields.add(new PbsAst.NamedTypeField(label.lexeme(), type, span(label.start(), type.span().getEnd())));
if (fields.size() == MAX_NAMED_TUPLE_ARITY + 1) {
report(label, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE,
"Named tuple type arity must be between 1 and 6 fields");
}
} while (cursor.match(PbsTokenKind.COMMA) && !cursor.check(PbsTokenKind.RIGHT_PAREN));
final var close = consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after named tuple type");
return PbsAst.TypeRef.namedTuple(ReadOnlyList.wrap(fields), span(open.start(), close.end()));
}
final var inner = parseTypeRef();
final var close = consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after grouped type");
return PbsAst.TypeRef.group(inner, span(open.start(), close.end()));
}
final var token = cursor.peek();
report(token, ParseErrors.E_PARSE_EXPECTED_TOKEN, "Expected type surface");
if (!cursor.isAtEnd()) {
cursor.advance();
}
return PbsAst.TypeRef.error(span(token.start(), token.end()));
return new PbsTypeParser(new PbsParserContext(cursor, fileId, diagnostics,
PbsParser.ParseMode.INTERFACE_MODULE)).parseTypeRef();
}
private boolean isTypeStart(final PbsTokenKind kind) {
@@ -174,7 +174,7 @@ final class PbsDeclarationParser {
}
PbsAst.ImplementsDecl parseImplementsDeclaration(final PbsToken implementsToken) {
final var contractName = consume(PbsTokenKind.IDENTIFIER, "Expected contract name in 'implements'");
final var contractType = typeParser.parseTypeRef();
consume(PbsTokenKind.FOR, "Expected 'for' in 'implements' declaration");
final var ownerName = consume(PbsTokenKind.IDENTIFIER, "Expected owner name after 'for'");
consume(PbsTokenKind.USING, "Expected 'using' in 'implements' declaration");
@@ -201,7 +201,7 @@ final class PbsDeclarationParser {
}
return new PbsAst.ImplementsDecl(
contractName.lexeme(),
contractType,
ownerName.lexeme(),
binderName.lexeme(),
ReadOnlyList.wrap(methods),
@@ -425,6 +425,7 @@ final class PbsDeclarationParser {
final PbsToken declareToken,
final ReadOnlyList<PbsAst.Attribute> attributes) {
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected contract name");
final var typeParameters = typeParser.parseTypeParameters();
consume(PbsTokenKind.LEFT_BRACE, "Expected '{' to start contract body");
final var signatures = new ArrayList<PbsAst.FunctionSignature>();
while (!cursor.check(PbsTokenKind.RIGHT_BRACE) && !cursor.isAtEnd()) {
@@ -445,7 +446,7 @@ final class PbsDeclarationParser {
signatures.add(parseFunctionSignature(cursor.previous(), signatureAttributes));
}
final var rightBrace = consume(PbsTokenKind.RIGHT_BRACE, "Expected '}' to end contract body");
return new PbsAst.ContractDecl(name.lexeme(), ReadOnlyList.wrap(signatures), attributes, span(declareToken.start(), rightBrace.end()));
return new PbsAst.ContractDecl(name.lexeme(), typeParameters, ReadOnlyList.wrap(signatures), attributes, span(declareToken.start(), rightBrace.end()));
}
private PbsAst.ServiceDecl parseServiceDeclaration(
@@ -17,11 +17,13 @@ final class PbsExprParser {
private final PbsTokenCursor cursor;
private final PbsExprControlFlowParser controlFlowParser;
private final PbsExprPrimaryParser primaryParser;
private final PbsTypeParser typeParser;
PbsExprParser(
final PbsParserContext parserContext,
final BlockParserDelegate blockParserDelegate) {
this.context = new PbsExprParserContext(parserContext, blockParserDelegate);
this.typeParser = new PbsTypeParser(parserContext);
this.cursor = context.cursor();
this.controlFlowParser = new PbsExprControlFlowParser(context, this::parseExpression, this::parsePrecedenceExpression);
this.primaryParser = new PbsExprPrimaryParser(context, this::parseExpression, controlFlowParser::parseErrorPath);
@@ -119,11 +121,11 @@ final class PbsExprParser {
private PbsAst.Expression parseAs() {
var expression = parseTerm();
if (cursor.match(PbsTokenKind.AS)) {
final var contract = context.consume(PbsTokenKind.IDENTIFIER, "Expected contract identifier after 'as'");
final var contract = typeParser.parseTypeRef();
expression = new PbsAst.AsExpr(
expression,
contract.lexeme(),
span(expression.span().getStart(), contract.end()));
contract,
span(expression.span().getStart(), contract.span().getEnd()));
}
return expression;
}
@@ -231,6 +231,23 @@ final class PbsExprPrimaryParser {
private PbsAst.Expression parseNewExpression(final PbsToken newToken) {
final var typeName = context.consume(PbsTokenKind.IDENTIFIER, "Expected type name after 'new'");
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 closeType = types.consumeTypeClose();
explicitType = PbsAst.TypeRef.array(element, context.span(typeName.start(), closeType.end()));
}
}
String ctorName = null;
if (cursor.match(PbsTokenKind.DOT)) {
ctorName = context.consume(PbsTokenKind.IDENTIFIER, "Expected constructor name after '.' in new target").lexeme();
@@ -248,6 +265,8 @@ final class PbsExprPrimaryParser {
typeName.lexeme(),
ctorName,
ReadOnlyList.wrap(arguments),
explicitType,
diamond,
context.span(newToken.start(), close.end()));
}
@@ -25,6 +25,25 @@ final class PbsTokenCursor {
}
}
/** Peel one type closer without changing expression tokenization. */
PbsToken consumeTypeClose() {
var token = peek();
if (!token.lexeme().startsWith(">")) return null;
if (token.lexeme().equals(">")) return advance();
var rest = token.lexeme().substring(1);
var kind = switch (rest) {
case "=" -> PbsTokenKind.EQUAL;
case ">" -> PbsTokenKind.GREATER;
case ">=" -> PbsTokenKind.GREATER_EQUAL;
default -> null;
};
if (kind == null) return null;
var close = new PbsToken(PbsTokenKind.GREATER, ">", token.start(), token.start() + 1);
tokens.set(current, close);
tokens.add(current + 1, new PbsToken(kind, rest, token.start() + 1, token.end()));
return advance();
}
/**
* Consumes the next token if it matches any provided kind.
*/
@@ -86,30 +86,20 @@ final class PbsTypeParser {
}
if (cursor.check(PbsTokenKind.IDENTIFIER) && cursor.peek().lexeme().equals("array")) {
final var start = cursor.advance();
int depth = 1;
if (cursor.match(PbsTokenKind.LEFT_BRACKET)) {
final var number = consume(PbsTokenKind.INT_LITERAL, "Array depth must be a positive integer literal");
try { depth = Integer.parseInt(number.lexeme()); }
catch (NumberFormatException invalid) { depth = 0; }
if (depth < 1) {
context.report(number, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE, "Array depth must be a positive integer literal");
depth = 1;
}
consume(PbsTokenKind.RIGHT_BRACKET, "Expected ']' after array depth");
if (!cursor.match(PbsTokenKind.LESS)) {
context.report(cursor.peek(), ParseErrors.E_PARSE_INVALID_TYPE_SURFACE,
"Array types use array<T>; legacy array T and array[N] T are not supported");
return PbsAst.TypeRef.error(context.span(start.start(), start.end()));
}
if (depth > MAX_TYPE_DEPTH - typeDepth) {
context.report(start, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE, "Array depth exceeds compiler type nesting limit of " + MAX_TYPE_DEPTH);
depth = 1;
var inner = parseTypeRef();
var close = consumeTypeClose();
if (cursor.check(PbsTokenKind.LEFT_BRACKET)) {
context.report(cursor.peek(), ParseErrors.E_PARSE_INVALID_TYPE_SURFACE,
"Nested arrays use array<array<T>>, not array<T>[N]");
}
typeDepth += depth - 1;
PbsAst.TypeRef inner;
try { inner = parseTypeRef(); }
finally { typeDepth -= depth - 1; }
for (int level = 0; level < depth; level++) {
inner = PbsAst.TypeRef.array(inner, context.span(start.start(), inner.span().getEnd()));
}
return inner;
return PbsAst.TypeRef.array(inner, context.span(start.start(), close.end()));
}
if (cursor.match(PbsTokenKind.OPTIONAL)) {
final var optionalToken = cursor.previous();
final var inner = parseTypeRef();
@@ -132,6 +122,15 @@ final class PbsTypeParser {
if (cursor.match(PbsTokenKind.IDENTIFIER)) {
final var token = cursor.previous();
if (cursor.match(PbsTokenKind.LESS)) {
var arguments = new ArrayList<PbsAst.TypeRef>();
if (!cursor.check(PbsTokenKind.GREATER) && !cursor.check(PbsTokenKind.GREATER_EQUAL)) {
do { arguments.add(parseTypeRef()); } while (cursor.match(PbsTokenKind.COMMA));
} else context.report(cursor.peek(), ParseErrors.E_PARSE_INVALID_TYPE_SURFACE, "Contract type arguments must be explicit and nonempty");
var close = consumeTypeClose();
return PbsAst.TypeRef.applied(token.lexeme(), p.studio.utilities.structures.ReadOnlyList.wrap(arguments),
context.span(token.start(), close.end()));
}
return PbsAst.TypeRef.simple(token.lexeme(), context.span(token.start(), token.end()));
}
@@ -167,7 +166,7 @@ final class PbsTypeParser {
final var resultToken = cursor.previous();
consume(PbsTokenKind.LESS, "Expected '<' after 'result'");
final var errorType = parseTypeRef();
consume(PbsTokenKind.GREATER, "Expected '>' after result error type");
consumeTypeClose();
final PbsAst.TypeRef payloadType;
if (isTypeStart(cursor.peek().kind())) {
@@ -215,6 +214,32 @@ final class PbsTypeParser {
|| kind == PbsTokenKind.LEFT_PAREN;
}
PbsAst.TypeRef parseArrayElementType() {
// Count the constructor's outer array just as an annotated array type.
typeDepth++;
try { return parseTypeRef(); }
finally { typeDepth--; }
}
PbsToken consumeTypeClose() {
var close = cursor.consumeTypeClose();
if (close != null) return close;
var token = cursor.peek();
context.report(token, ParseErrors.E_PARSE_EXPECTED_TOKEN, "Expected '>' after type argument");
return new PbsToken(PbsTokenKind.GREATER, "", token.start(), token.start());
}
p.studio.utilities.structures.ReadOnlyList<PbsAst.TypeParameter> parseTypeParameters() {
var parameters = new ArrayList<PbsAst.TypeParameter>();
if (!cursor.match(PbsTokenKind.LESS)) return p.studio.utilities.structures.ReadOnlyList.empty();
do {
var token = consume(PbsTokenKind.IDENTIFIER, "Expected type parameter name");
parameters.add(new PbsAst.TypeParameter(token.lexeme(), context.span(token.start(), token.end())));
} while (cursor.match(PbsTokenKind.COMMA));
consumeTypeClose();
return p.studio.utilities.structures.ReadOnlyList.wrap(parameters);
}
private PbsToken consume(final PbsTokenKind kind, final String message) {
if (cursor.check(kind)) {
return cursor.advance();
@@ -298,9 +298,9 @@ final class PbsAstDocumentSymbols {
return switch (typeRef.kind()) {
case UNIT -> typeRef.name() == null || typeRef.name().isBlank() ? "void" : typeRef.name();
case SELF -> "Self";
case SIMPLE -> typeRef.name() == null ? "void" : typeRef.name();
case SIMPLE -> typeRef.name() == null ? "void" : typeRef.surface();
case FN -> "Fn(" + typeRef.fields().stream().map(f -> formatTypeRef(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + formatTypeRef(typeRef.inner());
case ARRAY -> "array " + formatTypeRef(typeRef.inner());
case ARRAY -> "array<" + formatTypeRef(typeRef.inner()) + ">";
case OPTIONAL -> "optional " + formatTypeRef(typeRef.inner());
case GROUP -> "(" + formatTypeRef(typeRef.inner()) + ")";
case NAMED_TUPLE -> {
@@ -218,7 +218,7 @@ public final class PbsBuiltinLayoutResolver {
case SIMPLE -> typeRef.name();
case SELF -> "Self";
case FN -> "Fn(" + typeRef.fields().stream().map(f -> renderTypeSurface(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + renderTypeSurface(typeRef.inner());
case ARRAY -> "array %s".formatted(renderTypeSurface(typeRef.inner()));
case ARRAY -> "array<%s>".formatted(renderTypeSurface(typeRef.inner()));
case OPTIONAL -> "optional %s".formatted(renderTypeSurface(typeRef.inner()));
case UNIT -> "void";
case GROUP -> "(%s)".formatted(renderTypeSurface(typeRef.inner()));
@@ -67,6 +67,8 @@ public final class PbsEditorialSupportService {
}
final var scopeState = context.scopeStateAt(offset);
final var token = context.token(tokenIndex);
var generic = context.genericHover(token.lexeme(), offset);
if (generic.isPresent()) return generic;
final Integer previousTokenIndex = context.previousSignificantTokenIndex(tokenIndex);
if (previousTokenIndex != null && context.token(previousTokenIndex).kind() == PbsTokenKind.DOT) {
final TypeView receiverType = context.resolveReceiverTypeBeforeDot(previousTokenIndex, scopeState);
@@ -414,7 +416,10 @@ public final class PbsEditorialSupportService {
final String localName = item.alias() == null || item.alias().isBlank()
? item.name()
: item.alias();
final PbsAst.TopDecl target = findSupplementalTopDecl(item.name(), expandedSupplementals);
final PbsAst.TopDecl target = expandedSupplementals.stream()
.filter(d -> d instanceof PbsAst.TypeBindingDecl b && b.name().equals(localName) && b.span().getFileId().equals(ast.span().getFileId()))
.map(d -> ((PbsAst.TypeBindingDecl) d).declaration()).findFirst()
.orElseGet(() -> findSupplementalTopDecl(item.name(), expandedSupplementals));
if (target == null) {
continue;
}
@@ -765,7 +770,7 @@ public final class PbsEditorialSupportService {
});
final Map<String, List<CallableSymbol>> methods = receiverType.kind() == Kind.SERVICE
? Optional.ofNullable(model.services.get(receiverType.name())).map(ServiceInfo::methods).orElse(Map.of())
: Optional.ofNullable(model.contracts.get(receiverType.name())).map(ContractInfo::methods).orElse(Map.of());
: Optional.ofNullable(model.contractInfo(receiverType)).map(ContractInfo::methods).orElse(Map.of());
for (final var method : methods.entrySet()) {
completions.put(method.getKey(), new PbsEditorialCompletionCandidate(
method.getKey(),
@@ -877,7 +882,7 @@ public final class PbsEditorialSupportService {
List.of(), Model.documentationFromAttributes(constant.attributes())));
final Map<String, List<CallableSymbol>> methods = receiverType.kind() == Kind.SERVICE
? Optional.ofNullable(model.services.get(receiverType.name())).map(ServiceInfo::methods).orElse(Map.of())
: Optional.ofNullable(model.contracts.get(receiverType.name())).map(ContractInfo::methods).orElse(Map.of());
: Optional.ofNullable(model.contractInfo(receiverType)).map(ContractInfo::methods).orElse(Map.of());
final List<CallableSymbol> signatures = methods.get(memberName);
if (signatures != null && !signatures.isEmpty()) {
return Optional.of(new PbsEditorialResolvedSymbol(
@@ -899,6 +904,8 @@ public final class PbsEditorialSupportService {
}
final var scopeState = scopeStateAt(offset);
final var token = token(tokenIndex);
var parameter = typeParameterAt(token.lexeme(), offset);
if (parameter != null) return List.of(new PbsEditorialLocation(parameter.span()));
final Integer previousTokenIndex = previousSignificantTokenIndex(tokenIndex);
if (previousTokenIndex != null && token(previousTokenIndex).kind() == PbsTokenKind.DOT) {
final TypeView receiverType = resolveReceiverTypeBeforeDot(previousTokenIndex, scopeState);
@@ -907,6 +914,51 @@ public final class PbsEditorialSupportService {
return resolveSymbolDefinition(token.lexeme(), tokenIndex, scopeState, offset);
}
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)) {
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));
if (found[0]) return parameter;
}
}
return null;
}
private void findTypeAt(PbsAst.TypeRef type, String name, long offset, boolean[] found) {
if (type == null) return;
if (type.kind() == PbsAst.TypeRefKind.SIMPLE && type.name().equals(name)
&& type.span().getStart() <= offset && offset < type.span().getStart() + name.length()) found[0] = true;
findTypeAt(type.inner(), name, offset, found);
type.arguments().forEach(t -> findTypeAt(t, name, offset, found));
type.fields().forEach(f -> findTypeAt(f.typeRef(), name, offset, found));
}
private Optional<PbsEditorialResolvedSymbol> 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(), ""));
var references = new ArrayList<PbsAst.TypeRef>();
for (var declaration : ast.topDecls()) p.studio.compiler.pbs.ast.PbsTypeTraversal.visit(declaration, references::add);
var pending = new ArrayDeque<>(references);
while (!pending.isEmpty()) {
var reference = pending.removeFirst();
if (reference.kind() == PbsAst.TypeRefKind.SIMPLE && reference.name().equals(name) && !reference.arguments().isEmpty()
&& reference.span().getStart() <= offset && offset < reference.span().getStart() + name.length()
&& model.contractTypes.isContract(reference)) {
var instance = model.contractTypes.resolve(reference);
if (instance != null) return Optional.of(new PbsEditorialResolvedSymbol(instance.declaration().name(), PbsEditorialSymbolKind.CONTRACT,
"contract " + instance.declaration().name(), "contract", signaturesForTopDecl(instance.declaration()),
Model.documentationFromAttributes(instance.declaration().attributes())));
}
if (reference.inner() != null) pending.add(reference.inner());
pending.addAll(reference.arguments().asList());
reference.fields().forEach(f -> pending.add(f.typeRef()));
}
return Optional.empty();
}
private List<PbsEditorialLocation> usagesMatching(final Set<String> identityKeys) {
if (identityKeys == null || identityKeys.isEmpty()) {
return List.of();
@@ -996,7 +1048,7 @@ public final class PbsEditorialSupportService {
if (constant != null) return locations(constant.span());
final Map<String, List<CallableSymbol>> methods = receiverType.kind() == Kind.SERVICE
? Optional.ofNullable(model.services.get(receiverType.name())).map(ServiceInfo::methods).orElse(Map.of())
: Optional.ofNullable(model.contracts.get(receiverType.name())).map(ContractInfo::methods).orElse(Map.of());
: Optional.ofNullable(model.contractInfo(receiverType)).map(ContractInfo::methods).orElse(Map.of());
return callableLocations(methods.get(memberName));
}
return List.of();
@@ -1423,9 +1475,9 @@ public final class PbsEditorialSupportService {
return switch (typeRef.kind()) {
case UNIT -> "unit";
case SELF -> "Self";
case SIMPLE -> typeRef.name();
case SIMPLE -> 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 ARRAY -> "array<" + formatTypeRef(typeRef.inner()) + ">";
case OPTIONAL -> formatTypeRef(typeRef.inner()) + "?";
case GROUP -> formatTypeRef(typeRef.inner());
case NAMED_TUPLE -> {
@@ -2051,7 +2103,15 @@ public final class PbsEditorialSupportService {
return null;
}
return switch (typeRef.kind()) {
case SIMPLE -> aliasedTypeRefs.getOrDefault(typeRef.name(), typeRef);
case SIMPLE -> {
var base = aliasedTypeRefs.getOrDefault(typeRef.name(), typeRef);
var origin = model.contractTypes.declaration(typeRef);
if (origin != null && topDeclName(origin) != null) {
base = PbsAst.TypeRef.simple(topDeclName(origin), origin.span());
}
yield typeRef.arguments().isEmpty() ? base : PbsAst.TypeRef.applied(base.name(),
ReadOnlyList.wrap(typeRef.arguments().stream().map(this::aliasExpandedTypeRef).toList()), base.span());
}
case FN -> PbsAst.TypeRef.function(ReadOnlyList.wrap(typeRef.fields().stream().map(f ->
new PbsAst.NamedTypeField(null, aliasExpandedTypeRef(f.typeRef()), f.span())).toList()),
aliasExpandedTypeRef(typeRef.inner()), typeRef.span());
@@ -2165,7 +2225,7 @@ public final class PbsEditorialSupportService {
return new PbsAst.HostDecl(newName, hostDecl.signatures(), hostDecl.attributes(), hostDecl.span());
}
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
return new PbsAst.ContractDecl(newName, contractDecl.signatures(), contractDecl.attributes(), contractDecl.span());
return new PbsAst.ContractDecl(newName, contractDecl.typeParameters(), contractDecl.signatures(), contractDecl.attributes(), contractDecl.span());
}
if (topDecl instanceof PbsAst.EnumDecl enumDecl) {
@@ -108,6 +108,18 @@ final class PbsFlowBodyAnalyzer {
validateFunction(functionDecl, model, diagnostics);
return;
}
if (topDecl instanceof PbsAst.ImplementsDecl implementation) {
var ownerType = typeOps.typeFromTypeRef(PbsAst.TypeRef.simple(implementation.ownerName(), implementation.span()), model, null);
for (var method : implementation.methods()) {
var parameters = new ArrayList<PbsAst.Parameter>();
parameters.add(new PbsAst.Parameter(implementation.binderName(), PbsAst.TypeRef.simple(implementation.ownerName(), implementation.span()), implementation.span()));
parameters.addAll(method.parameters().asList());
validateCallableBody(ReadOnlyList.wrap(parameters), method.body(), typeOps.callableReturnType(
method.returnKind(), method.returnType(), method.resultErrorType(), model), errorName(method.resultErrorType()),
ownerType, model, diagnostics);
}
return;
}
if (topDecl instanceof PbsAst.StructDecl structDecl) {
validateStruct(structDecl, model, diagnostics);
return;
@@ -238,7 +238,7 @@ final class PbsFlowCallableResolutionAnalyzer {
}
if (receiver.kind() == Kind.CONTRACT) {
final var contract = model.contracts.get(receiver.name());
final var contract = model.contractInfo(receiver);
if (contract == null) {
return ExprResult.type(TypeView.unknown());
}
@@ -68,7 +68,14 @@ final class PbsFlowSemanticSupport {
TypeView inner,
TypeView errorType,
List<TypeView> functionInputs,
TypeView functionOutput) {
TypeView functionOutput,
String nominalIdentity,
PbsAst.TypeRef sourceType,
Set<String> implementers) {
TypeView(Kind kind, String name, List<TupleField> tupleFields, TypeView inner, TypeView errorType,
List<TypeView> functionInputs, TypeView functionOutput) {
this(kind, name, tupleFields, inner, errorType, functionInputs, functionOutput, null, null, Set.of());
}
static TypeView unknown() {
return new TypeView(Kind.UNKNOWN, null, List.of(), null, null, List.of(), null);
}
@@ -190,6 +197,7 @@ final class PbsFlowSemanticSupport {
}
static final class Model {
p.studio.compiler.pbs.PbsContractTypes contractTypes;
final Map<String, List<CallableSymbol>> topLevelCallables = new HashMap<>();
final Map<String, StructInfo> structs = new HashMap<>();
final Map<String, ServiceInfo> services = new HashMap<>();
@@ -219,6 +227,8 @@ final class PbsFlowSemanticSupport {
final FESurfaceContext feSurfaceContext,
final DiagnosticSink diagnostics) {
final var model = new Model();
model.contractTypes = new p.studio.compiler.pbs.PbsContractTypes(ast, supplementalTopDecls, diagnostics);
model.contractTypes.validate(ast);
for (final var topDecl : ast.topDecls()) {
model.registerKnownTopDecl(topDecl);
}
@@ -233,13 +243,37 @@ final class PbsFlowSemanticSupport {
}
for (var imported : ast.imports()) for (var item : imported.items()) {
if (item.alias() == null || item.alias().isBlank() || !model.services.containsKey(item.name())) continue;
model.services.put(item.alias(), model.services.get(item.name()));
model.serviceSingletons.put(item.alias(), TypeView.service(item.name()));
model.services.putIfAbsent(item.alias(), model.services.get(item.name()));
model.serviceSingletons.put(item.alias(), model.withIdentity(TypeView.service(item.alias()), PbsAst.TypeRef.simple(item.alias(), item.span())));
}
model.ingestAssetSurface(feSurfaceContext, diagnostics);
return model;
}
ContractInfo contractInfo(TypeView type) {
return contracts.get(type.nominalIdentity() == null ? type.name() : type.nominalIdentity());
}
TypeView withIdentity(TypeView type, PbsAst.TypeRef reference) {
if (contractTypes.declaration(reference) == null) return type;
return new TypeView(type.kind(), type.name(), type.tupleFields(), type.inner(), type.errorType(),
type.functionInputs(), type.functionOutput(), contractTypes.key(reference), reference, type.implementers());
}
TypeView contractView(PbsAst.TypeRef reference) {
var instance = contractTypes.resolve(reference);
if (instance == null) return TypeView.unknown();
if (!contracts.containsKey(instance.key())) {
var methods = new HashMap<String, List<CallableSymbol>>();
contracts.put(instance.key(), new ContractInfo(methods));
for (var signature : instance.declaration().signatures()) methods.computeIfAbsent(signature.name(), ignored -> new ArrayList<>())
.add(callableFrom(signature.name(), signature.parameters(), signature.returnKind(), signature.returnType(),
signature.resultErrorType(), signature.span(), documentationFromAttributes(signature.attributes())));
}
return new TypeView(Kind.CONTRACT, contractTypes.display(reference), List.of(), null, null, List.of(), null,
instance.key(), reference, contractTypes.implementers(reference));
}
boolean isOpaqueBuiltin(TypeView type) {
if (type == null || !knownBuiltinTypeNames.contains(type.name())) return false;
var declaration = structs.get(type.name());
@@ -247,6 +281,16 @@ final class PbsFlowSemanticSupport {
}
private void registerKnownTopDecl(final PbsAst.TopDecl topDecl) {
if (topDecl instanceof PbsAst.TypeBindingDecl binding) {
registerKnownTopDecl(binding.declaration());
if (binding.declaration() instanceof PbsAst.ContractDecl) knownContractNames.add(binding.name());
if (binding.declaration() instanceof PbsAst.StructDecl || binding.declaration() instanceof PbsAst.BuiltinTypeDecl) knownStructNames.add(binding.name());
if (binding.declaration() instanceof PbsAst.BuiltinTypeDecl) knownBuiltinTypeNames.add(binding.name());
if (binding.declaration() instanceof PbsAst.ServiceDecl) knownServiceNames.add(binding.name());
if (binding.declaration() instanceof PbsAst.EnumDecl) knownEnumNames.add(binding.name());
if (binding.declaration() instanceof PbsAst.ErrorDecl) knownErrorNames.add(binding.name());
return;
}
if (topDecl instanceof PbsAst.StructDecl structDecl) {
knownStructNames.add(structDecl.name());
return;
@@ -280,6 +324,24 @@ final class PbsFlowSemanticSupport {
}
private void ingestTopDecl(final PbsAst.TopDecl topDecl) {
if (topDecl instanceof PbsAst.TypeBindingDecl binding) {
ingestTopDecl(binding.declaration());
if (binding.declaration() instanceof PbsAst.StructDecl s) structs.put(binding.name(), structs.get(s.name()));
if (binding.declaration() instanceof PbsAst.BuiltinTypeDecl b) structs.put(binding.name(), structs.get(b.name()));
if (binding.declaration() instanceof PbsAst.EnumDecl e) enums.put(binding.name(), enums.get(e.name()));
if (binding.declaration() instanceof PbsAst.ErrorDecl e) errors.put(binding.name(), errors.get(e.name()));
if (binding.declaration() instanceof PbsAst.ServiceDecl s) {
services.put(binding.name(), services.get(s.name()));
serviceSingletons.put(binding.name(), withIdentity(TypeView.service(binding.name()), PbsAst.TypeRef.simple(binding.name(), binding.span())));
for (var constant : s.constants()) {
var original = s.name() + "." + constant.name();
var alias = binding.name() + "." + constant.name();
constTypes.put(alias, constTypes.get(original));
serviceConstants.put(alias, constant);
}
}
return;
}
if (topDecl instanceof PbsAst.StructDecl structDecl) {
final var fields = new HashMap<String, StructFieldInfo>();
for (final var field : structDecl.fields()) {
@@ -351,7 +413,7 @@ final class PbsFlowSemanticSupport {
serviceConstants.put(key, constant);
}
services.put(serviceDecl.name(), new ServiceInfo(methods));
serviceSingletons.put(serviceDecl.name(), TypeView.service(serviceDecl.name()));
serviceSingletons.put(serviceDecl.name(), withIdentity(TypeView.service(serviceDecl.name()), PbsAst.TypeRef.simple(serviceDecl.name(), serviceDecl.span())));
return;
}
if (topDecl instanceof PbsAst.HostDecl hostDecl) {
@@ -373,6 +435,7 @@ final class PbsFlowSemanticSupport {
return;
}
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
if (!contractDecl.typeParameters().isEmpty()) return;
final var methods = new HashMap<String, List<CallableSymbol>>();
for (final var signature : contractDecl.signatures()) {
methods.computeIfAbsent(signature.name(), ignored -> new ArrayList<>())
@@ -551,6 +614,7 @@ final class PbsFlowSemanticSupport {
case UNIT -> TypeView.unit();
case SELF, ERROR -> TypeView.unknown();
case SIMPLE -> {
if (contractTypes.isContract(typeRef)) yield contractView(typeRef);
if ("long".equals(typeRef.name())) {
yield TypeView.longType();
}
@@ -570,13 +634,13 @@ final class PbsFlowSemanticSupport {
yield TypeView.addressable(typeRef.name());
}
if (structs.containsKey(typeRef.name()) || knownStructNames.contains(typeRef.name())) {
yield TypeView.struct(typeRef.name());
yield withIdentity(TypeView.struct(typeRef.name()), typeRef);
}
if (services.containsKey(typeRef.name()) || knownServiceNames.contains(typeRef.name())) {
yield TypeView.service(typeRef.name());
yield withIdentity(TypeView.service(typeRef.name()), typeRef);
}
if (contracts.containsKey(typeRef.name()) || knownContractNames.contains(typeRef.name())) {
yield TypeView.contract(typeRef.name());
yield contractView(typeRef);
}
if (enums.containsKey(typeRef.name()) || knownEnumNames.contains(typeRef.name())) {
yield TypeView.enumType(typeRef.name());
@@ -586,7 +650,7 @@ final class PbsFlowSemanticSupport {
}
yield TypeView.unknown();
}
case FN -> TypeView.function("Fn", typeRef.fields().stream().map(f -> typeFrom(f.typeRef())).toList(), typeFrom(typeRef.inner()));
case FN -> TypeView.function("Fn", typeRef.fields().stream().map(f -> typeFrom(f.typeRef())).toList(), collapse(typeFrom(typeRef.inner())));
case ARRAY -> TypeView.array(typeFrom(typeRef.inner()));
case OPTIONAL -> TypeView.optional(typeFrom(typeRef.inner()));
case GROUP -> typeFrom(typeRef.inner());
@@ -116,9 +116,10 @@ final class PbsFlowStatementAnalyzer {
true,
this::analyzeNestedBlock);
if (expected != null && (expected.kind() == Kind.ARRAY || initializer.type().kind() == Kind.ARRAY
|| expected.kind() == Kind.FN || initializer.type().kind() == Kind.FN)
|| expected.kind() == Kind.FN || initializer.type().kind() == Kind.FN || expected.kind() == Kind.CONTRACT)
&& !typeOps.compatible(initializer.type(),expected)) {
Diagnostics.error(diagnostics,"E_SEM_ARRAY_TYPE_MISMATCH","Array assignment requires the exact element type",letStatement.span());
Diagnostics.error(diagnostics, expected.kind() == Kind.CONTRACT ? "E_SEM_CONTRACT_COERCION" : "E_SEM_ARRAY_TYPE_MISMATCH",
expected.kind() == Kind.CONTRACT ? "Initializer does not supply the selected contract application" : "Assignment requires the exact declared type",letStatement.span());
}
final var resolvedType = expected == null ? initializer.type() : expected;
scope.bind(letStatement.name(), resolvedType, !letStatement.isConst());
@@ -60,9 +60,20 @@ final class PbsFlowStructuralExpressionAnalyzer {
return ExprResult.type(TypeView.optional(receiver.inner()));
}
if (expression instanceof PbsAst.NewExpr allocation && allocation.typeName().equals("array")) {
final var array = requireArrayContext(expectedType, expression, context);
if (allocation.explicitType() != null) {
PbsTypeSurfaceSemanticsValidator.validateTypeSurfaceRecursive(
java.util.List.of(allocation.explicitType()), "array constructor", receiverType != null, diagnostics);
validateConstructionType(allocation.explicitType(), context);
}
final var array = allocation.explicitType() == null
? requireArrayContext(expectedType, expression, context)
: typeOps.typeFromTypeRef(allocation.explicitType(), model, receiverType);
if (expectedType != null && !typeOps.compatible(array, expectedType)) {
Diagnostics.error(diagnostics, "E_SEM_ARRAY_TYPE_MISMATCH",
"Array construction requires the exact expected element type", allocation.span());
}
if (allocation.ctorName() != null || allocation.arguments().size() != 1) {
Diagnostics.error(diagnostics, "E_SEM_ARRAY_CONSTRUCTION", "Use new array(length)", allocation.span());
Diagnostics.error(diagnostics, "E_SEM_ARRAY_CONSTRUCTION", "Use new array<T>(length), new array<>(length), or contextual new array(length)", allocation.span());
}
for (var length : allocation.arguments()) checkArrayIndex(length, context);
return ExprResult.type(array);
@@ -216,7 +227,7 @@ final class PbsFlowStructuralExpressionAnalyzer {
return ExprResult.type(TypeView.unknown());
}
if (model.structs.containsKey(newExpr.typeName())) {
return ExprResult.type(TypeView.struct(newExpr.typeName()));
return ExprResult.type(typeOps.typeFromTypeRef(PbsAst.TypeRef.simple(newExpr.typeName(), newExpr.span()), model, null));
}
return ExprResult.type(TypeView.unknown());
}
@@ -228,12 +239,15 @@ final class PbsFlowStructuralExpressionAnalyzer {
}
return ExprResult.type(typeOps.typeFromTypeRef(PbsAst.TypeRef.simple(asExpr.contractName(), asExpr.span()), model, null));
}
if (model.contracts.containsKey(asExpr.contractName())) {
if (model.contractTypes.isContract(asExpr.contractType())) {
if (model.isOpaqueBuiltin(source)) {
Diagnostics.error(diagnostics, "E_SEM_OPAQUE_BUILTIN_TYPE_MISMATCH",
"Opaque builtin references cannot adapt to contracts", asExpr.span());
}
return ExprResult.type(TypeView.contract(asExpr.contractName()));
var target = model.contractView(asExpr.contractType());
if (source.kind() != Kind.CONTRACT && !typeOps.compatible(source, target)) Diagnostics.error(diagnostics, "E_SEM_CONTRACT_COERCION",
"Source does not supply the selected contract implementation", asExpr.span());
return ExprResult.type(target);
}
return ExprResult.type(TypeView.unknown());
}
@@ -256,6 +270,16 @@ final class PbsFlowStructuralExpressionAnalyzer {
return null;
}
private void validateConstructionType(PbsAst.TypeRef type, PbsFlowExpressionContext context) {
if (type.kind() == PbsAst.TypeRefKind.SIMPLE
&& typeOps.typeFromTypeRef(type, context.model(), context.receiverType()).kind() == Kind.UNKNOWN) {
Diagnostics.error(context.diagnostics(), "E_SEM_ARRAY_ELEMENT_TYPE",
"Unknown array element type: " + type.name(), type.span());
}
if (type.inner() != null) validateConstructionType(type.inner(), context);
for (var field : type.fields()) validateConstructionType(field.typeRef(), context);
}
private TypeView requireArrayContext(TypeView expected, PbsAst.Expression expression, PbsFlowExpressionContext context) {
if (expected != null && expected.kind() == Kind.ARRAY) return expected;
Diagnostics.error(context.diagnostics(), "E_SEM_ARRAY_CONTEXT_REQUIRED",
@@ -45,12 +45,18 @@ final class PbsFlowTypeOps {
if (actual.kind() == Kind.UNKNOWN || expected.kind() == Kind.UNKNOWN) {
return true;
}
if (expected.kind() == Kind.CONTRACT && (actual.kind() == Kind.STRUCT || actual.kind() == Kind.SERVICE))
return expected.implementers().contains(actual.nominalIdentity() == null ? actual.name() : actual.nominalIdentity());
if (actual.kind() != expected.kind()) {
return false;
}
return switch (actual.kind()) {
case UNIT, INT, LONG, FLOAT, BOOL, STR -> true;
case STRUCT, SERVICE, CONTRACT, ENUM, ERROR, TYPE_REF, ASSET_NAMESPACE -> actual.name().equals(expected.name());
case CONTRACT -> actual.nominalIdentity() != null && expected.nominalIdentity() != null
? actual.nominalIdentity().equals(expected.nominalIdentity()) : actual.name().equals(expected.name());
case STRUCT, SERVICE, ENUM, ERROR -> actual.nominalIdentity() != null && expected.nominalIdentity() != null
? actual.nominalIdentity().equals(expected.nominalIdentity()) : actual.name().equals(expected.name());
case TYPE_REF, ASSET_NAMESPACE -> actual.name().equals(expected.name());
case FN -> actual.functionInputs().size() == expected.functionInputs().size()
&& java.util.stream.IntStream.range(0, actual.functionInputs().size()).allMatch(i ->
compatible(actual.functionInputs().get(i), expected.functionInputs().get(i)))
@@ -109,7 +115,8 @@ final class PbsFlowTypeOps {
return switch (typeRef.kind()) {
case UNIT -> TypeView.unit();
case SELF -> receiverType == null ? TypeView.unknown() : receiverType;
case SIMPLE -> simpleType(typeRef.name(), model);
case SIMPLE -> model.contractTypes.isContract(typeRef) ? model.contractView(receiverType == null ? typeRef : p.studio.compiler.pbs.PbsTypeSubstitution.replaceSelf(typeRef, receiverType.name()))
: model.withIdentity(simpleType(typeRef.name(), model), typeRef);
case FN -> TypeView.function("Fn", typeRef.fields().stream().map(f -> typeFromTypeRef(f.typeRef(), model, receiverType)).toList(),
collapseReturnPayload(typeFromTypeRef(typeRef.inner(), model, receiverType)));
case ARRAY -> TypeView.array(typeFromTypeRef(typeRef.inner(), model, receiverType));
@@ -23,7 +23,7 @@ final class PbsInlineHintSurfaceFormatter {
.collect(java.util.stream.Collectors.joining(", ")) + ") -> " + format(type.functionOutput());
case ARRAY -> {
final var inner = format(type.inner());
yield inner == null ? null : "array (" + inner + ")";
yield inner == null ? null : "array<" + inner + ">";
}
case OPTIONAL -> {
final var inner = format(type.inner());
@@ -21,6 +21,7 @@ final class PbsTypeSurfaceSemanticsValidator {
if (typeRef == null) {
continue;
}
pending.addAll(typeRef.arguments().asList());
switch (typeRef.kind()) {
case FN -> {
@@ -48,6 +48,24 @@ final class PbsImportedSemanticContextService {
for (final var entry : sourcesByModule.entrySet()) {
topDeclsByNameByModule.put(entry.getKey(), indexTopDeclsByName(entry.getValue()));
}
var moduleBySource = new HashMap<FileId, ModuleId>();
parsedSourceFiles.forEach(s -> moduleBySource.put(s.fileId(), s.moduleId()));
boolean exportedContractsChanged;
do {
exportedContractsChanged = false;
for (var source : parsedSourceFiles) for (var imported : source.ast().imports()) {
var target = moduleTable.register(new p.studio.compiler.source.tables.ModuleReference(imported.moduleRef().project(), imported.moduleRef().pathSegments()));
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) {
var candidates = localIndex.computeIfAbsent(importItemLocalName(item), ignored -> new ArrayList<>());
if (candidates.stream().noneMatch(d -> d.span().equals(declaration.span()))) {
candidates.add(declaration); exportedContractsChanged = true;
}
}
}
} while (exportedContractsChanged);
final var globalInfosByRef = indexGlobalInfos(sourcesByModule, topDeclsByNameByModule, moduleTable);
final Map<FileId, PbsImportedSemanticContext> contexts = new HashMap<>();
@@ -61,6 +79,15 @@ final class PbsImportedSemanticContextService {
var importedReservedMetadata = IRReservedMetadata.empty();
final var directlyVisibleGlobalRefs = new LinkedHashMap<String, PbsGlobalDependencySupport.GlobalRef>();
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(
new PbsAst.TypeBindingDecl(topDeclName(declaration), declaration, parsedSource.ast().span()), supplementalTopDecls, supplementalKeys);
if (declaration instanceof PbsAst.ImplementsDecl) appendSupplementalTopDecl(declaration, supplementalTopDecls, supplementalKeys);
}
}
for (final var importDecl : parsedSource.ast().imports()) {
final var moduleRef = importDecl.moduleRef();
final var importedModuleId = moduleTable.register(
@@ -83,24 +110,33 @@ final class PbsImportedSemanticContextService {
final var directDecls = importedTopDeclsByName.getOrDefault(importName, new ArrayList<>());
for (final var topDecl : directDecls) {
appendSupplementalTopDecl(topDecl, supplementalTopDecls, supplementalKeys);
appendTypeDependencyDecls(topDecl, importedTopDeclsByName, supplementalTopDecls, supplementalKeys);
if (isTypeDecl(topDecl)) 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)) {
appendSupplementalTopDecl(implementation, supplementalTopDecls, supplementalKeys);
appendTypeDependencyDecls(implementation, importedTopDeclsByName, supplementalTopDecls, supplementalKeys);
}
}
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
var accessor = p.studio.compiler.pbs.lowering.PbsExecutableCallableRegistryFactory.singletonAccessor(serviceDecl);
appendImportedCallable(importedCallables, importedCallableKeys,
new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId, serviceDecl.name()+".$instance", 0, 1,
accessor.returnKind(), accessor.returnType(), frontendCompiler.callableShapeSurfaceOf(accessor)));
new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId, localName+".$instance", 0, 1,
accessor.returnKind(), accessor.returnType(), frontendCompiler.callableShapeSurfaceOf(accessor), serviceDecl.name()+".$instance"));
for (final var method : serviceDecl.methods()) {
appendImportedCallable(
importedCallables,
importedCallableKeys,
new PbsFrontendCompiler.ImportedCallableSurface(
importedModuleId,
serviceDecl.name() + "." + method.name(),
localName + "." + method.name(),
method.parameters().size(),
returnSlotsFor(method),
method.returnKind(),
method.returnType(),
frontendCompiler.callableShapeSurfaceOf(method)));
frontendCompiler.callableShapeSurfaceOf(method), serviceDecl.name() + "." + method.name()));
}
continue;
}
@@ -114,7 +150,7 @@ final class PbsImportedSemanticContextService {
appendImportedCallable(importedCallables, importedCallableKeys,
new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId,localName+"."+method.name(),
executable.parameters().size(),returnSlotsFor(executable),executable.returnKind(),executable.returnType(),
frontendCompiler.callableShapeSurfaceOf(executable)));
frontendCompiler.callableShapeSurfaceOf(executable), structDecl.name()+"."+method.name()));
}
continue;
}
@@ -129,7 +165,7 @@ final class PbsImportedSemanticContextService {
returnSlotsFor(functionDecl),
functionDecl.returnKind(),
functionDecl.returnType(),
frontendCompiler.callableShapeSurfaceOf(functionDecl)));
frontendCompiler.callableShapeSurfaceOf(functionDecl), functionDecl.name()));
continue;
}
if (topDecl instanceof PbsAst.GlobalDecl globalDecl) {
@@ -170,6 +206,27 @@ final class PbsImportedSemanticContextService {
importedReservedMetadata));
}
// Preserve lexical bindings of provider signatures, including transitive imported aliases.
boolean changed;
do {
changed = false;
for (var source : parsedSourceFiles) {
var context = contexts.get(source.fileId());
var declarations = new ArrayList<>(context.supplementalTopDecls().asList());
var keys = new HashSet<String>();
declarations.forEach(d -> keys.add(topDeclKey(d)));
for (var imported : source.ast().imports()) {
var target = moduleTable.register(new p.studio.compiler.source.tables.ModuleReference(imported.moduleRef().project(), imported.moduleRef().pathSegments()));
for (var provider : sourcesByModule.getOrDefault(target, new ArrayList<>()))
for (var declaration : contexts.get(provider.fileId()).supplementalTopDecls())
if (declaration instanceof PbsAst.TypeBindingDecl && keys.add(topDeclKey(declaration))) {
declarations.add(declaration); changed = true;
}
}
if (declarations.size() != context.supplementalTopDecls().size()) contexts.put(source.fileId(), new PbsImportedSemanticContext(
ReadOnlyList.wrap(declarations), context.importedCallables(), context.importedGlobals(), context.importedReservedMetadata()));
}
} while (changed);
return contexts;
}
@@ -218,6 +275,12 @@ final class PbsImportedSemanticContextService {
private void collectReferencedTypeNames(
final PbsAst.TopDecl topDecl,
final ArrayDeque<String> sink) {
if (topDecl instanceof PbsAst.ImplementsDecl implementation) {
collectReferencedTypeNames(implementation.contractType(), sink);
sink.add(implementation.ownerName());
implementation.methods().forEach(m -> collectReferencedTypeNames(m, sink));
return;
}
if (topDecl instanceof PbsAst.StructDecl structDecl) {
for (final var field : structDecl.fields()) {
collectReferencedTypeNames(field.typeRef(), sink);
@@ -311,6 +374,7 @@ final class PbsImportedSemanticContextService {
if (typeRef == null) {
return;
}
for (var argument : typeRef.arguments()) collectReferencedTypeNames(argument, sink);
switch (typeRef.kind()) {
case SIMPLE -> {
final var simpleName = typeRef.name();
@@ -398,11 +462,17 @@ final class PbsImportedSemanticContextService {
}
private String topDeclKey(final PbsAst.TopDecl topDecl) {
if (topDecl instanceof PbsAst.TypeBindingDecl binding) return "binding:" + binding.span().getFileId().getId() + ":" + binding.name() + ":" + sourceKey(binding.declaration().span());
if (topDecl instanceof PbsAst.ImplementsDecl implementation) return "implementation:" + sourceKey(implementation.span());
final var declName = topDeclName(topDecl);
if (declName == null || declName.isBlank()) {
return null;
}
return topDecl.getClass().getSimpleName() + ":" + declName;
return topDecl.getClass().getSimpleName() + ":" + declName + ":" + sourceKey(topDecl.span());
}
private static String sourceKey(p.studio.compiler.source.Span span) {
return span.getFileId().getId() + ":" + span.getStart() + ":" + span.getEnd();
}
private String topDeclName(final PbsAst.TopDecl topDecl) {
@@ -5,7 +5,7 @@ declare struct ArrayExampleEnemy(pub mut hp: int) {
fn arrayExample() -> int {
let capacity: int = 3;
let enemies: array ArrayExampleEnemy = new array(capacity);
let enemies = new array<ArrayExampleEnemy>(capacity);
let enemy = new ArrayExampleEnemy(50);
enemies[1] = enemy;
@@ -15,7 +15,7 @@ fn arrayExample() -> int {
enemies.clear(1);
// Nested array allocation creates only the outer level.
let groups: array[2] int = new array(2);
let groups: array<array<int>> = new array<>(2);
groups[0] = [20, 22];
if let group = groups[0] {
let total = (group[0] else 0) + (group[1] else 0);
@@ -11,7 +11,7 @@ fn createExampleCounter(start: int) -> Fn() -> int {
fn closureExample() -> int {
let next = createExampleCounter(40);
let functions: array (Fn() -> int) = [next];
let functions: array<(Fn() -> int)> = [next];
if let action = functions[0] {
let first = action();
return action();
@@ -0,0 +1,18 @@
// The contract's element type is independent of the strategy receiver.
declare contract ExampleIdentity<T> {
fn hash(value: T) -> int;
fn equals(left: T, right: T) -> bool;
}
declare service ExampleIntIdentity {}
implements ExampleIdentity<int> for ExampleIntIdentity using strategy {
fn hash(value: int) -> int { return value; }
fn equals(left: int, right: int) -> bool { return left == right; }
}
fn contractExample() -> int {
let identity: ExampleIdentity<int> = ExampleIntIdentity;
if identity.equals(7, 7) { return identity.hash(42); }
return 0;
}
@@ -1,2 +1,3 @@
pub fn init() -> void;
pub fn frame() -> void;
pub fn contractExample() -> int;
@@ -0,0 +1,175 @@
package p.studio.compiler.pbs;
import org.junit.jupiter.api.Test;
import p.studio.compiler.models.IRBackendFile;
import p.studio.compiler.models.registry.IRRegistry;
import p.studio.compiler.pbs.lexer.PbsLexer;
import p.studio.compiler.pbs.parser.PbsBarrelParser;
import p.studio.compiler.pbs.ast.PbsAst;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.FileId;
import static org.junit.jupiter.api.Assertions.*;
class PbsGenericContractsTest {
private static final String IDENTITY = """
declare contract Identity<T> { fn hash(e: T) -> int; fn equals(a: T, b: T) -> bool; }
declare service IntIdentity {}
implements Identity<int> for IntIdentity using strategy {
fn hash(e: int) -> int { return e; }
fn equals(a: int, b: int) -> bool { return a == b; }
}
""";
private IRBackendFile compile(String source) {
var diagnostics = DiagnosticSink.empty();
var file = new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode() + ": " + d.getMessage()).toList().toString());
return file;
}
private void rejects(String source, String code) {
var diagnostics = DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals(code)), () -> diagnostics.stream().map(d -> d.getCode() + ": " + d.getMessage()).toList().toString());
}
@Test void explicitAndContextualApplicationsProduceConcreteTraits() {
var file = compile(IDENTITY + """
fn select(value: Identity<int>) -> Identity<int> { return value; }
fn demo() -> bool {
let identity: Identity<int> = IntIdentity;
let explicit = IntIdentity as Identity<int>;
return select(identity).equals(7, explicit.hash(7));
}
""");
var traits = file.registry().types().stream().filter(t -> t.body() instanceof IRRegistry.Trait).toList();
assertEquals(1, traits.size());
assertEquals("Identity<int>", traits.getFirst().name());
assertEquals(1, file.registry().implementations().size());
}
@Test void sameOwnerHasTwoIndependentApplications() {
var file = compile("""
declare contract Echo<T> { fn echo(value: T) -> T; }
declare service Strategy {}
implements Echo<int> for Strategy using s { fn echo(value: int) -> int { return value; } }
implements Echo<bool> for Strategy using s { fn echo(value: bool) -> bool { return value; } }
fn demo() -> int {
let ints: Echo<int> = Strategy;
let flags: Echo<bool> = Strategy;
if flags.echo(true) { return ints.echo(42); }
return 0;
}
""");
assertEquals(2, file.registry().implementations().size());
assertNotEquals(file.registry().implementations().get(0).trait(), file.registry().implementations().get(1).trait());
assertEquals(2, file.executableFunctions().stream().filter(f -> f.callableName().contains(".$impl.")).count());
}
@Test void multipleParametersAndComposedSignaturesAreSubstituted() {
compile("""
declare contract Convert<A, B> { fn convert(value: A) -> B; }
declare service Strategy {}
implements Convert<array<int>, (left: int, right: int)> for Strategy using s {
fn convert(value: array<int>) -> (left: int, right: int) { return (left: value[0] else 0, right: 2); }
}
fn demo() -> int {
let converter: Convert<array<int>, (left: int, right: int)> = Strategy;
let pair = converter.convert([40]);
return pair.left + pair.right;
}
""");
}
@Test void phantomArgumentsAndSharedArrayStorageRemainNominallyDistinct() {
var file = compile("""
declare contract Marker<T> {}
declare service Strategy {}
implements Marker<array<int>> for Strategy using s {}
implements Marker<array<bool>> for Strategy using s {}
fn demo() -> int {
let a: Marker<array<int>> = Strategy;
let b: Marker<array<bool>> = Strategy;
return 42;
}
""");
assertEquals(2, file.registry().types().stream().filter(t -> t.body() instanceof IRRegistry.Trait).count());
assertEquals(2, file.registry().implementations().size());
}
@Test void finiteRecursiveSignatureHasANominalAnchor() {
var file = compile("""
declare contract Node<T> { fn next() -> Node<T>; }
fn identity(value: Node<int>) -> Node<int> { return value; }
""");
assertEquals(1, file.registry().types().stream().filter(t -> t.body() instanceof IRRegistry.Trait).count());
}
@Test void expandingRecursiveSignatureIsDiagnosed() {
rejects("""
declare contract Growing<T> { fn next() -> Growing<array<T>>; }
fn use(value: Growing<int>) {}
""", "E_SEM_CONTRACT_EXPANSION");
}
@Test void finiteMutualApplicationsReuseTheirAnchors() {
var file = compile("""
declare contract Left<T> { fn next() -> Right<T>; }
declare contract Right<T> { fn next() -> Left<T>; }
fn identity(value: Left<int>) -> Left<int> { return value; }
""");
assertEquals(2, file.registry().types().stream().filter(t -> t.body() instanceof IRRegistry.Trait).count());
}
@Test void applicationsRequireExplicitExactArity() {
rejects("declare contract Identity<T> {} fn use(value: Identity) {}", "E_SEM_CONTRACT_ARITY");
rejects("declare contract Identity<T> {} fn use(value: Identity<int, bool>) {}", "E_SEM_CONTRACT_ARITY");
}
@Test void undeclaredAndDuplicateParametersAreRejected() {
rejects("declare contract Bad<T> { fn get(value: U); }", "E_SEM_CONTRACT_PARAMETER");
rejects("declare contract Bad<T, T> {}", "E_SEM_CONTRACT_PARAMETER");
}
@Test void invalidApplicationsAndImplementationsAreRejected() {
rejects("declare contract Echo<T> { fn echo(value: T) -> T; } declare service S {} implements Echo<int> for S using s {}", "E_SEM_CONTRACT_SIGNATURE");
rejects(IDENTITY + "implements Identity<int> for IntIdentity using s { fn hash(e: int) -> int { return e; } fn equals(a: int, b: int) -> bool { return true; } }", "E_SEM_CONTRACT_DUPLICATE_IMPLEMENTATION");
rejects("declare contract C<T> {} fn use(value: int<bool>) {}", "E_SEM_CONTRACT_ARGUMENT");
}
@Test void instantiatedContractsAreInvariant() {
rejects(IDENTITY + """
fn bad(value: Identity<bool>) { let wrong: Identity<int> = value; }
""", "E_SEM_CONTRACT_COERCION");
rejects(IDENTITY + "fn bad() { let wrong = IntIdentity as Identity<bool>; }", "E_SEM_CONTRACT_COERCION");
}
@Test void invalidPostSubstitutionArrayElementIsRejected() {
rejects("declare contract C<T> { fn accept(values: array<T>); } fn bad(value: C<optional int>) {}", "E_SEM_ARRAY_ELEMENT_TYPE");
}
@Test void composedPositionsKeepTheirExistingRestrictions() {
rejects("declare contract C<T> { fn accept(value: Fn(T) -> int); } fn bad(value: C<void>) {}", "E_SEM_FN_PARAMETER");
rejects("declare contract C<T> { fn get() -> optional T; } fn bad(value: C<void>) {}", "E_SEM_INVALID_OPTIONAL_VOID_TYPE_SURFACE");
rejects("declare contract C<T> {} fn bad(value: C<Self>) {}", "E_SEM_INVALID_SELF_CONTEXT");
}
@Test void functionReturnNormalizationDoesNotCreateAnotherApplication() {
compile("""
declare contract Marker<T> {}
declare service Strategy {}
implements Marker<Fn() -> int> for Strategy using s {}
fn demo() { let value: Marker<Fn() -> (value: int)> = Strategy; }
""");
}
@Test void barrelPreservesOrderedParameters() {
var diagnostics = DiagnosticSink.empty();
var fileId = new FileId(0);
var barrel = PbsBarrelParser.parse(PbsLexer.lex("pub contract Convert<A, B>;", fileId, diagnostics), fileId, diagnostics);
assertFalse(diagnostics.hasErrors());
var item = assertInstanceOf(PbsAst.BarrelContractItem.class, barrel.items().getFirst());
assertEquals(java.util.List.of("A", "B"), item.typeParameters().stream().map(PbsAst.TypeParameter::name).toList());
}
}
@@ -18,6 +18,27 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class PbsModuleVisibilityTest {
@Test void parameterizedExportsAndReexportsPreserveTheOriginalDeclaration() {
var diagnostics = DiagnosticSink.empty();
var next = new AtomicInteger(0);
var provider = module("app", "provider", List.of("declare contract Identity<T> {}"), "pub contract Identity<T>;", next, diagnostics);
var facade = module("app", "facade", List.of("import { Identity } from @app:provider;"), "pub contract Identity<T>;", next, diagnostics);
new PbsModuleVisibilityValidator().validate(ReadOnlyList.from(provider, facade), diagnostics);
assertTrue(!diagnostics.hasErrors(), diagnostics.stream().map(d -> d.getMessage()).toList().toString());
}
@Test void parameterizedBarrelArityAndOwnerModuleAreChecked() {
var diagnostics = DiagnosticSink.empty();
var next = new AtomicInteger(0);
var provider = module("app", "provider", List.of("declare contract Identity<T> {} declare service Strategy {}"),
"pub contract Identity; pub service Strategy;", next, diagnostics);
var consumer = module("app", "consumer", List.of("import { Identity, Strategy } from @app:provider; implements Identity<int> for Strategy using s {}"),
"", next, diagnostics);
new PbsModuleVisibilityValidator().validate(ReadOnlyList.from(provider, consumer), diagnostics);
assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals("E_LINK_CONTRACT_PARAMETERS")));
assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals("E_SEM_CONTRACT_OWNER_MODULE")));
}
@Test
void shouldReportMissingBarrelPerModule() {
final var diagnostics = DiagnosticSink.empty();
@@ -10,6 +10,18 @@ import static org.junit.jupiter.api.Assertions.*;
class PbsBarrelParserTest {
@Test
void parametricArraysAndFunctionsUseTheSharedTypeParser() {
var source = "pub fn make(a: array<array<int>>) -> array<Fn(int) -> int>;";
var diagnostics = DiagnosticSink.empty();
var id = new FileId(0);
var ast = PbsBarrelParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics);
assertFalse(diagnostics.hasErrors());
var function = (PbsAst.BarrelFunctionItem) ast.items().getFirst();
assertEquals(PbsAst.TypeRefKind.ARRAY, function.returnType().kind());
assertEquals(PbsAst.TypeRefKind.FN, function.returnType().inner().kind());
}
@Test
void shouldParseBarrelShapeWithFunctionReturnSurfaces() {
final var source = """
@@ -10,6 +10,55 @@ import static org.junit.jupiter.api.Assertions.*;
class PbsExprParserTest {
@Test
void typeCursorPeelsCompoundClosersAndPreservesRemainderSpans() {
var cursor = new PbsTokenCursor(p.studio.utilities.structures.ReadOnlyList.from(
new p.studio.compiler.pbs.lexer.PbsToken(p.studio.compiler.pbs.lexer.PbsTokenKind.GREATER_EQUAL, ">>=", 10, 13),
new p.studio.compiler.pbs.lexer.PbsToken(p.studio.compiler.pbs.lexer.PbsTokenKind.EOF, "", 13, 13)));
assertEquals(10, cursor.consumeTypeClose().start());
assertEquals(">=", cursor.peek().lexeme());
assertEquals(11, cursor.consumeTypeClose().start());
assertEquals(p.studio.compiler.pbs.lexer.PbsTokenKind.EQUAL, cursor.peek().kind());
assertEquals(12, cursor.peek().start());
assertEquals(13, cursor.peek().end());
assertNull(cursor.consumeTypeClose());
}
@Test
void parametricArraysPreserveArgumentsSpansAndContextualForms() {
var source = "fn main() { let a: array<array<int>>=new array<array<int>>(2); "
+ "let b: array<int>=new array<>(2); let c: array<int>=new array(2); let cmp = 2 >= 1; }";
var diagnostics = DiagnosticSink.empty();
var id = new FileId(0);
var ast = PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics);
assertFalse(diagnostics.hasErrors(), diagnostics.toString());
var statements = ast.functions().getFirst().body().statements();
var a = (PbsAst.LetStatement) statements.get(0);
var explicit = (PbsAst.NewExpr) a.initializer();
assertEquals("array<array<int>>", source.substring((int) a.explicitType().span().getStart(), (int) a.explicitType().span().getEnd()));
assertEquals("array<int>", source.substring((int) explicit.explicitType().inner().span().getStart(), (int) explicit.explicitType().inner().span().getEnd()));
assertEquals("int", explicit.explicitType().inner().inner().name());
assertFalse(explicit.diamond());
var diamond = (PbsAst.NewExpr) ((PbsAst.LetStatement) statements.get(1)).initializer();
assertTrue(diamond.diamond());
assertNull(diamond.explicitType());
var omitted = (PbsAst.NewExpr) ((PbsAst.LetStatement) statements.get(2)).initializer();
assertFalse(omitted.diamond());
assertNull(omitted.explicitType());
assertEquals(">=", ((PbsAst.BinaryExpr) ((PbsAst.LetStatement) statements.get(3)).initializer()).operator());
}
@Test
void excessiveNestingAndMissingClosersAreDiagnosed() {
for (var type : java.util.List.of("array<int", "array<".repeat(257) + "int" + ">".repeat(257))) {
var diagnostics = DiagnosticSink.empty();
var id = new FileId(0);
var source = "fn main() { let a: " + type + " = new array(1); }";
PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics);
assertTrue(diagnostics.hasErrors(), type);
}
}
@Test
void shouldParseApplyElseAndPostfixChains() {
final var source = """
@@ -56,12 +56,21 @@ final class PbsEditorialSupportServiceTest {
String source = """
declare struct Enemy(pub hp: int) { fn health() -> int { return this.hp; } }
fn main() {
let enemies: array Enemy = new array(2);
let enemies = new array<Enemy>(2);
if let enemy = enemies[0] { let hp = enemy.health(); }
enemies.clear(0);
}
""";
var ast = parseOrdinary(source);
int argumentType = source.indexOf("<Enemy>") + 1;
assertFalse(service.definition(source, ast, ReadOnlyList.empty(), argumentType).isEmpty());
assertTrue(service.hover(source, ast, ReadOnlyList.empty(), argumentType).isPresent());
var typeRename = service.rename(source, ast, ReadOnlyList.empty(), argumentType, "Opponent");
assertTrue(typeRename.allowed(), typeRename.refusal());
assertEquals(2, typeRename.sites().size());
var formatted = p.studio.compiler.pbs.PbsDocumentFormatter.format(source);
assertEquals(formatted, p.studio.compiler.pbs.PbsDocumentFormatter.format(formatted));
parseOrdinary(formatted);
int use = source.indexOf("enemy.health");
assertFalse(service.definition(source, ast, ReadOnlyList.empty(), use).isEmpty());
assertTrue(service.hover(source, ast, ReadOnlyList.empty(), use).isPresent());
@@ -0,0 +1,67 @@
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 PbsGenericContractsEditorialTest {
@Test void importedAliasesNavigateToOriginsAndShowCanonicalArguments() {
String provider = "declare struct Enemy() {} declare contract Echo<T> { fn echo(value: T) -> T; }";
String source = """
import { Echo as Policy, Enemy as Opponent } from @sdk:policy;
fn use(reader: Policy<Opponent>) {}
""";
var diagnostics = DiagnosticSink.empty();
var providerId = new FileId(1);
var localId = new FileId(2);
var remote = PbsParser.parse(PbsLexer.lex(provider, providerId, diagnostics), providerId, diagnostics, PbsParser.ParseMode.ORDINARY);
var local = PbsParser.parse(PbsLexer.lex(source, localId, diagnostics), localId, diagnostics, PbsParser.ParseMode.ORDINARY);
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getMessage()).toList().toString());
var enemy = remote.topDecls().get(0);
var contract = remote.topDecls().get(1);
var supplemental = ReadOnlyList.wrap(java.util.List.<PbsAst.TopDecl>of(
new PbsAst.TypeBindingDecl("Opponent", enemy, local.span()),
new PbsAst.TypeBindingDecl("Policy", contract, local.span())));
var service = new PbsEditorialSupportService();
int application = source.indexOf("Policy<");
assertEquals(contract.span(), service.definition(source, local, supplemental, application).getFirst().span());
assertEquals(enemy.span(), service.definition(source, local, supplemental, application + 7).getFirst().span());
var hover = service.hover(source, local, supplemental, application).orElseThrow();
assertEquals("Echo<Enemy>", hover.displayName());
assertEquals("echo(value: Enemy) -> Enemy", hover.signatures().getFirst().label());
}
@Test void parameterNavigationAndInstantiatedPresentationShareTheCompilerModel() {
String source = """
declare contract Echo<T> { fn echo(value: T) -> T; }
fn demo(reader: Echo<int>) -> int { return reader.echo(42); }
""";
var diagnostics = DiagnosticSink.empty();
var id = new FileId(0);
var ast = PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics, PbsParser.ParseMode.ORDINARY);
assertFalse(diagnostics.hasErrors());
var service = new PbsEditorialSupportService();
int parameterUse = source.indexOf("value: T") + 7;
var definition = service.definition(source, ast, ReadOnlyList.empty(), parameterUse);
assertEquals(source.indexOf("<T>") + 1, definition.getFirst().span().getStart());
assertTrue(service.hover(source, ast, ReadOnlyList.empty(), parameterUse).orElseThrow().detail().contains("type parameter"));
var application = service.hover(source, ast, ReadOnlyList.empty(), source.indexOf("Echo<int>"));
assertEquals("Echo<int>", application.orElseThrow().displayName());
assertEquals("echo(value: int) -> int", application.orElseThrow().signatures().getFirst().label());
int call = source.indexOf("reader.echo");
assertTrue(service.completion(source, ast, ReadOnlyList.empty(), call + 7).stream().anyMatch(c -> c.label().equals("echo") && c.detail().contains("int")));
assertEquals("echo(value: int) -> int", service.signatureHelp(source, ast, ReadOnlyList.empty(), source.indexOf("42)")).orElseThrow().signatures().getFirst().label());
assertFalse(service.definition(source, ast, ReadOnlyList.empty(), call + 7).isEmpty());
var formatted = p.studio.compiler.pbs.PbsDocumentFormatter.format(source);
assertEquals(formatted, p.studio.compiler.pbs.PbsDocumentFormatter.format(formatted));
var formattedDiagnostics = DiagnosticSink.empty();
PbsParser.parse(PbsLexer.lex(formatted, id, formattedDiagnostics), id, formattedDiagnostics, PbsParser.ParseMode.ORDINARY);
assertFalse(formattedDiagnostics.hasErrors());
}
}
@@ -9,6 +9,38 @@ import static org.junit.jupiter.api.Assertions.*;
class PbsSemanticsDeclarationsTest {
@Test
void arrayConstructorFormsShareExpectedTypePositions() {
for (var construction : java.util.List.of("new array<int>(2)", "new array<>(2)", "new array(2)")) {
var source = """
declare global values: array<int> = %s;
fn make() -> array<int> { return %s; }
fn use(items: array<int>) -> int { return items.length as int; }
fn main() -> int {
let local: array<int> = %s;
local = %s;
return use(%s);
}
""".formatted(construction, construction, construction, construction, construction);
var diagnostics = DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+":"+d.getMessage()).toList().toString());
}
}
@Test
void explicitArraysMustMatchReturnAndArgumentTypes() {
for (var source : java.util.List.of(
"fn make() -> array<int> { return new array<bool>(1); }",
"fn use(items: array<int>) {} fn main() { use(new array<bool>(1)); }",
"declare global items: array<int> = new array<bool>(1);",
"fn main() { let items: array<int> = new array(1); items = new array<bool>(1); }")) {
var diagnostics = DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
assertTrue(diagnostics.hasErrors(), source);
}
}
@Test
void shouldAcceptDocOnNamedApiDeclarations() {
final var source = """
@@ -115,7 +115,7 @@ public final class LifecycleAssemblerService {
}
final var entryPointCallableName = frameWrapperCallableName(entryPointModuleId);
final var bootGuardSlot = nextGlobalSlot(globals, entryPointModuleId);
final var bootGuardSlot = nextGlobalSlot(globals);
final var wrapperCallableId = new CallableId(callableSignatures.size());
callableSignatures.add(new CallableSignatureRef(
entryPointModuleId,
@@ -206,7 +206,7 @@ public final class LifecycleAssemblerService {
.entryPointModuleId(entryPointModuleId)
.functions(backend.getFunctions())
.syntheticFunctions(ReadOnlyList.wrap(syntheticFunctions))
.globals(ReadOnlyList.wrap(normalizeGlobalSlots(globals)))
.globals(ReadOnlyList.wrap(globals))
.executableFunctions(ReadOnlyList.wrap(executableFunctions))
.modulePool(backend.getModulePool())
.callableSignatures(ReadOnlyList.wrap(callableSignatures))
@@ -354,39 +354,14 @@ public final class LifecycleAssemblerService {
}
private int nextGlobalSlot(
final ArrayList<IRGlobal> globals,
final ModuleId moduleId) {
final ArrayList<IRGlobal> globals) {
var nextSlot = 0;
for (final var global : globals) {
if (sameModuleId(moduleId, global.moduleId())) {
nextSlot = Math.max(nextSlot, global.slot() + 1);
}
nextSlot = Math.max(nextSlot, Math.addExact(global.slot(), 1));
}
return nextSlot;
}
private ArrayList<IRGlobal> normalizeGlobalSlots(final ArrayList<IRGlobal> globals) {
final var nextSlotByModule = new LinkedHashMap<ModuleId, Integer>();
final var normalized = new ArrayList<IRGlobal>(globals.size());
for (final var global : globals) {
final var moduleId = normalizeModuleId(global.moduleId());
final var slot = nextSlotByModule.getOrDefault(moduleId, 0);
nextSlotByModule.put(moduleId, slot + 1);
normalized.add(new IRGlobal(
global.fileId(),
moduleId,
global.name(),
global.declaredTypeSurface(),
slot,
global.visibility(),
global.isHidden(),
global.hiddenKind(),
global.origin(),
global.span()));
}
return normalized;
}
private IRBackendExecutableFunction.Instruction callInstruction(
final IRBackendExecutableFunction callee,
final Span span) {
@@ -68,6 +68,7 @@ public class IRBackend implements IRBackendReader {
}
functions.addAll(backendFile.functions().asList());
final var moduleRemap = reindexModules(backendFile.modulePool());
final var globalRemap = new java.util.HashMap<Integer, Integer>();
for (final var syntheticFunction : backendFile.syntheticFunctions()) {
syntheticFunctions.add(new IRSyntheticFunction(
remapModuleId(syntheticFunction.moduleId(), moduleRemap, "synthetic function"),
@@ -76,12 +77,15 @@ public class IRBackend implements IRBackendReader {
syntheticFunction.origin()));
}
for (final var global : backendFile.globals()) {
final var linkedSlot = globals.size();
if (globalRemap.putIfAbsent(global.slot(), linkedSlot) != null)
throw new IllegalArgumentException("duplicate file-local global slot: " + global.slot());
globals.add(new IRGlobal(
global.fileId(),
remapModuleId(global.moduleId(), moduleRemap, "global"),
global.name(),
global.declaredTypeSurface(),
global.slot(),
linkedSlot,
global.visibility(),
global.isHidden(),
global.hiddenKind(),
@@ -101,7 +105,7 @@ public class IRBackend implements IRBackendReader {
ReadOnlyList.wrap(impl.methods().stream().map(id -> remapCallableId(id, callableRemap, "implementation")).toList())));
}
for (final var function : backendFile.executableFunctions()) {
executableFunctions.add(remapExecutableFunction(function, moduleRemap, callableRemap, intrinsicRemap));
executableFunctions.add(remapExecutableFunction(function, moduleRemap, callableRemap, intrinsicRemap, globalRemap));
}
if (backendFile.lifecycleDeclaration() != null && !backendFile.lifecycleDeclaration().isEmpty()) {
lifecycleFiles.add(remapLifecycleFileDeclaration(
@@ -172,7 +176,8 @@ public class IRBackend implements IRBackendReader {
final IRBackendExecutableFunction function,
final ModuleId[] moduleRemap,
final CallableId[] callableRemap,
final IntrinsicId[] intrinsicRemap) {
final IntrinsicId[] intrinsicRemap,
final java.util.Map<Integer, Integer> globalRemap) {
final var remappedInstructions = new ArrayList<IRBackendExecutableFunction.Instruction>(function.instructions().size());
final var remappedFunctionModuleId = remapModuleId(
function.moduleId(),
@@ -208,7 +213,10 @@ public class IRBackend implements IRBackendReader {
remappedIntrinsic,
instruction.label(),
instruction.targetLabel(),
instruction.expectedArgSlots(),
instruction.kind() == IRBackendExecutableFunction.InstructionKind.GET_GLOBAL
|| instruction.kind() == IRBackendExecutableFunction.InstructionKind.SET_GLOBAL
? globalRemap.getOrDefault(instruction.expectedArgSlots(), instruction.expectedArgSlots())
: instruction.expectedArgSlots(),
instruction.expectedRetSlots(),
instruction.span(), instruction.registryInstruction() == null ? null :
new p.studio.compiler.models.registry.IRRegistryInstruction(instruction.registryInstruction().kind(), instruction.registryInstruction().type(), instruction.registryInstruction().targetType(),
@@ -0,0 +1,32 @@
package p.studio.compiler.models;
import org.junit.jupiter.api.Test;
import p.studio.compiler.source.Span;
import p.studio.compiler.source.identifiers.*;
import p.studio.compiler.source.tables.CallableSignatureRef;
import p.studio.utilities.structures.ReadOnlyList;
import static org.junit.jupiter.api.Assertions.*;
class IRGlobalRelocationTest {
@Test void independentFileGlobalsCannotAliasAfterAggregation() {
var aggregator = IRBackend.aggregator();
for (int i = 0; i < 2; i++) {
var file = new FileId(i);
var span = new Span(file, 0, 1);
var function = new IRBackendExecutableFunction(file, ModuleId.none(), "read"+i, new CallableId(0),
0, 1, 0, 0, 1, 1, ReadOnlyList.from(
new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.GET_GLOBAL,
null,"",null,null,null,"","",0,null,span),
new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET,"",null,null,span)), span);
aggregator.merge(new IRBackendFile(file, null, null,
ReadOnlyList.from(new IRGlobal(file, ModuleId.none(), "state", "int", span)),
ReadOnlyList.from(function), null, null,
ReadOnlyList.from(new CallableSignatureRef("read"+i, 0, "()->simple:int")), null));
}
var backend = aggregator.emit();
assertEquals(0, backend.getGlobals().get(0).slot());
assertEquals(1, backend.getGlobals().get(1).slot());
assertEquals(0, backend.getExecutableFunctions().get(0).instructions().getFirst().expectedArgSlots());
assertEquals(1, backend.getExecutableFunctions().get(1).instructions().getFirst().expectedArgSlots());
}
}
@@ -1310,6 +1310,8 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
final List<FrontendSignature> signatures = symbol.signatures();
if (!signatures.isEmpty()) {
markdown.append("```pbs\n");
if (symbol.kind() == p.studio.compiler.services.FrontendSymbolKind.CONTRACT)
markdown.append(symbol.displayName()).append('\n');
for (int index = 0; index < signatures.size(); index += 1) {
if (index > 0) {
markdown.append('\n');
@@ -28,6 +28,32 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class CompilerLanguageServiceBridgeTest {
@Test void genericContractsKeepSubstitutedSignaturesAcrossTheBridge(@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 contract Echo<T> { fn echo(value: T) -> T; }
fn demo(reader: Echo<int>) -> int { return reader.echo(42); }
""";
Path file = Files.writeString(root.resolve("src/main.pbs"), text).toRealPath();
Files.writeString(root.resolve("src/mod.barrel"), "pub contract Echo<T>; pub fn demo(reader: Echo<int>) -> int;");
var bridge = new CompilerLanguageServiceBridge();
var context = new LspProjectContext("app", "pbs", root.toRealPath());
var mapper = new DocumentPositionMapper(text);
var applied = mapper.positionOf(text.indexOf("Echo<int>"));
var hover = bridge.hover(context, file.toUri().toString(), text, applied.line(), applied.character());
assertTrue(hover.markdown().contains("Echo<int>"), hover.markdown());
assertTrue(hover.markdown().contains("value: int"), hover.markdown());
var argument = mapper.positionOf(text.indexOf("42)"));
var help = bridge.signatureHelp(context, file.toUri().toString(), text, argument.line(), argument.character());
assertEquals("echo(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("<T>")+1, definition.locations().getFirst().startCharacter());
}
@Test
void retainedDependencyUsesOriginalSemanticSnapshotAfterDiskChanges(@TempDir Path temporary) throws Exception {
final Path root = temporary.toRealPath();
+29 -1
View File
@@ -7,7 +7,7 @@ From the Studio root:
```sh
./gradlew :prometeu-compiler:prometeu-build-pipeline:test --tests '*LinkedRegistryTest' --tests '*PbxRegistryConformanceTest' --tests '*TypedCommonPipelineTest' --tests '*RuntimeCatalogPipelineTest'
./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeAlignmentTest' --tests '*PbsStructuredValuesTest' --tests '*PbsClosuresTest'
./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeAlignmentTest' --tests '*PbsStructuredValuesTest' --tests '*PbsClosuresTest' --tests '*PbsGenericContractsTest'
python3 tools/pbx-conformance/run.py --runtime ../runtime
```
@@ -196,3 +196,31 @@ claims. Qualify those separately with the provider's `random_contract` suite and
`cargo test -p prometeu-vm --lib random` in debug/release. No alternate RNG or
public injection hook is used. Installed knowledge validation remains a separate
gate for packaged SDK/spec/example resources.
## PBS generic contracts
`PbsGenericContractsTest` generates fourteen mandatory source fixtures:
`identity`, `manual`, `multiple`, `tuple`, `optional`, `function`, `contract`,
`native`, `recursive`, `phantom`, `receiver`, `gc`, `installed` and `imports`.
The corpus uses ordinary concrete Trait descriptors on the existing runtime.
It checks several applications on one owner, ordered substitution, composed
multi-slot values, finite recursion, canonical aliases/reexports and distinct
same-named argument declarations. The imported program uses the production
workspace builder and lifecycle assembler.
The generic and handwritten concrete identity fixtures both execute with one
heap handle, establishing that contract adaptation needs no generic wrapper.
Typed absence and implementation index zero are valid. A mismatched Trait call
must be rejected by the verifier or trap with the runtime type check. The GC
fixture retains a contract receiver through a closure while at least 1,100
discarded objects are reclaimed. Reduced GuestBytes, HandleSlots and loader
implementation limits verify refusal and ownership release. Descriptor counts
and PBX byte sizes are printed as evidence, without a performance threshold.
```sh
./gradlew :prometeu-architecture-tests:test --tests '*PbsGenericContractsTest'
python3 tools/pbx-conformance/run.py --runtime ../runtime --generic-contracts-only
```
The full harness also requires these fixtures. The driver uses an external
runtime checkout without editing its sources or changing PBX, ISA or quotas.
+109 -2
View File
@@ -36,6 +36,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 == "--random-only") { verify_pbs_random_fixtures(&root); return; }
verify_pbs_math_fixtures(&root);
if std::env::args().any(|arg| arg == "--math-only") { return; }
@@ -43,6 +44,7 @@ fn main() {
verify_catalog_fixtures(&root);
verify_pbs_fixtures(&root);
verify_pbs_structured_fixtures(&root);
verify_pbs_generic_contract_fixtures(&root);
verify_pbs_resource_refusals(&root);
verify_pbs_closure_frames(&root);
for name in [
@@ -479,7 +481,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-") || 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-") || 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)
@@ -547,7 +549,7 @@ fn verify_pbs_fixtures(root: &std::path::Path) {
fn verify_pbs_structured_fixtures(root: &std::path::Path) {
use prometeu_vm::LogicalFrameEndingReason as End;
let success = ["closure-import", "closure-installed", "closure-groups", "closure-isolation", "closure-fields", "closure-functions", "closure-snapshot", "closure-objects", "closure-nested", "array-cycle", "array-nested", "optional-flow", "struct-contract", "service-contract",
let success = ["closure-import", "closure-installed", "closure-groups", "closure-isolation", "closure-fields", "closure-functions", "closure-snapshot", "closure-objects", "closure-nested", "array-cycle", "array-nested", "array-parametric", "optional-flow", "struct-contract", "service-contract",
"optional-tuple", "tuple-storage", "optional-intrinsics", "optional-lazy", "array-context",
"binding-scope", "overloads", "single-evaluation", "long-boundaries", "gc-roots", "native-groups", "contract-elements", "imports", "global-array", "installed-example", "return-overloads", "inferred-optional-tuple", "inline-integers"];
for name in success.into_iter().chain(["negative-index", "past-end", "negative-length", "large-length"]) {
@@ -590,6 +592,111 @@ fn verify_pbs_structured_fixtures(root: &std::path::Path) {
}
}
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};
let mut reference_heap = None;
for name in ["identity", "manual", "multiple", "tuple", "optional", "function", "contract", "native", "recursive", "phantom", "receiver", "gc", "installed", "imports"] {
let bytes = std::fs::read(root.join(format!("pbs-generic-contract-{name}.pbx")))
.unwrap_or_else(|error| panic!("missing mandatory generic-contract fixture {name}: {error}"));
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE)
.unwrap_or_else(|error| panic!("generic contract {name}: {error:?}"));
let declarations = image.registry().declarations();
let traits: Vec<_> = declarations.types.iter().enumerate().filter(|(_, t)| matches!(t.kind, TypeKind::Trait(_))).collect();
assert!(!traits.is_empty(), "{name}: source must emit concrete traits");
for (index, _) in &traits {
assert_eq!(image.registry().type_layout(TypeId(*index as u32)).unwrap().storage.default_values(), &[Value::Null, Value::Null], "{name}: absent concrete trait");
}
assert!(!declarations.implementations.is_empty());
// The first dense implementation is valid; zero must never act as an absence sentinel.
assert_eq!(image.registry().implementation(declarations.implementations[0].owner, declarations.implementations[0].trait_id).unwrap().0, 0);
if name == "multiple" || name == "phantom" {
assert_eq!(traits.len(), 2);
assert_eq!(declarations.implementations.len(), 2);
assert_eq!(declarations.implementations[0].owner, declarations.implementations[1].owner);
assert_ne!(declarations.implementations[0].trait_id, declarations.implementations[1].trait_id);
}
if name == "imports" { assert_eq!(traits.len(), 3); assert_eq!(declarations.implementations.len(), 3); }
if name == "phantom" {
let mut code = image.code().to_vec();
let mut pc = 0;
let mut changed = false;
while pc < code.len() {
let instruction = prometeu_bytecode::decode_next(pc, &code).unwrap();
if instruction.opcode == CoreOpCode::CallTrait {
let (original, _) = instruction.imm_u32x2().unwrap();
let other = traits.iter().map(|(index, _)| *index as u32).find(|id| *id != original).unwrap();
code[pc+2..pc+6].copy_from_slice(&other.to_le_bytes());
changed = true; break;
}
pc = instruction.next_pc;
}
assert!(changed);
let corrupt = replace(&bytes, 2, &code);
match ValidatedProgramImage::load(&corrupt, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) {
Err(error) => record_fault(root, "generic-contract-wrong-view", error),
Ok(image) => {
// Unknown receiver facts may defer rejection to the mandatory runtime check.
let mut invalid = VirtualMachine::from_image(image, RuntimeLimits::default());
invalid.prepare_boot_call().unwrap();
let report = invalid.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_TYPE), "mismatched concrete view: {report:?}");
}
}
println!("PBS GENERIC WRONG-VIEW REJECTION PASS");
}
println!("PBS GENERIC METADATA {name}: types={} implementations={} bytes={}", declarations.types.len(), declarations.implementations.len(), bytes.len());
let limits = if name == "identity" || name == "manual" {
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();
}
if name == "imports" {
assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}");
} else {
assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}");
assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(42)], "{name}");
}
if name == "identity" || name == "manual" {
assert_eq!(vm.heap().len(), 1, "no generic argument box or view wrapper");
let heap = observer.used(RuntimeResource::GuestBytes);
if let Some(reference) = reference_heap { assert_eq!(heap, reference, "generic and manual contract heap footprints"); }
reference_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 == "identity" || name == "receiver" {
for (resource, limit) in [(RuntimeResource::GuestBytes, 0), (RuntimeResource::GuestBytes, 1), (RuntimeResource::GuestBytes, 2), (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, "refusal cannot publish partial objects");
assert!(observed.used(resource) <= limit);
drop(refused);
for domain in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots, RuntimeResource::AuxiliaryBytes, RuntimeResource::TemporaryBytes] {
assert_eq!(observed.used(domain), 0);
}
}
reject(root, &format!("generic-contract-{name}-load-quota"), &bytes, LoadLimits { implementations: 0, ..LoadLimits::default() });
}
println!("PBS GENERIC SOURCE/LOAD/EXEC PASS {name}");
}
}
fn verify_pbs_resource_refusals(root: &std::path::Path) {
use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits, RuntimeResource}};
for name in ["closure-objects", "array-cycle", "tuple-storage", "struct-contract"] {
+2 -1
View File
@@ -14,6 +14,7 @@ parser.add_argument("--online", action="store_true", help="Allow Cargo to fetch
parser.add_argument("--release", action="store_true", help="Execute an optimized runtime harness")
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")
args = parser.parse_args()
runtime = args.runtime.resolve()
if not args.math_only:
@@ -42,4 +43,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 [])], 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 [])], check=True)