feat(pbs): implement first-class functions and explicit captures
This commit is contained in:
+113
@@ -0,0 +1,113 @@
|
||||
---
|
||||
id: LSN-0084
|
||||
ticket: pbs-closures-and-indirect-calls
|
||||
title: PBS Function Values and Explicit Captures
|
||||
created: 2026-10-17
|
||||
tags: [compiler, pbs, runtime-integration]
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Owner: `compiler/pbs`. PBS needed functions usable as ordinary values for game
|
||||
logic and agent-authored programs. Its nominal callback declarations and bind
|
||||
model did not provide the chosen structural function surface. Runtime support
|
||||
for closures already existed; source typing, lowering, tooling and executable
|
||||
integration still had to be delivered together.
|
||||
|
||||
The accepted DEC-0068 was implemented through PLN-0147. Both are completed
|
||||
workflow artifacts; this lesson preserves their durable rationale and outcome.
|
||||
|
||||
## Consolidated decision
|
||||
|
||||
`Fn(int) -> int` identifies the ordered parameter/result types. Named functions
|
||||
and lambdas with that signature can be assigned, passed, returned and stored.
|
||||
Calls use ordinary parentheses. Overloaded function identifiers need an expected
|
||||
signature that selects exactly one target.
|
||||
|
||||
Lambdas use `fn [captures](name: Type) -> Return { ... }`. Captures, parameter
|
||||
annotations, result annotation and block are explicit, including empty `[]`.
|
||||
This makes dependencies visible to both programmers and code-generating agents.
|
||||
The cost is deliberate verbosity; implicit capture and expression-body shorthand
|
||||
are not alternative forms.
|
||||
|
||||
Captures snapshot values at creation. Captured bindings cannot be reassigned,
|
||||
even when their source bindings were mutable. Capturing an object reference
|
||||
preserves object identity and permitted field mutation. Shared state therefore
|
||||
uses explicit objects instead of hidden shared lexical cells.
|
||||
|
||||
```pbs
|
||||
declare struct Counter(pub mut value: int);
|
||||
fn createCounter() -> Fn() -> int {
|
||||
let counter = new Counter(0);
|
||||
return fn [counter]() -> int {
|
||||
counter.value += 1;
|
||||
return counter.value;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
Each factory call creates independent state. Two closures capturing the same
|
||||
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.
|
||||
|
||||
## Objects and frames
|
||||
|
||||
A closure is a managed object with the same reachability lifecycle as other
|
||||
objects. Returning from its creator does not destroy it. Globals, arrays, fields
|
||||
and other captures can retain it across frames. GC traces its environment and
|
||||
collects unreachable closures and objects.
|
||||
|
||||
An invocation completes within its frame. Keeping a closure alive across frames
|
||||
does not suspend an invocation. PBS has no coroutine or sync syntax. The frontend
|
||||
already publishes FRAME_ROOT; the existing lifecycle assembler supplies the
|
||||
guarded wrapper and its return. Reuse that integration rather than introducing
|
||||
a new loop or frame-ending operation for closures.
|
||||
|
||||
## Implementation
|
||||
|
||||
The AST and type parser represent structural Fn inputs/results and explicit
|
||||
lambda captures. Semantic analysis creates an isolated capture/parameter scope,
|
||||
checks returns and signatures, and rejects uncaptured outer locals. Editor
|
||||
traversal uses lambda scopes so references, rename and completion preserve
|
||||
binding identity.
|
||||
|
||||
Lowering registers deterministic generated functions and ordered typed capture
|
||||
metadata. MAKE_CLOSURE creates values, GET_CAPTURE reads environments, and
|
||||
CALL_CLOSURE invokes the expected signature. Named functions use empty capture
|
||||
lists. Captures do not become public parameters. Existing common IR/PBX registry
|
||||
and runtime contracts supply the execution machinery without production changes
|
||||
to frame assembly or runtime authority.
|
||||
|
||||
Complete logical groups must survive capture and return: a tuple or contract
|
||||
receiver cannot be treated as one slot simply because its containing closure
|
||||
occupies one slot. Imported functions retain provider callable identity.
|
||||
|
||||
## Validation and pitfalls
|
||||
|
||||
The production VM executes nine closure programs returning 42 and six allocation
|
||||
quota/ownership cases. A separate fixture uses the real lifecycle wrapper for
|
||||
three frames: a stored closure and captured object survive the first collection,
|
||||
execute in the next frame, then become collectible after their root is cleared.
|
||||
Each frame discards another 1,200 closures. This proves both retention and release.
|
||||
|
||||
The final Gradle gates execute 513 tests without failures; 13 existing disabled
|
||||
tests and two existing runtime JSON-schema enum gaps are recorded explicitly.
|
||||
Installed knowledge includes the owner specification and a compiled example.
|
||||
|
||||
Common mistakes to avoid:
|
||||
|
||||
- Treating frame completion as destruction of all closure objects.
|
||||
- Adding coroutine/sync machinery merely to retain a function value.
|
||||
- Capturing a mutable local as a hidden shared cell instead of a snapshot.
|
||||
- Deep-copying captured objects and losing intended shared identity.
|
||||
- Testing only opcode emission while missing runtime roots, imports or full groups.
|
||||
- Leaving editor visitors or installed examples on the retired callback model.
|
||||
|
||||
## References
|
||||
|
||||
- [Normative function and capture specification](../../../docs/compiler/pbs/specs/first-class-functions-and-captures.md).
|
||||
- [Implementation evidence and reproducible commands](../../evidence/DSC-0080-implementation/README.md).
|
||||
- [Production VM conformance harness](../../../tools/pbx-conformance/README.md).
|
||||
- [Executable installed example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/closures.pbs).
|
||||
@@ -0,0 +1,76 @@
|
||||
# First-class functions and explicit value captures
|
||||
|
||||
Owner: `compiler/pbs`. This specification defines PBS function values and closures. Runtime Registry/PBX layout, allocation, GC, resource limits and faults remain governed by the runtime contracts. It supersedes the retired nominal callback and `bind` model.
|
||||
|
||||
## Types and calls
|
||||
|
||||
`Fn(T1, T2) -> R` is a structural function type. Its identity is the ordered logical parameter and result types, excluding parameter names, target identity and captures. Named functions and lambdas with the same signature have the same function type. Incompatible signatures do not convert implicitly. Physical slot count alone is not a type identity.
|
||||
|
||||
A function value can be assigned, passed, returned and stored in a collection or object. A named top-level function is referenced by its identifier without an address operator. When overloaded, its expected function type must select exactly one compatible overload. Calls use ordinary parentheses.
|
||||
|
||||
```pbs
|
||||
fn twice(value: int) -> int { return value * 2; }
|
||||
fn invoke(value: int, transform: Fn(int) -> int) -> int {
|
||||
return transform(value);
|
||||
}
|
||||
fn example() -> int {
|
||||
let transform: Fn(int) -> int = twice;
|
||||
return invoke(21, transform);
|
||||
}
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
The sole lambda form is `fn [captures](parameter: Type) -> Return { body }`. The capture list is mandatory, including `[]` for no captures. Parameter types and return type are explicit. The body is a block and values use explicit `return`; a trailing expression is not an implicit return. The initialized variable's type may be inferred from the lambda signature.
|
||||
|
||||
```pbs
|
||||
fn createMultiplier(factor: int) -> Fn(int) -> int {
|
||||
return fn [factor](value: int) -> int { return value * factor; };
|
||||
}
|
||||
```
|
||||
|
||||
A lambda may only access outer local bindings through its explicit capture list. Capture entries name unique available outer bindings. Parameters and local declarations have their ordinary lexical scopes. Captures are not hidden public parameters and do not affect the public Fn signature.
|
||||
|
||||
## Snapshot capture and object identity
|
||||
|
||||
Each capture fixes the binding's value when the closure is created. This includes mutable outer bindings: later assignment to the outer binding does not modify the capture. Assigning to a captured binding inside the closure is invalid. There are no automatic captures, reference captures or implicit shared cells for local variables.
|
||||
|
||||
```pbs
|
||||
fn snapshot() -> int {
|
||||
let bonus = 5;
|
||||
let add = fn [bonus](value: int) -> int { return value + bonus; };
|
||||
bonus = 20;
|
||||
return add(10); // 15
|
||||
}
|
||||
```
|
||||
|
||||
Capturing an object reference preserves that reference's identity; it does not deep-copy the object. Field mutation remains governed by the object's field access rules. Closures sharing the same object observe its mutations. Separate object instances retain separate state. Adapting a method to Fn requires an explicit lambda capturing its receiver; bare method extraction is not introduced.
|
||||
|
||||
```pbs
|
||||
declare struct Counter(pub mut value: int);
|
||||
fn createCounter() -> Fn() -> int {
|
||||
let counter = new Counter(0);
|
||||
return fn [counter]() -> int {
|
||||
counter.value += 1;
|
||||
return counter.value;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Object lifetime and frame execution
|
||||
|
||||
Closures are managed objects. They may escape their creator and remain reachable through globals, fields, arrays or other captures across frames. The GC traces their captures; unreachable closures and environments are collectible under the ordinary runtime contract.
|
||||
|
||||
An invocation runs to completion within its logical frame. PBS offers no coroutine, suspension/resumption construct or `sync` syntax. The existing frontend publishes FRAME_ROOT and the existing lifecycle assembler creates the guarded frame wrapper. This feature must reuse that lifecycle without adding an alternative frame loop or synthetic integration. Retaining a closure object across frames is different from retaining a suspended invocation.
|
||||
|
||||
## Lowering and validation
|
||||
|
||||
The frontend emits typed Fn descriptors and capture metadata, MAKE_CLOSURE, GET_CAPTURE and CALL_CLOSURE through the common IR. Named function values also use runtime Closure objects with empty captures. Captured multi-slot groups and function parameters/results must remain complete. Nested invocations use their own environments. Receiver adapters preserve receiver identity and contract dispatch order.
|
||||
|
||||
Function creation and calls remain subject to existing resource checks and runtime faults. No quota relaxation, allocation rescue GC, automatic scheduler or special fault isolation is introduced.
|
||||
|
||||
`declare callback`, callback barrel exports and `bind(context, function)` are retired source forms and must be rejected. Existing programs and examples must use structural Fn and explicit lambdas. Historical provenance and negative tests may mention the removed forms.
|
||||
|
||||
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.
|
||||
@@ -47,7 +47,7 @@ It must feel fluid for frame-driven gameplay code while remaining strict enough
|
||||
|
||||
- Runtime and bytecode authority override language preferences.
|
||||
- Closed VM compatibility is mandatory.
|
||||
- `FRAME_SYNC`-based execution semantics are preserved.
|
||||
- The existing synthetic frame lifecycle is preserved; PBS exposes no sync or coroutine construct.
|
||||
- Host API usage remains capability-gated and versioned.
|
||||
- Canonical host primitive bindings remain reserved to SDK/toolchain-controlled `declare host` surfaces.
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ The following inputs are already fixed elsewhere and must not be contradicted he
|
||||
- Struct values are reference-like and identity-bearing in v1 core.
|
||||
- Service values are canonical module-owned singleton values in v1 core.
|
||||
- `declare const` values are compile-time constants rather than mutable runtime module storage.
|
||||
- `FRAME_SYNC` is the only normative safepoint in PBS v1.
|
||||
- PBS uses the existing synthetic frame lifecycle. Runtime GC opportunities, including successful root return, follow the runtime contract; there is no PBS sync statement.
|
||||
- Core PBS v1 does not expose explicit lifetime-control syntax in ordinary user code.
|
||||
|
||||
## 6. Runtime Memory Spaces
|
||||
@@ -124,16 +124,9 @@ Contract values do not introduce a new user-visible identity distinct from the u
|
||||
|
||||
They are runtime views over an underlying identity-bearing value together with the selected contract implementation used for dispatch.
|
||||
|
||||
### 7.5 Callback values
|
||||
### 7.5 Function values and closures
|
||||
|
||||
Callback values are first-class callable values in PBS v1.
|
||||
|
||||
They may be assigned, passed, and returned, but callback identity is not promoted as a separate user-visible identity concept.
|
||||
|
||||
When formed through `bind(context, fn_name)`, a callback value retains:
|
||||
|
||||
- the target function,
|
||||
- and the same captured struct context identity without copying it.
|
||||
Closures are ordinary managed objects retaining their typed captures. Reachable closures may survive across frames; unreachable closures are eligible for GC. Their invocations do not suspend across frames. See [First-class functions and explicit value captures](../../../compiler/pbs/specs/first-class-functions-and-captures.md).
|
||||
|
||||
## 8. Identity, Aliasing, and Copy Behavior
|
||||
|
||||
@@ -201,11 +194,11 @@ The language does not promise:
|
||||
|
||||
### 9.3 Safepoint relationship
|
||||
|
||||
`FRAME_SYNC` is the only normative safepoint in PBS v1.
|
||||
PBS uses the existing synthetic frame lifecycle. Runtime GC opportunities, including successful root return, follow the runtime contract; there is no PBS sync statement.
|
||||
|
||||
No user-visible program rule may depend on another safepoint existing.
|
||||
|
||||
Implementations may perform internal GC work outside `FRAME_SYNC` only if doing so creates no additional user-visible semantic effects.
|
||||
GC timing remains a runtime concern and introduces no user callback or observable scheduling operation.
|
||||
|
||||
### 9.4 Observability
|
||||
|
||||
@@ -250,15 +243,9 @@ The normatively relevant cost facts in PBS v1 are:
|
||||
- whether an operation crosses the host boundary,
|
||||
- whether an operation may trap.
|
||||
|
||||
### 11.2 `bind`
|
||||
### 11.2 Explicit capture storage
|
||||
|
||||
`bind(context, fn_name)` is retention-bearing and requires runtime storage sufficient to preserve:
|
||||
|
||||
- the callback target identity,
|
||||
- the captured context,
|
||||
- and the captured context's continued liveness while the callback value remains alive.
|
||||
|
||||
This document does not freeze the exact runtime layout used to implement that storage.
|
||||
Closure creation retains the values named in its explicit capture list, including shared object identities. Lifetime follows ordinary reachability and runtime resource limits. Captured bindings cannot be reassigned.
|
||||
|
||||
### 11.3 Non-allocation-bearing surfaces by themselves
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ The v1 AST must represent, at minimum, declaration families for:
|
||||
- `service`,
|
||||
- `error`,
|
||||
- `enum`,
|
||||
- `callback`,
|
||||
- structural `Fn` types and lambda expressions with explicit captures,
|
||||
- `declare global`,
|
||||
- `declare const`,
|
||||
- and declaration nodes required by barrel/linking flow.
|
||||
|
||||
@@ -258,7 +258,7 @@ The mandatory warning identity for this rule is `W_SEM_IGNORED_VALUE`.
|
||||
|
||||
Tooling may surface qualitative cost facts as warnings or notes, especially for:
|
||||
|
||||
- retention-bearing `bind`,
|
||||
- retention-bearing explicit closure captures,
|
||||
- observable copy-versus-alias semantics,
|
||||
- and host-boundary crossings.
|
||||
|
||||
|
||||
@@ -163,7 +163,6 @@ BarrelItem ::= BarrelFnItem
|
||||
| BarrelServiceItem
|
||||
| BarrelGlobalItem
|
||||
| BarrelConstItem
|
||||
| BarrelCallbackItem
|
||||
BarrelVisibility ::= 'mod' | 'pub'
|
||||
|
||||
BarrelFnItem ::= BarrelVisibility 'fn' Identifier ParamList ReturnAnn? ';'
|
||||
@@ -175,7 +174,6 @@ BarrelEnumItem ::= BarrelVisibility 'enum' Identifier ';'
|
||||
BarrelServiceItem ::= BarrelVisibility 'service' Identifier ';'
|
||||
BarrelGlobalItem ::= BarrelVisibility 'global' Identifier ';'
|
||||
BarrelConstItem ::= BarrelVisibility 'const' Identifier ';'
|
||||
BarrelCallbackItem ::= BarrelVisibility 'callback' Identifier ';'
|
||||
```
|
||||
|
||||
Rules:
|
||||
@@ -191,7 +189,6 @@ Rules:
|
||||
- Multiple `fn` barrel entries with the same identifier are allowed only when signatures differ (overload set).
|
||||
- Barrel labels MAY differ from the implementation labels.
|
||||
- A `fn` barrel entry must resolve to exactly one declaration in module scope.
|
||||
- A `callback` barrel entry must resolve to exactly one top-level callback declaration in module scope.
|
||||
- A `host` barrel entry must resolve to exactly one top-level `declare host` declaration in module scope.
|
||||
- A `struct` barrel entry governs the visibility of the struct declaration and of all methods declared directly in that struct body.
|
||||
- A `host` barrel entry governs the visibility of the host declaration and of all method signatures declared directly in that host body.
|
||||
@@ -210,7 +207,6 @@ pub host Gfx;
|
||||
pub enum GameState;
|
||||
pub service Physics;
|
||||
pub global Palette;
|
||||
pub callback TickCb;
|
||||
```
|
||||
|
||||
## 6. File grammar
|
||||
@@ -272,7 +268,7 @@ Rules:
|
||||
### 6.2 Top-level declarations
|
||||
|
||||
```ebnf
|
||||
TopDecl ::= TypeDecl | CallbackDecl | FunctionDecl | GlobalDecl | ConstDecl | ImplDecl
|
||||
TopDecl ::= TypeDecl | FunctionDecl | GlobalDecl | ConstDecl | ImplDecl
|
||||
```
|
||||
|
||||
Top-level `let` forms and top-level executable statements are forbidden.
|
||||
@@ -366,20 +362,9 @@ Rules:
|
||||
- Contract values are formed from struct values or service singleton values by explicit or contextual conversion, as defined by static semantics.
|
||||
- Structs do not have static methods in v1 core.
|
||||
|
||||
### 7.2 Callbacks
|
||||
### 7.2 First-class function values
|
||||
|
||||
```ebnf
|
||||
CallbackDecl ::= 'declare' 'callback' Identifier ParamList ReturnAnn? ';'
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- A callback declaration introduces a nominal callback type.
|
||||
- A callback declaration defines exactly one callable signature.
|
||||
- A callback declaration has no body.
|
||||
- A callback declaration is distinct from `contract` and `fn`.
|
||||
- A callback declaration may be exported through `mod.barrel` using `callback`.
|
||||
- Callback values may be formed either by assigning a compatible top-level `fn` or by using `bind(context, fn_name)` under a callback-typed context.
|
||||
Function types use `Fn(T1, T2) -> R`. Lambdas use `fn [captures](name: Type) -> Return { ... }`; `[]` and all signature annotations are mandatory. See [First-class functions and explicit value captures](../../../compiler/pbs/specs/first-class-functions-and-captures.md).
|
||||
|
||||
### 7.3 Services
|
||||
|
||||
@@ -464,7 +449,7 @@ Rules:
|
||||
|
||||
```ebnf
|
||||
TypeRef ::= OptionalType | TypePrimary
|
||||
TypePrimary ::= SelfType | SimpleType | NamedTupleType | GroupType | UnitType
|
||||
TypePrimary ::= FnType | SelfType | SimpleType | NamedTupleType | GroupType | UnitType
|
||||
SelfType ::= 'Self'
|
||||
SimpleType ::= Identifier
|
||||
NamedTupleType ::= '(' NamedTupleField (',' NamedTupleField){0,5} ')'
|
||||
@@ -586,11 +571,13 @@ ArgList ::= Expr (',' Expr)*
|
||||
|
||||
Literal ::= IntLit | FloatLit | StringLit | BoolLit
|
||||
BoolLit ::= 'true' | 'false'
|
||||
PrimaryExpr ::= Literal | Identifier | ThisExpr | NewExpr | BindExpr | SomeExpr | NoneExpr | OkExpr | ErrExpr | UnitExpr | TupleExpr | GroupExpr | Block
|
||||
PrimaryExpr ::= Literal | Identifier | ThisExpr | NewExpr | LambdaExpr | SomeExpr | NoneExpr | OkExpr | ErrExpr | UnitExpr | TupleExpr | GroupExpr | Block
|
||||
ThisExpr ::= 'this'
|
||||
NewExpr ::= 'new' NewTarget '(' ArgList? ')'
|
||||
NewTarget ::= Identifier ('.' Identifier)?
|
||||
BindExpr ::= 'bind' '(' Expr ',' Identifier ')'
|
||||
LambdaExpr ::= 'fn' '[' CaptureNames? ']' ParamList '->' TypeRef Block
|
||||
CaptureNames ::= Identifier (',' Identifier)*
|
||||
FnType ::= 'Fn' '(' (TypeRef (',' TypeRef)*)? ')' '->' TypeRef
|
||||
SomeExpr ::= 'some' '(' Expr ')'
|
||||
NoneExpr ::= 'none'
|
||||
OkExpr ::= 'ok' '(' Expr ')'
|
||||
@@ -635,9 +622,6 @@ Rules:
|
||||
- Tuple expressions may be written with explicit labels (`(a: 1, b: 2)`) or positional sugar (`(1, 2)`).
|
||||
- Positional tuple expression sugar requires an expected named tuple shape supplied by context.
|
||||
- No single-slot tuple literal exists in v1 core syntax.
|
||||
- `bind(context, fn_name)` is the canonical surface for explicit callback context binding.
|
||||
- `bind(context, fn_name)` binds only the first parameter of `fn_name`.
|
||||
- The second operand of `bind` is a function identifier, not an arbitrary expression.
|
||||
- Mixing labeled and unlabeled tuple items in the same `TupleExpr` is a syntax error.
|
||||
- Member selection of a struct, service, host, or contract method is valid only as an immediate call target; bare method extraction such as `let m = s.compute;` is invalid.
|
||||
|
||||
@@ -677,14 +661,12 @@ Diagnostics that require name resolution, overload resolution, or type context a
|
||||
- invalid `ok(...)` construction form,
|
||||
- invalid `err(...)` construction form,
|
||||
- use of `ok(...)` or `err(...)` outside allowed result-flow positions,
|
||||
- invalid `bind(...)` construction form,
|
||||
- invalid `else` extraction form,
|
||||
- invalid `if` expression form,
|
||||
- invalid `switch` expression form,
|
||||
- invalid `for` loop form,
|
||||
- invalid `new` construction form,
|
||||
- invalid enum case path,
|
||||
- invalid callback declaration shape,
|
||||
- invalid struct field access modifier surface,
|
||||
- invalid struct method declaration shape,
|
||||
- invalid service method declaration shape,
|
||||
@@ -923,7 +905,6 @@ This section is the canonical reference example set for PBS v1 syntax.
|
||||
It consolidates the primary surface forms used by tooling and conformance for:
|
||||
|
||||
- `apply` and call sugar,
|
||||
- `bind` and nominal callbacks,
|
||||
- overloads that differ by return shape,
|
||||
- `optional`,
|
||||
- `result<Error>`,
|
||||
@@ -1019,45 +1000,21 @@ declare service Physics {
|
||||
}
|
||||
```
|
||||
|
||||
### 15.6 Nominal callback
|
||||
### 15.6 Function values
|
||||
|
||||
```pbs
|
||||
declare callback TickCb(dt: int) -> void;
|
||||
|
||||
fn on_tick(dt: int) -> void {
|
||||
let _ = dt;
|
||||
}
|
||||
|
||||
fn install(cb: TickCb) -> void {
|
||||
cb apply 16;
|
||||
cb(16);
|
||||
}
|
||||
|
||||
fn demo_callback() -> void {
|
||||
let cb: TickCb = on_tick;
|
||||
install(cb);
|
||||
fn twice(x: int) -> int { return x * 2; }
|
||||
fn demo_function() -> int {
|
||||
let f: Fn(int) -> int = twice;
|
||||
return f(21);
|
||||
}
|
||||
```
|
||||
|
||||
### 15.7 Bound callback
|
||||
### 15.7 Explicit captures
|
||||
|
||||
```pbs
|
||||
declare callback UpdateCb(dt: int) -> void;
|
||||
|
||||
declare struct Enemy(pub hp: int);
|
||||
|
||||
fn enemy_tick(self: Enemy, dt: int) -> void {
|
||||
let _ = self.hp;
|
||||
let _ = dt;
|
||||
}
|
||||
|
||||
fn install_update(cb: UpdateCb) -> void {
|
||||
cb apply 16;
|
||||
}
|
||||
|
||||
fn demo_bind(enemy: Enemy) -> void {
|
||||
let cb: UpdateCb = bind(enemy, enemy_tick);
|
||||
install_update(cb);
|
||||
fn create_adder(n: int) -> Fn(int) -> int {
|
||||
return fn [n](x: int) -> int { return n + x; };
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1240,3 +1197,5 @@ fn test(e: Enum) -> str {
|
||||
## 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.
|
||||
|
||||
Retired `declare callback`, callback exports and `bind(...)` are rejected. They do not provide alternative spellings for Fn or lambdas.
|
||||
|
||||
@@ -38,13 +38,13 @@ PBS distinguishes at least:
|
||||
|
||||
Rules:
|
||||
|
||||
- `declare struct`, `declare service`, `declare contract`, `declare error`, `declare enum`, `declare callback`, and `declare builtin type` introduce names in the type namespace.
|
||||
- `declare struct`, `declare service`, `declare contract`, `declare error`, `declare enum`, and `declare builtin type` introduce names in the type namespace.
|
||||
- `declare host` introduces names in the host-owner namespace.
|
||||
- `let`, parameters, `declare const`, and `declare global` introduce names in the value namespace.
|
||||
- `declare service Name` also introduces the canonical singleton value `Name` in the value namespace.
|
||||
- Top-level `fn`, service methods, and host methods participate in the callable namespace.
|
||||
- `fn` declarations are not first-class values in v1 core and therefore do not become ordinary value expressions.
|
||||
- `bind(...)` is a callback-formation construct, not a general function-value construct.
|
||||
- Named top-level functions can form first-class Fn values with structural signatures.
|
||||
- Function values use structural `Fn` types and explicit lambda captures.
|
||||
- `declare host` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source.
|
||||
- `declare builtin type` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source.
|
||||
- A host owner name is not an ordinary value expression in v1 core; it is used only as a qualified host-call owner.
|
||||
@@ -207,12 +207,12 @@ Rules:
|
||||
- Each semantic parameter record MUST carry its canonical source/API name, zero-based order, type when known, and origin/source sufficient for implementation and diagnostics.
|
||||
- A struct method is identified by `(struct type, method name, input tuple shape excluding the receiver slot, output tuple shape)`.
|
||||
- A contract value is identified at the type level by its contract type and at runtime by an underlying concrete struct instance or service singleton value plus its selected implementation.
|
||||
- A callback declaration defines a nominal callable type with exactly one input/output tuple shape.
|
||||
- A function type defines an ordered parameter/result signature independent of names or captures.
|
||||
- A service method is identified by `(service name, method name, input tuple shape, output tuple shape)`.
|
||||
- A host method is identified by `(host owner name, method name, input tuple shape, output tuple shape)` within the PBS declaration surface.
|
||||
- A builtin intrinsic method is identified within PBS declaration surface by `(builtin type name, method name, input tuple shape, output tuple shape)` and lowers further by canonical builtin/intrinsic metadata.
|
||||
- A top-level `fn` is identified by `(name, input tuple shape, output tuple shape)`.
|
||||
- A callback value is identified at the type level by its declared callback type and signature.
|
||||
- Function value compatibility uses its structural signature.
|
||||
- Contract signatures and barrel signatures must preserve the same callable shape.
|
||||
- Canonical host primitive identity and binding are governed by the Host ABI Binding specification rather than by ordinary v1 core declaration identity alone.
|
||||
- The compiler semantic model is the canonical owner of callable parameter names for completion, signature help, hover, diagnostics, and other editor-facing surfaces.
|
||||
@@ -312,7 +312,6 @@ Rules:
|
||||
- A non-builtin `declare const` initializer must not use:
|
||||
- callable application or call sugar,
|
||||
- `new`,
|
||||
- `bind(...)`,
|
||||
- `some(...)` or `none`,
|
||||
- tuple expressions,
|
||||
- block expressions,
|
||||
@@ -436,70 +435,9 @@ fn demo() -> int {
|
||||
}
|
||||
```
|
||||
|
||||
### 3.7 Nominal callbacks
|
||||
### 3.7 Structural function values
|
||||
|
||||
Rules:
|
||||
|
||||
- `declare callback Name(params...) -> R;` introduces a nominal callback type `Name`.
|
||||
- A callback type is not a `fn`, and a `fn` declaration does not implicitly define a callback type.
|
||||
- A value of callback type may be formed only from a compatible top-level `fn` in v1 core.
|
||||
- A value of callback type may also be formed by `bind(context, fn_name)` when the surrounding static type context expects a callback type.
|
||||
- Service methods are not assignable to callback values in v1 core.
|
||||
- Host methods are not assignable to callback values in v1 core.
|
||||
- Callback values do not capture local environment implicitly.
|
||||
- Assignment of a top-level `fn` to a callback type succeeds only when exactly one visible overload matches the callback signature.
|
||||
- `bind(context, fn_name)` succeeds only when exactly one visible top-level `fn` overload matches after consuming the first parameter with `context`.
|
||||
- Valid expected callback contexts for `bind(context, fn_name)` include variable initialization with an explicit callback type, assignment to an explicitly typed callback location, argument passing to a callback-typed parameter, and return from a callback-typed function.
|
||||
- The context expression in `bind(context, fn_name)` is evaluated once at bind time and stored explicitly in the resulting callback value.
|
||||
- When that stored context is identity-bearing, the resulting callback preserves the same captured identity rather than copying an independent underlying object.
|
||||
- `bind(context, fn_name)` does not introduce general closures; it is explicit partial binding of the first parameter only.
|
||||
- Callback compatibility ignores labels and compares ordered input/output slot types plus the return-surface kind.
|
||||
|
||||
Example:
|
||||
|
||||
```pbs
|
||||
declare callback TickCb(dt: int) -> void;
|
||||
|
||||
fn on_tick(dt: int) -> void {
|
||||
}
|
||||
|
||||
fn install_tick() -> void {
|
||||
let cb: TickCb = on_tick;
|
||||
let _ = cb;
|
||||
}
|
||||
```
|
||||
|
||||
Bound example:
|
||||
|
||||
```pbs
|
||||
declare callback UpdateCb(dt: int) -> void;
|
||||
|
||||
declare struct Enemy(hp: int);
|
||||
|
||||
fn update_enemy(self: Enemy, dt: int) -> void {
|
||||
}
|
||||
|
||||
fn install_update(enemy: Enemy) -> void {
|
||||
let cb: UpdateCb = bind(enemy, update_enemy);
|
||||
let _ = cb;
|
||||
}
|
||||
```
|
||||
|
||||
Ambiguous overload example:
|
||||
|
||||
```pbs
|
||||
declare callback TickCb(dt: int) -> void;
|
||||
|
||||
fn tick(dt: int) -> void {
|
||||
}
|
||||
|
||||
fn tick(time: int) -> void {
|
||||
}
|
||||
|
||||
fn install_tick() -> void {
|
||||
let cb: TickCb = tick; // error: ambiguous overloaded fn assignment
|
||||
}
|
||||
```
|
||||
[First-class functions and explicit value captures](../../../compiler/pbs/specs/first-class-functions-and-captures.md) defines structural Fn compatibility, explicit snapshot captures and lambda typing. Assignment of a named function requires exactly one matching overload. Bare method extraction remains invalid; use an explicit receiver-capturing lambda.
|
||||
|
||||
### 3.8 Canonical application
|
||||
|
||||
@@ -801,7 +739,6 @@ At minimum, deterministic static diagnostics are required for:
|
||||
- invalid contract coercion from concrete struct or service value,
|
||||
- unresolved barrel function signature after label-insensitive matching,
|
||||
- unresolved host barrel entry,
|
||||
- unresolved callback barrel entry,
|
||||
- invalid enum case path,
|
||||
- invalid enum intrinsic member call,
|
||||
- invalid named constructor target,
|
||||
@@ -811,9 +748,6 @@ At minimum, deterministic static diagnostics are required for:
|
||||
- ambiguous overloaded top-level `fn` assignment to callback type,
|
||||
- attempted assignment of service method to callback type,
|
||||
- attempted assignment of host method to callback type,
|
||||
- use of `bind(...)` without an expected callback type,
|
||||
- incompatible `bind(...)` context type for callback target,
|
||||
- ambiguous overloaded top-level `fn` target in `bind(...)`,
|
||||
- `apply` on a non-callable target,
|
||||
- arity mismatch in `apply`,
|
||||
- argument type mismatch in `apply`,
|
||||
|
||||
@@ -67,7 +67,7 @@ This document integrates the following accepted decisions:
|
||||
The following inputs are already fixed elsewhere and must not be contradicted here:
|
||||
|
||||
- PBS prioritizes determinism and compatibility over ergonomics when the two conflict.
|
||||
- `FRAME_SYNC`-based execution semantics remain preserved.
|
||||
- The existing synthetic frame lifecycle remains preserved; PBS exposes no sync or coroutine construct.
|
||||
- No non-deterministic async execution model is part of PBS v1.
|
||||
- Function application is defined on the canonical `apply` surface, with call sugar desugaring to `apply`.
|
||||
- `optional T` function fallthrough yields `none`.
|
||||
@@ -93,7 +93,7 @@ User-visible sequencing is defined by:
|
||||
|
||||
VM-internal frame layout, temporary storage, and lowering steps are not observable unless they change one of the semantic effects above.
|
||||
|
||||
`FRAME_SYNC` is the only normative safepoint in PBS v1.
|
||||
PBS uses the existing synthetic frame lifecycle. Runtime GC opportunities, including successful root return, follow the runtime contract; there is no PBS sync statement.
|
||||
|
||||
## 6.1 Lifecycle bootstrap
|
||||
|
||||
@@ -161,7 +161,7 @@ The following expressions are evaluated exactly once where they appear:
|
||||
- the payload expression of `some(expr)`,
|
||||
- the operand of `expr!`,
|
||||
- the operand of `handle expr { ... }`,
|
||||
- the context expression of `bind(context, fn_name)`,
|
||||
- explicit closure capture values,
|
||||
- call receivers, callees, and argument expressions as required by the call rule above.
|
||||
|
||||
## 8. Blocks and Abrupt Completion
|
||||
@@ -253,7 +253,7 @@ For the remap-only case, a short form such as `E1.case -> E2.case` is sugar for
|
||||
|
||||
`handle` does not intercept or convert traps.
|
||||
|
||||
## 11. `apply`, Call Sugar, and `bind`
|
||||
## 11. Function application and closures
|
||||
|
||||
### 11.1 Canonical role of `apply`
|
||||
|
||||
@@ -279,22 +279,9 @@ If a callable returns:
|
||||
- `optional<P>`, extraction remains explicit through `else`,
|
||||
- `result<E> P`, propagation or processing remains explicit through `!` or `handle`.
|
||||
|
||||
### 11.3 `bind`
|
||||
### 11.3 Closure creation and invocation
|
||||
|
||||
`bind(context, fn_name)` is the explicit callback-formation mechanism in PBS v1.
|
||||
|
||||
It:
|
||||
|
||||
- evaluates `context` exactly once,
|
||||
- captures the same struct context identity without copying it,
|
||||
- attaches that context to the resolved top-level function target,
|
||||
- produces a callback value whose invocation behaves as if the target function were called with the captured context as its first argument.
|
||||
|
||||
At the language-semantics level, `bind` is trap-free.
|
||||
|
||||
Incompatible binding shape remains a compile-time matter rather than a runtime failure mode.
|
||||
|
||||
Retention and storage consequences of `bind` belong to `Memory and Lifetime Specification.md`.
|
||||
Explicit capture lists snapshot values at creation. Object references retain identity. Calls complete within the current frame; objects may remain reachable between frames. See [First-class functions and explicit value captures](../../../compiler/pbs/specs/first-class-functions-and-captures.md).
|
||||
|
||||
## 12. Branch Selection
|
||||
|
||||
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
package p.studio.compiler.backend.irvm;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsClosuresTest {
|
||||
@Test void namedAndAnonymousFunctionsShareSignature() throws Exception {
|
||||
PbsStructuredValuesTest.compile("closure-functions", """
|
||||
fn twice(x: int) -> int { return x * 2; }
|
||||
fn invoke(x: int, f: Fn(int) -> int) -> int { return f(x); }
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let f: Fn(int) -> int = twice;
|
||||
let g = fn [](x: int) -> int { return x + 2; };
|
||||
return invoke(20, f) + g(0);
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void capturesSnapshotAndEscape() throws Exception {
|
||||
PbsStructuredValuesTest.compile("closure-snapshot", """
|
||||
fn create(n: int) -> Fn(int) -> int {
|
||||
let factor = n;
|
||||
let f = fn [factor](x: int) -> int { return x * factor; };
|
||||
factor = 100;
|
||||
return f;
|
||||
}
|
||||
declare service Probe {
|
||||
fn main() -> int { let f = create(3); return f(14); }
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void closuresShareObjectsAndTravelThroughArrays() throws Exception {
|
||||
PbsStructuredValuesTest.compile("closure-objects", """
|
||||
declare struct Counter(pub mut value: int);
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
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];
|
||||
increment(); increment();
|
||||
if let f = reads[0] { return f(); }
|
||||
return 999;
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void nestedClosuresCaptureFunctions() throws Exception {
|
||||
PbsStructuredValuesTest.compile("closure-nested", """
|
||||
fn create(n: int) -> Fn() -> Fn(int) -> int {
|
||||
let add = fn [n](x: int) -> int { return n + x; };
|
||||
return fn [add]() -> Fn(int) -> int { return add; };
|
||||
}
|
||||
declare service Probe {
|
||||
fn main() -> int { let factory = create(20); let f = factory(); return f(22); }
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void capturedGroupsAndContractReceiverPreserveTheirLayouts() throws Exception {
|
||||
PbsStructuredValuesTest.compile("closure-groups", """
|
||||
declare contract Answer { fn get() -> int; }
|
||||
declare struct Box(pub value: int) { fn get() -> int { return this.value; } }
|
||||
implements Answer for Box using box { fn get() -> int { return box.get(); } }
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let pair: (left: int, right: int) = (20, 21);
|
||||
let target: Answer = new Box(1);
|
||||
let f = fn [pair, target]() -> (left: int, right: int) {
|
||||
return (pair.left, pair.right + target.get());
|
||||
};
|
||||
let value = f();
|
||||
return value.left + value.right;
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void separateFactoriesKeepIndependentState() throws Exception {
|
||||
PbsStructuredValuesTest.compile("closure-isolation", """
|
||||
declare struct Counter(pub mut n: int);
|
||||
fn create(start: int) -> Fn() -> int {
|
||||
let state = new Counter(start);
|
||||
return fn [state]() -> int { state.n += 1; return state.n; };
|
||||
}
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let a = create(10);
|
||||
let b = create(18);
|
||||
let first = a();
|
||||
let second = a();
|
||||
return first + second + b();
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void functionFieldsAndOverloadsUseExpectedSignature() throws Exception {
|
||||
PbsStructuredValuesTest.compile("closure-fields", """
|
||||
fn value(x: int) -> int { return x + 2; }
|
||||
fn value(x: bool) -> int { return 999; }
|
||||
declare struct Behavior(pub run: Fn(int) -> int);
|
||||
declare service Probe {
|
||||
fn main() -> int {
|
||||
let behavior = new Behavior(value);
|
||||
return behavior.run(40);
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
|
||||
@Test void importedFunctionValuesLinkToProvider() throws Exception {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var compiler = new PbsFrontendCompiler();
|
||||
var names = new p.studio.compiler.source.tables.NameTable();
|
||||
var host = p.studio.compiler.messages.HostAdmissionContext.permissiveDefault();
|
||||
var surface = p.studio.compiler.messages.FESurfaceContext.empty();
|
||||
var modules = p.studio.utilities.structures.ReadOnlyList.from(
|
||||
new p.studio.compiler.source.tables.ModuleReference("test",p.studio.utilities.structures.ReadOnlyList.from("provider")),
|
||||
new p.studio.compiler.source.tables.ModuleReference("test",p.studio.utilities.structures.ReadOnlyList.from("client")));
|
||||
var providerId = new FileId(10);
|
||||
var providerAst = p.studio.compiler.pbs.parser.PbsParser.parse(p.studio.compiler.pbs.lexer.PbsLexer.lex(
|
||||
"fn twice(x: int) -> int { return x * 2; }",providerId,diagnostics),providerId,diagnostics);
|
||||
var provider = compiler.compileParsedFile(providerId,providerAst,diagnostics,p.studio.compiler.models.SourceKind.PROJECT,
|
||||
new p.studio.compiler.source.identifiers.ModuleId(0),modules,host,surface,names);
|
||||
var function = providerAst.functions().getFirst();
|
||||
var signature = provider.callableSignatures().getFirst();
|
||||
var imported = new PbsFrontendCompiler.ImportedCallableSurface(new p.studio.compiler.source.identifiers.ModuleId(0),
|
||||
signature.callableName(),signature.arity(),1,function.returnKind(),function.returnType(),signature.typeShape());
|
||||
var clientId = new FileId(11);
|
||||
var source = "declare service Probe { fn main() -> int { let f: Fn(int) -> int = twice; return f(21); } }";
|
||||
var ast = p.studio.compiler.pbs.parser.PbsParser.parse(p.studio.compiler.pbs.lexer.PbsLexer.lex(source,clientId,diagnostics),clientId,diagnostics);
|
||||
var client = compiler.compileParsedFile(clientId,ast,diagnostics,p.studio.compiler.models.SourceKind.PROJECT,
|
||||
new p.studio.compiler.source.identifiers.ModuleId(1),modules,host,surface,names,providerAst.topDecls(),
|
||||
p.studio.utilities.structures.ReadOnlyList.from(imported),p.studio.utilities.structures.ReadOnlyList.empty(),
|
||||
p.studio.compiler.models.IRReservedMetadata.empty(),java.util.Map.of());
|
||||
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+":"+d.getMessage()).toList().toString());
|
||||
var aggregator = p.studio.compiler.models.IRBackend.aggregator();
|
||||
aggregator.merge(provider); aggregator.merge(client);
|
||||
var backend = aggregator.entryPointCallableName("Probe.main").entryPointModuleId(new p.studio.compiler.source.identifiers.ModuleId(1)).emit();
|
||||
var program = new LowerToIRVMService().lower(backend);
|
||||
var output = new p.studio.compiler.backend.bytecode.BytecodeEmitter().emit(program.coherentEmissionPlan());
|
||||
new p.studio.compiler.backend.bytecode.BytecodePreloadVerifierService().verify(output);
|
||||
java.nio.file.Files.write(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory"),"pbs-structured-closure-import.pbx"),output.serialize());
|
||||
}
|
||||
|
||||
@Test void installedExampleProducesExecutableClosures() throws Exception {
|
||||
try(var resource = PbsFrontendCompiler.class.getResourceAsStream("/pbs-knowledge/examples/game/1/src/closures.pbs")) {
|
||||
assertNotNull(resource);
|
||||
var source = new String(resource.readAllBytes(),java.nio.charset.StandardCharsets.UTF_8);
|
||||
PbsStructuredValuesTest.compile("closure-installed", source + "\ndeclare service Probe { fn main() -> int { return closureExample(); } }");
|
||||
}
|
||||
}
|
||||
|
||||
@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 frames: int = 0;
|
||||
[Frame]
|
||||
fn frame() -> void {
|
||||
if frames == 0 {
|
||||
let counter = new Counter(40);
|
||||
callbacks[0] = fn [counter]() -> int {
|
||||
counter.value += 1;
|
||||
return counter.value;
|
||||
};
|
||||
} else {
|
||||
if let action = callbacks[0] {
|
||||
let first = action();
|
||||
let second = action();
|
||||
if first != 41 { callbacks[-1] = action; }
|
||||
if second != 42 { callbacks[-1] = action; }
|
||||
callbacks.clear(0);
|
||||
}
|
||||
}
|
||||
for i: int from 0 until 1200 {
|
||||
let discarded = fn [i]() -> int { return i; };
|
||||
}
|
||||
frames += 1;
|
||||
}
|
||||
""";
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var id = new FileId(0);
|
||||
var moduleId = new p.studio.compiler.source.identifiers.ModuleId(0);
|
||||
var ast = p.studio.compiler.pbs.parser.PbsParser.parse(p.studio.compiler.pbs.lexer.PbsLexer.lex(source,id,diagnostics),id,diagnostics);
|
||||
var modules = p.studio.utilities.structures.ReadOnlyList.from(new p.studio.compiler.source.tables.ModuleReference("test",
|
||||
p.studio.utilities.structures.ReadOnlyList.from("main")));
|
||||
var file = new PbsFrontendCompiler().compileParsedFile(id,ast,diagnostics,p.studio.compiler.models.SourceKind.PROJECT,
|
||||
moduleId,modules,p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(),
|
||||
p.studio.compiler.messages.FESurfaceContext.empty(),new p.studio.compiler.source.tables.NameTable());
|
||||
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+":"+d.getMessage()).toList().toString());
|
||||
var aggregator = p.studio.compiler.models.IRBackend.aggregator();
|
||||
aggregator.merge(file);
|
||||
var backend = aggregator.lifecycleModuleOrder(p.studio.utilities.structures.ReadOnlyList.from(moduleId)).emit();
|
||||
var issues = p.studio.compiler.messages.BuildingIssueSink.empty();
|
||||
var assembled = new p.studio.compiler.lifecycle.LifecycleAssemblerService().assemble(backend,issues);
|
||||
assertFalse(issues.hasErrors(), issues.asCollection().toString());
|
||||
var program = new LowerToIRVMService().lower(assembled);
|
||||
var output = new p.studio.compiler.backend.bytecode.BytecodeEmitter().emit(program.coherentEmissionPlan());
|
||||
new p.studio.compiler.backend.bytecode.BytecodePreloadVerifierService().verify(output);
|
||||
java.nio.file.Files.write(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory"),"closure-frame-lifecycle.pbx"),output.serialize());
|
||||
}
|
||||
|
||||
@Test void retiredCallbackDeclarationsAndExportsReject() {
|
||||
var source = "declare callback Tick(x: int) -> int; fn probe() -> void {}";
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0),source,diagnostics);
|
||||
assertTrue(diagnostics.hasErrors());
|
||||
var barrelDiagnostics = DiagnosticSink.empty();
|
||||
var id = new FileId(0);
|
||||
p.studio.compiler.pbs.parser.PbsBarrelParser.parse(
|
||||
p.studio.compiler.pbs.lexer.PbsLexer.lex("pub callback Tick;",id,barrelDiagnostics),id,barrelDiagnostics);
|
||||
assertTrue(barrelDiagnostics.hasErrors());
|
||||
}
|
||||
|
||||
@Test void invalidCapturesAndSignaturesReject() {
|
||||
for (var body : new String[] {
|
||||
"declare callback Old() -> void;",
|
||||
"let x = bind(ctx, handler);",
|
||||
"let n = 1; let f = fn []() -> int { return n; };",
|
||||
"let n = 1; let f = fn [n]() -> void { n = 2; };",
|
||||
"let f = fn [missing]() -> int { return missing; };",
|
||||
"let n = 1; let f = fn [n,n]() -> int { return n; };",
|
||||
"let f: Fn(int) -> bool = fn [](x: int) -> int { return x; };",
|
||||
"let f = fn (x: int) -> int { return x; };",
|
||||
"let f = fn [](x: int) { return x; };",
|
||||
"let f = fn [](x) -> int { return x; };",
|
||||
"let f = fn [](x: int) -> int { x };",
|
||||
"let f = fn [](x: int) -> int { return x; }; let x = f(true);"
|
||||
}) {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0), "fn probe() { " + body + " }", diagnostics);
|
||||
assertTrue(diagnostics.hasErrors(), body);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -15,7 +15,7 @@ import p.studio.compiler.source.identifiers.ModuleId;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsStructuredValuesTest {
|
||||
private static BytecodeModule compile(String name,String source) throws Exception {
|
||||
static BytecodeModule compile(String name,String source) throws Exception {
|
||||
var diagnostics=DiagnosticSink.empty();
|
||||
var fileId = new FileId(0);
|
||||
var ast = p.studio.compiler.pbs.parser.PbsParser.parse(p.studio.compiler.pbs.lexer.PbsLexer.lex(source,fileId,diagnostics),fileId,diagnostics,p.studio.compiler.pbs.parser.PbsParser.ParseMode.INTERFACE_MODULE);
|
||||
|
||||
+1
-3
@@ -251,8 +251,6 @@ public final class PBSSemanticTokenProvider implements FrontendSemanticTokenProv
|
||||
exportedKinds.put(globalItem.name(), semanticKind);
|
||||
} else if (item instanceof PbsAst.BarrelConstItem constItem && constItem.visibility() == PbsAst.Visibility.PUB) {
|
||||
exportedKinds.put(constItem.name(), semanticKind);
|
||||
} else if (item instanceof PbsAst.BarrelCallbackItem callbackItem && callbackItem.visibility() == PbsAst.Visibility.PUB) {
|
||||
exportedKinds.put(callbackItem.name(), semanticKind);
|
||||
}
|
||||
}
|
||||
return exportedKinds;
|
||||
@@ -284,7 +282,7 @@ public final class PBSSemanticTokenProvider implements FrontendSemanticTokenProv
|
||||
case PbsAst.BarrelServiceItem ignored -> PbsSemanticKind.SERVICE;
|
||||
case PbsAst.BarrelGlobalItem ignored -> PbsSemanticKind.GLOBAL;
|
||||
case PbsAst.BarrelConstItem ignored -> PbsSemanticKind.CONST;
|
||||
case PbsAst.BarrelCallbackItem ignored -> PbsSemanticKind.CALLBACK;
|
||||
|
||||
case PbsAst.BarrelFunctionItem ignored -> null;
|
||||
};
|
||||
}
|
||||
|
||||
+1
@@ -238,6 +238,7 @@ public final class PbsReservedMetadataExtractor {
|
||||
return switch (typeRef.kind()) {
|
||||
case SIMPLE -> "simple:" + typeRef.name();
|
||||
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()) + ")";
|
||||
case OPTIONAL -> "optional(" + typeSurfaceKey(typeRef.inner()) + ")";
|
||||
case UNIT -> "unit";
|
||||
|
||||
+4
-2
@@ -150,7 +150,7 @@ public final class PbsStructureRanges {
|
||||
case PbsAst.HostDecl hostDecl -> visitAttributes(hostDecl.attributes(), collected);
|
||||
case PbsAst.EnumDecl enumDecl -> visitAttributes(enumDecl.attributes(), collected);
|
||||
case PbsAst.ErrorDecl errorDecl -> visitAttributes(errorDecl.attributes(), collected);
|
||||
case PbsAst.CallbackDecl callbackDecl -> visitAttributes(callbackDecl.attributes(), collected);
|
||||
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
@@ -216,6 +216,8 @@ public final class PbsStructureRanges {
|
||||
private static void coverStatement(
|
||||
final PbsAst.Statement statement,
|
||||
final Collected collected) {
|
||||
if (statement != null) for (var expression : p.studio.compiler.pbs.ast.PbsLambdaTraversal.expressions(statement))
|
||||
p.studio.compiler.pbs.ast.PbsLambdaTraversal.visit(expression, lambda -> coverBlock(lambda.body(), true, collected));
|
||||
switch (statement) {
|
||||
case null -> {
|
||||
}
|
||||
@@ -239,7 +241,7 @@ public final class PbsStructureRanges {
|
||||
|| topDecl instanceof PbsAst.HostDecl
|
||||
|| topDecl instanceof PbsAst.EnumDecl
|
||||
|| topDecl instanceof PbsAst.ErrorDecl
|
||||
|| topDecl instanceof PbsAst.CallbackDecl;
|
||||
;
|
||||
}
|
||||
|
||||
private static List<SpanPair> delimiters(
|
||||
|
||||
+2
@@ -10,6 +10,8 @@ public final class PbsTypeSubstitution {
|
||||
public static PbsAst.TypeRef replaceSelf(PbsAst.TypeRef type, String owner) {
|
||||
if (type == null) return null;
|
||||
if (type.kind() == PbsAst.TypeRefKind.SELF) return PbsAst.TypeRef.simple(owner, type.span());
|
||||
if (type.kind() == PbsAst.TypeRefKind.FN) return PbsAst.TypeRef.function(ReadOnlyList.wrap(type.fields().stream().map(f ->
|
||||
new PbsAst.NamedTypeField(null, replaceSelf(f.typeRef(), owner), f.span())).toList()), replaceSelf(type.inner(), owner), type.span());
|
||||
if (type.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) {
|
||||
return PbsAst.TypeRef.namedTuple(ReadOnlyList.wrap(type.fields().stream().map(field ->
|
||||
new PbsAst.NamedTypeField(field.label(), replaceSelf(field.typeRef(), owner), field.span())).toList()), type.span());
|
||||
|
||||
+20
-21
@@ -18,6 +18,7 @@ public final class PbsAst {
|
||||
|
||||
public enum TypeRefKind {
|
||||
SIMPLE,
|
||||
FN,
|
||||
SELF,
|
||||
OPTIONAL,
|
||||
ARRAY,
|
||||
@@ -119,7 +120,6 @@ public final class PbsAst {
|
||||
ServiceDecl,
|
||||
ErrorDecl,
|
||||
EnumDecl,
|
||||
CallbackDecl,
|
||||
GlobalDecl,
|
||||
ConstDecl,
|
||||
ImplementsDecl,
|
||||
@@ -198,15 +198,7 @@ public final class PbsAst {
|
||||
Span span) implements TopDecl {
|
||||
}
|
||||
|
||||
public record CallbackDecl(
|
||||
String name,
|
||||
ReadOnlyList<Parameter> parameters,
|
||||
ReturnKind returnKind,
|
||||
TypeRef returnType,
|
||||
TypeRef resultErrorType,
|
||||
ReadOnlyList<Attribute> attributes,
|
||||
Span span) implements TopDecl {
|
||||
}
|
||||
|
||||
|
||||
public record GlobalDecl(
|
||||
String name,
|
||||
@@ -255,6 +247,10 @@ public final class PbsAst {
|
||||
ReadOnlyList<NamedTypeField> fields,
|
||||
TypeRef inner,
|
||||
Span span) {
|
||||
public static TypeRef function(ReadOnlyList<NamedTypeField> inputs, TypeRef output, Span span) {
|
||||
return new TypeRef(TypeRefKind.FN, "Fn", inputs, output, span);
|
||||
}
|
||||
|
||||
public static TypeRef simple(final String name, final Span span) {
|
||||
return new TypeRef(TypeRefKind.SIMPLE, name, ReadOnlyList.empty(), null, span);
|
||||
}
|
||||
@@ -448,7 +444,7 @@ public final class PbsAst {
|
||||
GroupExpr,
|
||||
ThisExpr,
|
||||
NewExpr,
|
||||
BindExpr,
|
||||
LambdaExpr,
|
||||
SomeExpr,
|
||||
NoneExpr,
|
||||
OkExpr,
|
||||
@@ -629,12 +625,20 @@ public final class PbsAst {
|
||||
Span span) implements Expression {
|
||||
}
|
||||
|
||||
public record BindExpr(
|
||||
Expression contextExpression,
|
||||
String functionName,
|
||||
public record LambdaExpr(
|
||||
ReadOnlyList<IdentifierExpr> captures,
|
||||
ReadOnlyList<Parameter> parameters,
|
||||
TypeRef returnType,
|
||||
Block body,
|
||||
Span span) implements Expression {
|
||||
public TypeRef functionType() {
|
||||
return TypeRef.function(ReadOnlyList.wrap(parameters.stream().map(p ->
|
||||
new NamedTypeField(null, p.typeRef(), p.span())).toList()), returnType, span);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public record SomeExpr(
|
||||
Expression value,
|
||||
Span span) implements Expression {
|
||||
@@ -688,8 +692,7 @@ public final class PbsAst {
|
||||
BarrelEnumItem,
|
||||
BarrelServiceItem,
|
||||
BarrelGlobalItem,
|
||||
BarrelConstItem,
|
||||
BarrelCallbackItem {
|
||||
BarrelConstItem {
|
||||
Span span();
|
||||
}
|
||||
|
||||
@@ -756,9 +759,5 @@ public final class PbsAst {
|
||||
Span span) implements BarrelItem {
|
||||
}
|
||||
|
||||
public record BarrelCallbackItem(
|
||||
Visibility visibility,
|
||||
String name,
|
||||
Span span) implements BarrelItem {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package p.studio.compiler.pbs.ast;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Expression traversal shared by source scopes and structural editor projections. */
|
||||
public final class PbsLambdaTraversal {
|
||||
private PbsLambdaTraversal() {}
|
||||
|
||||
public static List<PbsAst.Expression> expressions(PbsAst.Statement statement) {
|
||||
var result = new ArrayList<PbsAst.Expression>();
|
||||
switch (statement) {
|
||||
case PbsAst.LetStatement s -> add(result, s.initializer());
|
||||
case PbsAst.AssignStatement s -> { add(result, s.target().expression()); add(result, s.value()); }
|
||||
case PbsAst.ReturnStatement s -> add(result, s.value());
|
||||
case PbsAst.ExpressionStatement s -> add(result, s.expression());
|
||||
case PbsAst.IfStatement s -> add(result, s.condition());
|
||||
case PbsAst.WhileStatement s -> add(result, s.condition());
|
||||
case PbsAst.ForStatement s -> { add(result, s.fromExpression()); add(result, s.untilExpression()); add(result, s.stepExpression()); }
|
||||
default -> { }
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static PbsAst.LambdaExpr enclosing(PbsAst.Statement statement, long offset) {
|
||||
for (var expression : expressions(statement)) {
|
||||
var found = enclosing(expression, offset);
|
||||
if (found != null) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static PbsAst.LambdaExpr enclosing(PbsAst.Expression expression, long offset) {
|
||||
if (expression == null || !expression.span().contains(offset)) return null;
|
||||
if (expression instanceof PbsAst.LambdaExpr lambda) return lambda;
|
||||
for (var child : children(expression)) {
|
||||
var found = enclosing(child, offset);
|
||||
if (found != null) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void visit(PbsAst.Expression expression, Consumer<PbsAst.LambdaExpr> visitor) {
|
||||
if (expression == null) return;
|
||||
if (expression instanceof PbsAst.LambdaExpr lambda) { visitor.accept(lambda); return; }
|
||||
for (var child : children(expression)) visit(child, visitor);
|
||||
}
|
||||
|
||||
private static List<PbsAst.Expression> children(PbsAst.Expression expression) {
|
||||
var children = new ArrayList<PbsAst.Expression>();
|
||||
switch (expression) {
|
||||
case PbsAst.CallExpr e -> { add(children,e.callee()); children.addAll(e.arguments().asList()); }
|
||||
case PbsAst.ApplyExpr e -> { add(children,e.callee()); add(children,e.argument()); }
|
||||
case PbsAst.ArrayLiteralExpr e -> children.addAll(e.elements().asList());
|
||||
case PbsAst.TupleExpr e -> e.items().forEach(item -> add(children,item.expression()));
|
||||
case PbsAst.GroupExpr e -> add(children,e.expression());
|
||||
case PbsAst.UnaryExpr e -> add(children,e.expression());
|
||||
case PbsAst.BinaryExpr e -> { add(children,e.left()); add(children,e.right()); }
|
||||
case PbsAst.MemberExpr e -> add(children,e.receiver());
|
||||
case PbsAst.IndexExpr e -> { add(children,e.receiver()); add(children,e.index()); }
|
||||
case PbsAst.NewExpr e -> children.addAll(e.arguments().asList());
|
||||
case PbsAst.SomeExpr e -> add(children,e.value());
|
||||
case PbsAst.OkExpr e -> add(children,e.value());
|
||||
case PbsAst.AsExpr e -> add(children,e.expression());
|
||||
case PbsAst.PropagateExpr e -> add(children,e.expression());
|
||||
case PbsAst.ElseExpr e -> { add(children,e.optionalExpression()); add(children,e.fallbackExpression()); }
|
||||
case PbsAst.BlockExpr e -> addBlock(children,e.block());
|
||||
case PbsAst.IfExpr e -> { add(children,e.condition()); addBlock(children,e.thenBlock()); add(children,e.elseExpression()); }
|
||||
case PbsAst.SwitchExpr e -> { add(children,e.selector()); e.arms().forEach(a -> addBlock(children,a.block())); }
|
||||
case PbsAst.HandleExpr e -> { add(children,e.value()); e.arms().forEach(a -> addBlock(children,a.block())); }
|
||||
default -> { }
|
||||
}
|
||||
return children;
|
||||
}
|
||||
private static void addBlock(List<PbsAst.Expression> result, PbsAst.Block block) {
|
||||
if (block == null) return;
|
||||
add(result,block.tailExpression());
|
||||
for (var statement : block.statements()) {
|
||||
result.addAll(expressions(statement));
|
||||
switch (statement) {
|
||||
case PbsAst.IfStatement s -> { addBlock(result,s.thenBlock()); addBlock(result,s.elseBlock());
|
||||
if(s.elseIf()!=null) addBlock(result,new PbsAst.Block(p.studio.utilities.structures.ReadOnlyList.from(s.elseIf()),null,s.elseIf().span())); }
|
||||
case PbsAst.ForStatement s -> addBlock(result,s.body());
|
||||
case PbsAst.WhileStatement s -> addBlock(result,s.body());
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
}
|
||||
private static void add(List<PbsAst.Expression> values, PbsAst.Expression expression) {
|
||||
if (expression != null) values.add(expression);
|
||||
}
|
||||
}
|
||||
+4
-13
@@ -284,8 +284,6 @@ public final class PbsModuleVisibilityValidator {
|
||||
registerNonFunctionDeclaration(declarations, NonFunctionKind.GLOBAL, globalDecl.name(), globalDecl.span(), nameTable);
|
||||
} else if (topDecl instanceof PbsAst.ConstDecl constDecl) {
|
||||
registerNonFunctionDeclaration(declarations, NonFunctionKind.CONST, constDecl.name(), constDecl.span(), nameTable);
|
||||
} else if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||
registerNonFunctionDeclaration(declarations, NonFunctionKind.CALLBACK, callbackDecl.name(), callbackDecl.span(), nameTable);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -370,9 +368,7 @@ public final class PbsModuleVisibilityValidator {
|
||||
if (item instanceof PbsAst.BarrelConstItem) {
|
||||
return NonFunctionKind.CONST;
|
||||
}
|
||||
if (item instanceof PbsAst.BarrelCallbackItem) {
|
||||
return NonFunctionKind.CALLBACK;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -401,9 +397,7 @@ public final class PbsModuleVisibilityValidator {
|
||||
if (item instanceof PbsAst.BarrelConstItem constItem) {
|
||||
return constItem.name();
|
||||
}
|
||||
if (item instanceof PbsAst.BarrelCallbackItem callbackItem) {
|
||||
return callbackItem.name();
|
||||
}
|
||||
|
||||
return "<unknown>";
|
||||
}
|
||||
|
||||
@@ -432,9 +426,7 @@ public final class PbsModuleVisibilityValidator {
|
||||
if (item instanceof PbsAst.BarrelConstItem constItem) {
|
||||
return constItem.visibility();
|
||||
}
|
||||
if (item instanceof PbsAst.BarrelCallbackItem callbackItem) {
|
||||
return callbackItem.visibility();
|
||||
}
|
||||
|
||||
return PbsAst.Visibility.MOD;
|
||||
}
|
||||
|
||||
@@ -487,8 +479,7 @@ public final class PbsModuleVisibilityValidator {
|
||||
ENUM,
|
||||
SERVICE,
|
||||
GLOBAL,
|
||||
CONST,
|
||||
CALLBACK
|
||||
CONST
|
||||
}
|
||||
|
||||
private record NonFunctionSymbolKey(
|
||||
|
||||
+1
@@ -70,6 +70,7 @@ final class PbsCallableShapeSurfaceService {
|
||||
return switch (unwrapped.kind()) {
|
||||
case SIMPLE -> "simple:" + unwrapped.name();
|
||||
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()) + ")";
|
||||
case OPTIONAL -> "optional(" + typeSurfaceKey(unwrapped.inner()) + ")";
|
||||
case UNIT -> "unit";
|
||||
|
||||
+101
-3
@@ -49,6 +49,15 @@ final class PbsExecutableBodyLowerer {
|
||||
var separator=callableName.indexOf('.');
|
||||
if(separator>0 && metadataIndex.types().services.containsKey(callableName.substring(0,separator))) context.serviceOwner=callableName.substring(0,separator);
|
||||
context.returnType = functionDecl.returnType();
|
||||
int captureIndex = 0;
|
||||
for (var capture : metadataIndex.types().capturesByFunction.getOrDefault(functionDecl.name(), java.util.List.of())) {
|
||||
var type = capture.typeRef();
|
||||
for (var part : context.types().results(type))
|
||||
registry(GET_CAPTURE, null, captureIndex++, 0, registryWidth(part, context), capture.span(), context);
|
||||
context.localTypes.put(capture.label(), type);
|
||||
int slot = context.declareLocalSlots(capture.label(), context.types().slots(type));
|
||||
emitStoreLocalSlots(slot, context.types().slots(type), capture.span(), context);
|
||||
}
|
||||
final var terminated = lowerBlock(functionDecl.body(), context);
|
||||
finalizeFunctionInstructions(functionDecl, context, terminated);
|
||||
|
||||
@@ -313,7 +322,10 @@ final class PbsExecutableBodyLowerer {
|
||||
private boolean lowerForStatement(
|
||||
final PbsAst.ForStatement forStatement,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
final var outerScope = context.snapshotScope();
|
||||
context.localSlotByNameId().remove(context.nameTable().register(forStatement.iteratorName()));
|
||||
final var iteratorSlot = context.declareLocalSlot(forStatement.iteratorName());
|
||||
context.localTypes.put(forStatement.iteratorName(), forStatement.iteratorType());
|
||||
lowerExpression(forStatement.fromExpression(), context);
|
||||
emitSetLocal(iteratorSlot, forStatement.span(), context);
|
||||
final var loopStart = context.nextLabel("for_start");
|
||||
@@ -338,6 +350,7 @@ final class PbsExecutableBodyLowerer {
|
||||
emitSetLocal(iteratorSlot, forStatement.span(), context);
|
||||
emitJump(IRBackendExecutableFunction.InstructionKind.JMP, loopStart, forStatement.span(), context);
|
||||
emitLabel(loopExit, forStatement.span(), context);
|
||||
context.restoreScope(outerScope);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -390,6 +403,7 @@ final class PbsExecutableBodyLowerer {
|
||||
return;
|
||||
}
|
||||
switch (expression) {
|
||||
case PbsAst.LambdaExpr lambda -> lowerLambda(lambda, context);
|
||||
case PbsAst.ArrayLiteralExpr literal -> lowerArrayLiteral(literal, context);
|
||||
case PbsAst.IndexExpr index -> lowerArrayRead(index, context);
|
||||
case PbsAst.CallExpr callExpr -> lowerCallExpression(callExpr, context);
|
||||
@@ -428,7 +442,7 @@ final class PbsExecutableBodyLowerer {
|
||||
var fields = context.types().fields.get(newExpr.typeName());
|
||||
for(int i=0; i<newExpr.arguments().size(); i++) lowerExpected(newExpr.arguments().get(i), fields != null && i < fields.size() ? fields.get(i).typeRef() : null, context);
|
||||
}
|
||||
case PbsAst.BindExpr bindExpr -> lowerExpression(bindExpr.contextExpression(), context);
|
||||
|
||||
case PbsAst.SomeExpr someExpr -> {
|
||||
var optional = PbsRuntimeTypes.unwrap(context.expectedType);
|
||||
var payload = optional != null && optional.kind() == PbsAst.TypeRefKind.OPTIONAL ? optional.inner() : expressionType(someExpr.value(), context);
|
||||
@@ -463,9 +477,66 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isDirectFunction(PbsAst.Expression callee, PbsExecutableLoweringContext c) {
|
||||
if (callee instanceof PbsAst.GroupExpr group) return isDirectFunction(group.expression(), c);
|
||||
return callee instanceof PbsAst.IdentifierExpr id && !c.localTypes.containsKey(id.name())
|
||||
&& !c.types().values.containsKey(id.name()) && c.types().functions.containsKey(id.name());
|
||||
}
|
||||
|
||||
private void makeClosure(IRRegistry.TypeRef type, p.studio.compiler.source.identifiers.CallableId target,
|
||||
int captures, Span span, PbsExecutableLoweringContext c) {
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.REGISTRY,
|
||||
null, "", null, null, null, "", "", captures, 1, span,
|
||||
new IRRegistryInstruction(MAKE_CLOSURE, type, null, target, 0)));
|
||||
}
|
||||
|
||||
private void lowerLambda(PbsAst.LambdaExpr lambda, PbsExecutableLoweringContext c) {
|
||||
var captures = new java.util.ArrayList<PbsAst.NamedTypeField>();
|
||||
int slots = 0;
|
||||
for (var capture : lambda.captures()) {
|
||||
var type = c.localTypes.get(capture.name());
|
||||
if (type == null) throw new IllegalStateException("Unresolved capture: " + capture.name());
|
||||
captures.add(new PbsAst.NamedTypeField(capture.name(), type, capture.span()));
|
||||
lowerExpected(capture, type, c);
|
||||
slots += c.types().slots(type);
|
||||
}
|
||||
var name = "$lambda." + lambda.span().getFileId().getId() + "." + lambda.span().getStart();
|
||||
var function = new PbsAst.FunctionDecl(name, lambda.parameters(),
|
||||
lambda.returnType().kind() == PbsAst.TypeRefKind.UNIT ? PbsAst.ReturnKind.EXPLICIT_UNIT : PbsAst.ReturnKind.PLAIN,
|
||||
lambda.returnType(), null, ReadOnlyList.empty(), PbsAst.LifecycleMarker.NONE, lambda.body(), lambda.span());
|
||||
var callable = new PbsLowerableCallable(name, function);
|
||||
var registry = c.callableRegistry();
|
||||
var id = registry.callableIdByDeclaration().get(callable);
|
||||
if (id == null) {
|
||||
id = new p.studio.compiler.source.identifiers.CallableId(registry.callableSignatureByCallableId().size());
|
||||
registry.callableIdByDeclaration().put(callable,id);
|
||||
var module = registry.callableSignatures().isEmpty() ? ModuleId.none() : registry.callableSignatures().getFirst().moduleId();
|
||||
registry.callableSignatureByCallableId().put(id, new p.studio.compiler.source.tables.CallableSignatureRef(
|
||||
module,name,lambda.parameters().size(),new PbsCallableShapeSurfaceService().callableShapeSurfaceOf(function)));
|
||||
c.types().capturesByFunction.put(name, java.util.List.copyOf(captures));
|
||||
c.types().closureBodies.add(new PbsRuntimeTypes.ClosureBody(function, java.util.List.copyOf(captures)));
|
||||
}
|
||||
makeClosure(c.types().registryType(lambda.functionType()), id, slots, lambda.span(), c);
|
||||
}
|
||||
|
||||
private void lowerCallExpression(
|
||||
final PbsAst.CallExpr callExpr,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
var functionType = isDirectFunction(callExpr.callee(), context) ? null : PbsRuntimeTypes.unwrap(expressionType(callExpr.callee(), context));
|
||||
if (functionType != null && functionType.kind() == PbsAst.TypeRefKind.FN) {
|
||||
lowerExpected(callExpr.callee(), functionType, context);
|
||||
int closureSlot = save(1, callExpr.callee().span(), context);
|
||||
int argumentSlots = 0;
|
||||
for (int i = 0; i < callExpr.arguments().size(); i++) {
|
||||
var type = functionType.fields().get(i).typeRef();
|
||||
lowerExpected(callExpr.arguments().get(i), type, context);
|
||||
argumentSlots += context.types().slots(type);
|
||||
}
|
||||
emitGetLocal(closureSlot, callExpr.span(), context);
|
||||
registry(CALL_CLOSURE, context.types().registryType(functionType), 0, argumentSlots + 1,
|
||||
context.types().slots(functionType.inner()), callExpr.span(), context);
|
||||
return;
|
||||
}
|
||||
if (lowerStructuredCall(callExpr, context)) return;
|
||||
if (callExpr.callee() instanceof PbsAst.MemberExpr member) {
|
||||
var receiverType = PbsRuntimeTypes.unwrap(expressionType(member.receiver(), context));
|
||||
@@ -656,6 +727,15 @@ final class PbsExecutableBodyLowerer {
|
||||
private void lowerIdentifierExpression(
|
||||
final PbsAst.IdentifierExpr identifierExpr,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
if (!context.localTypes.containsKey(identifierExpr.name()) && !context.types().values.containsKey(identifierExpr.name())) {
|
||||
var type = PbsRuntimeTypes.unwrap(expressionType(identifierExpr, context));
|
||||
if (type != null && type.kind() == PbsAst.TypeRefKind.FN) {
|
||||
var id = context.exactLocalCallable(identifierExpr.name(), type.fields().stream().map(PbsAst.NamedTypeField::typeRef).toList(), type.inner());
|
||||
if (id == null) { reportUnsupportedLowering("Unresolved function reference: " + identifierExpr.name(), identifierExpr.span(), context); return; }
|
||||
makeClosure(context.types().registryType(type), id, 0, identifierExpr.span(), context);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (context.types().services.containsKey(identifierExpr.name())) {
|
||||
lowerServiceValue(identifierExpr.name(), identifierExpr.span(), context);
|
||||
return;
|
||||
@@ -767,7 +847,8 @@ final class PbsExecutableBodyLowerer {
|
||||
case PbsAst.PropagateExpr propagateExpr -> materializedValueSlots(propagateExpr.expression(), context);
|
||||
case PbsAst.GroupExpr groupExpr -> materializedValueSlots(groupExpr.expression(), context);
|
||||
case PbsAst.NewExpr newExpr -> expressionListValueSlots(newExpr.arguments(), context);
|
||||
case PbsAst.BindExpr bindExpr -> materializedValueSlots(bindExpr.contextExpression(), context);
|
||||
case PbsAst.LambdaExpr lambda -> 1;
|
||||
|
||||
case PbsAst.SomeExpr someExpr -> materializedValueSlots(someExpr.value(), context);
|
||||
case PbsAst.OkExpr okExpr -> materializedValueSlots(okExpr.value(), context);
|
||||
case PbsAst.TupleExpr tupleExpr -> {
|
||||
@@ -813,6 +894,8 @@ final class PbsExecutableBodyLowerer {
|
||||
private boolean producesIdentifierValue(
|
||||
final PbsAst.IdentifierExpr identifierExpr,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
var valueType = PbsRuntimeTypes.unwrap(expressionType(identifierExpr, context));
|
||||
if (valueType != null && valueType.kind() == PbsAst.TypeRefKind.FN) return true;
|
||||
if (context.types().services.containsKey(identifierExpr.name())) {
|
||||
return true;
|
||||
}
|
||||
@@ -953,6 +1036,7 @@ final class PbsExecutableBodyLowerer {
|
||||
|
||||
private PbsAst.TypeRef expressionType(PbsAst.Expression e, PbsExecutableLoweringContext c) {
|
||||
if (e == null) return null;
|
||||
if (e instanceof PbsAst.LambdaExpr lambda) return lambda.functionType();
|
||||
if (e instanceof PbsAst.ArrayLiteralExpr || e instanceof PbsAst.NoneExpr) return c.expectedType;
|
||||
if (e instanceof PbsAst.TupleExpr tuple) return PbsAst.TypeRef.namedTuple(ReadOnlyList.wrap(tuple.items().stream()
|
||||
.map(item -> new PbsAst.NamedTypeField(item.label(),expressionType(item.expression(),c),item.span())).toList()),tuple.span());
|
||||
@@ -971,7 +1055,19 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
if (e instanceof PbsAst.IdentifierExpr i) {
|
||||
if(c.types().services.containsKey(i.name()))return PbsRuntimeTypes.type(i.name());
|
||||
return c.localTypes.getOrDefault(i.name(), c.types().values.get(i.name()));
|
||||
var local = c.localTypes.getOrDefault(i.name(), c.types().values.get(i.name()));
|
||||
if (local != null) return local;
|
||||
var functions = c.types().functions.get(i.name());
|
||||
if (functions != null && !functions.isEmpty()) {
|
||||
var expected = PbsRuntimeTypes.unwrap(c.expectedType);
|
||||
if (expected != null && expected.kind() == PbsAst.TypeRefKind.FN) return expected;
|
||||
if (functions.size() == 1) {
|
||||
var f = functions.getFirst();
|
||||
return PbsAst.TypeRef.function(ReadOnlyList.wrap(f.parameters().stream().map(p ->
|
||||
new PbsAst.NamedTypeField(null,p.typeRef(),p.span())).toList()),f.returnType(),f.span());
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (e instanceof PbsAst.GroupExpr g) return expressionType(g.expression(), c);
|
||||
if (e instanceof PbsAst.AsExpr a) return PbsRuntimeTypes.type(a.contractName());
|
||||
@@ -982,6 +1078,8 @@ final class PbsExecutableBodyLowerer {
|
||||
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.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();
|
||||
var sourceFunction = sourceFunction(call,c);
|
||||
if (sourceFunction != null) return sourceFunction.returnType();
|
||||
if (call.callee() instanceof PbsAst.MemberExpr member && member.memberName().equals("clear")) {
|
||||
|
||||
+1
-6
@@ -369,12 +369,7 @@ final class PbsExecutableCallsiteEmitter {
|
||||
identifierExpr.name(),
|
||||
nameTable.register(identifierExpr.name()));
|
||||
case PbsAst.MemberExpr memberExpr -> resolveMemberCalleeIdentity(memberExpr, nameTable);
|
||||
case PbsAst.BindExpr bindExpr ->
|
||||
new PbsCalleeIdentity(
|
||||
nameTable.register(bindExpr.functionName()),
|
||||
null,
|
||||
bindExpr.functionName(),
|
||||
nameTable.register(bindExpr.functionName()));
|
||||
|
||||
case PbsAst.GroupExpr groupExpr -> resolveCalleeIdentity(groupExpr.expression(), nameTable);
|
||||
default -> null;
|
||||
};
|
||||
|
||||
+1
@@ -25,6 +25,7 @@ final class PbsExecutableLoweringContext {
|
||||
final Map<String, p.studio.compiler.pbs.ast.PbsAst.TypeRef> localTypes = new HashMap<>();
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef expectedType;
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType;
|
||||
PbsExecutableCallableRegistry callableRegistry() { return callableRegistry; }
|
||||
PbsRuntimeTypes types() { return metadataIndex.types(); }
|
||||
String serviceOwner;
|
||||
private int nextLabelId = 0;
|
||||
|
||||
+10
-1
@@ -95,13 +95,22 @@ public final class PbsExecutableLoweringService {
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < metadataIndex.types().closureBodies.size(); i++) {
|
||||
var generated = metadataIndex.types().closureBodies.get(i);
|
||||
var callable = new PbsLowerableCallable(generated.function().name(), generated.function());
|
||||
var lowered = lowerExecutableFunction(fileId, normalizedModuleId, callable, callableRegistry,
|
||||
diagnostics, nameTable, metadataIndex, intrinsicIdTable);
|
||||
if (lowered != null) executableFunctions.add(lowered);
|
||||
}
|
||||
|
||||
final var intrinsicPool = new ArrayList<IntrinsicReference>(intrinsicIdTable.size());
|
||||
for (final var intrinsicId : intrinsicIdTable.identifiers()) {
|
||||
intrinsicPool.add(intrinsicIdTable.get(intrinsicId));
|
||||
}
|
||||
return new PbsExecutableLoweringResult(
|
||||
ReadOnlyList.wrap(executableFunctions),
|
||||
callableRegistry.callableSignatures(),
|
||||
ReadOnlyList.wrap(callableRegistry.callableSignatureByCallableId().entrySet().stream()
|
||||
.sorted(java.util.Comparator.comparingInt(e -> e.getKey().getIndex())).map(java.util.Map.Entry::getValue).toList()),
|
||||
ReadOnlyList.wrap(intrinsicPool), metadataIndex.types().registry());
|
||||
}
|
||||
|
||||
|
||||
+17
-1
@@ -8,6 +8,9 @@ import java.util.*;
|
||||
|
||||
/** PBS-owned source identities and layouts; never inferred from slot widths. */
|
||||
final class PbsRuntimeTypes {
|
||||
record ClosureBody(PbsAst.FunctionDecl function, java.util.List<PbsAst.NamedTypeField> captures) {}
|
||||
final java.util.List<ClosureBody> closureBodies = new ArrayList<>();
|
||||
final Map<String, java.util.List<PbsAst.NamedTypeField>> capturesByFunction = new HashMap<>();
|
||||
final Map<String, String> builtinNames;
|
||||
final Map<String, String> aliases = new HashMap<>();
|
||||
final Map<String, ReadOnlyList<PbsAst.BuiltinFieldDecl>> fields = new HashMap<>();
|
||||
@@ -82,6 +85,7 @@ final class PbsRuntimeTypes {
|
||||
String key(PbsAst.TypeRef t) {
|
||||
t = unwrap(t);
|
||||
if (t == null) return "void";
|
||||
if (t.kind() == PbsAst.TypeRefKind.FN) return "Fn(" + t.fields().stream().map(f->key(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ")->" + shapeKey(t.inner());
|
||||
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("")+")";
|
||||
@@ -119,6 +123,16 @@ final class PbsRuntimeTypes {
|
||||
}
|
||||
IRRegistry.TypeRef registryType(PbsAst.TypeRef type) {
|
||||
var t = unwrap(type);
|
||||
if (t.kind() == PbsAst.TypeRefKind.FN) {
|
||||
var ref = new IRRegistry.TypeRef("pbs:" + key(t));
|
||||
if (!used.containsKey(ref.declarationKey())) {
|
||||
var params = new ArrayList<IRRegistry.NamedType>();
|
||||
for (var input : t.fields()) for (var part : results(input.typeRef())) params.add(new IRRegistry.NamedType(part, null));
|
||||
var signature = new IRRegistry.Signature(ReadOnlyList.wrap(params), ReadOnlyList.wrap(results(t.inner())));
|
||||
used.put(ref.declarationKey(), new IRRegistry.TypeDeclaration(ref, null, new IRRegistry.Fn(signature)));
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
if (t.kind() == PbsAst.TypeRefKind.ARRAY) return arrayStorage();
|
||||
if (t.kind() == PbsAst.TypeRefKind.OPTIONAL || t.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) {
|
||||
var ref = new IRRegistry.TypeRef("pbs:value:"+key(t));
|
||||
@@ -180,7 +194,9 @@ final class PbsRuntimeTypes {
|
||||
var params=new ArrayList<IRRegistry.NamedType>();
|
||||
for(var p:f.parameters()) for(var type:results(p.typeRef())) params.add(new IRRegistry.NamedType(type,p.name()));
|
||||
var returns=f.returnKind()==PbsAst.ReturnKind.PLAIN ? results(f.returnType()) : List.<IRRegistry.TypeRef>of();
|
||||
return IRRegistry.FunctionMetadata.ordinary(new IRRegistry.Signature(ReadOnlyList.wrap(params),ReadOnlyList.wrap(returns)));
|
||||
var captures = capturesByFunction.getOrDefault(f.name(), List.of()).stream().flatMap(c -> results(c.typeRef()).stream()).toList();
|
||||
return new IRRegistry.FunctionMetadata(new IRRegistry.Signature(ReadOnlyList.wrap(params),ReadOnlyList.wrap(returns)),
|
||||
ReadOnlyList.wrap(captures), IRRegistry.Role.NONE);
|
||||
}
|
||||
IRRegistry registry() { return new IRRegistry(ReadOnlyList.wrap(new ArrayList<>(used.values())),ReadOnlyList.wrap(runtimeImplementations)); }
|
||||
Integer enumValue(String owner,String label) {
|
||||
|
||||
+2
-4
@@ -104,9 +104,7 @@ public final class PbsBarrelParser {
|
||||
if (cursor.match(PbsTokenKind.CONST)) {
|
||||
return parseSimpleItem(visibility, visibilityToken, PbsTokenKind.CONST);
|
||||
}
|
||||
if (cursor.match(PbsTokenKind.CALLBACK)) {
|
||||
return parseSimpleItem(visibility, visibilityToken, PbsTokenKind.CALLBACK);
|
||||
}
|
||||
|
||||
|
||||
report(cursor.peek(), ParseErrors.E_PARSE_UNEXPECTED_TOKEN,
|
||||
"Expected barrel declaration kind after visibility");
|
||||
@@ -131,7 +129,7 @@ public final class PbsBarrelParser {
|
||||
case SERVICE -> new PbsAst.BarrelServiceItem(visibility, name.lexeme(), itemSpan);
|
||||
case GLOBAL -> new PbsAst.BarrelGlobalItem(visibility, name.lexeme(), itemSpan);
|
||||
case CONST -> new PbsAst.BarrelConstItem(visibility, name.lexeme(), itemSpan);
|
||||
case CALLBACK -> new PbsAst.BarrelCallbackItem(visibility, name.lexeme(), itemSpan);
|
||||
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
+1
-23
@@ -127,10 +127,7 @@ final class PbsDeclarationParser {
|
||||
rejectUnsupportedDeclarationAttributes(pendingAttributes, "enum declarations");
|
||||
return parseEnumDeclaration(declareToken, pendingAttributes);
|
||||
}
|
||||
if (cursor.match(PbsTokenKind.CALLBACK)) {
|
||||
rejectUnsupportedDeclarationAttributes(pendingAttributes, "callback declarations");
|
||||
return parseCallbackDeclaration(declareToken, pendingAttributes);
|
||||
}
|
||||
|
||||
if (cursor.match(PbsTokenKind.GLOBAL)) {
|
||||
rejectAttributesBeforeUnsupportedTopDecl(pendingAttributes, "global declarations");
|
||||
return parseGlobalDeclaration(declareToken);
|
||||
@@ -614,26 +611,7 @@ final class PbsDeclarationParser {
|
||||
return token;
|
||||
}
|
||||
|
||||
private PbsAst.CallbackDecl parseCallbackDeclaration(
|
||||
final PbsToken declareToken,
|
||||
final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected callback name");
|
||||
consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after callback name");
|
||||
final var parameters = typeParser.parseParametersUntilRightParen();
|
||||
final var rightParen = consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after callback parameter list");
|
||||
|
||||
final var returnSpec = typeParser.parseCallableReturnSpec(rightParen);
|
||||
|
||||
final var semicolon = consume(PbsTokenKind.SEMICOLON, "Expected ';' after callback declaration");
|
||||
return new PbsAst.CallbackDecl(
|
||||
name.lexeme(),
|
||||
ReadOnlyList.wrap(parameters),
|
||||
returnSpec.kind(),
|
||||
returnSpec.returnType(),
|
||||
returnSpec.resultErrorType(),
|
||||
attributes,
|
||||
span(declareToken.start(), semicolon.end()));
|
||||
}
|
||||
|
||||
private PbsAst.ConstDecl parseConstDeclaration(
|
||||
final PbsToken declareToken,
|
||||
|
||||
+2
@@ -18,6 +18,8 @@ final class PbsExprParserContext {
|
||||
this.blockParserDelegate = blockParserDelegate;
|
||||
}
|
||||
|
||||
PbsTypeParser typeParser() { return new PbsTypeParser(parserContext); }
|
||||
|
||||
PbsTokenCursor cursor() {
|
||||
return cursor;
|
||||
}
|
||||
|
||||
+21
-13
@@ -87,6 +87,7 @@ final class PbsExprPrimaryParser {
|
||||
}
|
||||
|
||||
PbsAst.Expression parsePrimary() {
|
||||
if (cursor.match(PbsTokenKind.FN)) return parseLambda(cursor.previous());
|
||||
if (cursor.match(PbsTokenKind.LEFT_BRACKET)) {
|
||||
final var open = cursor.previous();
|
||||
final var elements = new ArrayList<PbsAst.Expression>();
|
||||
@@ -108,9 +109,7 @@ final class PbsExprPrimaryParser {
|
||||
if (cursor.match(PbsTokenKind.NEW)) {
|
||||
return parseNewExpression(cursor.previous());
|
||||
}
|
||||
if (cursor.match(PbsTokenKind.BIND)) {
|
||||
return parseBindExpression(cursor.previous());
|
||||
}
|
||||
|
||||
if (cursor.match(PbsTokenKind.SOME)) {
|
||||
return parseSomeExpression(cursor.previous());
|
||||
}
|
||||
@@ -252,18 +251,27 @@ final class PbsExprPrimaryParser {
|
||||
context.span(newToken.start(), close.end()));
|
||||
}
|
||||
|
||||
private PbsAst.Expression parseBindExpression(final PbsToken bindToken) {
|
||||
context.consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after 'bind'");
|
||||
final var contextExpression = expressionParserDelegate.parse();
|
||||
context.consume(PbsTokenKind.COMMA, "Expected ',' in bind(context, fn_name)");
|
||||
final var functionName = context.consume(PbsTokenKind.IDENTIFIER, "Expected function identifier in bind(context, fn_name)");
|
||||
final var close = context.consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after bind arguments");
|
||||
return new PbsAst.BindExpr(
|
||||
contextExpression,
|
||||
functionName.lexeme(),
|
||||
context.span(bindToken.start(), close.end()));
|
||||
private PbsAst.Expression parseLambda(PbsToken start) {
|
||||
context.consume(PbsTokenKind.LEFT_BRACKET, "Lambda requires explicit capture list, including []");
|
||||
var captures = new ArrayList<PbsAst.IdentifierExpr>();
|
||||
if (!cursor.check(PbsTokenKind.RIGHT_BRACKET)) do {
|
||||
var name = context.consume(PbsTokenKind.IDENTIFIER, "Expected captured binding name");
|
||||
captures.add(new PbsAst.IdentifierExpr(name.lexeme(), context.span(name.start(), name.end())));
|
||||
} while (cursor.match(PbsTokenKind.COMMA));
|
||||
context.consume(PbsTokenKind.RIGHT_BRACKET, "Expected ']' after captures");
|
||||
context.consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after captures");
|
||||
var types = context.typeParser();
|
||||
var parameters = types.parseParametersUntilRightParen();
|
||||
context.consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after lambda parameters");
|
||||
context.consume(PbsTokenKind.ARROW, "Lambda requires explicit result type");
|
||||
var result = types.parseTypeRef();
|
||||
var body = context.parseSurfaceBlock("Lambda requires a block body");
|
||||
return new PbsAst.LambdaExpr(ReadOnlyList.wrap(captures), ReadOnlyList.wrap(parameters), result, body,
|
||||
context.span(start.start(), body.span().getEnd()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
private PbsAst.Expression parseSomeExpression(final PbsToken someToken) {
|
||||
context.consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after 'some'");
|
||||
final var value = expressionParserDelegate.parse();
|
||||
|
||||
+14
@@ -70,6 +70,20 @@ final class PbsTypeParser {
|
||||
}
|
||||
|
||||
private PbsAst.TypeRef parseTypeRefBody() {
|
||||
if (cursor.check(PbsTokenKind.IDENTIFIER) && cursor.peek().lexeme().equals("Fn")) {
|
||||
var start = cursor.advance();
|
||||
consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after Fn");
|
||||
var inputs = new ArrayList<PbsAst.NamedTypeField>();
|
||||
if (!cursor.check(PbsTokenKind.RIGHT_PAREN)) do {
|
||||
var type = parseTypeRef();
|
||||
inputs.add(new PbsAst.NamedTypeField(null, type, type.span()));
|
||||
} while (cursor.match(PbsTokenKind.COMMA));
|
||||
consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after Fn parameter types");
|
||||
consume(PbsTokenKind.ARROW, "Fn requires an explicit result type");
|
||||
var output = parseTypeRef();
|
||||
return PbsAst.TypeRef.function(p.studio.utilities.structures.ReadOnlyList.wrap(inputs), output,
|
||||
context.span(start.start(), output.span().getEnd()));
|
||||
}
|
||||
if (cursor.check(PbsTokenKind.IDENTIFIER) && cursor.peek().lexeme().equals("array")) {
|
||||
final var start = cursor.advance();
|
||||
int depth = 1;
|
||||
|
||||
+2
-10
@@ -70,16 +70,7 @@ final class PbsAstDocumentSymbols {
|
||||
if (topDecl instanceof PbsAst.ErrorDecl errorDecl) {
|
||||
return errorSymbol(errorDecl);
|
||||
}
|
||||
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||
return callableSymbol(
|
||||
callbackDecl.name(),
|
||||
PbsEditorialSymbolKind.CALLBACK,
|
||||
callbackDecl.parameters(),
|
||||
callbackDecl.returnKind(),
|
||||
callbackDecl.returnType(),
|
||||
callbackDecl.resultErrorType(),
|
||||
callbackDecl.span());
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.GlobalDecl globalDecl) {
|
||||
return namedSymbol(
|
||||
globalDecl.name(),
|
||||
@@ -306,6 +297,7 @@ final class PbsAstDocumentSymbols {
|
||||
case UNIT -> typeRef.name() == null || typeRef.name().isBlank() ? "void" : typeRef.name();
|
||||
case SELF -> "Self";
|
||||
case SIMPLE -> typeRef.name() == null ? "void" : typeRef.name();
|
||||
case FN -> "Fn(" + typeRef.fields().stream().map(f -> formatTypeRef(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + formatTypeRef(typeRef.inner());
|
||||
case ARRAY -> "array " + formatTypeRef(typeRef.inner());
|
||||
case OPTIONAL -> "optional " + formatTypeRef(typeRef.inner());
|
||||
case GROUP -> "(" + formatTypeRef(typeRef.inner()) + ")";
|
||||
|
||||
+1
@@ -217,6 +217,7 @@ public final class PbsBuiltinLayoutResolver {
|
||||
return switch (typeRef.kind()) {
|
||||
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 OPTIONAL -> "optional %s".formatted(renderTypeSurface(typeRef.inner()));
|
||||
case UNIT -> "void";
|
||||
|
||||
+1
@@ -78,6 +78,7 @@ final class PbsCallableShape {
|
||||
return switch (unwrapped.kind()) {
|
||||
case SIMPLE -> "simple:" + unwrapped.name();
|
||||
case SELF -> "self";
|
||||
case FN -> "Fn(" + unwrapped.fields().stream().map(f -> typeKey(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + typeKey(unwrapped.inner());
|
||||
case ARRAY -> "array(" + typeKey(unwrapped.inner()) + ")";
|
||||
case OPTIONAL -> "optional(" + typeKey(unwrapped.inner()) + ")";
|
||||
case UNIT -> "unit";
|
||||
|
||||
+1
-15
@@ -116,21 +116,7 @@ final class PbsDeclarationRuleValidator {
|
||||
}
|
||||
}
|
||||
|
||||
void validateCallbackDeclaration(final PbsAst.CallbackDecl callbackDecl) {
|
||||
validateParameters(callbackDecl.parameters(), "callback '%s'".formatted(callbackDecl.name()));
|
||||
validateReturnSurface(
|
||||
callbackDecl.returnKind(),
|
||||
callbackDecl.returnType(),
|
||||
callbackDecl.resultErrorType(),
|
||||
"callback '%s'".formatted(callbackDecl.name()),
|
||||
callbackDecl.span(),
|
||||
false);
|
||||
PbsTypeSurfaceSemanticsValidator.validateTypeSurfaceRecursive(
|
||||
callbackDecl.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),
|
||||
"callback '%s'".formatted(callbackDecl.name()),
|
||||
false,
|
||||
diagnostics);
|
||||
}
|
||||
|
||||
|
||||
void validateConstDeclaration(final PbsAst.ConstDecl constDecl) {
|
||||
validateConstDeclaration(constDecl, true);
|
||||
|
||||
+1
-6
@@ -147,12 +147,7 @@ public final class PbsDeclarationSemanticsValidator {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||
validateDocAttributes(callbackDecl.attributes(), "callback declarations", diagnostics);
|
||||
binder.registerType(callbackDecl.name(), callbackDecl.span(), "callback");
|
||||
rules.validateCallbackDeclaration(callbackDecl);
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
if (topDecl instanceof PbsAst.GlobalDecl globalDecl) {
|
||||
binder.registerValue(globalDecl.name(), globalDecl.span(), "global");
|
||||
|
||||
+40
-32
@@ -18,9 +18,9 @@ import static p.studio.compiler.pbs.semantics.PbsFlowSemanticSupport.*;
|
||||
public final class PbsEditorialSupportService {
|
||||
private static final Set<String> BUILTIN_TYPE_NAMES = Set.of("int", "long", "float", "bool", "str", "string", "i32", "i64", "f32", "f64");
|
||||
private static final List<String> KEYWORDS = List.of(
|
||||
"fn", "declare", "let", "const", "global", "struct", "service", "host", "contract", "enum", "error", "callback",
|
||||
"fn", "declare", "let", "const", "global", "struct", "service", "host", "contract", "enum", "error", "Fn",
|
||||
"if", "else", "switch", "for", "until", "step", "while", "break", "continue", "return",
|
||||
"new", "bind", "apply", "handle", "some", "none", "ok", "err", "true", "false");
|
||||
"new", "apply", "handle", "some", "none", "ok", "err", "true", "false");
|
||||
|
||||
public List<PbsEditorialCompletionCandidate> completion(
|
||||
final String sourceText,
|
||||
@@ -456,8 +456,6 @@ public final class PbsEditorialSupportService {
|
||||
typeRefs.put(entry.getKey(), PbsAst.TypeRef.simple(enumDecl.name(), enumDecl.span()));
|
||||
} else if (entry.getValue().decl() instanceof PbsAst.ErrorDecl errorDecl) {
|
||||
typeRefs.put(entry.getKey(), PbsAst.TypeRef.simple(errorDecl.name(), errorDecl.span()));
|
||||
} else if (entry.getValue().decl() instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||
typeRefs.put(entry.getKey(), PbsAst.TypeRef.simple(callbackDecl.name(), callbackDecl.span()));
|
||||
}
|
||||
}
|
||||
return Map.copyOf(typeRefs);
|
||||
@@ -492,6 +490,19 @@ public final class PbsEditorialSupportService {
|
||||
break;
|
||||
}
|
||||
if (statement.span().contains(offset)) {
|
||||
var lambda = p.studio.compiler.pbs.ast.PbsLambdaTraversal.enclosing(statement, offset);
|
||||
if (lambda != null && (lambda.body().span().contains(offset)
|
||||
|| lambda.parameters().stream().anyMatch(p -> p.span().contains(offset)))) {
|
||||
var captured = new Scope();
|
||||
for (var capture : lambda.captures()) {
|
||||
var type = scope.resolve(capture.name());
|
||||
if (type != null) captured.bind(capture.name(), type, false);
|
||||
}
|
||||
for (var parameter : lambda.parameters()) captured.bind(parameter.name(),
|
||||
typeOps.typeFromTypeRef(parameter.typeRef(), model, frame.receiverType()));
|
||||
return lambda.body().span().contains(offset)
|
||||
? populateScopeUntilOffset(lambda.body(), captured, frame, offset) : captured;
|
||||
}
|
||||
if (statement instanceof PbsAst.IfStatement ifStatement) {
|
||||
if (ifStatement.thenBlock().span().contains(offset)
|
||||
|| (ifStatement.bindingSpan() != null && ifStatement.bindingSpan().contains(offset))) {
|
||||
@@ -987,7 +998,7 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
for (final var parameter : callableFrame.parameters()) {
|
||||
if (symbolName.equals(parameter.name())) {
|
||||
return locations(parameter.span());
|
||||
return locations(bindingSpan(callableFrame.body(), symbolName, offset, parameter.span()));
|
||||
}
|
||||
}
|
||||
return List.of();
|
||||
@@ -1000,7 +1011,9 @@ public final class PbsEditorialSupportService {
|
||||
if (callableFrame == null) {
|
||||
return List.of();
|
||||
}
|
||||
return locations(bindingSpan(callableFrame.body(), symbolName, offset, null));
|
||||
Span seed = null;
|
||||
for (var parameter : callableFrame.parameters()) if (parameter.name().equals(symbolName)) seed = parameter.span();
|
||||
return locations(bindingSpan(callableFrame.body(), symbolName, offset, seed));
|
||||
}
|
||||
|
||||
private Span bindingSpan(
|
||||
@@ -1017,6 +1030,16 @@ public final class PbsEditorialSupportService {
|
||||
found = letStatement.nameSpan() == null ? letStatement.span() : letStatement.nameSpan();
|
||||
}
|
||||
if (statement.span().contains(offset)) {
|
||||
var lambda = p.studio.compiler.pbs.ast.PbsLambdaTraversal.enclosing(statement, offset);
|
||||
if (lambda != null) {
|
||||
for (var parameter : lambda.parameters()) if (parameter.name().equals(symbolName)
|
||||
&& (parameter.span().contains(offset) || lambda.body().span().contains(offset)))
|
||||
return bindingSpan(lambda.body(), symbolName, offset, parameter.span());
|
||||
if (lambda.body().span().contains(offset)) {
|
||||
boolean captured = lambda.captures().stream().anyMatch(c -> c.name().equals(symbolName));
|
||||
return bindingSpan(lambda.body(), symbolName, offset, captured ? found : null);
|
||||
}
|
||||
}
|
||||
if (statement instanceof PbsAst.IfStatement ifStatement) {
|
||||
if (symbolName.equals(ifStatement.bindingName()) && ifStatement.bindingSpan() != null
|
||||
&& ifStatement.bindingSpan().contains(offset)) return ifStatement.bindingSpan();
|
||||
@@ -1236,9 +1259,7 @@ public final class PbsEditorialSupportService {
|
||||
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
|
||||
return contractDecl.attributes();
|
||||
}
|
||||
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||
return callbackDecl.attributes();
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.EnumDecl enumDecl) {
|
||||
return enumDecl.attributes();
|
||||
}
|
||||
@@ -1282,9 +1303,7 @@ public final class PbsEditorialSupportService {
|
||||
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||
return List.of(signatureFromFunction(functionDecl.name(), functionDecl.parameters(), functionDecl.returnKind(), functionDecl.returnType(), functionDecl.resultErrorType()));
|
||||
}
|
||||
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||
return List.of(signatureFromFunction(callbackDecl.name(), callbackDecl.parameters(), callbackDecl.returnKind(), callbackDecl.returnType(), callbackDecl.resultErrorType()));
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||
return serviceDecl.methods().stream()
|
||||
.map(method -> signatureFromFunction(method.name(), method.parameters(), method.returnKind(), method.returnType(), method.resultErrorType()))
|
||||
@@ -1392,7 +1411,8 @@ public final class PbsEditorialSupportService {
|
||||
case UNIT -> "unit";
|
||||
case SELF -> "Self";
|
||||
case SIMPLE -> typeRef.name();
|
||||
case ARRAY -> "array " + formatTypeRef(typeRef.inner());
|
||||
case FN -> "Fn(" + typeRef.fields().stream().map(f -> formatTypeRef(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + formatTypeRef(typeRef.inner());
|
||||
case ARRAY -> "array " + formatTypeRef(typeRef.inner());
|
||||
case OPTIONAL -> formatTypeRef(typeRef.inner()) + "?";
|
||||
case GROUP -> formatTypeRef(typeRef.inner());
|
||||
case NAMED_TUPLE -> {
|
||||
@@ -1537,9 +1557,7 @@ public final class PbsEditorialSupportService {
|
||||
if (topDecl instanceof PbsAst.ErrorDecl errorDecl) {
|
||||
return TypeView.error(errorDecl.name());
|
||||
}
|
||||
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||
return typeOps.typeFromTypeRef(PbsAst.TypeRef.simple(callbackDecl.name(), callbackDecl.span()), model, null);
|
||||
}
|
||||
|
||||
return TypeView.unknown();
|
||||
}
|
||||
|
||||
@@ -2021,6 +2039,9 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
return switch (typeRef.kind()) {
|
||||
case SIMPLE -> aliasedTypeRefs.getOrDefault(typeRef.name(), typeRef);
|
||||
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());
|
||||
case ARRAY -> PbsAst.TypeRef.array(aliasExpandedTypeRef(typeRef.inner()), typeRef.span());
|
||||
case OPTIONAL -> PbsAst.TypeRef.optional(aliasExpandedTypeRef(typeRef.inner()), typeRef.span());
|
||||
case GROUP -> PbsAst.TypeRef.group(aliasExpandedTypeRef(typeRef.inner()), typeRef.span());
|
||||
@@ -2065,9 +2086,7 @@ public final class PbsEditorialSupportService {
|
||||
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
|
||||
return contractDecl.name();
|
||||
}
|
||||
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||
return callbackDecl.name();
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.EnumDecl enumDecl) {
|
||||
return enumDecl.name();
|
||||
}
|
||||
@@ -2135,16 +2154,7 @@ public final class PbsEditorialSupportService {
|
||||
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
|
||||
return new PbsAst.ContractDecl(newName, contractDecl.signatures(), contractDecl.attributes(), contractDecl.span());
|
||||
}
|
||||
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||
return new PbsAst.CallbackDecl(
|
||||
newName,
|
||||
callbackDecl.parameters(),
|
||||
callbackDecl.returnKind(),
|
||||
callbackDecl.returnType(),
|
||||
callbackDecl.resultErrorType(),
|
||||
callbackDecl.attributes(),
|
||||
callbackDecl.span());
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.EnumDecl enumDecl) {
|
||||
return new PbsAst.EnumDecl(newName, enumDecl.cases(), enumDecl.attributes(), enumDecl.span());
|
||||
}
|
||||
@@ -2191,9 +2201,7 @@ public final class PbsEditorialSupportService {
|
||||
if (topDecl instanceof PbsAst.ContractDecl) {
|
||||
return PbsEditorialSymbolKind.CONTRACT;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.CallbackDecl) {
|
||||
return PbsEditorialSymbolKind.CALLBACK;
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.EnumDecl) {
|
||||
return PbsEditorialSymbolKind.ENUM;
|
||||
}
|
||||
|
||||
-1
@@ -266,7 +266,6 @@ final class PbsFlowAssignmentAnalyzer {
|
||||
return model.serviceSingletons.containsKey(rootName)
|
||||
|| model.constTypes.containsKey(rootName)
|
||||
|| model.topLevelCallables.containsKey(rootName)
|
||||
|| model.callbacks.containsKey(rootName)
|
||||
|| model.enums.containsKey(rootName)
|
||||
|| model.errors.containsKey(rootName)
|
||||
|| model.structs.containsKey(rootName)
|
||||
|
||||
-50
@@ -265,57 +265,7 @@ final class PbsFlowCallableResolutionAnalyzer {
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
|
||||
ExprResult analyzeBindExpression(
|
||||
final PbsAst.BindExpr bindExpr,
|
||||
final PbsFlowExpressionContext context) {
|
||||
final var contextType = analyzeValueExpression(bindExpr.contextExpression(), context, null).type();
|
||||
final var expectedType = context.expectedType();
|
||||
final var model = context.model();
|
||||
final var diagnostics = context.diagnostics();
|
||||
if (expectedType == null || expectedType.kind() != Kind.CALLBACK) {
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
|
||||
final var topLevel = model.topLevelCallables.get(bindExpr.functionName());
|
||||
if (topLevel == null || topLevel.isEmpty()) {
|
||||
return ExprResult.type(expectedType);
|
||||
}
|
||||
final var compatible = new ArrayList<CallableSymbol>();
|
||||
for (final var candidate : topLevel) {
|
||||
if (candidate.inputTypes().size() != expectedType.callbackInputs().size() + 1) {
|
||||
continue;
|
||||
}
|
||||
if (!typeOps.compatible(contextType, candidate.inputTypes().getFirst())) {
|
||||
continue;
|
||||
}
|
||||
var ok = true;
|
||||
for (int i = 0; i < expectedType.callbackInputs().size(); i++) {
|
||||
if (!typeOps.compatible(expectedType.callbackInputs().get(i), candidate.inputTypes().get(i + 1))) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!ok) {
|
||||
continue;
|
||||
}
|
||||
if (!typeOps.compatible(candidate.outputType(), expectedType.callbackOutput())) {
|
||||
continue;
|
||||
}
|
||||
compatible.add(candidate);
|
||||
}
|
||||
if (compatible.size() > 1) {
|
||||
Diagnostics.error(diagnostics,
|
||||
PbsSemanticsErrors.E_SEM_APPLY_AMBIGUOUS_OVERLOAD.name(),
|
||||
"Bind target resolves ambiguously for callback type",
|
||||
bindExpr.span());
|
||||
} else if (compatible.isEmpty()) {
|
||||
Diagnostics.error(diagnostics,
|
||||
PbsSemanticsErrors.E_SEM_APPLY_UNRESOLVED_OVERLOAD.name(),
|
||||
"Bind target does not resolve for callback type",
|
||||
bindExpr.span());
|
||||
}
|
||||
return ExprResult.type(expectedType);
|
||||
}
|
||||
|
||||
private ExprResult resolveCallableApplication(
|
||||
final Span wholeSpan,
|
||||
|
||||
+32
-3
@@ -73,6 +73,7 @@ final class PbsFlowExpressionAnalyzer {
|
||||
private ExprResult analyzeExpressionInternal(
|
||||
final PbsAst.Expression expression,
|
||||
final PbsFlowExpressionContext context) {
|
||||
if (expression instanceof PbsAst.LambdaExpr lambda) return analyzeLambda(lambda, context);
|
||||
final var structural = structuralExpressionAnalyzer.analyze(expression, context);
|
||||
if (structural != null) {
|
||||
return structural;
|
||||
@@ -101,13 +102,41 @@ final class PbsFlowExpressionAnalyzer {
|
||||
if (expression instanceof PbsAst.HandleExpr handleExpr) {
|
||||
return ExprResult.type(controlExpressionAnalyzer.analyzeHandleExpression(handleExpr, context));
|
||||
}
|
||||
if (expression instanceof PbsAst.BindExpr bindExpr) {
|
||||
return callableResolutionAnalyzer.analyzeBindExpression(bindExpr, context);
|
||||
}
|
||||
|
||||
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
|
||||
private ExprResult analyzeLambda(PbsAst.LambdaExpr lambda, PbsFlowExpressionContext context) {
|
||||
var scope = new Scope();
|
||||
scope.rejectUnknown = true;
|
||||
var names = new java.util.HashSet<String>();
|
||||
for (var capture : lambda.captures()) {
|
||||
var type = context.scope().resolve(capture.name());
|
||||
if (type == null || !names.add(capture.name())) {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(), "E_SEM_CAPTURE",
|
||||
"Capture must name a unique outer local binding: " + capture.name(), capture.span());
|
||||
type = TypeView.unknown();
|
||||
}
|
||||
scope.bind(capture.name(), type, false);
|
||||
}
|
||||
for (var parameter : lambda.parameters()) {
|
||||
if (!names.add(parameter.name())) p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(),
|
||||
"E_SEM_LAMBDA_PARAMETER", "Duplicate parameter or capture name: " + parameter.name(), parameter.span());
|
||||
scope.bind(parameter.name(), typeOps.typeFromTypeRef(parameter.typeRef(), context.model(), context.receiverType()));
|
||||
}
|
||||
PbsTypeSurfaceSemanticsValidator.validateTypeSurfaceRecursive(java.util.List.of(lambda.functionType()),
|
||||
"lambda", context.receiverType() != null, context.diagnostics());
|
||||
var fn = typeOps.typeFromTypeRef(lambda.functionType(), context.model(), context.receiverType());
|
||||
context.blockAnalyzer().analyze(lambda.body(), scope, fn.functionOutput(), null, null,
|
||||
context.model(), context.diagnostics(), false, null);
|
||||
new PbsFlowCompletionAnalyzer().validateCallableCompletion(lambda.body(), new PbsFlowBodyContext(scope,
|
||||
fn.functionOutput(), null, null, context.model(), context.diagnostics()));
|
||||
if (lambda.body().tailExpression() != null) p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(),
|
||||
"E_SEM_LAMBDA_RETURN", "Lambda bodies use explicit return statements", lambda.body().tailExpression().span());
|
||||
return ExprResult.type(fn);
|
||||
}
|
||||
|
||||
private TypeView analyzeBlock(
|
||||
final PbsAst.Block block,
|
||||
final PbsFlowExpressionContext context,
|
||||
|
||||
+12
-37
@@ -17,6 +17,8 @@ final class PbsFlowSemanticSupport {
|
||||
List<CallableSymbol> callables,
|
||||
boolean methodTarget) {
|
||||
static ExprResult type(final TypeView type) {
|
||||
if (type.kind() == Kind.FN) return new ExprResult(type,
|
||||
List.of(new CallableSymbol("Fn", List.of(), type.functionInputs(), type.functionOutput(), Span.none(), null)), false);
|
||||
return new ExprResult(type, List.of(), false);
|
||||
}
|
||||
|
||||
@@ -42,7 +44,7 @@ final class PbsFlowSemanticSupport {
|
||||
STRUCT,
|
||||
SERVICE,
|
||||
CONTRACT,
|
||||
CALLBACK,
|
||||
FN,
|
||||
ENUM,
|
||||
ERROR,
|
||||
OPTIONAL,
|
||||
@@ -65,8 +67,8 @@ final class PbsFlowSemanticSupport {
|
||||
List<TupleField> tupleFields,
|
||||
TypeView inner,
|
||||
TypeView errorType,
|
||||
List<TypeView> callbackInputs,
|
||||
TypeView callbackOutput) {
|
||||
List<TypeView> functionInputs,
|
||||
TypeView functionOutput) {
|
||||
static TypeView unknown() {
|
||||
return new TypeView(Kind.UNKNOWN, null, List.of(), null, null, List.of(), null);
|
||||
}
|
||||
@@ -107,11 +109,11 @@ final class PbsFlowSemanticSupport {
|
||||
return new TypeView(Kind.CONTRACT, name, List.of(), null, null, List.of(), null);
|
||||
}
|
||||
|
||||
static TypeView callback(
|
||||
static TypeView function(
|
||||
final String name,
|
||||
final List<TypeView> inputTypes,
|
||||
final TypeView outputType) {
|
||||
return new TypeView(Kind.CALLBACK, name, List.of(), null, null, List.copyOf(inputTypes), outputType);
|
||||
return new TypeView(Kind.FN, name, List.of(), null, null, List.copyOf(inputTypes), outputType);
|
||||
}
|
||||
|
||||
static TypeView enumType(final String name) {
|
||||
@@ -167,10 +169,6 @@ final class PbsFlowSemanticSupport {
|
||||
Span span) {
|
||||
}
|
||||
|
||||
record CallbackSignature(
|
||||
List<TypeView> inputTypes,
|
||||
TypeView outputType) {
|
||||
}
|
||||
|
||||
record StructInfo(
|
||||
Map<String, StructFieldInfo> fields,
|
||||
@@ -196,7 +194,6 @@ final class PbsFlowSemanticSupport {
|
||||
final Map<String, StructInfo> structs = new HashMap<>();
|
||||
final Map<String, ServiceInfo> services = new HashMap<>();
|
||||
final Map<String, ContractInfo> contracts = new HashMap<>();
|
||||
final Map<String, CallbackSignature> callbacks = new HashMap<>();
|
||||
final Map<String, Set<String>> enums = new HashMap<>();
|
||||
final Map<String, Set<String>> errors = new HashMap<>();
|
||||
final Map<String, TypeView> constTypes = new HashMap<>();
|
||||
@@ -208,7 +205,6 @@ final class PbsFlowSemanticSupport {
|
||||
final Set<String> knownContractNames = new HashSet<>();
|
||||
final Set<String> knownEnumNames = new HashSet<>();
|
||||
final Set<String> knownErrorNames = new HashSet<>();
|
||||
final Set<String> knownCallbackNames = new HashSet<>();
|
||||
final Map<String, Integer> assetIdByAddress = new HashMap<>();
|
||||
final Set<String> assetNamespacePrefixes = new HashSet<>();
|
||||
|
||||
@@ -268,9 +264,7 @@ final class PbsFlowSemanticSupport {
|
||||
knownErrorNames.add(errorDecl.name());
|
||||
return;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||
knownCallbackNames.add(callbackDecl.name());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void ingestTopDecl(final PbsAst.TopDecl topDecl) {
|
||||
@@ -389,22 +383,7 @@ final class PbsFlowSemanticSupport {
|
||||
documentationFromAttributes(functionDecl.attributes())));
|
||||
return;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.CallbackDecl(
|
||||
String name, ReadOnlyList<PbsAst.Parameter> parameters, PbsAst.ReturnKind returnKind,
|
||||
PbsAst.TypeRef returnType, PbsAst.TypeRef resultErrorType,
|
||||
ReadOnlyList<PbsAst.Attribute> ignoredAttributes, Span span
|
||||
)) {
|
||||
final var symbol = callableFrom(
|
||||
name,
|
||||
parameters,
|
||||
returnKind,
|
||||
returnType,
|
||||
resultErrorType,
|
||||
span,
|
||||
"");
|
||||
callbacks.put(name, new CallbackSignature(symbol.inputTypes(), symbol.outputType()));
|
||||
return;
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.EnumDecl enumDecl) {
|
||||
final var cases = new HashSet<String>();
|
||||
for (final var enumCase : enumDecl.cases()) {
|
||||
@@ -588,15 +567,9 @@ final class PbsFlowSemanticSupport {
|
||||
if (errors.containsKey(typeRef.name()) || knownErrorNames.contains(typeRef.name())) {
|
||||
yield TypeView.error(typeRef.name());
|
||||
}
|
||||
final var callbackSignature = callbacks.get(typeRef.name());
|
||||
if (callbackSignature != null) {
|
||||
yield TypeView.callback(typeRef.name(), callbackSignature.inputTypes(), callbackSignature.outputType());
|
||||
}
|
||||
if (knownCallbackNames.contains(typeRef.name())) {
|
||||
yield TypeView.callback(typeRef.name(), List.of(), TypeView.unknown());
|
||||
}
|
||||
yield TypeView.unknown();
|
||||
}
|
||||
case FN -> TypeView.function("Fn", typeRef.fields().stream().map(f -> typeFrom(f.typeRef())).toList(), typeFrom(typeRef.inner()));
|
||||
case ARRAY -> TypeView.array(typeFrom(typeRef.inner()));
|
||||
case OPTIONAL -> TypeView.optional(typeFrom(typeRef.inner()));
|
||||
case GROUP -> typeFrom(typeRef.inner());
|
||||
@@ -613,6 +586,7 @@ final class PbsFlowSemanticSupport {
|
||||
|
||||
static final class Scope {
|
||||
private final Map<String, LocalSymbol> names = new HashMap<>();
|
||||
boolean rejectUnknown;
|
||||
|
||||
record LocalSymbol(
|
||||
TypeView type,
|
||||
@@ -622,6 +596,7 @@ final class PbsFlowSemanticSupport {
|
||||
Scope copy() {
|
||||
final var scope = new Scope();
|
||||
scope.names.putAll(names);
|
||||
scope.rejectUnknown = rejectUnknown;
|
||||
return scope;
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -115,7 +115,8 @@ final class PbsFlowStatementAnalyzer {
|
||||
ExprUse.VALUE,
|
||||
true,
|
||||
this::analyzeNestedBlock);
|
||||
if (expected != null && (expected.kind() == Kind.ARRAY || initializer.type().kind() == Kind.ARRAY)
|
||||
if (expected != null && (expected.kind() == Kind.ARRAY || initializer.type().kind() == Kind.ARRAY
|
||||
|| expected.kind() == Kind.FN || initializer.type().kind() == Kind.FN)
|
||||
&& !typeOps.compatible(initializer.type(),expected)) {
|
||||
Diagnostics.error(diagnostics,"E_SEM_ARRAY_TYPE_MISMATCH","Array assignment requires the exact element type",letStatement.span());
|
||||
}
|
||||
|
||||
+12
-5
@@ -124,13 +124,18 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
return ExprResult.type(globalType);
|
||||
}
|
||||
|
||||
final var callbackSignature = model.callbacks.get(identifierExpr.name());
|
||||
if (callbackSignature != null) {
|
||||
return ExprResult.type(TypeView.callback(identifierExpr.name(), callbackSignature.inputTypes(), callbackSignature.outputType()));
|
||||
}
|
||||
|
||||
final var callables = model.topLevelCallables.get(identifierExpr.name());
|
||||
if (callables != null && !callables.isEmpty()) {
|
||||
if (context.use() == PbsFlowSemanticSupport.ExprUse.VALUE) {
|
||||
var candidates = callables.stream().filter(f -> expectedType == null ||
|
||||
typeOps.compatible(TypeView.function("Fn", f.inputTypes(), f.outputType()), expectedType)).toList();
|
||||
if (candidates.size() == 1) {
|
||||
var f = candidates.getFirst();
|
||||
return ExprResult.type(TypeView.function("Fn", f.inputTypes(), f.outputType()));
|
||||
}
|
||||
Diagnostics.error(diagnostics, "E_SEM_FN_REFERENCE", "Function reference requires one compatible signature", identifierExpr.span());
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
return ExprResult.callables(callables, false);
|
||||
}
|
||||
|
||||
@@ -142,6 +147,8 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
return ExprResult.type(TypeView.typeRef(identifierExpr.name()));
|
||||
}
|
||||
|
||||
if (context.scope().rejectUnknown) Diagnostics.error(diagnostics, "E_SEM_CAPTURE_REQUIRED",
|
||||
"Unknown binding or missing explicit capture: " + identifierExpr.name(), identifierExpr.span());
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
if (expression instanceof PbsAst.GroupExpr groupExpr) {
|
||||
|
||||
+7
-5
@@ -50,7 +50,11 @@ final class PbsFlowTypeOps {
|
||||
}
|
||||
return switch (actual.kind()) {
|
||||
case UNIT, INT, LONG, FLOAT, BOOL, STR -> true;
|
||||
case STRUCT, SERVICE, CONTRACT, CALLBACK, ENUM, ERROR, TYPE_REF, ASSET_NAMESPACE -> actual.name().equals(expected.name());
|
||||
case STRUCT, SERVICE, CONTRACT, ENUM, ERROR, 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)))
|
||||
&& compatible(actual.functionOutput(), expected.functionOutput());
|
||||
case ADDRESSABLE -> true;
|
||||
case ARRAY -> compatible(actual.inner(), expected.inner());
|
||||
case OPTIONAL -> compatible(actual.inner(), expected.inner());
|
||||
@@ -106,6 +110,8 @@ final class PbsFlowTypeOps {
|
||||
case UNIT -> TypeView.unit();
|
||||
case SELF -> receiverType == null ? TypeView.unknown() : receiverType;
|
||||
case SIMPLE -> simpleType(typeRef.name(), model);
|
||||
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));
|
||||
case OPTIONAL -> TypeView.optional(typeFromTypeRef(typeRef.inner(), model, receiverType));
|
||||
case GROUP -> typeFromTypeRef(typeRef.inner(), model, receiverType);
|
||||
@@ -210,10 +216,6 @@ final class PbsFlowTypeOps {
|
||||
if (model.errors.containsKey(name)) {
|
||||
return TypeView.error(name);
|
||||
}
|
||||
final var callbackSignature = model.callbacks.get(name);
|
||||
if (callbackSignature != null) {
|
||||
return TypeView.callback(name, callbackSignature.inputTypes(), callbackSignature.outputType());
|
||||
}
|
||||
return TypeView.unknown();
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -15,11 +15,12 @@ final class PbsInlineHintSurfaceFormatter {
|
||||
case STRUCT,
|
||||
SERVICE,
|
||||
CONTRACT,
|
||||
CALLBACK,
|
||||
ENUM,
|
||||
ERROR,
|
||||
TYPE_REF,
|
||||
ADDRESSABLE -> type.name();
|
||||
case FN -> "Fn(" + type.functionInputs().stream().map(this::format)
|
||||
.collect(java.util.stream.Collectors.joining(", ")) + ") -> " + format(type.functionOutput());
|
||||
case ARRAY -> {
|
||||
final var inner = format(type.inner());
|
||||
yield inner == null ? null : "array (" + inner + ")";
|
||||
|
||||
+1
-4
@@ -232,10 +232,7 @@ public final class PbsLifecycleSemanticsValidator {
|
||||
validateExpression(propagateExpr.expression(), hostPolicy, diagnostics);
|
||||
return;
|
||||
}
|
||||
if (expression instanceof PbsAst.BindExpr bindExpr) {
|
||||
validateExpression(bindExpr.contextExpression(), hostPolicy, diagnostics);
|
||||
return;
|
||||
}
|
||||
|
||||
if (expression instanceof PbsAst.AsExpr asExpr) {
|
||||
validateExpression(asExpr.expression(), hostPolicy, diagnostics);
|
||||
return;
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ public final class PbsQuickFixCollector {
|
||||
}
|
||||
case PbsAst.ErrorDecl errorDecl -> duplicateDoc(errorDecl.attributes(), repairs);
|
||||
case PbsAst.EnumDecl enumDecl -> duplicateDoc(enumDecl.attributes(), repairs);
|
||||
case PbsAst.CallbackDecl callbackDecl -> duplicateDoc(callbackDecl.attributes(), repairs);
|
||||
|
||||
case PbsAst.ConstDecl constDecl -> {
|
||||
duplicateDoc(constDecl.attributes(), repairs);
|
||||
duplicateNamed(constDecl.attributes(), "BuiltinConst", repairs);
|
||||
|
||||
+9
@@ -23,6 +23,15 @@ final class PbsTypeSurfaceSemanticsValidator {
|
||||
}
|
||||
|
||||
switch (typeRef.kind()) {
|
||||
case FN -> {
|
||||
pending.add(typeRef.inner());
|
||||
for (var parameter : typeRef.fields()) {
|
||||
if (parameter.typeRef().kind() == PbsAst.TypeRefKind.UNIT)
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics, "E_SEM_FN_PARAMETER",
|
||||
"Fn parameter must be a value type", parameter.span());
|
||||
pending.add(parameter.typeRef());
|
||||
}
|
||||
}
|
||||
case ARRAY -> {
|
||||
var element = typeRef.inner();
|
||||
while (element != null && element.kind() == PbsAst.TypeRefKind.GROUP) element = element.inner();
|
||||
|
||||
+7
-8
@@ -259,10 +259,7 @@ final class PbsImportedSemanticContextService {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||
collectReferencedTypeNames(callbackDecl.parameters(), callbackDecl.returnType(), callbackDecl.resultErrorType(), sink);
|
||||
return;
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||
collectReferencedTypeNames(functionDecl, sink);
|
||||
return;
|
||||
@@ -321,6 +318,10 @@ final class PbsImportedSemanticContextService {
|
||||
sink.addLast(simpleName);
|
||||
}
|
||||
}
|
||||
case FN -> {
|
||||
collectReferencedTypeNames(typeRef.inner(), sink);
|
||||
for (var parameter : typeRef.fields()) collectReferencedTypeNames(parameter.typeRef(), sink);
|
||||
}
|
||||
case ARRAY, OPTIONAL, GROUP -> collectReferencedTypeNames(typeRef.inner(), sink);
|
||||
case NAMED_TUPLE -> {
|
||||
for (final var field : typeRef.fields()) {
|
||||
@@ -346,7 +347,7 @@ final class PbsImportedSemanticContextService {
|
||||
|| topDecl instanceof PbsAst.ServiceDecl
|
||||
|| topDecl instanceof PbsAst.HostDecl
|
||||
|| topDecl instanceof PbsAst.ContractDecl
|
||||
|| topDecl instanceof PbsAst.CallbackDecl
|
||||
|
||||
|| topDecl instanceof PbsAst.EnumDecl
|
||||
|| topDecl instanceof PbsAst.ErrorDecl;
|
||||
}
|
||||
@@ -429,9 +430,7 @@ final class PbsImportedSemanticContextService {
|
||||
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||
return functionDecl.name();
|
||||
}
|
||||
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||
return callbackDecl.name();
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.EnumDecl enumDecl) {
|
||||
return enumDecl.name();
|
||||
}
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
// A closure keeps its object alive; each invocation completes in its own frame.
|
||||
declare struct ClosureExampleCounter(pub mut value: int);
|
||||
|
||||
fn createExampleCounter(start: int) -> Fn() -> int {
|
||||
let counter = new ClosureExampleCounter(start);
|
||||
return fn [counter]() -> int {
|
||||
counter.value += 1;
|
||||
return counter.value;
|
||||
};
|
||||
}
|
||||
|
||||
fn closureExample() -> int {
|
||||
let next = createExampleCounter(40);
|
||||
let functions: array (Fn() -> int) = [next];
|
||||
if let action = functions[0] {
|
||||
let first = action();
|
||||
return action();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
+2
-2
@@ -17,7 +17,7 @@ class PbsBarrelParserTest {
|
||||
mod fn run(state: optional int) -> result<Err> (value: int, meta: float);
|
||||
pub struct Vec2;
|
||||
mod global Palette;
|
||||
pub callback Tick;
|
||||
pub fn tick(dt: int) -> void;
|
||||
""";
|
||||
|
||||
final var diagnostics = DiagnosticSink.empty();
|
||||
@@ -41,7 +41,7 @@ class PbsBarrelParserTest {
|
||||
|
||||
assertInstanceOf(PbsAst.BarrelStructItem.class, barrel.items().get(2));
|
||||
assertInstanceOf(PbsAst.BarrelGlobalItem.class, barrel.items().get(3));
|
||||
assertInstanceOf(PbsAst.BarrelCallbackItem.class, barrel.items().get(4));
|
||||
assertInstanceOf(PbsAst.BarrelFunctionItem.class, barrel.items().get(4));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-2
@@ -134,7 +134,7 @@ class PbsExprParserTest {
|
||||
err(Game.Fail);
|
||||
new Vec(v);
|
||||
new Vec.zero(v);
|
||||
bind(ctx, handler);
|
||||
fn [ctx](x: int) -> int { return ctx + x; };
|
||||
return v;
|
||||
}
|
||||
""";
|
||||
@@ -158,7 +158,7 @@ class PbsExprParserTest {
|
||||
assertInstanceOf(PbsAst.ExpressionStatement.class, body.get(4)).expression());
|
||||
assertInstanceOf(PbsAst.NewExpr.class,
|
||||
assertInstanceOf(PbsAst.ExpressionStatement.class, body.get(5)).expression());
|
||||
assertInstanceOf(PbsAst.BindExpr.class,
|
||||
assertInstanceOf(PbsAst.LambdaExpr.class,
|
||||
assertInstanceOf(PbsAst.ExpressionStatement.class, body.get(6)).expression());
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -51,7 +51,7 @@ class PbsParserTest {
|
||||
|
||||
fn first() -> int { return 1; }
|
||||
declare struct Point(x: int, y: int);
|
||||
declare callback Tick(dt: int) -> int;
|
||||
fn tick(dt: int) -> int { return dt; }
|
||||
""";
|
||||
final var diagnostics = DiagnosticSink.empty();
|
||||
final var fileId = new FileId(0);
|
||||
@@ -64,7 +64,7 @@ class PbsParserTest {
|
||||
assertEquals(3, ast.topDecls().size());
|
||||
assertInstanceOf(PbsAst.FunctionDecl.class, ast.topDecls().get(0));
|
||||
assertInstanceOf(PbsAst.StructDecl.class, ast.topDecls().get(1));
|
||||
assertInstanceOf(PbsAst.CallbackDecl.class, ast.topDecls().get(2));
|
||||
assertInstanceOf(PbsAst.FunctionDecl.class, ast.topDecls().get(2));
|
||||
|
||||
final var importDecl = ast.imports().getFirst();
|
||||
assertEquals("core", importDecl.moduleRef().project());
|
||||
@@ -84,7 +84,7 @@ class PbsParserTest {
|
||||
declare service Game { fn tick(x: int) -> int { return x; } }
|
||||
declare error Err { Fail; Crash; }
|
||||
declare enum Mode(Idle = 0, Run = 1);
|
||||
declare callback TickCb(x: int) -> result<Err> int;
|
||||
fn tick(x: int) -> result<Err> int { return ok(x); }
|
||||
declare global STATE: int = 10;
|
||||
declare const LIMIT: int = 10;
|
||||
implements C for S using s { fn run(x: int) -> int { return x; } }
|
||||
@@ -122,7 +122,7 @@ class PbsParserTest {
|
||||
final var enumDecl = assertInstanceOf(PbsAst.EnumDecl.class, ast.topDecls().get(7));
|
||||
assertEquals(2, enumDecl.cases().size());
|
||||
|
||||
final var callbackDecl = assertInstanceOf(PbsAst.CallbackDecl.class, ast.topDecls().get(8));
|
||||
final var callbackDecl = assertInstanceOf(PbsAst.FunctionDecl.class, ast.topDecls().get(8));
|
||||
assertEquals(PbsAst.ReturnKind.RESULT, callbackDecl.returnKind());
|
||||
assertEquals("Err", callbackDecl.resultErrorType().name());
|
||||
|
||||
|
||||
+28
-2
@@ -16,6 +16,32 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
final class PbsEditorialSupportServiceTest {
|
||||
private final PbsEditorialSupportService service = new PbsEditorialSupportService();
|
||||
|
||||
@Test
|
||||
void closuresExposeCapturedObjectsAndOwnParameters() {
|
||||
String source = """
|
||||
declare struct Counter(pub mut value: int);
|
||||
fn main() {
|
||||
let counter = new Counter(40);
|
||||
let f = fn [counter](delta: int) -> int {
|
||||
counter.value += delta;
|
||||
return counter.value;
|
||||
};
|
||||
let answer = f(2);
|
||||
}
|
||||
""";
|
||||
var ast = parseOrdinary(source);
|
||||
int use = source.indexOf("counter.value");
|
||||
assertTrue(service.hover(source,ast,ReadOnlyList.empty(),use).isPresent());
|
||||
assertTrue(service.completion(source,ast,ReadOnlyList.empty(),use+8).stream().anyMatch(c -> c.label().equals("value")));
|
||||
assertFalse(service.definition(source,ast,ReadOnlyList.empty(),source.indexOf("delta;")).isEmpty());
|
||||
var rename = service.rename(source,ast,ReadOnlyList.empty(),use,"state");
|
||||
assertTrue(rename.allowed(),rename.refusal());
|
||||
assertEquals(4,rename.sites().size(),rename.sites().toString());
|
||||
var parameter = service.rename(source,ast,ReadOnlyList.empty(),source.indexOf("delta;"),"amount");
|
||||
assertTrue(parameter.allowed(),parameter.refusal());
|
||||
assertEquals(2,parameter.sites().size(),parameter.sites().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void arrayAndOptionalBindingShareEditorialScope() {
|
||||
String source = """
|
||||
@@ -552,7 +578,7 @@ final class PbsEditorialSupportServiceTest {
|
||||
declare service Physics { fn tick() -> void { return; } }
|
||||
declare error Io { NotFound; Busy; }
|
||||
declare enum Mode(Idle = 0, Run = 1);
|
||||
declare callback OnClick(x: int) -> result<Io> int;
|
||||
fn OnClick(x: int) -> result<Io> int { return ok(x); }
|
||||
declare global STATE: int = 10;
|
||||
declare const LIMIT: int = 10;
|
||||
implements TickLike for Point using s { fn tick(dt: int) -> void { return; } }
|
||||
@@ -613,7 +639,7 @@ final class PbsEditorialSupportServiceTest {
|
||||
assertEquals("0", mode.children().getFirst().detail());
|
||||
|
||||
final var callback = requireNamed(symbols, "OnClick");
|
||||
assertEquals(PbsEditorialSymbolKind.CALLBACK, callback.kind());
|
||||
assertEquals(PbsEditorialSymbolKind.FUNCTION, callback.kind());
|
||||
assertEquals("(x: int) -> result<Io> int", callback.detail());
|
||||
|
||||
assertEquals(PbsEditorialSymbolKind.GLOBAL, requireNamed(symbols, "STATE").kind());
|
||||
|
||||
+2
-2
@@ -199,7 +199,7 @@ class PbsSemanticsDeclarationsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectInvalidCtorServiceAndCallbackShapes() {
|
||||
void shouldRejectInvalidCtorServiceAndFunctionShapes() {
|
||||
final var source = """
|
||||
declare struct S(a: int) {
|
||||
ctor make(x: int) { return; }
|
||||
@@ -211,7 +211,7 @@ class PbsSemanticsDeclarationsTest {
|
||||
fn run(b: int) -> int { return b; }
|
||||
}
|
||||
|
||||
declare callback Tick(a: int, a: int) -> int;
|
||||
fn tick(a: int, a: int) -> int { return a; }
|
||||
""";
|
||||
final var diagnostics = DiagnosticSink.empty();
|
||||
|
||||
|
||||
@@ -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'
|
||||
./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeAlignmentTest' --tests '*PbsStructuredValuesTest' --tests '*PbsClosuresTest'
|
||||
python3 tools/pbx-conformance/run.py --runtime ../runtime
|
||||
```
|
||||
|
||||
@@ -112,3 +112,22 @@ nested references, tuples and strings remain readable. `resource-diagnostics`
|
||||
is enabled solely for observation. Default production ceilings and GC threshold
|
||||
are unchanged outside the explicitly lowered quota runs. This is semantic and
|
||||
resource conformance, not a performance benchmark or installed game qualification.
|
||||
|
||||
## PBS first-class functions and closure lifetime
|
||||
|
||||
`PbsClosuresTest` adds nine mandatory source/load/execute fixtures: named and
|
||||
anonymous functions, snapshots, shared objects/arrays, nested function captures,
|
||||
complete tuple groups and contract receivers, independent environments, Fn fields
|
||||
and overload selection, imported functions, and the installed example. Each
|
||||
returns 42. Six additional GuestBytes/HandleSlots runs at limits 0, 1 and 2 check
|
||||
closure allocation faults and session ownership, bringing structured quota runs
|
||||
to 24.
|
||||
|
||||
The tenth fixture, `closure-frame-lifecycle.pbx`, uses the existing production
|
||||
lifecycle assembler without bytecode patching. Its first frame stores a closure
|
||||
capturing an object; the next frame invokes it twice (41, then 42) and drops the
|
||||
reference. Each of three frames also discards 1,200 closures. The harness asserts
|
||||
threshold collections, retained closure/object reachability after frame one,
|
||||
and reclamation after release. The remaining root is the global array.
|
||||
PBS publishes FRAME_ROOT and the existing guarded wrapper returns normally.
|
||||
No sync syntax, new frame integration, suspension or coroutine is introduced.
|
||||
|
||||
@@ -40,6 +40,7 @@ fn main() {
|
||||
verify_pbs_fixtures(&root);
|
||||
verify_pbs_structured_fixtures(&root);
|
||||
verify_pbs_resource_refusals(&root);
|
||||
verify_pbs_closure_frames(&root);
|
||||
for name in [
|
||||
"minimal",
|
||||
"jump-end",
|
||||
@@ -542,7 +543,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 = ["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", "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"]) {
|
||||
@@ -587,7 +588,7 @@ fn verify_pbs_structured_fixtures(root: &std::path::Path) {
|
||||
|
||||
fn verify_pbs_resource_refusals(root: &std::path::Path) {
|
||||
use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits, RuntimeResource}};
|
||||
for name in ["array-cycle", "tuple-storage", "struct-contract"] {
|
||||
for name in ["closure-objects", "array-cycle", "tuple-storage", "struct-contract"] {
|
||||
for resource in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots] {
|
||||
for limit in [0, 1, 2] {
|
||||
let bytes = std::fs::read(root.join(format!("pbs-structured-{name}.pbx"))).unwrap();
|
||||
@@ -610,3 +611,22 @@ fn verify_pbs_resource_refusals(root: &std::path::Path) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_pbs_closure_frames(root: &std::path::Path) {
|
||||
use prometeu_vm::LogicalFrameEndingReason as End;
|
||||
let bytes = std::fs::read(root.join("closure-frame-lifecycle.pbx")).expect("mandatory closure frame fixture");
|
||||
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap();
|
||||
let mut vm = VirtualMachine::from_image(image, Default::default());
|
||||
for frame in 0..3 {
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let report = vm.run_budget(2_000_000, &mut NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert!(matches!(report.reason, End::Halted | End::EndOfRom), "frame {frame}: {report:?}");
|
||||
assert!(vm.operand_stack_top(1).is_empty(), "frame root returns void");
|
||||
let snapshot = vm.resource_snapshot();
|
||||
assert!(snapshot.gc.collections >= frame + 1, "frame {frame}: {:?}", snapshot.gc);
|
||||
assert!(snapshot.gc.reclaimed >= (frame + 1) * 1200, "frame {frame}: {:?}", snapshot.gc);
|
||||
if frame == 0 { assert!(vm.heap().len() >= 3, "array, closure and capture survive root return"); }
|
||||
else { assert_eq!(vm.heap().len(), 1, "only the empty global array remains after closure release"); }
|
||||
}
|
||||
println!("PBS CLOSURE FRAME LIFECYCLE/RETENTION/GC PASS");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user