This commit is contained in:
2026-03-24 13:42:37 +00:00
parent b33dc7c18d
commit e0f1d74204
112 changed files with 0 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
# General Documentation
This directory contains documentation that applies to language implementations in general, not only PBS.
## Tree
```text
docs/general/
└── specs/
```
## Purpose
`general/specs` is the cross-language acceptance layer.
Use it to define:
- shared conformance and quality-gate contracts,
- shared compatibility and verification policy,
- and backend/runtime acceptance boundaries that are language-agnostic.
@@ -0,0 +1,135 @@
# PBS Conformance Test Specification
Status: Draft v1 (Quality-Gate Baseline)
Applies to: executable quality gates for PBS language frontends and language-level regression evidence
## 1. Purpose
This document defines the minimum quality-gate contract for PBS language implementations.
The goal is practical and test-driven:
- keep quality measurable while language, lowering, and runtime integration are still evolving,
- require only gates that can be proved with tests today,
- avoid freezing speculative backend policy too early.
## 2. Scope
This document defines:
- required unit-test gates for language frontend work,
- required regression gate behavior for published language behavior,
- and the boundary for runtime integration regression tests when a backend can emit executable artifacts.
This document does not define:
- runtime semantics or VM behavior taxonomy,
- full artifact-level compatibility matrices,
- one test harness layout,
- or one repository structure for fixtures.
## 3. Authority and Precedence
Normative precedence:
1. `1. Language Charter.md`
2. `2. Governance and Versioning.md`
3. `3. Core Syntax Specification.md`
4. `4. Static Semantics Specification.md`
5. `12. Diagnostics Specification.md`
6. `13. Lowering IRBackend Specification.md`
7. `20. IRBackend to IRVM Lowering Specification.md`
8. `21. IRVM Optimization Pipeline Specification.md`
9. This document
This document must not weaken normative requirements from higher-precedence specs.
## 4. Normative Inputs
This document depends on:
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `12. Diagnostics Specification.md`
- `13. Lowering IRBackend Specification.md`
- `20. IRBackend to IRVM Lowering Specification.md`
- `21. IRVM Optimization Pipeline Specification.md`
- `17. Compatibility and Evolution Policy.md`
## 5. Quality Gate Model
PBS v1 uses two practical gate families.
### 5.1 Gate U: Language Unit Quality Gate (Required)
Every language frontend integrated into Studio/compiler must have passing unit tests that cover, at minimum:
1. lexer behavior (valid tokenization and deterministic lexical rejection),
2. parser behavior (valid parse and deterministic syntax rejection),
3. AST shape for representative valid programs,
4. frontend-to-IR backend emission (`IRBackend`/`IRBackendFile`) for representative valid programs,
5. diagnostics surface for required rejection cases (`code`, `severity`, and primary attribution).
This gate is mandatory for each language regardless of backend maturity.
### 5.2 Gate I: Integration Regression Gate With Runtime (Conditional)
When a language backend can emit executable artifacts (for example bytecode), integration regression tests must be introduced for that language.
At minimum, those tests must:
1. compile selected fixtures through the executable pipeline for that language,
2. execute them against the runtime line declared for that backend,
3. assert deterministic observable outcomes for supported fixtures,
4. preserve fixed bugs and published supported examples as regression tests,
5. and cover deterministic behavior across `LowerToVM`, `OptimizeIRVM`, and `EmitBytecode` boundaries when those stages are present.
Until executable artifact emission exists for a language, Gate I is explicitly `deferred` for that language and does not block frontend progress.
## 6. Regression Policy
Published supported behavior must remain regression-protected.
At minimum, each language corpus must retain:
1. bug reproductions for fixes that remain in supported scope,
2. published supported examples,
3. and core gate fixtures required to justify the language support state.
Regression grouping by language is expected; one shared monolithic corpus is not required.
## 7. Claims and Evidence
For PBS quality claims at this stage:
- a language may be considered `frontend-ready` only with Gate U passing,
- a language may be considered `integration-ready` only with Gate U and Gate I passing where Gate I applies,
- and a published support claim must map to executable evidence from these gates.
- conformance-relevant FE/BE changes in executable backend paths MUST update `22. Backend Spec-to-Test Conformance Matrix.md` and pass matrix hard-gate policy checks.
The exact publication vocabulary is owned by `17. Compatibility and Evolution Policy.md`.
## 8. Explicit Deferrals
The following are intentionally deferred until backend/runtime contracts stabilize further:
- detailed artifact-level conformance taxonomy,
- verifier-facing conformance taxonomy,
- full compatibility matrix axes beyond the current minimum support table,
- and one mandatory fixture repository layout.
## 9. Non-Goals
- Replacing normative language specs with tests.
- Defining runtime semantics in this document.
- Freezing backend architecture decisions prematurely.
- Treating performance benchmarks as conformance gates.
## 10. Exit Criteria
This document is in a healthy state when:
1. every active language has an explicit Gate U status,
2. languages with executable backends have an explicit Gate I status,
3. published supported language behavior has regression evidence,
4. and no support claim exists without mapped test evidence.
@@ -0,0 +1,405 @@
# PBS Name Resolution and Module Linking Specification
Status: Draft v1 (Normative)
Applies to: scope formation, name lookup, imports, exports, barrel visibility, cross-module resolution, and semantic linking of PBS programs
## 1. Purpose
This document defines the normative name-resolution and semantic-linking model for PBS v1.
Its purpose is to make the visible declaration space of a PBS program deterministic enough that:
- frontend implementations do not invent lookup or collision rules,
- diagnostics can classify failures consistently,
- conformance can test source-facing rejection classes,
- and lowering begins from an already-linked visible program.
## 2. Scope
This document defines:
- module scope construction,
- lookup order by namespace,
- import and alias resolution,
- barrel-mediated visibility,
- reserved stdlib shell resolution for builtin and host-backed surfaces,
- callable visibility across modules,
- and linking-time rejection conditions before lowering.
This document does not define:
- runtime execution behavior,
- optimizer or backend internals,
- full PBX binary linking,
- or loader/runtime artifact behavior after lowering.
## 3. Authority and Precedence
Normative precedence:
1. `3. Core Syntax Specification.md`
2. `4. Static Semantics Specification.md`
3. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
4. `6. VM-owned vs Host-backed.md`
5. `6.1. Intrinsics and Builtin Types Specification.md`
6. `6.2. Host ABI Binding and Loader Resolution Specification.md`
7. `8. Stdlib Environment Packaging and Loading Specification.md`
8. `18. Standard Library Surface Specification.md`
9. This document
If a rule here conflicts with higher-precedence specs, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `5. Manifest, Stdlib, and SDK Resolution Specification.md`
- `6. VM-owned vs Host-backed.md`
- `6.1. Intrinsics and Builtin Types Specification.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `8. Stdlib Environment Packaging and Loading Specification.md`
- `18. Standard Library Surface Specification.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- PBS has distinct type, value, callable, and host-owner namespaces.
- `mod.barrel` is the single source of module visibility.
- Imports target modules, not files.
- Reserved stdlib project spaces are resolved only from the selected stdlib environment.
- Only `pub` symbols may be imported from another module.
- Reserved stdlib/interface modules may expose compile-time-only shells for both host-backed and VM-owned surfaces, and may expose service facades over non-public host owners.
- Source-visible builtin names are resolved through imported builtin shell declarations rather than by hardcoded source spelling alone.
- Canonical builtin identity and canonical intrinsic identity are governed by builtin metadata rather than by the imported PBS-visible declaration name alone.
- Canonical host identity is governed by host metadata rather than by imported owner spelling alone.
## 6. Module Scope Construction
### 6.1 Module collection
For one module:
- the compiler collects top-level declarations from all `.pbs` files in that module,
- forms one module-level declaration space,
- and only then applies `mod.barrel` to determine `mod` and `pub` visibility.
Rules:
- declaration existence is not derived from barrel entries,
- module-internal top-level declaration availability does not depend on source-file order,
- and `mod.barrel` is a visibility filter over existing declarations rather than a declaration source.
### 6.2 Lexical scope
Inside executable bodies:
- lexical block scope nests normally over module scope,
- nearest local bindings win within value lookup,
- and lexical nesting remains independent from cross-module visibility.
## 7. Lookup Order By Namespace
Lookup in PBS remains namespace-based.
### 7.1 Value position
Value-position lookup follows this order:
1. nearest local lexical bindings,
2. parameters in the current lexical function scope,
3. visible module-local values,
4. visible imported values.
For lookup purposes, parameters and local `let` bindings participate in one nearest lexical value layer.
### 7.2 Type position
Type-position lookup follows this order:
1. visible module-local type declarations,
2. visible imported type declarations,
3. builtin simple types `int`, `float`, `bool`, and `str` as always-available reserved type names.
Builtin simple types:
- are not treated as ordinary imported declarations,
- do not participate in ordinary import competition,
- and remain always available without import.
### 7.3 Callable position
Callable-position lookup follows this order:
1. visible module-local callables,
2. visible imported callables.
Callable lookup operates only on already-formed visible callable sets as defined later in this document.
### 7.4 Host-owner position
Host-owner lookup follows this order:
1. visible module-local host owners,
2. visible imported host owners.
Host-owner lookup remains separate from type, value, and callable lookup.
## 8. Import Surface And Naming
### 8.1 Effective local imported name
The local visible name introduced by an import is always the post-alias name when an alias is present.
Rules:
- `import { X } from @project:path;` introduces the visible local name `X`,
- `import { X as Y } from @project:path;` introduces only the visible local name `Y`,
- and alias spelling changes only the local visible name, never canonical builtin identity or canonical host identity.
### 8.2 Named import
`import { X } from @project:path;`:
- resolves the target module,
- checks that `X` is exported and importable from that module,
- and introduces `X` into the corresponding namespace locally.
### 8.3 Whole-module import
`import { * } from @project:path;`:
- resolves the target module,
- introduces the target module's exported visible names under their exported spellings,
- but does not create a module-valued binding,
- does not create a namespace object,
- and does not authorize qualified member access by itself.
If PBS later wants module-object or namespace-qualified source semantics, that must be added explicitly rather than inferred from this import form.
## 9. Collision And Ambiguity Rules
### 9.1 Local versus imported
If a module-local declaration and an imported declaration produce the same visible name in the same namespace:
- the program is rejected,
- and the implementation must not silently shadow either declaration.
This includes function names.
A module-local function and an imported function with the same visible name are rejected rather than merged.
### 9.2 Imported versus imported
If two imports produce the same visible name in the same namespace:
- the program is not rejected only when both imports resolve to the same canonical underlying declaration after module resolution,
- such same-origin duplication is redundant but tolerated,
- and the program is rejected if the imports resolve to different canonical underlying declarations.
### 9.3 Namespace separation
Names in different namespaces do not collide merely by spelling.
For example:
- a host owner and a type declaration do not collide by spelling alone,
- because host-owner namespace remains distinct from type namespace.
### 9.4 Non-callable names do not merge
Non-callable namespaces do not merge by name.
## 10. Callable Sets And Cross-Module Linking
### 10.1 Imported callable set
`import { f } from @project:path;` imports the exported callable set named `f` from the target module.
Rules:
- the imported callable set for `f` consists only of those overload signatures of `f` that are exported through that module's `mod.barrel`,
- non-exported overloads in the target module do not participate in the imported callable set,
- and import operates on the exported callable name rather than on one overload at a time.
### 10.2 Same-origin versus different-origin callable imports
If the same visible callable name is imported more than once:
- same-origin duplicate imports are tolerated as redundancy when they resolve to the same canonical callable-set origin,
- different-origin imports are rejected immediately,
- and the implementation must not wait until a callsite to reject different-origin callable-name collisions.
### 10.3 Local versus imported callable names
If a module-local function name and an imported function name are the same visible callable name:
- the program is rejected immediately,
- and the implementation must not merge the local and imported callable sets.
### 10.4 Overload-resolution boundary
PBS separates:
- callable-set formation,
- and overload resolution at a callsite.
Rules:
- the implementation must first form one unambiguous visible callable set,
- only then may ordinary overload resolution operate on the candidate signatures of that set,
- and callsite context must not be used to resolve ambiguity between different imported callable origins.
## 11. Reserved Stdlib Shell Resolution
### 11.1 Reserved shells as imported declarations
Source-visible declarations exposed by reserved builtin shells are imported into their ordinary corresponding namespaces.
This means:
- builtin-exposed types enter type lookup as imported type declarations,
- builtin-exposed constants enter value lookup as imported values,
- and host owners enter host-owner lookup as imported host-owner declarations.
`declare builtin type` itself remains a reserved stdlib/toolchain declaration form rather than ordinary user-authored source syntax.
### 11.2 Builtin simple types versus imported builtin shells
PBS distinguishes:
- the predeclared builtin simple-type set `int`, `float`, `bool`, `str`,
- and imported builtin shells such as `Vec2` or `Color`.
Imported builtin shells are not promoted to the same always-available status as builtin simple types.
### 11.3 Intrinsic member lookup
Builtin intrinsic methods:
- never participate in free lookup,
- are not introduced by import as free functions,
- and are resolved only through member lookup on a receiver already known to have the corresponding builtin type.
Alias changes to the imported builtin type affect only the local visible owner spelling, not the canonical builtin or intrinsic identity.
### 11.4 Collision policy for reserved shells
Reserved builtin shells and host owners follow the same collision policy as ordinary imported declarations.
Rules:
- same visible name in the same namespace is an error unless another already-closed rule explicitly permits otherwise,
- reserved-shell status does not authorize silent shadowing,
- and host owners do not collide with types or values merely by spelling because host-owner namespace remains separate.
### 11.5 Reserved project-space policy
For source-level policy:
- builtin shells are preferred under `@core:*`,
- and host-facing capability surfaces remain the natural fit for `@sdk:*`.
### 11.6 Canonical identity
Canonical builtin identity and canonical host identity are not derived from local alias spelling.
Duplicate canonical builtin identities or duplicate canonical host identities in one resolved environment are rejected as linking failures.
## 12. Linking Phase Boundary And Deterministic Failures
### 12.1 Normative phase baseline
PBS v1 adopts the following normative phase baseline for name resolution and related frontend failures:
1. `syntax`
2. `manifest/import resolution`
3. `linking`
4. `static semantics`
### 12.2 Syntax
`syntax` owns malformed import grammar and other token-shape or grammar-shape failures.
### 12.3 Manifest and import resolution
`manifest/import resolution` owns failures to resolve:
- project space,
- reserved stdlib space,
- dependency graph target,
- module path,
- or environment source.
### 12.4 Linking
`linking` owns assembly of visible declarations across files and modules.
At minimum, `linking` owns:
1. import of non-exported names,
2. unresolved barrel entries against module declarations,
3. collisions between visible imported names from different canonical origins,
4. local-versus-import visibility collisions,
5. callable-origin conflicts across module boundaries,
6. duplicate canonical builtin identities in one resolved environment,
7. duplicate canonical host identities in one resolved environment.
### 12.5 Static semantics
`static semantics` owns:
1. duplicate local declarations,
2. declaration validity,
3. type checking,
4. member lookup once the receiver type is known,
5. overload resolution within an already-formed visible callable set.
Member lookup failure on an already-typed builtin receiver therefore belongs to `static semantics`.
### 12.6 Imported-origin conflicts are rejected before callsite analysis
Conflicts between different imported origins are rejected in `linking` immediately.
The implementation must not:
- wait for a specific callsite,
- use overload resolution to rescue imported-origin ambiguity,
- or defer visible declaration conflicts to later typing work.
## 13. Deterministic Resolution Failures
At minimum, a conforming implementation must reject:
1. import of a non-exported builtin type shell,
2. import of a non-exported builtin constant shell,
3. import of a non-exported host owner shell,
4. import of any non-exported name from a resolved module,
5. unresolved barrel entries against module declarations,
6. local-versus-import same-namespace collisions,
7. imported same-name collisions from different canonical origins,
8. local-versus-import function-name collisions,
9. duplicate visible builtin type declarations that claim the same canonical builtin identity in one resolved environment,
10. duplicate visible builtin constants that claim the same canonical builtin constant identity in one resolved environment,
11. duplicate visible host owners that claim the same canonical host identity in one resolved environment,
12. member lookup on a builtin receiver where the imported builtin shell does not declare the requested field or intrinsic member,
13. any resolution path that attempts to derive host or builtin canonical identity from alias spelling alone.
## 14. Non-Goals
- Reopening the already-settled import surface syntax.
- Defining runtime loader behavior.
- Freezing one compiler symbol-table implementation.
- Freezing one internal compiler pass graph.
## 15. Exit Criteria
This document is ready to move beyond its current draft status only when:
1. name lookup is deterministic across all relevant scopes,
2. barrel and module linking behavior is explicit,
3. reserved stdlib shell resolution is explicit for host-backed and VM-owned surfaces,
4. cross-module callable visibility and ambiguity behavior are normatively defined,
5. and the phase ownership of source-facing name-resolution failures is explicit enough for diagnostics and conformance.
@@ -0,0 +1,178 @@
# PBS Bytecode and PBX Mapping Specification
Status: Draft v1 (Backend Baseline)
Applies to: mapping from lowered/optimized backend programs into PBX sections, bytecode-facing artifacts, and source-to-artifact invariants required by loader/verifier/runtime
## 1. Purpose
This document defines the normative mapping between backend-lowered semantics and emitted PBX/bytecode-facing artifacts.
Its purpose is to keep artifact emission deterministic and compatible with runtime loader/verifier contracts.
## 2. Scope
This document defines:
- artifact-level obligations at `IRVM -> BytecodeModule` emission boundary,
- mapping invariants for function layout, code layout, callsite forms, and host-binding declarations,
- minimum debug/source-attribution hooks for v1 backend/runtime diagnostics and conformance,
- and deterministic artifact rejection expectations for emitter-side failures.
This document does not define:
- full ISA semantics,
- runtime loader patching internals,
- or one mandatory emitter implementation architecture.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `docs/pbs/specs/6.1. Intrinsics and Builtin Types Specification.md`
4. `docs/pbs/specs/6.2. Host ABI Binding and Loader Resolution Specification.md`
5. `20. IRBackend to IRVM Lowering Specification.md`
6. `21. IRVM Optimization Pipeline Specification.md`
7. This document
If a rule here conflicts with higher-precedence authorities, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `docs/pbs/specs/6.1. Intrinsics and Builtin Types Specification.md`
- `docs/pbs/specs/6.2. Host ABI Binding and Loader Resolution Specification.md`
- `20. IRBackend to IRVM Lowering Specification.md`
- `21. IRVM Optimization Pipeline Specification.md`
## 5. Already-Settled Inputs
The following are fixed and must not be contradicted:
- The compiler emits host-binding declarations in PBX `SYSC`.
- Host-backed callsites are emitted in pre-load form as `HOSTCALL <sysc_index>`.
- `SYSC` entries are deduplicated by canonical identity and ordered by first occurrence.
- The loader resolves host bindings and rewrites `HOSTCALL` to `SYSCALL` before execution.
- Raw `SYSCALL` in pre-load artifacts is rejected.
- VM-owned intrinsic artifacts are distinct from `SYSC`, `HOSTCALL`, and `SYSCALL`.
- `SYSC` section is mandatory in valid PBX artifacts (empty section is valid).
## 6. Artifact Mapping Contract (v1)
### 6.1 Required module surfaces
Emitter output must map to a `BytecodeModule` shape containing:
1. `const_pool`,
2. `functions`,
3. `code`,
4. `exports`,
5. `syscalls`,
6. optional `debug_info` that still satisfies v1 minimum debug obligations.
### 6.2 Function ordering and IDs
Function ordering must be deterministic:
1. entrypoint function index is `0`,
2. entrypoint index `0` is selected from qualified `EntrypointRef(entryPointModuleId, entryPointCallableName)`,
3. remaining functions are ordered by `(moduleId -> modulePool canonical key, callable_name, source_start)`,
4. identical admitted input graph yields identical function ordering and function ids.
### 6.3 Function code layout
Emitter must satisfy:
1. `code_offset` values are unique and monotonic over function order,
2. `code_len` exactly matches emitted bytes for each function body,
3. `code_offset + code_len` stays within `code.len`,
4. and final code concatenation is deterministic.
### 6.4 Instruction encoding
Emitter must satisfy:
1. little-endian encoding,
2. instruction layout `[opcode: u16][immediate]`,
3. jump immediates as `u32` offsets relative to function start,
4. immediate sizes matching selected Core ISA opcode spec.
### 6.5 Host-backed mapping obligations
For host-backed operations:
1. emit canonical declarations in `SYSC` (`module`, `name`, `version`, `arg_slots`, `ret_slots`),
2. deduplicate by canonical identity,
3. order by first occurrence,
4. emit callsites as `HOSTCALL <sysc_index>` only,
5. do not emit raw `SYSCALL` in pre-load artifact form.
### 6.6 VM-owned intrinsic mapping obligations
For VM-owned intrinsic operations:
1. emit VM-owned intrinsic call form (`INTRINSIC <id>`),
2. resolve `<id>` from the canonical ISA-scoped intrinsic registry artifact,
3. keep intrinsic path distinct from host-binding metadata and host call opcodes,
4. and do not emit VM-owned builtin/intrinsic semantics through `SYSC`.
### 6.7 Internal symbolic-to-index mapping
Compilers may use internal symbolic references before final index materialization.
If used, symbolic references must be resolved deterministically to final numeric indices before serialization.
## 7. Minimum Debug Attribution Contract (v1)
For v1 backend/runtime diagnostics and conformance support, emitted artifacts must preserve at minimum:
1. `function_names` entries for all emitted function indices,
2. `pc_to_span` entries for each emitted instruction start PC.
This minimum does not require one universal source-map format.
## 8. Deterministic Emitter Rejection
Emitter-side rejection must be deterministic for malformed or inconsistent artifact candidates, including at minimum:
1. inconsistent function layout bounds,
2. unresolved symbolic references at serialization boundary,
3. illegal pre-load host call form (`SYSCALL` in pre-load image),
4. duplicate `SYSC` canonical identities,
5. and declared host ABI shape mismatch detectable at compile target metadata line.
## 9. Conformance-Facing Baseline
At minimum, artifact conformance checks should assert:
1. canonical `SYSC` declarations for admitted host-backed operations,
2. deterministic `SYSC` dedup/order,
3. pre-load `HOSTCALL` callsites for host-backed paths,
4. no host-binding leakage for VM-owned intrinsic/builtin operations,
5. minimum debug attribution hooks required by v1,
6. deterministic function ordering and code layout invariants.
## 10. Explicit Deferrals
The following remain deferred:
- richer optional debug/source-map formats,
- additional PBX section-level contracts beyond current baseline,
- and profile-specific binary compatibility policy details beyond current v1 baseline.
## 11. Non-Goals
- Repeating full ISA/runtime documentation.
- Mandating one byte-for-byte whole-image golden as sole conformance oracle.
- Defining loader patching internals already owned elsewhere.
## 12. Exit Criteria
This document is healthy when:
1. artifact mapping obligations are explicit and testable,
2. host-backed and VM-owned emission boundaries are explicit,
3. deterministic ordering/layout rules are explicit,
4. and v1 minimum debug/source attribution contract is explicit.
@@ -0,0 +1,155 @@
# PBS Runtime Execution and Initialization Specification
Status: Draft v1 (Temporary)
Applies to: runtime startup, entry behavior, module/service initialization, and execution lifecycle of PBS programs after successful load
## 1. Purpose
This document defines the PBS-visible runtime entry and execution-lifecycle contract after successful artifact load.
Its purpose is to keep runtime startup, frame-driven execution, and fatal-failure behavior aligned with:
- runtime authority,
- dynamic semantics,
- memory/lifetime guarantees,
- and the closed capability-gated host model.
## 2. Scope
This document defines:
- when PBS program execution may begin,
- which preconditions must already hold before userland runs,
- the runtime execution model of a loaded PBS program instance,
- the only normative frame/safepoint boundary in v1,
- and which startup or fatal-failure outcomes are PBS-visible.
This document does not define:
- loader-side host resolution details,
- the full packaging or process model,
- scheduler models outside the v1 single-threaded execution contract,
- shutdown/finalization APIs or hooks,
- or subsystem-specific host resource lifecycles.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. `1. Language Charter.md`
3. `6.2. Host ABI Binding and Loader Resolution Specification.md`
4. `9. Dynamic Semantics Specification.md`
5. `10. Memory and Lifetime Specification.md`
6. This document
If a rule here conflicts with higher-precedence authorities, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `1. Language Charter.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `7. Cartridge Manifest and Runtime Capabilities Specification.md`
- `9. Dynamic Semantics Specification.md`
- `10. Memory and Lifetime Specification.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- `FRAME_SYNC`-based execution semantics are preserved.
- Loader-side host binding resolution and capability gating happen before program execution begins.
- A PBS program instance executes single-threaded in v1.
- Dynamic semantics are deterministic at the language-observable level.
- Any runtime trap aborts PBS program execution and enters the runtime/firmware crash path rather than a userland recovery path.
- Service values are canonical module-owned singleton values.
- Top-level executable statements are forbidden in PBS source modules.
## 6. Runtime Entry Preconditions
PBS userland execution may begin only after all of the following are true:
1. the program artifact has been accepted by the relevant runtime/load authority,
2. capability gating and host-binding resolution required for startup have completed successfully,
3. runtime state required to begin frame-driven execution has been established,
4. and no prior fatal startup failure has occurred.
If these preconditions are not satisfied, ordinary PBS userland execution does not begin.
This document does not define loader-internal sequencing in detail; it only defines that the userland-visible start boundary occurs after successful load- and capability-level admission.
## 7. Program Instance Model
Each loaded PBS program executes as one single-threaded program instance in v1.
Within a program instance:
- userland execution is not concurrently interleaved by another userland thread,
- the dynamic-semantics evaluation order defined in `9. Dynamic Semantics Specification.md` remains authoritative,
- and runtime/host activity must not perturb that language-level sequencing.
PBS source modules do not contribute a user-authored top-level execution phase. Any startup activity that exists outside ordinary function/method execution is runtime-owned unless and until another specification makes a narrower PBS-visible contract explicit.
## 8. Frame Boundary and Host Work
`FRAME_SYNC` is the only normative runtime step boundary and the only normative safepoint in PBS v1.
Consequences:
- the runtime may use the interval around `FRAME_SYNC` to process host-side demands and internal work,
- userland execution must remain semantically ordered as defined by `9. Dynamic Semantics Specification.md`,
- and PBS user code cannot rely on any other boundary as a guaranteed safepoint, collection point, or scheduling point.
Internal runtime work may exist outside `FRAME_SYNC`, but it must remain semantically invisible to PBS userland unless a higher-precedence authority explicitly defines otherwise.
## 9. Failure and Non-Start Conditions
PBS distinguishes between two broad classes of failure at this layer:
1. non-start conditions, where userland never begins because artifact admission, capability checks, or required startup preconditions fail;
2. fatal runtime traps, where an already-running PBS program aborts.
Traps are not recoverable in PBS userland. When a trap occurs:
- it does not enter `result` flow,
- it is not intercepted by `handle`,
- and it aborts the PBS program execution path into the runtime/firmware crash path.
This document does not define a userland-visible trap catalog.
## 10. Service and Module Initialization Boundaries
The current v1 baseline is intentionally narrow:
- service values are canonical singleton values,
- top-level executable statements do not exist,
- and no userland-visible module-initialization statement phase is defined here.
The exact timing at which service-owned runtime state becomes initialized and observable remains an open item for this document. Until that is closed, implementations must not infer extra userland-visible initialization hooks beyond what is already guaranteed by higher-precedence specs.
## 11. TODO
The following items remain open for later closure:
- the exact runtime entry contract between successful load and first userland-observable execution,
- whether service-owned runtime state has a more precise initialization point than the baseline stated here,
- which runtime lifecycle boundaries, if any, are userland-observable beyond `FRAME_SYNC` and trap abort,
- and whether shutdown behavior has any PBS-visible contract in v1.
## 12. Non-Goals
- Defining OS/process lifecycle outside Prometeu runtime authority.
- Reopening the ban on top-level executable statements.
- Designing a future async runtime.
- Defining userland recovery from trap.
## 13. Exit Criteria
This document is ready to move beyond temporary status only when:
1. runtime startup and non-start boundaries are normatively described,
2. service and module runtime lifecycle assumptions are explicit enough to remove the remaining TODO items,
3. execution lifecycle boundaries are aligned with dynamic semantics and runtime authority,
4. and the document no longer relies on unresolved TODO items for ordinary v1 runtime startup behavior.
@@ -0,0 +1,119 @@
# PBS Compatibility and Evolution Policy
Status: Draft v0 (Quality-Gate Baseline)
Applies to: practical support states and compatibility publication policy tied to executable quality gates
## 1. Purpose
This document defines how PBS support is published at the current project stage.
The policy is intentionally minimal:
- publish only support claims that are backed by tests,
- use a small support-state model that a solo project can maintain,
- and avoid over-specifying compatibility promises before backend/runtime contracts settle.
## 2. Scope
This document defines:
- support-state vocabulary for language lines,
- minimum published support table fields,
- and how support-state changes must be recorded.
This document does not define:
- full deprecation-window math per domain,
- one binary/PBX compatibility model,
- one release process implementation.
## 3. Authority and Precedence
Normative precedence:
1. `1. Language Charter.md`
2. `2. Governance and Versioning.md`
3. `13. Conformance Test Specification.md`
4. This document
If a rule here conflicts with higher-precedence authorities, it is invalid.
## 4. Normative Inputs
This document depends on:
- `2. Governance and Versioning.md`
- `13. Conformance Test Specification.md`
## 5. Support States
PBS currently uses three support states:
- `unsupported`
- `experimental`
- `supported`
Meaning:
- `unsupported`: no compatibility promise.
- `experimental`: active development; behavior may change; tests may exist but are not yet a stable support promise.
- `supported`: active compatibility promise for declared scope, backed by required quality gates.
## 6. Gate-Backed Support Rule
Support states must map to quality-gate evidence:
1. `frontend-ready` evidence requires Gate U from `13`.
2. `integration-ready` evidence requires Gate U plus Gate I when Gate I applies to the language/backend.
3. `supported` state requires maintained evidence for the scope being promised.
No published `supported` claim may exist without mapped test evidence.
Unsupported executable surfaces excluded from a claim (for example `SPAWN`/`YIELD` outside `core-v1`) MUST be stated explicitly in published notes.
## 7. Minimum Published Support Table
A published support table must include, at minimum:
1. language identifier,
2. language line/version scope,
3. runtime line (or `N/A` when Gate I is not applicable yet),
4. Gate U status,
5. Gate I status (`pass`, `fail`, or `deferred`),
6. support state (`unsupported`, `experimental`, `supported`),
7. optional notes.
No additional matrix dimensions are mandatory at this stage.
## 8. Support-State Changes
When support changes, the project must update together:
1. support table state,
2. gate evidence status,
3. and a short rationale note when users could be affected.
This document requires visibility of change, not a specific changelog format.
## 9. Explicit Deferrals
The following remain intentionally open:
- domain-specific promise strength beyond the current gate-backed model,
- exact deprecation/removal windows,
- PBX/binary compatibility policy details,
- mandatory migration tooling triggers.
## 10. Non-Goals
- Simulating large-organization compatibility governance.
- Freezing domains that are still not implemented.
- Requiring one matrix tooling format.
## 11. Exit Criteria
This document is in a healthy state when:
1. every active language line has an explicit support state,
2. every `supported` state has mapped gate evidence,
3. support changes are reflected in table + evidence + note,
4. and no compatibility promise depends on undocumented assumptions.
@@ -0,0 +1,188 @@
# PBS Standard Library Surface Specification
Status: Draft v0 (Skeleton)
Applies to: normative stdlib-facing API surface, reserved stdlib project spaces, and versioned standard-library contracts exposed to PBS programs
## 1. Purpose
This document will define the normative user-facing standard-library surface for PBS.
## 2. Scope
This document is intended to define:
- what counts as part of the PBS stdlib contract,
- how stdlib modules are grouped and versioned,
- which APIs are normative versus implementation-private,
- how VM-owned builtin shells are exposed to user code,
- how reserved stdlib project spaces expose user-facing surfaces over host-backed capabilities.
This document does not define:
- one physical packaging layout,
- registry/publication mechanics,
- host loader behavior,
- implementation-private helper modules.
## 3. Authority and Precedence
Normative precedence:
1. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
2. `8. Stdlib Environment Packaging and Loading Specification.md`
3. `6. VM-owned vs Host-backed.md`
4. `6.1. Intrinsics and Builtin Types Specification.md`
5. `6.2. Host ABI Binding and Loader Resolution Specification.md`
6. This document
If a rule here conflicts with higher-precedence specs, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `5. Manifest, Stdlib, and SDK Resolution Specification.md`
- `6. VM-owned vs Host-backed.md`
- `6.1. Intrinsics and Builtin Types Specification.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `8. Stdlib Environment Packaging and Loading Specification.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- Reserved stdlib project spaces include `@sdk:*` and `@core:*`.
- Stdlib interface modules are compile-time-only and loaded as PBS-like modules.
- Stdlib interface modules may include service facades whose bodies delegate to reserved host owners; such bodies are source-surface ergonomics and not standalone runtime modules.
- User code must import stdlib modules explicitly.
- Canonical host identity comes from reserved host-binding metadata, not from source owner spelling.
- VM-owned builtin type, builtin constant, and intrinsic surfaces may be exposed through reserved stdlib shells without transferring semantic ownership away from the VM.
## 6. Initial Section Targets
At minimum, the completed document should contain normative sections for:
1. stdlib contract boundaries,
2. reserved stdlib project spaces and module families,
3. normative versus non-normative API surfaces,
4. VM-owned builtin shells exposed to user code,
5. host-backed SDK surfaces exposed to user code,
6. versioning and deprecation expectations for stdlib APIs.
## 7. TODO
The following items remain to be closed in future agenda discussion.
- Which stdlib modules are mandatory in each active stdlib line.
- Which APIs are part of the normative core teaching surface versus optional library growth.
- Whether `@core:*` is specified as language-adjacent utility surface or as ordinary stdlib contract.
- How stdlib API evolution is documented and conformance-tested.
- Whether some interface modules remain toolchain-private and outside user-facing stdlib surface.
- Whether builtin shells may appear in `@sdk:*` as well as `@core:*`, or whether `@sdk:*` should remain host-facing only by policy.
## 8. Non-Goals
- Replacing the resolution/packaging specs.
- Defining all future libraries in one pass.
- Hardcoding one distribution format.
## 9. Exit Criteria
This document is ready to move beyond skeleton status only when:
1. the normative user-facing stdlib surface is explicitly bounded,
2. reserved project-space API responsibilities are clear,
3. VM-owned and host-backed stdlib surfaces are explicitly separated,
4. stdlib versioning and deprecation expectations are aligned with compatibility policy,
5. the document no longer relies on unresolved `TODO` items for ordinary v1 stdlib contract claims.
## 10. Reserved Project-Space Responsibilities
The current stdlib direction distinguishes two user-facing reserved spaces.
### 10.1 `@core:*`
`@core:*` is the preferred surface for VM-owned declarations that belong to the
language-adjacent semantic platform.
Examples:
- builtin type shells,
- builtin constants,
- and other VM-owned helper declarations that are not host capability surfaces.
### 10.2 `@sdk:*`
`@sdk:*` is the preferred surface for host-backed capability-facing APIs.
Examples:
- `declare host` surfaces,
- capability-facing wrappers over host services,
- and domain SDK modules whose execution meaning ultimately depends on host-backed operations.
Rules:
- source packaging location is part of the stdlib contract surface,
- but ownership remains governed by the VM-owned vs host-backed classification,
- and placing a builtin shell in stdlib does not make it host-backed.
## 11. Builtin Shell Surfaces
Reserved stdlib modules may expose builtin declarations as compile-time-only
shells.
Rules:
- stdlib builtin shells may expose `declare builtin type` declarations,
- stdlib builtin shells may expose reserved `declare const` declarations carrying `BuiltinConst(...)`,
- stdlib builtin shells may expose builtin methods carrying `IntrinsicCall(...)`,
- these shells exist for import, name resolution, type checking, and lowering,
- and these shells do not provide executable PBS bodies for builtin behavior.
Stdlib is therefore the delivery surface, not the semantic owner.
## 12. Host-backed SDK Surfaces
Reserved stdlib modules may expose host-backed declarations as compile-time-only
shells.
Rules:
- host-backed stdlib surfaces use `declare host`,
- host-backed stdlib modules may also expose `declare service` facades that call internal non-public host owners,
- host-backed method signatures carry `Host(...)`,
- internal low-level host owners can remain non-public via `mod` barrel visibility while higher-level services are exported with `pub`,
- user code may import those host owners through ordinary stdlib module imports,
- and lowering continues through canonical host identity, `SYSC`, `HOSTCALL`, loader resolution, and final `SYSCALL`.
## 13. Stdlib Contract Expectations for Builtin MVP
For the current builtin MVP, stdlib should be able to expose at least:
1. a builtin type shell for `Color`,
2. a builtin type shell for `Vec2`,
3. a builtin type shell for `Pixel`,
4. a builtin constant shell for `vec2.zero`,
5. and any associated documentation-level or teaching-level module organization needed to make those surfaces discoverable.
Illustrative example:
```pbs
import { Vec2, ZERO } from @core:math;
```
The imported names are source-visible conveniences.
Their canonical runtime-facing identities still come from builtin metadata such
as `BuiltinType(name="vec2", version=1)` and
`BuiltinConst(target="vec2", name="zero", version=1)`.
## 14. Deterministic Stdlib Surface Failures
At minimum, a conforming implementation must reject:
1. a stdlib builtin shell that attempts to use host-binding metadata for VM-owned intrinsic behavior,
2. a stdlib host shell that attempts to use builtin metadata in place of host-binding metadata,
3. a user-facing stdlib module that exports executable PBS bodies for builtin semantics,
4. a stdlib line that exposes conflicting canonical builtin identities through the same resolved environment,
5. a stdlib line that exposes conflicting canonical host identities through the same resolved environment.
@@ -0,0 +1,135 @@
# PBS Verification and Safety Checks Specification
Status: Draft v1 (Quality-Gate Baseline)
Applies to: test-backed safety gates for backend compiler stages and integration regression safety checks against runtime
## 1. Purpose
This document defines the minimum safety/verification quality gates that must be enforced for executable backend pipelines.
Its purpose is to keep safety measurable and deterministic across:
- lowering,
- optimization,
- emission,
- and runtime integration boundaries.
## 2. Scope
This document defines:
- mandatory compiler-stage safety checks for executable pipeline stages,
- conditional integration safety regression checks against runtime line,
- and evidence requirements for safety-related support claims.
This document does not define:
- full runtime verifier algorithm internals,
- formal proof of all runtime safety properties,
- or one mandatory verifier/optimizer architecture.
## 3. Authority and Precedence
Normative precedence:
1. `docs/pbs/specs/2. Governance and Versioning.md`
2. `docs/pbs/specs/12. Diagnostics Specification.md`
3. `20. IRBackend to IRVM Lowering Specification.md`
4. `21. IRVM Optimization Pipeline Specification.md`
5. `15. Bytecode and PBX Mapping Specification.md`
6. `13. Conformance Test Specification.md`
7. This document
If a rule here conflicts with higher-precedence authorities, it is invalid.
## 4. Normative Inputs
This document depends on:
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `13. Conformance Test Specification.md`
- `15. Bytecode and PBX Mapping Specification.md`
- `20. IRBackend to IRVM Lowering Specification.md`
- `21. IRVM Optimization Pipeline Specification.md`
## 5. Safety Gate Model
### 5.1 Gate S-U: Compiler-Stage Safety Unit Tests (Required)
For executable pipelines, S-U must cover stage-level safety checks at minimum:
1. `LowerToVM` safety checks:
- deterministic control-flow lowering checks,
- deterministic function-id assignment checks,
- mandatory slot/return shape checks,
- mandatory callsite form checks.
2. `OptimizeIRVM` safety checks:
- semantic-preservation regression checks,
- deterministic output checks for same input graph,
- profile-compatibility checks (`vm_profile`).
3. `EmitBytecode` safety checks:
- deterministic function/code layout checks,
- host-backed pre-load form checks (`HOSTCALL`, `SYSC`),
- deterministic rejection for malformed emission candidates,
- minimum debug-attribution output checks.
4. deterministic diagnostics identity for required rejection surfaces (`code`, `severity`, primary attribution when applicable).
This gate is mandatory regardless of backend maturity stage.
### 5.2 Gate S-I: Integration Safety Regression With Runtime (Required for Executable Backends)
For backends that emit executable artifacts, S-I must cover integration safety at minimum:
1. valid pre-load host path that loader patches and runtime executes,
2. rejection of out-of-bounds `HOSTCALL` index,
3. rejection of unused `SYSC` declarations,
4. rejection of raw `SYSCALL` in pre-load artifact,
5. rejection of host ABI mismatch (`arg_slots`/`ret_slots`),
6. rejection of missing capability at load-time,
7. valid VM-owned intrinsic path,
8. repeatability across declared runtime line.
When executable artifact emission is not present, S-I may be explicitly `deferred`.
## 6. Evidence Requirements
Safety claims must map to gate evidence:
1. S-U evidence is required for baseline safety posture,
2. S-I evidence is required for integration-ready safety claims,
3. and published safety-related support claims must remain evidence-backed and current.
For executable backends, evidence should include deterministic regression fixtures that prove pipeline order and stage-boundary safety behavior.
## 7. Deterministic Failure Taxonomy Expectations
Backend safety checks should expose stable rejection families at minimum:
1. `MARSHAL_FORMAT_*`,
2. `MARSHAL_LINKAGE_*`,
3. `MARSHAL_VERIFY_PRECHECK_*`.
This taxonomy complements existing diagnostics contracts and does not replace runtime loader/verifier error surfaces.
## 8. Explicit Deferrals
The following are intentionally deferred:
- full formal verifier obligation catalog,
- formal proof frameworks for optimizer equivalence,
- and richer standardized source-map formats beyond v1 minimum hooks.
## 9. Non-Goals
- Replacing runtime or bytecode authority.
- Freezing optimizer/verifier internal architecture prematurely.
- Defining performance tooling in a safety specification.
## 10. Exit Criteria
This document is healthy when:
1. required stage-level safety checks are test-backed,
2. executable backends have explicit S-I status (`pass`/`fail`/`deferred`),
3. integration safety regressions are preserved in tests,
4. and safety-related support claims remain evidence-backed.
@@ -0,0 +1,174 @@
# PBS IRBackend to IRVM Lowering Specification
Status: Draft v1 (Backend Baseline)
Applies to: executable-backend lowering from `IRBackend` handoff into `IRVM`
## 1. Purpose
This document defines the normative lowering contract from executable `IRBackend` to `IRVM`.
Its purpose is to make backend lowering deterministic, reviewable, and compatible with runtime ISA/verification authority.
## 2. Scope
This document defines:
- required backend preconditions before `IRBackend -> IRVM` starts,
- `IRVM` structural obligations needed before optimization/emission,
- deterministic function-id assignment and control-flow lowering obligations,
- callsite lowering obligations across function, host-backed, and VM-owned intrinsic paths,
- mandatory compiler-side structural pre-verification before bytecode emission,
- and deterministic rejection obligations for backend-originated failures.
This document does not define:
- binary PBX layout details,
- loader patching internals,
- runtime execution internals,
- or one mandatory optimizer implementation.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
4. This document
If a rule here conflicts with higher-precedence authorities, it is invalid.
## 4. Normative Inputs
This document depends on:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/pbs/specs/6.1. Intrinsics and Builtin Types Specification.md`
- `docs/pbs/specs/6.2. Host ABI Binding and Loader Resolution Specification.md`
- `15. Bytecode and PBX Mapping Specification.md`
- `21. IRVM Optimization Pipeline Specification.md`
## 5. Backend Entry Preconditions
Lowering from `IRBackend` to `IRVM` may start only when:
1. frontend admission to `IRBackend` is complete for the active slice,
2. required callsite categories (`CALL_FUNC`/`CALL_HOST`/`CALL_INTRINSIC`) are available,
3. required canonical host/intrinsic metadata is available for admitted callsites,
4. dependency-scoped fail-fast exclusions have already been applied at the `IRBackend` boundary,
5. frontend-declared qualified `EntrypointRef` is present:
- `IRBackend.entryPointCallableName` is non-blank,
- `IRBackend.entryPointModuleId` is non-none,
6. and target `vm_profile` is selected deterministically.
## 6. IRVM Model Obligations
`IRVM` v1 is a quasi-ISA backend form:
1. it may contain Core ISA ops and internal extension ops (`IRVM_EXT`),
2. each `IRVM_EXT` must declare structural metadata equivalent to opcode-spec needs:
- `pops`,
- `pushes`,
- `is_branch`,
- `is_terminator`,
3. and `IRVM_EXT` must be eliminable before bytecode emission.
`IRVM` must preserve, per function:
1. `param_slots`,
2. `local_slots`,
3. `return_slots`,
4. `max_stack_slots`,
5. function entry mapping and deterministic identity.
## 7. Control-Flow Lowering Obligations
Control-flow lowering must satisfy:
1. symbolic labels are allowed internally in lowering,
2. final jump immediates must be resolved to `u32` offsets relative to function start before emission,
3. jump targets must be instruction-boundary-valid within function ranges,
4. and reachable fallthrough beyond function end without terminator is rejected.
## 8. Deterministic Function-ID Assignment
Function indexing must be deterministic:
1. entrypoint callable is selected by exact qualified match against `EntrypointRef(entryPointModuleId, entryPointCallableName)`,
2. selected entrypoint function id is `0`,
3. remaining functions are ordered by `(moduleId -> modulePool canonical key, callable_name, source_start)`,
4. name-only entrypoint fallback is forbidden,
5. and identical admitted input graphs must produce identical function-id assignments.
## 9. Callsite Lowering Obligations
### 9.1 Function calls
`CALL_FUNC` lowers to `CALL <func_id>` with valid index and arity-consistent signature contracts.
### 9.2 Host-backed calls
`CALL_HOST` lowers to pre-load `HOSTCALL <sysc_index>`, not raw `SYSCALL`.
### 9.3 VM-owned intrinsic calls
`CALL_INTRINSIC` lowers to VM-owned intrinsic path and must remain distinct from host-binding paths.
Final intrinsic id resolution rules:
1. compiler must resolve final intrinsic ids from the canonical ISA-scoped intrinsic registry artifact,
2. compiler-local hardcoded maps or runtime-source parsing must not be authoritative identity sources,
3. runtime and compiler consumers must validate parity against the same canonical artifact in strict CI mode.
### 9.4 Closure and coroutine constraints (v1)
1. closure calls with unknown static callee are rejected in v1,
2. `SPAWN` and `YIELD` are outside the executable `core-v1` claim scope and MUST be rejected as unsupported forms in v1 backend admission,
3. `SPAWN` argument-count and `YIELD` stack-shape invariants remain reserved for a future profile that explicitly admits these opcodes,
4. and any profile that admits `SPAWN`/`YIELD` MUST publish dedicated conformance evidence before claiming support.
## 10. Mandatory Compiler-Side Pre-Verification
Before bytecode emission, backend must run structural pre-verification on lowered `IRVM` (after resolving to Core-ISA-compatible form), covering at minimum:
1. jump target validity,
2. stack-depth join consistency,
3. underflow/overflow against declared limits,
4. return-shape consistency,
5. function-id validity,
6. callsite arity consistency,
7. and structural validity of host/intrinsic call forms.
This pre-verification does not replace runtime verifier authority.
## 11. Deterministic Rejection Policy
When backend lowering fails at this boundary:
1. rejection must be deterministic,
2. diagnostics identity and phase must remain stable,
3. and source attribution must be preserved whenever the failure remains source-attributable and user-actionable.
## 12. Explicit Deferrals
The following are intentionally deferred:
- optimizer pass catalog and tuning policy,
- richer internal IR analysis models beyond v1 obligations,
- advanced closure/lifetime optimizations beyond v1 constraints,
- and executable support for `SPAWN`/`YIELD` in `core-v1`.
## 13. Non-Goals
- Defining one in-memory IR implementation graph.
- Redefining runtime verifier/loader internals.
- Defining PBX binary chunk policy in this document.
## 14. Exit Criteria
This document is healthy when:
1. `IRBackend -> IRVM` obligations are explicit and testable,
2. deterministic function/call/control-flow lowering rules are explicit,
3. mandatory pre-verification boundary is explicit,
4. and scope boundaries with optimization/emission specs are explicit.
@@ -0,0 +1,124 @@
# PBS IRVM Optimization Pipeline Specification
Status: Draft v1 (Pipeline Baseline)
Applies to: placement and invariants of the `OptimizeIRVM` stage between lowering and bytecode emission
## 1. Purpose
This document defines the normative placement and safety invariants of the `OptimizeIRVM` stage.
Its purpose is to allow optimization in the backend pipeline without transferring semantic optimization responsibility to runtime.
## 2. Scope
This document defines:
- canonical stage placement for `OptimizeIRVM`,
- input/output contracts of optimization stage boundaries,
- semantic-preservation invariants for optimization passes,
- profile-compatibility obligations (`vm_profile`) across optimization and emission,
- and minimum validation expectations for optimization-stage regressions.
This document does not define:
- a mandatory list of optimization passes,
- pass scheduling heuristics,
- or runtime dynamic optimization/JIT policies.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `20. IRBackend to IRVM Lowering Specification.md`
4. `15. Bytecode and PBX Mapping Specification.md`
5. This document
If a rule here conflicts with higher-precedence authorities, it is invalid.
## 4. Normative Inputs
This document depends on:
- `20. IRBackend to IRVM Lowering Specification.md`
- `15. Bytecode and PBX Mapping Specification.md`
- `19. Verification and Safety Checks Specification.md`
- `docs/pbs/decisions/IRVM Optimization Stage Placement Decision.md`
## 5. Canonical Backend Pipeline Order
For executable backends, the canonical order is:
1. `LowerToVM`: `IRBackend -> IRVM`,
2. `OptimizeIRVM`: `IRVM -> IRVM` optimized,
3. `EmitBytecode`: optimized `IRVM -> BytecodeModule` pre-load artifact.
`OptimizeIRVM` must not be skipped in a pipeline that claims this profile unless explicitly configured as a no-op stage that still preserves contracts.
## 6. Input and Output Contracts
### 6.1 Input contract
`OptimizeIRVM` input must:
1. satisfy lowering obligations from `20`,
2. carry selected `vm_profile`,
3. and remain structurally valid for optimizer analyses.
### 6.2 Output contract
`OptimizeIRVM` output must:
1. be semantically equivalent to input under the selected `vm_profile`,
2. preserve callable/slot/return contracts,
3. preserve deterministic mapping behavior required by emission,
4. and be valid for bytecode emission and subsequent runtime verification.
## 7. Optimization Invariants
Optimization passes must satisfy all of:
1. semantic preservation of observable program behavior,
2. determinism for the same admitted input graph and selected profile,
3. profile compatibility (no introduction of out-of-profile executable opcode forms),
4. preservation of host-backed vs VM-owned call-boundary classification,
5. and preservation of diagnostics/source-attribution hooks required at v1 minimum.
## 8. Runtime Responsibility Boundary
1. Semantic/structural program optimization belongs to compile-time backend stages.
2. Runtime remains responsible for load, patch, verify, and execute responsibilities.
3. Runtime-internal micro-optimizations are allowed only when they do not alter bytecode-observable semantics or contract behavior.
## 9. Validation Expectations
At minimum, optimization-stage validation must include:
1. equivalence-oriented regression fixtures across optimized vs non-optimized pipeline outputs,
2. preservation of known negative loader/verifier rejection behavior,
3. and deterministic reproduction of artifact-level invariants required by `15`.
## 10. Explicit Deferrals
The following are intentionally deferred:
- target-specific optimization profitability models,
- advanced interprocedural pipelines beyond v1 baseline,
- and formal equivalence proof frameworks.
## 11. Non-Goals
- Defining runtime JIT or adaptive execution.
- Replacing loader/verifier contracts.
- Mandating one optimizer architecture or pass framework.
## 12. Exit Criteria
This document is healthy when:
1. stage placement is explicit and implemented in pipeline order,
2. optimization invariants are explicit and test-backed,
3. backend/runtime responsibility boundary is explicit,
4. and integration safety evidence references this stage concretely.
@@ -0,0 +1,113 @@
# Backend Spec-to-Test Conformance Matrix
Status: Draft v1 (Traceability Baseline)
Applies to: backend conformance traceability for `IRBackend -> IRVM -> OptimizeIRVM -> EmitBytecode`
Last Updated: 2026-03-09
## 1. Purpose
This matrix maps each normative backend MUST from:
1. `docs/general/specs/19. Verification and Safety Checks Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/21. IRVM Optimization Pipeline Specification.md`
4. `docs/pbs/specs/13. Lowering IRBackend Specification.md` (Section 12 addendum only)
to concrete positive/negative test evidence and current status.
## 2. Status Legend
- `pass`: requirement has explicit positive and/or negative evidence and currently passes.
- `partial`: requirement is partially covered; evidence exists but scope is incomplete.
- `missing`: no concrete automated evidence yet.
- `deferred`: intentionally out of current executable scope.
## 3. Normative Matrix
| Requirement ID | Source MUST | Positive Tests | Negative Tests | Status | Notes |
| --- | --- | --- | --- | --- | --- |
| G19-5.1.1 | Gate S-U MUST cover LowerToVM stage safety checks. | `LowerToIRVMServiceTest#lowerMustAssignEntrypointIdZeroAndSortRemainingDeterministically`; `LowerToIRVMServiceTest#lowerMustResolveJumpTargetsFromLabels` | `LowerToIRVMServiceTest#lowerMustRejectMissingCallee`; `LowerToIRVMServiceTest#lowerMustRejectMissingJumpTargetLabel`; `LowerToIRVMServiceTest#lowerMustRejectUnterminatedFunction` | pass | Includes deterministic id/callsite/control-flow checks. |
| G19-5.1.2 | Gate S-U MUST cover OptimizeIRVM stage safety checks. | `OptimizeIRVMServiceTest#optimizeDefaultPassesMustRemoveUnreachableInstructions`; `OptimizeIRVMServiceTest#simplifyJumpToNextPcPassMustRemoveDirectFallthroughJump` | `OptimizeIRVMServiceTest#optimizeMustRejectPassThatMutatesVmProfile` | pass | Determinism also covered by `BackendSafetyGateSUTest#optimizeStageMustBeDeterministicForSameInputProgram`. |
| G19-5.1.3 | Gate S-U MUST cover EmitBytecode stage safety checks. | `EmitBytecodePipelineStageTest#runMustEmitBytecodeWhenPreconditionsAreSatisfied`; `BytecodeEmitterTest#emitMustDeduplicateSyscallsByCanonicalIdentityAndPreserveFirstOccurrenceOrder` | `EmitBytecodePipelineStageTest#runMustFailWhenInternalOpcodesRemain`; `BytecodeEmitterTest#emitMustRejectRawSyscallInPreloadPlan` | pass | Covers layout, host-backed preload form and deterministic rejection. |
| G19-5.1.4 | Gate S-U MUST cover deterministic diagnostics identity for required rejection surfaces. | `BackendSafetyGateSUTest#lowerStageMustExposeDeterministicFailureCodeForSameInvalidInput` | `BackendSafetyGateSUTest#emitStageMustExposeMarshalingLinkageFailureDeterministically` | pass | Uses stable `code` and `phase`. |
| G19-5.2.1 | Gate S-I MUST cover valid pre-load host path. | `BackendGateIIntegrationTest#gateI_validHostcallPath` | N/A | pass | Runtime-backed and local adapter paths covered. |
| G19-5.2.2 | Gate S-I MUST reject out-of-bounds HOSTCALL index. | N/A | `BackendGateIIntegrationTest#gateI_rejectHostcallOutOfBounds` | pass | |
| G19-5.2.3 | Gate S-I MUST reject unused SYSC declarations. | N/A | `BackendGateIIntegrationTest#gateI_rejectUnusedSyscallDeclaration` | pass | |
| G19-5.2.4 | Gate S-I MUST reject raw SYSCALL in pre-load artifact. | N/A | `BackendGateIIntegrationTest#gateI_rejectRawSyscallInPreloadArtifact` | pass | |
| G19-5.2.5 | Gate S-I MUST reject host ABI mismatch. | N/A | `BackendGateIIntegrationTest#gateI_rejectHostAbiMismatchAtEmitTime` | pass | |
| G19-5.2.6 | Gate S-I MUST reject missing capability at load-time. | N/A | `BackendGateIIntegrationTest#gateI_rejectMissingCapability` | pass | |
| G19-5.2.7 | Gate S-I MUST cover valid VM-owned intrinsic path. | `BackendGateIIntegrationTest#gateI_validIntrinsicPath` | N/A | pass | |
| G19-5.2.8 | Gate S-I MUST cover repeatability across runtime line. | `RuntimeBackedCompatibilityAdapterTest#checkMustPassInStrictModeWhenRuntimeCommandIsValid`; `RuntimeBackedCompatibilityAdapterTest#checkMustBeRepeatableAcrossDeclaredRuntimeLinesInStrictMode` | `RuntimeBackedCompatibilityAdapterTest#checkMustFailInStrictModeWhenRuntimeCommandIsUnavailable` | pass | Multi-line repeatability is asserted with strict runtime-backed checks over distinct declared runtime lines. |
| G20-6.2 | `IRVM_EXT` MUST declare structural metadata (`pops/pushes/is_branch/is_terminator`). | `IRVMValidatorTest#validateMustApplyStructuralMetadataForCustomInternalExtension`; `IRVMValidatorTest#validateMustRejectCustomInternalExtensionWhenStructuralMetadataUnderflowsStack`; `IRVMOp` record contract (`pops/pushes/branch/terminator/internal`) | N/A | pass | Dedicated extension fixtures now assert structural metadata is consumed by validation behavior. |
| G20-6.3 | `IRVM_EXT` MUST be eliminable before bytecode emission. | `OptimizeIRVMServiceTest#optimizeDefaultPassesMustEliminateUnreachableInternalExtensionBeforeEmission` | `EmitBytecodePipelineStageTest#runMustFailWhenInternalOpcodesRemain`; `EmitBytecodePipelineStageTest#runMustFailWhenInternalOpcodesRemainEvenWithNonEmptyEmissionPlan`; `IRVMValidatorTest#validateMustRejectInternalOpcodeWhenConfigured` | pass | Optimizer elimination path and emit-stage hard rejection path are both covered. |
| G20-6.4 | IRVM MUST preserve per-function slot and identity headers. | `IRVMProgramTest#constructorMustRejectModuleAndEmissionPlanMismatch` | `IRVMProgramTest#constructorMustRejectModuleAndEmissionPlanMismatch` | pass | Header mismatch is rejected deterministically. |
| G20-7.2 | Jump immediates MUST resolve to u32 function-relative offsets before emission. | `LowerToIRVMServiceTest#lowerMustResolveJumpTargetsFromLabels`; `BytecodeEmitterTest#emitMustEncodeJumpOpcodesWithU32Immediate` | `LowerToIRVMServiceTest#lowerMustRejectMissingJumpTargetLabel` | pass | |
| G20-7.3 | Jump targets MUST be instruction-boundary valid. | N/A | `IRVMValidatorTest#validateMustRejectInvalidJumpTarget` | pass | |
| G20-7.4 | Reachable fallthrough beyond function end MUST be rejected. | N/A | `LowerToIRVMServiceTest#lowerMustRejectUnterminatedFunction`; `IRVMValidatorTest#validateMustRejectRetShapeMismatch` | pass | |
| G20-8.1 | Qualified entrypoint function id MUST be 0. | `LowerToIRVMServiceTest#lowerMustAssignEntrypointIdZeroAndSortRemainingDeterministically`; `LowerToIRVMServiceTest#lowerMustUseQualifiedEntrypointIdentityWhenProvided` | `LowerToIRVMServiceTest#lowerMustRejectWhenEntrypointDeclarationIsMissing`; `LowerToIRVMServiceTest#lowerMustRejectMissingQualifiedEntrypointIdentity`; `LowerToIRVMServiceTest#lowerMustRejectWhenEntrypointIsAmbiguous` | pass | Entrypoint is resolved strictly by `EntrypointRef(entryPointModuleId, entryPointCallableName)`. |
| G20-8.2 | Remaining function ids MUST follow deterministic moduleId-only ordering. | `LowerToIRVMServiceTest#lowerMustAssignEntrypointIdZeroAndSortRemainingDeterministically`; `LowerToIRVMServiceTest#lowerMustUseModulePoolCanonicalIdentityForNonEntrypointOrdering` | N/A | pass | Ordering key is `(moduleId -> modulePool canonical key, callable_name, source_start)`. |
| G20-8.3 | Same admitted input graph MUST produce identical function-id assignment. | `BackendSafetyGateSUTest#fullPipelineMustProduceDeterministicBytecodeForSameInput` | N/A | pass | Artifact determinism implies stable function mapping for fixed input. |
| G20-9.3 | `CALL_INTRINSIC` MUST remain distinct from host-binding path and resolve ids from canonical registry artifact. | `LowerToIRVMServiceTest#lowerMustMapHostAndIntrinsicCallsites`; `BackendGateIIntegrationTest#gateI_validIntrinsicPath`; `IRVMIntrinsicRegistryParityTest#registryResourceMustExposeExpectedCanonicalEntries`; `IRVMIntrinsicRegistryParityTest#registryMustStayInSyncWithRuntimeBuiltinsTable` | `IRVMValidatorTest#validateProgramMustRejectIntrinsicWithoutSignatureMetadata` | pass | Distinct operation kinds and canonical registry parity checks are enforced. |
| G20-9.4.2 | `SPAWN` arg count MUST match callee `param_slots`. | `BackendClaimScopeSpecTest#loweringSpecMustDeclareSpawnYieldOutsideCoreV1ClaimScope`; `BackendClaimScopeSpecTest#matrixMustMarkSpawnYieldRowsAsClaimRescoped`; `BackendClaimScopeSpecTest#decisionRecordMustExistForSpawnYieldClaimRescope` | N/A | pass | Requirement is out of scope for core-v1 claim by accepted Track B rescope decision; future profile must reintroduce executable coverage with dedicated tests. |
| G20-9.4.3 | `YIELD` with non-empty operand stack MUST be rejected. | `BackendClaimScopeSpecTest#loweringSpecMustDeclareSpawnYieldOutsideCoreV1ClaimScope`; `BackendClaimScopeSpecTest#matrixMustMarkSpawnYieldRowsAsClaimRescoped`; `BackendClaimScopeSpecTest#decisionRecordMustExistForSpawnYieldClaimRescope` | N/A | pass | Requirement is out of scope for core-v1 claim by accepted Track B rescope decision; future profile must reintroduce executable coverage with dedicated tests. |
| G20-10 | Backend MUST run structural pre-verification before emission. | `LowerToIRVMService` + `OptimizeIRVMService` validator invocation; `LowerToIRVMServiceTest` positive fixtures | `IRVMValidatorTest#validateMustRejectStackMismatchJoin`; `IRVMValidatorTest#validateProgramMustApplyHostcallStackEffectsFromMetadata` | pass | Pre-verification checks jump/stack/ret/callsite constraints. |
| G20-11.1 | Lowering rejection MUST be deterministic. | `BackendSafetyGateSUTest#lowerStageMustExposeDeterministicFailureCodeForSameInvalidInput` | same | pass | |
| G20-11.2 | Diagnostics identity/phase MUST remain stable. | `BackendSafetyGateSUTest#lowerStageMustExposeDeterministicFailureCodeForSameInvalidInput` | `BackendSafetyGateSUTest#emitStageMustExposeMarshalingLinkageFailureDeterministically` | pass | Stable rejection families are exercised. |
| G20-11.3 | Source attribution MUST be preserved when source-actionable. | `LowerToIRVMPipelineStageTest#runMustAttachSourceAttributionForLoweringFailure`; `LowerToIRVMServiceTest#lowerMustMapHostAndIntrinsicCallsites` | `LowerToIRVMServiceTest#lowerMustRejectMissingCallee` | pass | Stage-level failure now carries explicit `file/start/end` attribution for lowering errors. |
| G21-5 | `OptimizeIRVM` MUST NOT be skipped in canonical pipeline order. | `BuilderPipelineServiceOrderTest#canonicalOrderMustContainOptimizeBetweenLowerAndEmit` | N/A | pass | Canonical stage order is enforced. |
| G21-6.1 | Optimize input MUST satisfy lowering obligations/profile/structural validity. | `OptimizeIRVMPipelineStageTest#runMustAcceptSupportedNonDefaultVmProfile` | `OptimizeIRVMPipelineStageTest#runMustRejectUnsupportedVmProfile` | pass | Input validation occurs before pass execution. |
| G21-6.2 | Optimize output MUST preserve semantics/contracts and remain emission-valid. | `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForLoweredHostIntrinsicFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForConditionalJoinFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForSimpleLoopFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForLinearCallFixture`; `EmitBytecodePipelineStageTest#runMustEmitBytecodeWhenPreconditionsAreSatisfied` | `OptimizeIRVMServiceTest#optimizeMustRejectPassThatMutatesVmProfile` | pass | Equivalence harness now validates on/off semantics and emission validity over CFG corpus with host/intrinsic paths. |
| G21-7.1 | Optimization passes MUST preserve observable semantics. | `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForConditionalJoinFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForSimpleLoopFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForLinearCallFixture` | N/A | pass | Observable trace equivalence is asserted across branching, loops, and call graphs. |
| G21-7.2 | Optimization passes MUST be deterministic for same input/profile. | `BackendSafetyGateSUTest#optimizeStageMustBeDeterministicForSameInputProgram` | N/A | pass | |
| G21-7.3 | Optimization passes MUST preserve profile compatibility. | `OptimizeIRVMPipelineStageTest#runMustAcceptSupportedNonDefaultVmProfile` | `OptimizeIRVMServiceTest#optimizeMustRejectPassThatMutatesVmProfile` | pass | |
| G21-7.4 | Optimization passes MUST preserve host-vs-intrinsic boundary classification. | `LowerToIRVMServiceTest#lowerMustMapHostAndIntrinsicCallsites`; `BackendGateIIntegrationTest#gateI_validIntrinsicPath` | N/A | pass | No pass rewrites operation kind domains. |
| G21-7.5 | Optimization passes MUST preserve diagnostics/source-attribution hooks. | `OptimizeIRVMServiceTest#unreachableInstructionEliminationPassMustPreserveJumpSpanWhenTargetIsRemapped`; `OptimizeIRVMServiceTest#normalizeRedundantJumpTargetsPassMustPreserveJumpSpanAfterRewrite`; `OptimizeIRVMServiceTest#simplifyJumpToNextPcPassMustPreserveSpanOnSurvivingOperation`; `LowerToIRVMServiceTest#lowerMustMapHostAndIntrinsicCallsites` | N/A | pass | Dedicated optimizer regressions now assert span/source-hook preservation for rewrite and elimination paths. |
| G21-9.1 | Validation MUST include optimized-vs-non-optimized equivalence fixtures. | `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForLoweredHostIntrinsicFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForConditionalJoinFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForSimpleLoopFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForLinearCallFixture` | N/A | pass | Dedicated opt on/off harness with reusable interpreter and deterministic trace assertions is in place. |
| G21-9.2 | Validation MUST preserve known negative loader/verifier behavior. | `BackendSafetyGateSUTest#emitStageMustExposeMarshalingLinkageFailureDeterministically`; `BackendGateIIntegrationTest` rejection suite | N/A | pass | |
| G21-9.3 | Validation MUST preserve deterministic artifact-level invariants. | `BackendSafetyGateSUTest#fullPipelineMustProduceDeterministicBytecodeForSameInput`; `BytecodeEmitterTest#emitMustRemainDeterministicAfterInterning` | N/A | pass | |
| PBS13-12.0 | Executable backend handoff MUST satisfy addendum obligations. | `IRBackendExecutableContractTest` suite | N/A | pass | Row group `PBS13-12.x` details each obligation. |
| PBS13-12.1.1 | Callable identity MUST be preserved at handoff. | `IRBackendExecutableContractTest#aggregatorMustPreserveExecutableFunctionOrderDeterministically` | N/A | pass | |
| PBS13-12.1.2 | Observable callable signature MUST be preserved at handoff. | `IRBackendExecutableContractTest#functionContractMustRejectInvalidSlotAndSpanBounds` | N/A | pass | |
| PBS13-12.1.3 | Callable category MUST be preserved at handoff. | `PbsFrontendCompilerTest#shouldLowerExecutableFunctionsWithCallsiteCategories` | N/A | pass | |
| PBS13-12.1.4 | Source anchor (`fileId/start/end`) MUST be preserved. | `IRBackendExecutableContractTest#aggregatorMustPreserveExecutableSourceAttribution`; `IRBackendExecutableContractTest#functionContractMustRejectInvalidSlotAndSpanBounds` | N/A | pass | Handoff preserves function and instruction source anchors after aggregation/reindexing. |
| PBS13-12.1.5 | Executable body representation MUST be backend-lowerable. | `LowerToIRVMServiceTest#lowerMustMapHostAndIntrinsicCallsites` | `LowerToIRVMServiceTest#lowerMustRejectMissingCallee` | pass | |
| PBS13-12.2.1 | Callsite MUST be exactly one of `CALL_FUNC/CALL_HOST/CALL_INTRINSIC`. | `IRBackendExecutableContractTest#callInstructionMustRequireCategorySpecificMetadata` | `IRBackendExecutableContractTest#instructionContractMustRejectMixedMetadataKinds` | pass | |
| PBS13-12.2.2 | Backend MUST NOT infer callsite category by textual heuristics. | `PbsFrontendCompilerTest#shouldClassifyCallableCallEvenWhenNameLooksHostLike`; `PbsFrontendCompilerTest#shouldNotInferCallableCategoryFromMemberCallText`; `PbsFrontendCompilerTest#shouldRejectAmbiguousCallableIdentityInsteadOfGuessingByText`; `IRBackendExecutableContractTest#callInstructionMustRequireCategorySpecificMetadata` | N/A | pass | Dedicated regression fixtures now cover textually misleading names and ambiguous callable identity without category guessing. |
| PBS13-12.3.1 | Host-backed callsite MUST preserve canonical `(module,name,version)`. | `LowerToIRVMServiceTest#lowerMustMapHostAndIntrinsicCallsites` | N/A | pass | |
| PBS13-12.3.2 | Host ABI shape (`arg_slots`,`ret_slots`) MUST be preserved when available. | `LowerToIRVMServiceTest#lowerMustMapHostAndIntrinsicCallsites` | `BytecodeEmitterTest#emitMustRejectAbiMismatch` | pass | |
| PBS13-12.4.1 | Intrinsic callsite MUST preserve canonical intrinsic identity. | `IRBackendExecutableContractTest#aggregatorMustReindexIntrinsicsToBuildGlobalPool` | N/A | pass | |
| PBS13-12.4.2 | VM-owned intrinsics MUST NOT be reclassified as host bindings. | `LowerToIRVMServiceTest#lowerMustMapHostAndIntrinsicCallsites`; `BackendGateIIntegrationTest#gateI_validIntrinsicPath` | N/A | pass | |
| PBS13-12.5 | `requiredCapabilities` MUST be deterministic for same admitted graph. | `PbsFrontendCompilerTest#shouldExtractReservedMetadataForInterfaceModuleSurfaces` | `PbsFrontendCompilerTest#shouldRejectHostBindingCapabilityNotDeclaredInStrictContext`; `PBSFrontendPhaseServiceTest#shouldBlockDependentModulesWhenUpstreamModuleFailsHostAdmission` | pass | Deterministic derivation + strict admission path. |
## 4. PR-05.0.X Identity Foundation Coverage
| PR Item | Scope | Evidence | Status |
| --- | --- | --- | --- |
| PR-05.0.1 | Shared `NameTable` context across frontend phases | `NameTableTest`; `PBSFrontendPhaseServiceTest` multi-module fixtures | pass |
| PR-05.0.2 | `ModuleId` dense table and module wiring | `ModuleTableTest`; `PBSFrontendPhaseServiceTest#shouldBlockDependentModulesTransitivelyWhenUpstreamModuleFailsLinking` | pass |
| PR-05.0.3 | Typed `CallableId`/`IntrinsicId` in executable contract | `IRBackendExecutableContractTest`; `LowerToIRVMServiceTest` | pass |
| PR-05.0.4 | Callable shape and type-surface interning | `CallableShapeTableTest`; `TypeSurfaceTableTest`; `PbsModuleVisibilityTest` | pass |
| PR-05.0.5 | Synthetic stdlib `FileId` via `FileTable` | `InterfaceModuleLoaderTest#shouldRegisterSyntheticStdlibFilesInFileTable` | pass |
| PR-05.0.6 | Host binding canonical identity interning | `HostBindingTableTest`; host admission fixtures in `PbsFrontendCompilerTest` | pass |
## 5. Maintenance Procedure
1. Any backend PR that changes conformance-relevant behavior in FE/BE pipeline MUST update this matrix.
2. If requirement coverage changes, update: mapped tests, status, and `Last Updated` date.
3. New normative MUSTs in specs `19/20/21` or PBS `13` addendum MUST add a new matrix row before merge.
4. Conformance-relevant FE/BE code paths for hard-gate are:
- `prometeu-compiler/prometeu-build-pipeline/`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/`
- `prometeu-compiler/prometeu-frontend-api/`
- `prometeu-compiler/prometeu-compiler-core/`
## 6. Review/Lint Gate
Matrix integrity is enforced by automated document lint:
- `BackendConformanceMatrixSpecTest` validates file presence, required requirement IDs, and row status integrity.
- `BackendConformanceMatrixSpecTest` enforces hard-gate policy:
- if `PROMETEU_MATRIX_HARD_GATE=true` and `PROMETEU_CHANGED_FILES` contains a path under conformance-relevant FE/BE prefixes,
- then this matrix file MUST be present in `PROMETEU_CHANGED_FILES`, otherwise the gate fails.
- CI policy uses strict Gate I mode via `PROMETEU_GATE_I_STRICT=true` (or `CI=true`) and requires `PROMETEU_RUNTIME_CHECK_CMD` for runtime-backed evidence.
+24
View File
@@ -0,0 +1,24 @@
# General Specs
This directory contains shared acceptance specifications for all supported languages in Prometeu.
## Scope
These specs are above language-specific specs and should be reused by each language line.
Typical topics:
- conformance gates and evidence,
- compatibility publication policy,
- verification/safety acceptance boundaries,
- artifact/runtime acceptance contracts.
Current backend-facing chapter additions:
- `20. IRBackend to IRVM Lowering Specification.md`
- `21. IRVM Optimization Pipeline Specification.md`
- `22. Backend Spec-to-Test Conformance Matrix.md`
## Rule
Language-specific specs (for example `docs/pbs/specs`) must reference this layer instead of duplicating cross-language acceptance policy.
+90
View File
@@ -0,0 +1,90 @@
# PBS Documentation
This directory contains the working and normative documentation for PBS.
## Tree
```text
docs/pbs/
├── agendas/
├── decisions/
├── pull-requests/
└── specs/
```
## Responsibilities
### `agendas/`
`agendas/` contains open topics.
Use it to:
- record unresolved questions,
- define scope, dependencies, and non-goals,
- structure discussion order,
- keep only active TODO topics visible.
An agenda is a discussion artifact, not a final normative document.
Once a topic is settled, it should leave this directory.
### `decisions/`
`decisions/` contains closed decision records between discussion and spec integration.
Use it to:
- record the adopted decision clearly,
- capture invariants and architectural constraints,
- state what was explicitly left undecided,
- identify which specs must be updated,
- preserve traceability without turning specs into debate logs.
Architecture and decisions come before implementation.
### `specs/`
`specs/` contains the normative PBS corpus.
Use it to:
- consolidate the official PBS contract,
- integrate already-closed decisions in normative language,
- define precedence, scope, rules, and exit criteria,
- provide the baseline for implementation, verification, and conformance.
`docs/pbs/specs` is language-specific.
Cross-language acceptance specs live in `docs/general/specs`.
Specs must not operate as discussion backlogs.
If a point is still disputed or underspecified, it belongs in `agendas/` or `decisions/`, not directly in `specs/`.
### `pull-requests/`
`pull-requests/` contains self-contained change proposals for review.
Use it to:
- package a proposed change across multiple documents,
- explain motivation, target, method, acceptance criteria, and tests,
- make the review surface explicit before final integration,
- keep architectural and decision-level review ahead of implementation work.
If implementation reveals an unresolved ambiguity, stop and ask the question explicitly.
Do not infer missing architectural decisions during implementation.
## Recommended Flow
The preferred pipeline is:
1. `agendas/`: open and discuss unresolved topics.
2. `decisions/`: record the decision and its constraints.
3. `specs/`: integrate the closed decision into normative text.
4. `pull-requests/`: use when a change should be reviewed as a self-contained proposal before merge.
## Practical Rule
- `agendas/` stores open questions.
- `decisions/` stores closed answers.
- `specs/` stores the PBS-specific normative contract.
- `pull-requests/` stores reviewable change packages.
+55
View File
@@ -0,0 +1,55 @@
# PBS Agendas
This directory contains active PBS discussion agendas.
Closed agendas are moved to `docs/pbs/agendas/archive`.
## Active Agendas
1. `18.0. Backend VM Pipeline - Orchestration Agenda.md`
2. `18.1. Backend Workshop 1 - IRBackend Input Contract.md`
3. `18.2. Backend Workshop 2 - LowerToIRVM and IRVM Contract.md`
4. `18.3. Backend Workshop 3 - Bytecode Marshaling and Runtime Conformance.md`
## Purpose
An agenda exists to drive a decision, not to serve as final normative text.
Use an agenda when:
- the topic is still open,
- multiple options or tradeoffs must be evaluated,
- the scope and non-goals need to be made explicit,
- the order of discussion matters.
Move an agenda to `docs/pbs/agendas/archive` once the topic is no longer active.
## Expected Format
An agenda should usually include:
1. Title
2. Status
3. Purpose
4. Context
5. Decisions to Produce
6. Core Questions
7. Expected Spec Material
8. Non-Goals
9. Inputs
## Writing Rules
- Keep the document oriented around unresolved questions.
- Separate open questions from assumptions already fixed elsewhere.
- Name the concrete decisions the discussion must produce.
- Avoid drafting large blocks of final normative spec text here.
- Prefer explicit non-goals to prevent scope drift.
## Exit Rule
An agenda should move out of the active set when:
- the key questions have been answered,
- the architectural direction is clear enough to record,
- and the topic is ready to become a decision record and then a spec update.
@@ -0,0 +1,53 @@
# AST Contract and Root Model Decision
Status: Accepted
Date: 2026-03-05
Related Agenda: `docs/pbs/agendas/archive/11.1. AST Workshop 1 - AST Contract and Root Model.md`
## Context
PBS introduced `11. AST Specification.md` as the language-specific AST layer between parser output and frontend lowering to `IRBackend`.
The open question was whether AST should be standardized by one mandatory implementation model (for example one Java class hierarchy) or by observable contract obligations.
## Decision
PBS adopts an obligations-first AST contract.
The specification standardizes required observable AST behavior and invariants, not one mandatory in-memory representation.
The following are required:
1. one AST root per source file;
2. deterministic child ordering consistent with source order;
3. mandatory source attribution (`file`, `start`, `end`) on nodes consumed by diagnostics or lowering;
4. explicit declaration/statement/expression node families for the supported v1 source slice;
5. deterministic rejection for unsupported forms, without permissive synthetic AST that hides rejection.
## Invariants
1. AST conformance is implementation-language agnostic.
2. Missing required attribution on mandatory nodes is non-conformant.
3. Parser recovery may produce partial AST, but structural integrity must remain valid for continued diagnostics.
4. Lowering and diagnostics are allowed to depend on the required AST invariants above.
## Explicit Non-Decisions
1. This decision does not freeze one parser architecture.
2. This decision does not define full static-semantics rules.
3. This decision does not define `IRBackend -> IRVM` lowering.
4. This decision does not define runtime/bytecode/verifier policies.
## Spec Impact
1. `docs/pbs/specs/11. AST Specification.md` must encode the obligations-first contract and invariants.
2. `docs/pbs/specs/12. Diagnostics Specification.md` remains the authority for diagnostic identity/phase/attribution payload rules consumed by AST-facing diagnostics.
3. `docs/pbs/specs/13. Lowering IRBackend Specification.md` may assume the mandatory AST invariants as lowering preconditions.
## Validation Notes
At minimum, Gate U evidence (per `docs/general/specs/13. Conformance Test Specification.md`) should include:
1. valid AST shape fixtures for representative declarations/statements/expressions;
2. deterministic syntax rejection fixtures with stable diagnostics;
3. attribution checks (`file/start/end`) on nodes required by diagnostics and lowering.
@@ -0,0 +1,69 @@
# AST Declarations and Type Surfaces Decision
Status: Accepted
Date: 2026-03-05
Related Agenda: `docs/pbs/agendas/archive/11.2. AST Workshop 2 - Declarations and Type Surfaces.md`
## Context
After closing the AST contract/root model, PBS needed a precise declaration-layer AST decision for v1 so parser output, diagnostics, and IRBackend lowering remain aligned.
The open points were:
- mandatory declaration families in AST,
- declaration identity preservation,
- declaration metadata requirements for downstream phases,
- AST/static-semantics phase boundary,
- rejection and recovery behavior for malformed declarations,
- and minimum Gate U evidence.
## Decision
PBS adopts the following declaration/type-surface AST policy for v1:
1. Mandatory declaration families include:
- imports,
- top-level `fn`,
- `struct`, `contract`, `service`, `error`, `enum`, `callback`,
- `declare const`,
- and declaration nodes required by barrel/linking flow.
2. Declaration identity is preserved at AST boundary; implementations must not prematurely merge declarations (including overload sets).
3. Minimum declaration metadata includes:
- declaration name,
- declared signature/surface (parameters/return when applicable),
- stable source attribution (`file/start/end`),
- and required declaration-level syntactic flags/attributes needed by later phases.
4. AST/static boundary is explicit:
- AST preserves structure,
- static/linking phases own semantic compatibility and resolution rules.
5. Unsupported declaration forms are deterministic parser/AST rejection with stable diagnostics.
6. Recovery may continue after declaration syntax errors, but recovered AST must remain structurally coherent and attribution-consistent.
7. Gate U evidence must include positive and negative declaration fixtures with AST-shape, attribution, and diagnostics assertions.
## Invariants
1. Declaration AST remains obligations-first and implementation-language agnostic.
2. Overload identity is not collapsed at AST layer.
3. Missing required declaration metadata on mandatory nodes is non-conformant.
4. Recovery must not fabricate permissive declaration shapes that hide syntax failures.
## Explicit Non-Decisions
1. This decision does not define static type-checking algorithms.
2. This decision does not define lowering from `IRBackend` to `IRVM`.
3. This decision does not define runtime/bytecode/verifier policy.
4. This decision does not freeze one parser architecture.
## Spec Impact
1. `docs/pbs/specs/11. AST Specification.md` must encode declaration families, identity preservation, metadata minimums, and recovery/rejection invariants.
2. `docs/pbs/specs/12. Diagnostics Specification.md` remains authority for diagnostic identity/phase/attribution semantics consumed by declaration diagnostics.
3. `docs/pbs/specs/13. Lowering IRBackend Specification.md` may assume declaration metadata invariants as lowering preconditions.
## Validation Notes
Gate U evidence (per `docs/general/specs/13. Conformance Test Specification.md`) should include:
1. valid declaration fixtures for each mandatory family,
2. malformed declaration fixtures with deterministic rejection diagnostics,
3. AST assertions for declaration identity, spans, and required metadata fields.
@@ -0,0 +1,64 @@
# AST Diagnostics, Recovery, and Gate Evidence Decision
Status: Accepted
Date: 2026-03-05
Related Agenda: `docs/pbs/agendas/archive/11.4. AST Workshop 4 - Diagnostics, Recovery, and Gate Evidence.md`
## Context
After closing AST contract, declaration surfaces, and statement/expression surfaces, PBS needed to close AST-facing diagnostics and parser-recovery policy plus the minimum Gate U evidence baseline.
Additionally, localization policy needed explicit alignment: diagnostics wording is locale-dependent and should be keyed by stable message tokens/template ids.
## Decision
PBS adopts the following AST diagnostics/recovery/evidence policy:
1. AST must preserve diagnostic fidelity:
- required syntax diagnostics remain stable in `code`, `severity`, `phase`, `primary file`, and `primary span`.
2. Human-readable message text is locale/rendering-dependent and not a conformance identity key.
3. Stable diagnostics identity for i18n is carried by:
- `diagnostic code`,
- `phase`,
- `message template id` (token),
- and primary attribution.
4. Parser recovery is allowed to continue diagnostics, but recovered AST must remain structurally coherent and attribution-consistent.
5. Recovery must not fabricate permissive valid shapes that hide real syntax failures.
6. Gate U AST evidence must include:
- representative valid AST fixtures,
- malformed/recovery fixtures,
- deterministic diagnostics assertions,
- and attribution assertions (`file/start/end`) on required nodes.
7. Minimum mandatory negative fixture families include:
- unexpected token in declaration context,
- missing required closer (`)`, `}`, or `;`) as applicable,
- non-associative forbidden chain forms,
- unsupported form outside the active syntax slice with deterministic rejection.
## Invariants
1. Diagnostics identity is token-based and locale-agnostic.
2. Recovery cannot downgrade a required rejection into accepted semantics.
3. AST attribution quality remains sufficient for `12` diagnostics contract and `13` lowering preconditions.
4. Gate U fixtures must lock rejection stability for required AST-facing failures.
## Explicit Non-Decisions
1. This decision does not define transport-specific wire schemas.
2. This decision does not define static type-checking rules.
3. This decision does not define backend/runtime/verifier algorithms.
4. This decision does not require one exact localized wording set.
## Spec Impact
1. `docs/pbs/specs/11. AST Specification.md` must encode recovery integrity and AST-facing rejection/recovery invariants.
2. `docs/pbs/specs/12. Diagnostics Specification.md` remains authority for diagnostics identity fields, including template/token identity.
3. `docs/general/specs/13. Conformance Test Specification.md` provides Gate U evidence obligations referenced here.
## Validation Notes
Gate U validation should assert:
1. stable diagnostic identity keys (`code`, `phase`, template/token id, primary attribution),
2. recovery integrity without semantic masking,
3. deterministic results for the mandatory negative fixture families above.
@@ -0,0 +1,51 @@
# AST Statements and Expressions Decision
Status: Accepted
Date: 2026-03-05
Related Agenda: `docs/pbs/agendas/archive/11.3. AST Workshop 3 - Statements and Expressions.md`
## Context
After closing AST contract/root and declaration surfaces, PBS needed a precise v1 decision for statement/expression AST obligations, including precedence/associativity representation, unsupported-form behavior, and Gate U evidence.
## Decision
PBS adopts the following statement/expression AST policy for v1:
1. Mandatory statement/expression AST families must cover the supported PBS core syntax slice, including at minimum:
- statements: `block`, `let`, `return`, expression statement, and other supported statement forms;
- expressions: `identifier`, literals, `unary`, `binary`, `call`, `group`, and other supported expression forms.
2. Precedence and associativity parsing outcomes are normative via AST shape and must be preserved explicitly.
3. Non-associative or forbidden chained forms are deterministic reject with stable diagnostics.
4. AST remains structural; semantic compatibility/type decisions are owned by static semantics/linking phases.
5. Unsupported statement/expression forms are deterministic reject and must not be represented by permissive synthetic placeholder nodes that mask real rejection.
6. Parser recovery may continue after syntax errors, but recovered AST must remain structurally coherent with stable attribution.
7. Gate U evidence must include positive and negative fixtures with AST-shape assertions and diagnostics assertions.
## Invariants
1. Statement/expression AST obligations are implementation-language agnostic.
2. AST shape must not be post-rewritten in a way that changes source-observable parse meaning.
3. Required nodes for diagnostics/lowering must preserve stable `file/start/end`.
4. Recovery must preserve integrity and must not silently convert invalid syntax into valid semantics.
## Explicit Non-Decisions
1. This decision does not define static type-checking algorithms.
2. This decision does not define `IRBackend -> IRVM` lowering.
3. This decision does not define runtime/bytecode/verifier policy.
4. This decision does not freeze one parser implementation strategy.
## Spec Impact
1. `docs/pbs/specs/11. AST Specification.md` must encode statement/expression node-family obligations, precedence/associativity shape obligations, and recovery/rejection invariants.
2. `docs/pbs/specs/12. Diagnostics Specification.md` remains the authority for stable diagnostics identity/phase/attribution requirements.
3. `docs/pbs/specs/13. Lowering IRBackend Specification.md` may assume statement/expression AST invariants as lowering preconditions.
## Validation Notes
Gate U evidence (per `docs/general/specs/13. Conformance Test Specification.md`) should include:
1. valid fixtures proving expected precedence/associativity AST shape;
2. invalid fixtures for non-associative or unsupported forms with deterministic diagnostics;
3. assertions for stable node attribution (`file/start/end`) where diagnostics and lowering consume those nodes.
@@ -0,0 +1,154 @@
# Allocation and Cost Visibility Decision
Status: Accepted (Implemented)
Cycle: Initial allocation-and-cost closure pass
## 1. Context
PBS v1 needs a minimal but explicit contract for which runtime cost facts matter semantically and which belong only to diagnostics/profiling quality.
Earlier decisions already fixed important inputs:
- `bind(context, fn_name)` has real retention/storage consequences,
- `optional`, `result`, `handle`, `!`, `if`, and `switch` are not intended to hide implicit allocation semantics,
- host/userland interaction is stack-only across the boundary,
- and value categories already distinguish copied payload from preserved aliasing.
## 2. Decision
PBS v1 adopts the following cost-visibility baseline:
1. The normatively relevant cost facts are:
- whether an operation may allocate VM-owned runtime storage,
- whether an operation retains state beyond the current evaluation,
- whether an operation copies payload versus preserves aliasing,
- whether an operation crosses the host boundary,
- and whether an operation may trap.
2. `bind(context, fn_name)` is normatively retention-bearing and requires runtime storage sufficient to keep the callback target and captured context alive.
3. `apply` is not allocation-bearing by itself.
4. `optional`, `result`, `handle`, `!`, `if`, and `switch` are not allocation-bearing by themselves.
5. Host-boundary crossing is a normatively relevant cost fact, but concrete host-side allocation details belong to subsystem-specific contracts rather than to a general PBS rule.
6. Quantitative reporting such as exact byte counts, exact object counts, or precise collector timing is not a normative language guarantee in v1.
## 3. Normatively Relevant Cost Facts
The following cost facts are part of the PBS semantic model and may be relied on by later tooling/spec work:
- VM allocation-bearing versus non-allocation-bearing behavior,
- retention-bearing versus non-retention-bearing behavior,
- copy versus aliasing preservation,
- host-boundary crossing,
- trap possibility.
These facts matter because they affect how advanced tooling, diagnostics, and performance reasoning should interpret a construct.
## 4. `bind`
`bind(context, fn_name)` is the strongest closed cost case in the current PBS core.
Rules:
- `bind` is not semantically free,
- `bind` is retention-bearing,
- `bind` requires runtime storage sufficient to preserve the callback target and captured context,
- the captured context remains alive while the callback value remains alive.
This decision does not require the spec to freeze the exact runtime layout used to implement that storage.
## 5. Non-Allocation-Bearing Surfaces
The following constructs are not allocation-bearing by themselves in PBS v1:
- `optional`
- `result`
- `handle`
- `!`
- `if`
- `switch`
- `apply`
If allocation or retention occurs while evaluating one of these constructs, that cost arises from:
- subexpression evaluation,
- called targets,
- payload formation already defined elsewhere,
- or runtime behavior outside the surface itself.
## 6. Copy Versus Aliasing
Copy versus aliasing is a normatively relevant cost fact.
The language already distinguishes:
- pure values copied by value,
- identity-bearing values passed by preserved aliasing,
- carriers that preserve the semantics of their contained values.
Tooling and later specs may rely on these distinctions even if PBS v1 does not require a warning at every such site.
## 7. Host Boundary
Crossing the host boundary is a normatively relevant cost fact.
However, this decision does not impose a universal rule for:
- host-side allocation volume,
- host-side object count,
- or host-side retention internals.
Those details belong to subsystem-specific contracts when and if they become relevant.
## 8. Normative Versus Best-Effort Reporting
### 8.1 Normative facts
The following facts are normative and may be surfaced by diagnostics/tooling:
- whether a construct is retention-bearing,
- whether a construct crosses the host boundary,
- whether semantics preserve aliasing or copy payload,
- whether a construct may trap.
### 8.2 Best-effort facts
The following facts are not normative language guarantees in v1:
- exact byte counts,
- exact object counts,
- exact collector timing,
- exact host-side allocation volume,
- precise performance ranking beyond the semantic facts above.
These may be surfaced by implementations as profiling or tooling enrichment, but they are not part of the core language contract.
## 9. Invariants
- The language must not imply hidden allocation semantics where none were intentionally specified.
- `bind` remains the canonical retention-bearing callback-forming construct in v1.
- Cost visibility must be strong enough for advanced tooling without forcing exact runtime accounting into the language spec.
- Host-boundary cost reporting must not pretend to know subsystem-specific runtime internals unless those are explicitly specified.
## 10. Explicit Non-Decisions
This decision record does not yet close:
- the final diagnostics wording for warnings or notes,
- subsystem-specific host cost contracts,
- precise collection/profiling metrics,
- optimizer-facing reporting policy.
## 11. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
## 12. Validation Notes
The intended split is:
- semantic cost facts are explicit,
- `bind` is the main retained-storage construct already closed,
- most other core surfaces are not allocation-bearing by themselves,
- and quantitative performance reporting remains tooling-quality rather than normative language behavior.
@@ -0,0 +1,133 @@
# Artifact-Level Conformance and Fixture Model Decision
Status: Superseded
Cycle: Conformance agenda closure pass
Superseded by:
- `docs/general/specs/13. Conformance Test Specification.md` (Quality-Gate Baseline)
- `docs/general/specs/19. Verification and Safety Checks Specification.md` (Quality-Gate Baseline)
Superseded on: 2026-03-04
## 1. Context
PBS v1 needed a decision for the point where conformance stops being source-only and begins asserting artifact-facing behavior.
The open questions from the conformance agenda closure pass and Workshop 3 were:
- whether artifact-level conformance is mandatory for every claim or only for full toolchain claims,
- whether conformance should snapshot whole binaries or only stable invariants,
- what the smallest honest fixture model is for stdlib and host-backed scenarios,
- and how `13`, `12`, `15`, and `19` divide responsibility.
The adopted direction needed to keep full conformance meaningful without freezing one emitter layout, one repository structure, or one implementation-specific binary image.
## 2. Decision
PBS v1 adopts the following artifact-level conformance baseline:
1. Artifact-level conformance belongs only to `full toolchain conformance`.
2. `frontend conformance` and `source-runtime conformance` do not require artifact-level oracle checks.
3. Full toolchain conformance must assert stable artifact invariants rather than one opaque byte-for-byte binary snapshot.
4. The conformance fixture model must explicitly declare the resolved environment assumptions that affect observable admission or lowering behavior.
5. `12` defines what semantic and artifact-boundary facts lowering must preserve.
6. `15` defines how the conformance-facing artifact facts appear in PBX/bytecode-visible form.
7. `19` defines which later safety and validation obligations are checked by loader and verifier rather than by lowering itself.
## 3. Artifact-Level Oracle Baseline
The v1 artifact-level oracle is invariant-based.
Full toolchain conformance must be able to assert, at minimum:
1. required canonical host-binding declarations are emitted for admitted host-backed uses;
2. `SYSC` entries are deduplicated by canonical identity;
3. `SYSC` entry order follows first occurrence in the lowered program;
4. host-backed callsites are emitted in pre-load form as `HOSTCALL <sysc_index>` referencing the emitted canonical binding set;
5. VM-owned builtin projections, builtin constants, and intrinsic callsites do not leak into host-binding metadata such as `SYSC`;
6. stdlib interface modules remain compile-time-only and do not emit executable bytecode by themselves;
7. emitted artifacts preserve at least one source-attribution hook for backend failures that remain source-attributable and user-actionable under the diagnostics contract.
This baseline does not require:
- one full PBX binary snapshot,
- one exact section byte layout outside the stable invariants above,
- one exact source-map format,
- or one verifier-internal trace shape.
## 4. Fixture Model
Conformance fixtures must model the resolved environment honestly whenever the selected environment affects acceptance, lowering, or artifact meaning.
Every fixture that depends on environment selection must declare, as applicable:
- selected stdlib environment or reserved stdlib line,
- selected host registry line,
- granted capability set,
- and selected runtime line.
If an axis is irrelevant for a fixture, the fixture should declare that explicitly rather than leaving it implicit.
The minimum reusable fixture families for v1 are:
1. source-only fixtures whose expectations do not depend on host registry or runtime selection;
2. stdlib-resolved fixtures that name the selected stdlib environment when reserved modules affect acceptance or behavior;
3. host-admitted fixtures that name both host registry line and granted capabilities for positive host-backed cases;
4. host-rejected fixtures that name the missing or unauthorized capability or host-registry condition for deterministic negative cases;
5. full-toolchain artifact fixtures that name the runtime line whenever emitted intrinsic or host-binding form depends on the selected executable target line.
This model is intentionally small. It is sufficient to prevent fake portability claims while avoiding one mandatory repository layout.
## 5. Boundary Across `13`, `12`, `15`, and `19`
The adopted boundary is:
- `13. Conformance Test Specification.md` defines which invariant families are pass/fail conformance obligations and which fixture assumptions must be declared;
- `13. Lowering IRBackend Specification.md` defines the semantic and artifact-boundary facts that lowering must preserve before loader or verifier work begins;
- `15. Bytecode and PBX Mapping Specification.md` defines the PBX/bytecode-visible mapping of those facts into inspectable artifact surfaces;
- `19. Verification and Safety Checks Specification.md` defines the later validation and rejection obligations applied after lowering and, where relevant, after loader patching.
Conformance therefore does not require `12` to define one binary encoding and does not require `15` to redefine semantic ownership already fixed in `12`.
## 6. Invariants
- Artifact-level conformance is required only for the full toolchain claim.
- The v1 artifact oracle is invariant-based, not whole-image-based.
- Fixture assumptions that change observable behavior must be explicit.
- Host-binding metadata remains distinct from VM-owned builtin and intrinsic lowering.
- The boundary among lowering, encoding, and verification must remain reviewable and non-overlapping.
- Source-attributable backend failures must retain at least one recoverable source location, but richer debug surfaces remain optional.
## 7. Explicit Non-Decisions
This decision record does not yet close:
- which PBX sections beyond the current stable invariant baseline become part of the PBS-facing contract,
- whether intrinsic declarations require an additional dedicated PBX preload section in v1,
- the full verifier test surface for conformance,
- the compatibility-matrix policy for aging and retirement of published combinations,
- or one repository structure for the conformance corpus.
## 8. Spec Impact
This decision should feed at least:
- `docs/general/specs/13. Conformance Test Specification.md`
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
It should also constrain later work in:
- `docs/general/specs/19. Verification and Safety Checks Specification.md`
- `docs/general/specs/17. Compatibility and Evolution Policy.md`
- `docs/pbs/decisions/Compatibility Matrix and Published Claims Decision.md`
- `docs/pbs/agendas/13.4. IR and Lowering Workshop 4 - Builtins, Host Bindings, and Artifact Invariants.md`
## 9. Validation Notes
The intended operational reading is:
- a direct interpreter may still claim `source-runtime conformance` without artifact checks,
- a full compiler toolchain must expose enough artifact surface to prove the stable invariants above,
- and a host-backed test is not valid conformance evidence unless the selected registry, capability set, and runtime assumptions are declared where they affect the outcome.
@@ -0,0 +1,164 @@
# Compatibility Matrix and Published Claims Decision
Status: Superseded
Cycle: Conformance and compatibility agenda closure pass
Superseded by:
- `docs/general/specs/13. Conformance Test Specification.md` (Quality-Gate Baseline)
- `docs/general/specs/17. Compatibility and Evolution Policy.md` (Quality-Gate Baseline)
Superseded on: 2026-03-04
## 1. Context
PBS v1 needed one operational policy for how support claims are published, tested, aged, and retired over time.
The open questions from the conformance closure pass, especially Workshop 4, and from `17. Compatibility and Evolution Policy Agenda.md`, Workshop 3 were:
- what enters the regression corpus,
- which compatibility dimensions PBS must publish explicitly,
- what counts as a published support claim,
- how claims relate to conformance evidence,
- and how supported combinations retire without becoming ambiguous.
The adopted direction needed to ensure that compatibility tables and support statements are executable commitments rather than prose-only promises.
## 2. Decision
PBS v1 adopts the following baseline policy:
1. Published support claims must be represented by an explicit compatibility matrix.
2. Every published supported combination must be backed by maintained conformance or regression evidence appropriate to the claim level being published.
3. The regression corpus is not limited to bug reproductions; it also includes already-published normative examples, accepted behavior claims, and supported matrix combinations.
4. Unsupported combinations must be stated explicitly rather than inferred from silence.
5. Claim retirement must be deliberate: when support narrows or ends, the matrix entry, supporting tests, and migration/support note must all change together.
## 3. Compatibility Matrix Baseline
The minimum PBS compatibility matrix must expose, at minimum, the following dimensions where support is published:
1. language line,
2. stdlib line when reserved stdlib environment selection affects the claim,
3. runtime line when execution target selection affects the claim,
4. conformance claim level.
The matrix must also expose an explicit support state for each published combination.
The minimum support states are:
- `supported`
- `unsupported`
- `provisional`
Meanings:
- `supported` means the combination is promised by the publisher and backed by maintained evidence.
- `unsupported` means the combination is intentionally not promised and tools may reject or decline it without violating the published support policy.
- `provisional` means the combination is published as incomplete or experimental and must not be confused with ordinary stable support.
Silence must not be used where a published matrix exists and a reasonable reader could infer support.
## 4. Published Claims and Evidence
A published support claim exists whenever a publisher represents, in user-facing or tool-facing form, that a combination or behavior is supported, conforming, or maintained.
This includes, at minimum:
- a matrix entry marked `supported`,
- an unqualified or qualified PBS conformance claim,
- compatibility statements in product or release documentation,
- and published examples or fixtures presented as normative or supported behavior.
Every published claim must map to maintained executable evidence.
The evidence may be:
- conformance tests,
- regression tests,
- or both,
provided the evidence covers the claim scope actually being published.
`frontend conformance`, `source-runtime conformance`, and `full toolchain conformance` may therefore have different evidence sets, but each published claim still needs evidence inside its own scope.
## 5. Regression Corpus Policy
The regression corpus must preserve already-published behavior inside the scope of active support claims.
At minimum, the regression corpus must include:
1. bug reproductions for behavior that was fixed and remains within a supported scope;
2. published examples that are treated as normative or supported behavior;
3. accepted conformance claims and the behavior they promise;
4. supported compatibility-matrix combinations and their required outcomes.
The regression corpus may be organized into separate slices by claim level or domain.
What matters normatively is:
- published supported behavior is regression-protected,
- evidence remains attributable to the claim it protects,
- and narrowing support requires deliberate retirement rather than silent drift.
## 6. Retirement and Narrowing Policy
When a supported combination is retired or narrowed:
1. the matrix entry must change explicitly;
2. the old support state must not remain implied by stale documentation;
3. the corresponding evidence must be retired, reclassified, or moved to a historical/non-supporting corpus deliberately;
4. a migration, support-boundary, or rationale note must accompany the change when users could reasonably depend on the retired combination.
Retirement does not require one universal changelog format in this decision.
It does require that the support boundary become visible and reviewable.
## 7. Boundary Between `13` and `17`
The adopted split is:
- `13. Conformance Test Specification.md` defines the executable evidence obligations: what must enter the conformance or regression corpus and how supported claims become test-backed;
- `17. Compatibility and Evolution Policy.md` defines the publication policy: which matrix dimensions and support states are required and how supported combinations age or retire.
This keeps `13` test-oriented and `17` promise-oriented while ensuring both documents describe the same support contract.
## 8. Invariants
- Published support claims must be test-backed.
- A compatibility matrix is normative only when its states have executable meaning.
- `unsupported` must be explicit when omission would mislead users.
- `provisional` must not be mistaken for ordinary supported compatibility.
- Regression protection follows published supported behavior, not only bug history.
- Narrowing support is a deliberate policy act, not an accidental omission.
## 9. Explicit Non-Decisions
This decision record does not yet close:
- exact compatibility-window lengths by domain,
- exact migration-tooling triggers,
- PBX-specific binary compatibility policy,
- release tooling implementation,
- or one repository layout for matrix and regression data.
## 10. Spec Impact
This decision should feed at least:
- `docs/general/specs/13. Conformance Test Specification.md`
- `docs/general/specs/17. Compatibility and Evolution Policy.md`
It should also constrain later work in:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
- `docs/pbs/agendas/17.4. Compatibility Workshop 4 - Artifact and PBX Compatibility Policy.md`
## 11. Validation Notes
The intended operational reading is:
- if a publisher marks one matrix row as `supported`, there must be maintained evidence for that row;
- if a combination is no longer supported, the matrix must say so explicitly rather than simply dropping mention of it;
- and if an example or claim is published as supported behavior, it belongs in the regression story even if it did not originate as a bug report.
@@ -0,0 +1,167 @@
# Conformance Claim Levels Decision
Status: Superseded
Cycle: Conformance agenda closure pass
Superseded by:
- `docs/general/specs/13. Conformance Test Specification.md` (Quality-Gate Baseline)
- `docs/general/specs/17. Compatibility and Evolution Policy.md` (Quality-Gate Baseline)
Superseded on: 2026-03-04
## 1. Context
PBS v1 needed a conformance-claim model that stays honest while the conformance corpus matures across frontend, runtime, and artifact-facing work.
The open questions from the conformance agenda closure pass and Workshop 1 were:
- whether PBS should use one conformance label or staged claims,
- what a partial implementation is allowed to claim,
- how published conformance claims must describe missing coverage,
- and how claim levels constrain later compatibility policy.
The adopted direction needed to avoid two failure modes:
- pretending an unfinished backend is already full PBS v1 conformance,
- and allowing vague marketing language that hides excluded domains such as artifact emission or verifier behavior.
## 2. Decision
PBS v1 adopts staged conformance claims.
The canonical claim levels are:
1. `frontend conformance`
2. `source-runtime conformance`
3. `full toolchain conformance`
These claims mean:
1. `frontend conformance` covers deterministic source acceptance and rejection behavior through parsing, manifest/import resolution, linking/static semantics, and the stable diagnostics surface required for those rejection tests.
2. `source-runtime conformance` covers all frontend obligations plus source-level runtime, memory/identity, and host-boundary behavior already defined as language-observable in the active specs.
3. `full toolchain conformance` covers all source-runtime obligations plus the artifact-facing, loader-facing, verifier-facing, and compatibility obligations required by the full active PBS v1 spec set.
Only `full toolchain conformance` may be published without qualifier as `PBS v1 conforming`.
Any narrower claim must remain explicitly qualified in published wording, for example:
- `PBS v1 frontend conforming`
- `PBS v1 source-runtime conforming`
An implementation that does not satisfy one complete canonical level must not claim PBS conformance merely because it implements a subset such as parsing-only or parser-plus-binder behavior.
Any partial claim must explicitly state excluded domains when they matter to user expectations, including as applicable:
- artifact emission,
- loader interaction,
- verifier behavior,
- supported runtime line,
- selected stdlib environment,
- host-registry line,
- and capability assumptions.
The unqualified claim `PBS v1 conforming` is reserved until the artifact-facing conformance surface is fully closed in `13`, `12`, `15`, and `19`.
## 3. Claim Meanings
### 3.1 Frontend Conformance
`frontend conformance` is the minimum canonical PBS conformance claim.
It requires:
- deterministic parsing behavior,
- deterministic source rejection for in-scope syntax, linking, and static-semantics failures,
- deterministic manifest/import resolution outcomes,
- regression protection for already-published behavior inside that claim scope,
- and the stable diagnostics fields required by the diagnostics contract for those failures.
It does not imply:
- runtime execution support,
- host-backed call execution,
- artifact emission,
- loader integration,
- or verifier integration.
### 3.2 Source-Runtime Conformance
`source-runtime conformance` extends `frontend conformance`.
It additionally requires:
- source-level runtime oracle coverage,
- source-level memory and identity oracle coverage,
- host-boundary behavior already fixed by the Host ABI and capability specs at source-visible level,
- and regression protection for already-published behavior inside that claim scope.
It does not by itself imply:
- one normative PBX image shape,
- one artifact-level golden contract,
- loader patching behavior beyond source-visible requirements,
- or verifier-surface conformance.
### 3.3 Full Toolchain Conformance
`full toolchain conformance` is the top-level PBS v1 conformance claim.
It requires:
- all `source-runtime conformance` obligations,
- all artifact-level oracle requirements once closed,
- loader/verifier-facing acceptance and rejection obligations that belong to PBS-facing conformance,
- required fixture modeling for stdlib, registry, capability, and runtime lines,
- and maintained regression/compatibility evidence for every published supported combination inside the claim.
Until those artifact-facing obligations are normatively closed, implementations may publish only the narrower qualified claims above.
## 4. Naming and Publication Rules
- If the word `conforming` is used in a PBS v1 product claim, it must use one of the canonical claim levels.
- The bare wording `PBS v1 conforming` is reserved for the full toolchain claim only.
- `frontend` and `source-runtime` claims must keep the qualifier adjacent to the published claim and must not be shortened to imply full PBS v1 conformance.
- If an implementation is still below `frontend conformance`, it should describe itself as partial, experimental, or implementation-specific rather than conforming.
- Published conformance claims must state the tested scope when environment selection changes observable behavior.
## 5. Invariants
- PBS conformance is staged, not all-or-nothing, during the v1 maturation path.
- The meaning of the unqualified top-level claim must remain stronger than any partial claim.
- Partial claims must not hide excluded domains behind vague wording.
- Conformance claims and compatibility claims are related but not identical; compatibility policy may refine promise strength per claim level without redefining the claim levels themselves.
- Published claims must be backed by executable evidence in the conformance or regression corpus appropriate to that claim level.
## 6. Explicit Non-Decisions
This decision record does not yet close:
- the full fixture model for stdlib, host-registry, capability, and runtime-line scenarios,
- the final artifact-level oracle for PBX or lowering invariants,
- the compatibility-matrix dimensions and retirement policy,
- or the exact repository layout of the conformance corpus.
## 7. Spec Impact
This decision should feed at least:
- `docs/general/specs/13. Conformance Test Specification.md`
- `docs/general/specs/17. Compatibility and Evolution Policy.md`
It should also constrain later work in:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
- `docs/general/specs/19. Verification and Safety Checks Specification.md`
- `docs/pbs/decisions/Artifact-Level Conformance and Fixture Model Decision.md`
- `docs/pbs/decisions/Compatibility Matrix and Published Claims Decision.md`
- `docs/pbs/agendas/17.1. Compatibility Workshop 1 - Compatibility Domains and Promise Levels.md`
## 8. Validation Notes
The intended operational reading is:
- a parser-plus-binder implementation may claim `frontend conformance` only if it actually satisfies the complete frontend obligations, including deterministic rejection behavior and the stable diagnostics surface in scope,
- an interpreter or direct-execution implementation may claim `source-runtime conformance` without yet claiming artifact or verifier conformance,
- and no implementation should imply full PBS v1 conformance until the artifact-facing contract is normatively testable.
@@ -0,0 +1,215 @@
# Diagnostics Contract Decision
Status: Accepted (Implemented)
Cycle: Diagnostics agenda closure pass
## 1. Context
PBS v1 needed one coherent diagnostics contract that closes the open questions from the diagnostics agenda:
- diagnostic identity,
- attribution and cross-file reporting,
- wording and localization boundaries,
- warning and cost-diagnostics policy,
- and the boundary between PBS-facing diagnostics and backend/artifact-facing failures.
The adopted direction needed to stay deterministic and conformance-friendly without freezing one editor UX, one compiler architecture, or one backend-internal reporting format.
## 2. Decision
PBS v1 adopts the following diagnostics baseline:
1. Every PBS-facing diagnostic has a mandatory `diagnostic code`.
2. Every PBS-facing diagnostic has a mandatory `severity`.
3. The stable external diagnostic phases include:
- `syntax`,
- `static semantics`,
- `manifest/import resolution`,
- `linking`,
- `host-binding/capability admission`,
- and load-facing rejection when directly attributable to malformed or unauthorized PBS-facing artifact usage.
4. `linking` is a first-class diagnostics phase and should remain visible to users as part of the didactic pipeline.
5. The minimum source-facing payload is:
- `diagnostic code`,
- `severity`,
- `phase`,
- `primary file`,
- `primary span/location`,
- and a human-readable message.
6. The diagnostics model must also carry a stable `message template id` with stable named placeholders for localized rendering.
7. Human wording is not byte-for-byte normative. The normative contract is the stable association among diagnostic code, message template id, placeholders, and rejection meaning.
8. Implementations may localize rendered messages by language, provided the rendered message preserves the same normative rejection meaning.
9. For future interoperability-oriented transports such as a possible LSP integration, implementations should preserve the ability to render an English default/fallback message even when a product renders another locale locally.
10. In cross-file failures, the primary site must be the source location where the user action triggered the failure.
11. `notes` and `related sites` are optional by default.
12. For `duplicate` and `conflict` classes, at least one related site is mandatory.
13. `hint` is a reserved diagnostics category in v1, but hint content is not mandatory.
14. `help` and guided remediation are outside the core conformance contract in v1.
15. Warnings are supported and recommended in v1, but they are not part of the minimum mandatory conformance baseline.
16. Qualitative cost facts may be surfaced as warnings or notes, especially for:
- retention-bearing `bind`,
- host-boundary crossings,
- and observable copy-versus-alias behavior.
17. Quantitative reporting such as byte counts, allocation counts, and performance ranking is outside the diagnostics contract and belongs to profiling/tooling.
18. Only backend-originated failures that remain source-attributable and user-actionable belong to the PBS-facing diagnostics contract.
19. Pure artifact corruption, verifier internals, loader internals, and compiler implementation bugs remain outside the PBS-facing diagnostics contract unless they are directly attributable to validly analyzed PBS source or to malformed/unauthorized PBS-facing artifact usage already in scope.
20. When a backend-originated failure remains in scope for PBS-facing diagnostics, v1 requires at least one source location but does not require one standardized source-map, artifact-offset, or verifier-trace format.
## 3. Diagnostic Identity and Payload
The minimum stable identity of a PBS-facing diagnostic is not free-form wording.
The stable identity is carried by:
- `diagnostic code`,
- stable phase attribution,
- and the rejection class semantics represented by the code/template pair.
The minimum externally relevant fields are:
- `diagnostic code`,
- `severity`,
- `phase`,
- `primary file`,
- `primary span/location`,
- `message template id`,
- stable named placeholders,
- and a rendered human-readable message.
This baseline keeps diagnostics testable and localizable without forcing one exact byte-for-byte phrasing.
## 4. Cross-File Attribution
Cross-file attribution follows an action-first rule.
Rules:
- import failures point primarily to the importing site,
- barrel failures point primarily to the barrel entry or reference site that triggered the failure,
- linking or cross-module lookup failures point primarily to the use or reference site that could not be resolved,
- related sites may be attached when known,
- and `duplicate` or `conflict` diagnostics must include at least one related site in addition to the primary site.
This keeps diagnostics actionable for users and stable enough for conformance.
## 5. Message Rendering and Localization
PBS v1 permits localized diagnostics, including localized editor-first experiences.
The normative boundary is:
- codes are stable,
- template ids are stable,
- placeholders are stable,
- and rendered wording may vary by locale and product surface.
Examples in specs should therefore be treated as illustrative unless a spec explicitly marks a template shape or placeholder contract as normative.
## 6. Categories, Notes, and Hints
The stable visible categories currently reserved are:
- `error`,
- `warning`,
- `note`,
- `hint`.
`notes` are optional by default in v1.
`hint` exists in the diagnostics model from v1 onward so implementations can grow into educational guidance without changing the core schema.
This decision does not require one exact distinction between short hints and richer remediation flows.
## 7. Warning and Cost-Diagnostics Boundary
PBS v1 deliberately keeps warnings out of the minimum conformance baseline.
This means:
- implementations may emit warnings,
- the editor can use warnings aggressively for pedagogy,
- but conformance does not currently fail merely because an implementation omits optional warnings.
The diagnostics contract does recognize the importance of qualitative cost facts already fixed elsewhere, but it does not promote them to mandatory warnings in v1.
## 8. Backend-Originated Failure Boundary
PBS-facing diagnostics stop where failures stop being source-attributable and user-actionable.
In scope for PBS-facing diagnostics:
- lowering failures that reflect a normative source-facing lowering rule or impossibility,
- verifier or loader rejections that are directly attributable to malformed or unauthorized PBS-facing artifact usage,
- and backend-originated failures that can still be mapped back to source in a way the user can act on.
Out of scope for PBS-facing diagnostics:
- internal compiler exceptions,
- implementation bugs,
- artifact corruption not attributable to valid PBS source or to in-scope malformed/unauthorized artifact usage,
- and backend-internal failure surfaces with no stable user-facing source attribution.
## 9. Conformance Boundary
The conformance surface for diagnostics should check only stable external fields.
Conformance may assert:
- rejection versus acceptance,
- diagnostic code,
- severity/category when in scope,
- phase,
- source attribution,
- and related-site requirements for narrow classes such as `duplicate` or `conflict`.
Conformance should not require:
- one exact rendered message,
- one exact localized wording,
- one exact note shape outside explicitly required classes,
- one verifier/loader internal format,
- or one profiling/reporting style.
Warnings remain outside pass/fail conformance in v1, though any emitted warning must remain semantically compatible with the spec.
## 10. Invariants
- The diagnostics contract must remain deterministic across conforming implementations.
- Diagnostic identity must not depend on one locale or one exact rendered sentence.
- `linking` remains a visible diagnostics phase rather than being collapsed away into a generic resolution bucket.
- Cross-file diagnostics must remain action-oriented from the user's point of view.
- Localized rendering must not erase the stable machine-readable identity of a diagnostic.
- The contract must stay narrow enough that more than one toolchain can implement it.
- Backend-internal reporting must not leak into the PBS language contract unless the failure is source-attributable and user-actionable.
## 11. Explicit Non-Decisions
This decision record does not yet close:
- the full warning catalog for future versions,
- whether a future version promotes a subset of warnings into mandatory conformance,
- exact remediation/help-content policy,
- exact source-map or artifact-offset formats,
- verifier trace schemas,
- transport-specific LSP field mapping,
- or internal compiler bug-reporting policy.
## 12. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `docs/general/specs/13. Conformance Test Specification.md`
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
- `docs/general/specs/19. Verification and Safety Checks Specification.md`
## 13. Validation Notes
The intended operational reading is:
- diagnostics are machine-identifiable first and human-rendered second,
- localized editor UX is fully compatible with the contract,
- a future interoperable transport can still fall back to English rendering,
- warnings are available for pedagogy without being required for conformance,
- and backend-originated failures only enter the PBS-facing contract when they still behave like actionable source diagnostics rather than internal tool failures.
@@ -0,0 +1,128 @@
# Dynamic Semantics - Branch Selection Decision
Status: Accepted (Implemented)
Cycle: Initial branch-selection closure pass
## 1. Context
PBS v1 needs a closed runtime contract for `if` and `switch` before the dynamic semantics spec can be completed.
The remaining questions were:
- whether conditions and selectors are evaluated once,
- whether non-selected branches evaluate at all,
- which selector categories are admitted for `switch`,
- and whether branch selection itself may trap.
## 2. Decision
PBS v1 adopts the following branch-selection rules:
1. `if` evaluates its condition exactly once.
2. `switch` evaluates its selector exactly once.
3. Only the selected branch or arm executes.
4. Non-selected branches and arms perform no evaluation.
5. `if` and `switch` are trap-free by themselves; only selected subexpressions may trap.
6. `switch` is limited to statically discriminable selector categories.
7. `switch` does not accept `result`, `error`, structs, string objects, or heap-backed types as selectors in v1.
## 3. `if`
For:
```text
if cond { then_block } else { else_block }
```
the runtime behaves as follows:
1. evaluate `cond` exactly once,
2. if it yields `true`, execute only `then_block`,
3. if it yields `false`, execute only `else_block`.
The non-selected branch is not evaluated, even partially.
Any trap associated with `if` arises only from:
- evaluating `cond`,
- or executing the selected branch.
## 4. `switch`
### 4.1 Selector evaluation
For:
```text
switch selector { ... }
```
the runtime:
1. evaluates `selector` exactly once,
2. determines the matching arm using the canonical matching rule for the selector category,
3. executes exactly one selected arm.
No non-selected arm is evaluated.
### 4.2 Admitted selector categories
In v1, `switch` is restricted to selector categories with static, deterministic matching behavior.
These include:
- literal-comparable scalar values,
- enum values,
- `str` values with canonical static identity,
- and other compile-time-constant-compatible selector categories only if explicitly admitted elsewhere.
`switch` does not accept:
- `result` values,
- `error` values,
- structs,
- string object/reference types distinct from canonical `str`,
- or heap-backed selector categories.
Dynamic or structural matching belongs to a future `match`-style construct rather than to `switch`.
### 4.3 Matching rule
`switch` arm selection is exact and deterministic for the admitted selector type.
- Enum selectors match by canonical enum-case identity.
- Scalar selectors match by the exact equality rule already defined for that scalar category.
- `str` selectors match by canonical static string identity rather than by heap-object comparison.
`switch` does not perform structural matching, guard evaluation, or user-defined equality dispatch.
## 5. Invariants
- `if` and `switch` never evaluate more than one branch or arm.
- Branch selection is deterministic for the same selector value.
- `switch` remains a static discriminant-selection construct, not a result/error-processing construct.
- Error processing with logic belongs to `handle`, not to `switch`.
## 6. Explicit Non-Decisions
This decision record does not yet close:
- the final future design of `match`,
- whether additional scalar-like selector categories will be admitted later,
- the complete memory/cost wording associated with selector evaluation.
## 7. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/9. Dynamic Semantics Specification.md`
- `docs/pbs/specs/4. Static Semantics Specification.md`
- `docs/pbs/specs/3. Core Syntax Specification.md`
## 8. Validation Notes
The intended split is:
- `if` and `switch` perform static, deterministic branch selection,
- `handle` processes modeled `result` errors,
- future dynamic or structural branching belongs to `match`, not to `switch`.
@@ -0,0 +1,355 @@
# Dynamic Semantics - Effect Surfaces Decision
Status: Accepted (Implemented)
Cycle: Initial effect-surfaces closure pass
## 1. Context
PBS v1 already commits to several effect and control surfaces in syntax and static semantics, but their runtime behavior must be closed before normative dynamic semantics can be written.
This decision record captures the first closed subset of that work:
- `optional`,
- `result<E>`,
- `!` propagation,
- `handle` processing.
Allocation, retention, copy visibility, and heap-facing cost wording are delegated to the memory and heap decision track.
## 2. Decision
PBS v1 adopts the following baseline runtime rules for `optional` and `result<E>` surfaces:
1. `optional` is a runtime presence/absence carrier with canonical `some(payload)` and `none` states.
2. `some(expr)` evaluates `expr` eagerly and exactly once before forming the `some` carrier.
3. `opt else fallback` evaluates the left operand exactly once and evaluates `fallback` only when the left operand is `none`.
4. `optional` is trap-free by itself; only subexpression evaluation may trap.
5. `result<E>` is the runtime carrier for expected, modelable failure in function return flow.
6. `expr!` evaluates `expr` exactly once and performs immediate enclosing-function error propagation on failure.
7. `handle expr { ... }` evaluates `expr` exactly once and, on error, executes exactly one matching arm.
8. A `handle` arm may execute user-defined logic.
9. A `handle` arm must terminate with either `ok(payload)` or `err(E2.case)`.
10. `ok(payload)` in a `handle` arm recovers locally and yields the payload as the value of the `handle` expression.
11. `err(E2.case)` in a `handle` arm performs immediate enclosing-function return with that error.
12. `handle` supports a short remap form `E1.case -> E2.case` as sugar for a block that returns `err(E2.case)`.
13. Neither `!` nor `handle` intercepts or converts traps.
14. `apply` is the canonical universal call surface for PBS v1 across all callable categories.
15. `apply` chains parse right-associatively but preserve the already-closed left-to-right observable evaluation model.
16. `apply` does not introduce implicit composition of `optional` or `result` surfaces.
17. `bind(context, fn_name)` forms a nominal callback value by attaching a struct context to a top-level function target.
18. `bind` evaluates its context expression exactly once, captures the same runtime context identity without copying it, and injects that context as the first argument when the callback is invoked.
19. `bind` is not a general closure mechanism and is trap-free at the language level.
## 3. `optional`
### 3.1 Runtime model
`optional` has exactly two runtime states:
- `some(payload)`
- `none`
`none` is the canonical absence of payload.
### 3.2 Construction
`some(expr)`:
- evaluates `expr` eagerly,
- evaluates it exactly once,
- then forms the `some(payload)` carrier from the produced payload.
### 3.3 Extraction
`opt else fallback`:
1. evaluates `opt` exactly once,
2. if the result is `some(payload)`, yields the extracted payload and does not evaluate `fallback`,
3. if the result is `none`, evaluates `fallback` and yields that value.
`else` is extraction with fallback, not error handling.
### 3.4 Trap behavior
`optional` itself does not trap.
Any trap associated with `some(expr)` or `opt else fallback` arises only from:
- evaluating `expr`,
- evaluating the left operand,
- or evaluating the fallback when it is needed.
## 4. `result<E>`
### 4.1 Runtime role
`result<E>` is the runtime carrier for success-or-modeled-failure at function boundaries and in expressions whose static type is `result<E> P`.
In v1, `ok(...)` and `err(...)` are special result-flow forms.
They are not general-purpose first-class userland constructors for arbitrary data modeling.
They are valid in:
- function return flow for `result<E>`,
- and `handle` arms, where they control recovery or propagation.
### 4.2 `!` propagation
`expr!`:
1. evaluates `expr` exactly once,
2. if `expr` yields success, yields the extracted success payload as the value of the expression,
3. if `expr` yields error, performs immediate enclosing-function return with the same `err(...)`.
`!` does not:
- remap the error,
- intercept traps,
- or continue ordinary evaluation after the propagated error path is chosen.
### 4.3 `handle`
`handle expr { ... }`:
1. evaluates `expr` exactly once,
2. if `expr` yields success, yields the extracted success payload directly,
3. if `expr` yields error, selects exactly one matching handle arm,
4. executes the selected arm,
5. requires that arm to terminate with either `ok(payload)` or `err(E2.case)`.
### 4.4 `handle` arm results
The selected `handle` arm has two admissible result forms:
- `ok(payload)`
- `err(E2.case)`
Their semantics are:
- `ok(payload)` recovers locally and makes the `handle` expression yield `payload`,
- `err(E2.case)` performs immediate enclosing-function return with `err(E2.case)`.
The `payload` in `ok(payload)` must be compatible with the success payload shape produced by the surrounding `handle` expression.
The `E2.case` in `err(E2.case)` must belong to the target error type required by the enclosing context.
### 4.5 `handle` sugar
For the common remap-only case, `handle` supports a short arm form:
```text
E1.case -> E2.case
```
This is sugar for:
```text
E1.case -> { err(E2.case) }
```
Recovery with `ok(payload)` requires the explicit block form.
### 4.6 `handle` scope
`handle` may execute user-defined logic inside an arm, but it remains specific to modeled `result` errors.
It does not provide:
- trap interception,
- arbitrary processing of non-`result` failure channels,
- or a general-purpose exception system.
## 5. Invariants
- `optional` models absence, not failure.
- Expected recoverable failure remains in `result<E>`, not in `optional`.
- `!` is an early-return propagation surface.
- `handle` is a typed result-processing surface with controlled recovery or propagation.
- Success paths produce payload values directly.
- Error paths in `result<E>` remain explicit and typed.
- Trap remains outside ordinary recoverable error flow.
- `apply` remains the single semantic call surface even when user code uses direct-call sugar.
- Callable-specific dispatch differences do not change the user-visible call pipeline.
- Effect boundaries remain explicit; `apply` does not auto-lift through `optional` or `result`.
## 6. `apply`
### 6.1 Canonical role
`apply` is the canonical universal call surface in PBS v1.
Direct call syntax is only sugar over `apply` and does not define separate runtime semantics.
The same observable call model applies to:
- top-level functions,
- struct methods,
- service methods,
- contract calls,
- callback calls,
- host-backed calls.
### 6.2 Shared observable pipeline
For `lhs apply rhs`, the shared observable runtime pipeline is:
1. form the call target from `lhs`,
2. evaluate any receiver or callable artifact needed for target formation exactly once,
3. evaluate `rhs` exactly once,
4. invoke the resolved target,
5. produce one of:
- normal return,
- explicit `result<Error>` propagation,
- or `trap`.
Callable-specific dispatch strategy may differ internally, but it does not change this user-visible sequencing model.
### 6.3 Chained `apply`
`apply` chains are parsed right-associatively.
For example:
```text
f1 apply f2 apply f3 apply params
```
parses as:
```text
f1 apply (f2 apply (f3 apply params))
```
The observable evaluation order still follows the already-closed left-to-right model:
1. form the target of `f1`,
2. evaluate the argument expression for `f1`,
3. within that argument expression, form the target of `f2`,
4. evaluate the argument expression for `f2`,
5. within that argument expression, form the target of `f3`,
6. evaluate `params`,
7. invoke `f3`,
8. invoke `f2`,
9. invoke `f1`.
### 6.4 Effect boundaries
`apply` does not introduce implicit effect composition.
If a callable returns:
- `optional<P>`, extraction remains explicit through `else`,
- `result<E> P`, propagation or remapping remains explicit through `!` or `handle`.
PBS v1 does not auto-lift ordinary call chains through `optional` or `result` boundaries.
## 7. `bind`
### 7.1 Role
`bind(context, fn_name)` is the explicit callback-formation mechanism in PBS v1.
It exists to attach a struct context to a compatible top-level function without introducing general lexical closures.
### 7.2 Context and target
`bind` requires:
- a context expression whose runtime value is a struct instance,
- a top-level function target whose first parameter is compatible with that struct type,
- and an expected callback type already validated by static semantics.
### 7.3 Runtime artifact
`bind(context, fn_name)` produces a nominal callback value that stores:
- the resolved top-level function target,
- the captured runtime identity of the context value.
The context is not copied or rematerialized during binding.
When the callback is later invoked, the runtime behaves as if it calls:
```text
fn_name(context, ...)
```
where `context` is the same captured runtime instance.
### 7.4 Evaluation and identity
The context expression is evaluated exactly once at bind time.
That evaluation exists only to obtain the struct instance that will be attached to the callback.
After capture:
- the same runtime context identity remains attached,
- mutations performed through the callback observe and affect that same context instance,
- `bind` does not create a detached copy of the context.
### 7.5 Storage and retention
`bind` is not semantically free.
Forming a callback through `bind` requires runtime storage sufficient to keep:
- the callback target identity,
- and the captured context alive while the callback value remains alive.
For the purposes of PBS v1 semantics, `bind` should be treated as a callback-forming operation with real retention and heap-facing consequences, even though the final memory/lifetime wording belongs in the dedicated memory specification.
### 7.6 Trap behavior
At the language-semantics level, `bind` is trap-free.
Incompatible context type, incompatible function target, or invalid callback shape are compile-time errors rather than runtime traps.
`bind` introduces no ordinary recoverable error surface and no bind-specific trap surface.
### 7.7 Non-goal
`bind` is not:
- general closure capture,
- arbitrary local-environment capture,
- or a promise that future closure features must behave identically.
It is the explicit v1 callback-binding mechanism only.
## 8. Explicit Non-Decisions
This decision record does not yet close:
- the final memory/lifetime wording for allocation, copy, and retention visibility,
- the final catalog of trap sources that may arise from subexpression evaluation.
## 9. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/9. Dynamic Semantics Specification.md`
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
The unresolved cost and retention wording for these surfaces should be completed through:
- `docs/pbs/agendas/Memory and Lifetime - Agenda.md`
- `docs/pbs/agendas/Heap Model - Agenda.md`
## 10. Validation Notes
The intended behavior is:
- `some(expr)` is eager,
- `opt else fallback` is short-circuit on `some`,
- `!` propagates the same typed error unchanged,
- `handle` remaps typed errors without introducing custom logic,
- `apply` remains the universal call surface across callable kinds,
- chained `apply` does not create implicit optional/result composition,
- `bind` captures a struct context identity without copying it,
- `bind` forms a callback with real retention/storage consequences,
- `handle` may recover with `ok(payload)` or propagate with `err(E2.case)`,
- short-form `handle` arms are sugar for propagation-only remap blocks,
- `trap` remains outside both `!` and `handle`.
@@ -0,0 +1,131 @@
# Dynamic Semantics - Execution Model Decision
Status: Accepted (Implemented)
Cycle: Initial execution-model closure pass
## 1. Context
PBS needs a closed execution-model baseline before effect surfaces and memory/lifetime semantics can be specified normatively.
The key open questions were:
- whether execution is single-threaded per program instance,
- which runtime effects are observable to user code,
- what the default evaluation order is,
- which constructs guarantee single evaluation,
- how abrupt completion behaves,
- how `result<Error>` differs from `trap`,
- and how host calls interact with `FRAME_SYNC` without perturbing user-visible sequencing.
## 2. Decision
PBS v1 adopts the following execution-model baseline:
1. Execution is single-threaded per program instance.
2. User-visible execution is deterministic and does not expose concurrent interleaving.
3. The default evaluation rule is strict left-to-right unless a construct explicitly states otherwise.
4. Call evaluation proceeds by forming the call target first, then evaluating arguments left-to-right, then invoking the target.
5. Abrupt completion terminates the current construct immediately and prevents later sibling evaluation.
6. Recoverable, expected failures belong to `result<Error>`, not to `trap`.
7. `trap` is reserved for non-recoverable runtime failures outside ordinary userland error flow.
8. Any trap aborts the current PBS program execution rather than returning control to ordinary userland flow.
9. `FRAME_SYNC` is the only normative safepoint in PBS v1.
10. `FRAME_SYNC` remains the execution boundary for userland progress; host-side work during that boundary must not reorder PBS-observable semantics.
## 3. Invariants
- PBS v1 does not expose a user-visible concurrent execution model.
- User-visible sequencing is defined by evaluation order, branch selection, abrupt completion, result propagation, trap propagation, and host-call boundaries.
- Traps are not recoverable in userland and do not resume PBS execution.
- VM-internal frame layout, temporary storage, and lowering steps are not observable unless they change the semantic effects above.
- Unless a construct states otherwise, subexpressions are evaluated once and in left-to-right order.
- `return`, `break`, `continue`, result propagation via `!`, and `trap` abort further evaluation in the current construct.
- Host calls must not introduce user-visible reordering of already-defined PBS evaluation order.
- No normative safepoint exists in v1 other than `FRAME_SYNC`.
## 4. Call Evaluation Rule
The runtime call rule for v1 is:
1. Form the call target.
2. Evaluate any receiver that participates in target formation.
3. Evaluate arguments in source order from left to right.
4. Invoke the resolved target.
5. Produce one of:
- normal return,
- explicit `result<Error>` propagation,
- or `trap`.
This rule applies to canonical `apply` and to ordinary call sugar that desugars to `apply`.
## 5. Error Boundary
`result<Error>` and `trap` are distinct runtime categories.
### 5.1 `result<Error>`
`result<Error>` is the required mechanism for failures that are:
- expected by the API contract,
- recoverable in ordinary userland control flow,
- modelable through an explicit PBS error type.
Such failures may be:
- processed with `handle`,
- propagated with `!`,
- and discussed as part of ordinary function contract design.
### 5.2 `trap`
`trap` is reserved for failures that are:
- outside the ordinary userland contract,
- not suitably representable as the declared `result<Error>` surface,
- caused by runtime or host invariant failure,
- or severe enough that ordinary userland recovery is not part of the v1 language model.
PBS v1 does not define `try/catch` for traps.
Traps are not part of ordinary recoverable control flow.
Once a trap is raised, PBS userland execution aborts and control transfers to runtime or firmware crash handling outside the ordinary language model.
## 6. Consequences
- User-authored code does not explicitly throw traps as part of ordinary PBS semantics.
- API surfaces must not use trap as a substitute for a modelable `result<Error>` failure.
- Host-backed operations must expose predictable operational failures through `result<Error>` when those failures are part of the callable contract.
- Residual host or runtime failures that cannot be represented by the declared PBS contract may still trap.
- The language-level consequence of trap is program abort rather than catchable failure handling.
- In v1, no safepoint inventory is normative beyond `FRAME_SYNC`.
## 7. Explicit Non-Decisions
This decision does not yet close:
- the exact list of constructs with explicit single-evaluation wording as finally integrated into the dynamic-semantics spec,
- the final wording split between dynamic semantics and runtime-initialization for trap/crash handoff.
Those points must be integrated by the remaining dynamic-semantics and memory/lifetime decisions.
## 8. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/9. Dynamic Semantics Specification.md`
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/general/specs/16. Runtime Execution and Initialization Specification.md`
It should also constrain future work in:
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `docs/general/specs/13. Conformance Test Specification.md`
## 9. Validation Notes
The intended rule is:
- expected domain failure: `result<Error>`
- remappable, processable, or propagatable failure: `result<Error>`
- runtime invariant breakage or non-contract catastrophic failure: `trap`
In practical terms, a host-backed API must not rely on trap for ordinary operational failures if those failures can be declared and modeled explicitly in PBS. The only normative safepoint in v1 is `FRAME_SYNC`, and any trap aborts PBS userland execution rather than returning through an in-language recovery path.
@@ -0,0 +1,130 @@
# GC and Reachability Decision
Status: Accepted (Implemented)
Cycle: Initial GC-and-reachability closure pass
## 1. Context
PBS v1 uses GC as the baseline runtime model, but the language still needs a precise statement of:
- what reachability guarantees are normative,
- what reclamation guarantees are normative,
- what remains implementation-defined,
- how GC interacts with the single normative safepoint at `FRAME_SYNC`,
- and what user code may or may not observe.
## 2. Decision
PBS v1 adopts the following GC-and-reachability baseline:
1. GC is the baseline runtime model for VM-owned memory in PBS core.
2. Reachability is the normative liveness criterion for GC-managed values.
3. Eventual reclamation is the strongest reclamation guarantee in v1.
4. `FRAME_SYNC` is the only normative safepoint relevant to GC-observable behavior.
5. User code cannot observe reclamation directly.
6. PBS v1 defines no user-authored finalizers, destructors, or reclamation callbacks.
7. Implementations may perform internal GC work outside `FRAME_SYNC` only if doing so creates no additional user-visible semantic effects.
## 3. Normative Reachability Contract
For GC-managed VM-owned values, liveness is defined by reachability from the runtime roots that matter to PBS semantics.
At minimum, these roots include:
- currently active local/frame state,
- reachable fields of reachable struct instances,
- service singleton roots,
- retained callback state that remains reachable,
- and any other runtime roots required to preserve already-observable PBS behavior.
If a GC-managed value remains reachable through the normative runtime state, the implementation must preserve its continued semantic availability.
If a value becomes unreachable, user code must not rely on when reclamation occurs.
## 4. Reclamation Guarantee
PBS v1 guarantees eventual reclamation, not prompt reclamation.
This means:
- unreachable GC-managed memory may be reclaimed later,
- the language does not promise immediate reclamation,
- the language does not promise reclamation at a specific frame boundary,
- and the language does not expose a semantic event when reclamation occurs.
## 5. Safepoint Relationship
`FRAME_SYNC` is the only normative safepoint in PBS v1.
For GC semantics, this means:
- the language does not promise any additional observable GC safepoints,
- no user-visible program rule may depend on another safepoint existing,
- and any internal collector work outside `FRAME_SYNC` must remain semantically invisible to PBS userland.
The spec does not require a specific collector architecture.
It only constrains what may become observable.
## 6. Observability
User code cannot observe reclamation directly.
PBS v1 provides no user-visible mechanism for:
- detecting that a value was collected,
- registering a callback on reclamation,
- forcing immediate collection,
- or sequencing user code against GC timing.
GC-related information may appear in diagnostics, profiling, or runtime tooling, but those surfaces are not ordinary language semantics.
## 7. Finalization and Cleanup
PBS v1 forbids user-authored finalizers and destructor-like reclamation hooks.
GC reclamation of pure VM-owned values does not trigger user code.
Host-backed cleanup policy is not defined by GC finalization semantics in this decision.
If host-backed resources require explicit or contract-specific cleanup rules, those belong to the host-boundary decision track rather than to GC finalization in userland.
## 8. Invariants
- Reachability, not timing, is the normative semantic axis.
- Reclamation timing remains implementation-defined.
- No direct user-visible behavior is allowed to depend on collector timing.
- The only normative safepoint is `FRAME_SYNC`.
- GC must not create extra user-visible sequencing effects outside the already-closed execution model.
## 9. Beginner-Facing Model
The user-facing explanation should be:
- if a value can still be reached by the program, it remains alive,
- once it can no longer be reached, the runtime may clean it up later,
- the program does not control or directly observe that cleanup moment.
## 10. Explicit Non-Decisions
This decision record does not yet close:
- the exact collector algorithm,
- host-backed resource cleanup semantics,
- diagnostics wording for GC-related tooling surfaces,
- the full root-set wording as finally integrated into the memory specification.
## 11. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `docs/general/specs/16. Runtime Execution and Initialization Specification.md`
## 12. Validation Notes
The intended split is:
- GC defines reachability and eventual reclamation,
- `FRAME_SYNC` is the only normative safepoint,
- reclamation timing is not user-observable,
- host-backed cleanup is a separate boundary question rather than a user finalization feature.
@@ -0,0 +1,115 @@
# Host Memory Boundary Decision
Status: Accepted (Implemented)
Cycle: Initial host-boundary closure pass
## 1. Context
PBS needs a user-visible contract for the boundary between VM-owned semantics and host-provided runtime services.
At the current stage of the language, userland does not expose complex host-owned resource models.
The runtime offers features and the frontend consumes them; PBS should be careful not to project unnecessary language-level memory abstractions into runtime internals too early.
## 2. Decision
PBS v1 adopts the following host-memory boundary baseline:
1. Cross-boundary interaction between host and PBS userland is restricted to stack-only values.
2. PBS userland does not expose host memory as ordinary language values.
3. Raw pointers are not exposed in PBS userland.
4. Borrowed host-memory views are not exposed in PBS userland.
5. Pinning is not exposed in PBS v1.
6. Zero-copy transfer is not exposed in PBS v1.
7. Heap-shared boundary values between host and PBS userland are not part of the v1 model.
8. Long-lived host resources, if later exposed, must be specified explicitly by subsystem contract rather than inferred from a general host-memory model.
## 3. Boundary Rule
The host/userland boundary in PBS v1 is value-based rather than memory-sharing-based.
This means:
- host-backed interaction happens through explicit call boundaries,
- data crossing that boundary is limited to stack-only value forms,
- and userland never receives direct access to host-owned memory regions.
PBS therefore does not model host memory as something the language can directly hold, borrow, pin, or traverse.
## 4. What Is Not Exposed
PBS v1 does not expose any general userland model for:
- raw host pointers,
- borrowed host slices or views,
- pinned host memory,
- zero-copy host/userland transfer,
- shared heap objects spanning host memory and VM memory.
These features are out of scope for the v1 language model.
## 5. Role of Syscalls
At the current stage, host interaction should be understood primarily through syscall-style host-backed contracts.
Those contracts may accept and return stack-only values, but they do not imply that PBS userland owns, borrows, or directly manipulates host memory.
## 6. Long-Lived Host Resources
PBS v1 does not yet define a general-purpose language model for long-lived host-owned resources such as:
- banks,
- mixers,
- or other subsystem-specific retained resources.
If such resources are exposed later, they must be specified by explicit subsystem contract rather than by assuming a general host-memory-handle model in core PBS.
## 7. Failure Model Scope
This decision does not force a universal language-level error projection for all runtime-internal host behavior.
It only closes the memory-boundary side of the question:
- PBS userland does not directly manipulate host memory,
- and cross-boundary interaction remains stack-value-based.
Concrete error modeling for particular host-backed surfaces belongs to the contract of those surfaces rather than to a general raw-memory boundary rule.
## 8. Invariants
- The host/runtime may own internal memory and resource lifetimes that PBS userland never sees directly.
- PBS userland remains insulated from host-memory unsoundness by not exposing raw memory access at the language level.
- The absence of pointers and borrowed host views is a core v1 safety property.
- Boundary simplicity takes priority over premature expressiveness in this area.
## 9. Beginner-Facing Model
The user-facing explanation should be:
- the runtime can provide services to PBS programs,
- programs pass ordinary values into those services and receive ordinary values back,
- but programs do not directly hold or manipulate host memory.
## 10. Explicit Non-Decisions
This decision record does not yet close:
- the future design of subsystem-specific long-lived host resources,
- the future design of any explicit resource-release APIs,
- the concrete error contract of each host-backed surface,
- the final wording of host-boundary diagnostics.
## 11. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/pbs/specs/6. VM-owned vs Host-backed.md`
- `docs/pbs/specs/6.2. Host ABI Binding and Loader Resolution Specification.md`
## 12. Validation Notes
The intended split is:
- runtime and host internals may remain complex,
- PBS userland sees only stack-only value exchange across the boundary,
- and any richer host-resource model must be introduced later by explicit subsystem contract.
@@ -0,0 +1,64 @@
# IRVM Optimization Stage Placement Decision
Status: Accepted
Date: 2026-03-07
Related Agendas:
- `docs/pbs/agendas/18.0. Backend VM Pipeline - Orchestration Agenda.md`
- `docs/pbs/agendas/18.2. Backend Workshop 2 - LowerToIRVM and IRVM Contract.md`
- `docs/pbs/agendas/18.3. Backend Workshop 3 - Bytecode Marshaling and Runtime Conformance.md`
## Context
Ao fechar a trilha backend executavel (`IRBackend -> IRVM -> bytecode`), surgiu a necessidade de definir onde a otimizacao deve ocorrer.
As opcoes praticas eram:
1. otimizar no runtime,
2. otimizar durante emissao de bytecode,
3. otimizar em etapa dedicada sobre `IRVM` antes da emissao.
O runtime atual privilegia determinismo, loader/verifier estritos e execucao numeric-only.
## Decision
PBS adota etapa dedicada de otimizacao entre lowering e emissao:
1. `LowerToIRVM` gera `IRVM`;
2. `OptimizeIRVM` aplica transformacoes `IRVM -> IRVM` semanticamente equivalentes;
3. `EmitBytecode` serializa o `IRVM` otimizado em artefato pre-load.
A etapa `OptimizeIRVM` passa a ser parte canônica do pipeline backend executavel.
## Invariants
1. `OptimizeIRVM` e compile-time, nao runtime.
2. `OptimizeIRVM` MUST preservar semantica observavel do programa.
3. `OptimizeIRVM` MUST preservar contratos de chamada/retorno/slots.
4. `OptimizeIRVM` MUST preservar determinismo para o mesmo grafo de entrada admitido.
5. `OptimizeIRVM` MUST respeitar `vm_profile` alvo e nao deixar opcodes internos nao-eliminados para a emissao final.
6. `EmitBytecode` continua responsavel por produzir artefato pre-load conforme contrato de loader/verifier.
7. Runtime nao assume papel de otimizador semantico do programa.
## Explicit Non-Decisions
1. Esta decisao nao define o catalogo completo de passes de otimizacao.
2. Esta decisao nao define heuristicas de custo/performance por alvo.
3. Esta decisao nao redefine regras de verifier/loader do runtime.
4. Esta decisao nao define fluxo de packer/cartucho.
## Spec Impact
1. A orquestracao de pipeline em `18.0` passa a incluir `OptimizeIRVM` entre `LowerToIRVM` e `EmitBytecode`.
2. A futura spec de `IRVM` (`18.2`) deve explicitar pre/post-condicoes da etapa de otimizacao.
3. A futura spec de marshaling (`18.3`) deve explicitar que a emissao opera sobre `IRVM` pos-otimizacao.
4. `docs/general/specs/19. Verification and Safety Checks Specification.md` deve refletir cobertura de regressao para pipeline com otimizacao intermediaria.
## Validation Notes
Para validacao minima da decisao:
1. o pipeline executa na ordem `LowerToIRVM -> OptimizeIRVM -> EmitBytecode`;
2. fixtures equivalentes com e sem otimizacao produzem comportamento runtime equivalente;
3. casos negativos de loader/verifier continuam falhando de forma deterministica apos a introducao de `OptimizeIRVM`.
@@ -0,0 +1,121 @@
# Lifetime Control and Future Profiles Decision
Status: Accepted (Implemented)
Cycle: Initial lifetime-control policy closure pass
## 1. Context
PBS v1 no longer uses the old RC/HIP model as an active core-language direction.
The remaining question is not how to design explicit lifetime control now, but how the project should treat legacy concepts and what policy should govern any future reintroduction of lifetime-oriented language features.
## 2. Decision
PBS v1 adopts the following lifetime-control policy baseline:
1. No lifetime-control keyword is reserved in core PBS merely for possible future use.
2. If a lifetime-control surface is not active in v1, it should not remain in the language as a reserved future-only keyword on that basis alone.
3. Advanced memory workflows should default to library/tooling-first exploration rather than syntax-first activation.
4. GC remains the default core model; future explicit lifetime control, if ever introduced, must be profile-gated rather than silently folded into the default language.
5. Future lifetime-oriented syntax may be introduced only when there is concrete evidence that library/tooling approaches are insufficient.
## 3. Legacy RC/HIP Concepts
Legacy concepts such as:
- `alloc`
- `borrow`
- `take`
- `weak`
- pool-style and arena-style control patterns
- object reuse patterns
do not remain active merely by historical inertia.
For PBS v1 policy:
- legacy concepts may survive as historical or design-reference material,
- but they do not imply reserved syntax commitment,
- and they do not imply a roadmap promise of later activation.
## 4. Language Versus Library Boundary
The default policy is:
- library first,
- tooling first,
- profile later only if justified,
- syntax last.
This means advanced workflows should first be explored through:
- stdlib APIs,
- tooling support,
- diagnostics,
- profiling guidance,
- subsystem-specific contracts where needed.
The language should not absorb explicit lifetime syntax simply because a legacy concept existed before.
## 5. Migration Narrative
The official migration narrative is:
- PBS v1 moves away from RC/HIP-style user-authored lifetime control as the core user model,
- GC plus deterministic execution is the baseline,
- performance-sensitive reasoning remains important,
- but performance and memory control should rise through explicit APIs and tooling before new syntax is considered.
This is a deliberate simplification, not a temporary placeholder awaiting automatic return to explicit ownership syntax.
## 6. Future Activation Criteria
Any future lifetime-oriented language/profile work must satisfy all of the following:
1. Real implementation and product evidence shows that library/tooling-first approaches are insufficient.
2. The proposed feature has a coherent semantic model that does not break the GC baseline by accident.
3. The feature can be isolated behind an explicit profile or equivalent opt-in boundary.
4. Diagnostics, conformance, and migration obligations are clear.
5. The feature does not degrade the beginner-facing default language without strong justification.
Future activation must be justified by present need and validated design, not by preserving speculative syntax in the current language.
## 7. Invariants
- GC remains the default core runtime model.
- Core PBS v1 does not promise future activation of legacy lifetime syntax.
- Absence of reserved lifetime keywords is a deliberate policy choice.
- Future explicit control must be explicit, justified, and profile-gated.
## 8. Beginner-Facing Model
The user-facing explanation should be:
- PBS v1 does not require ownership or lifetime syntax in ordinary code,
- advanced control is not removed as a future possibility,
- but it will be introduced only if it proves necessary and only through explicit design, not through dormant keywords left in the language.
## 9. Explicit Non-Decisions
This decision record does not yet close:
- the exact shape of any future profile mechanism,
- the exact syntax of any future explicit lifetime feature,
- the future stdlib design for pools, arenas, or weak-reference-like patterns.
## 10. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/general/specs/17. Compatibility and Evolution Policy.md`
- `docs/pbs/specs/3. Core Syntax Specification.md`
## 11. Validation Notes
The intended policy is:
- no dormant lifetime keywords in core v1,
- no nostalgia-based reservation policy,
- library/tooling first,
- profile-gated language activation only when clearly justified.
@@ -0,0 +1,168 @@
# Name Resolution - Builtin Shells and Host Owners Decision
Status: Accepted (Implemented)
Cycle: Initial name-resolution closure pass
## 1. Context
PBS v1 needs a deterministic rule for how reserved stdlib shells participate in source-level name resolution.
The open questions were:
- whether builtin shells and host owners enter lookup as ordinary imported declarations or as special compiler-only names,
- whether builtin intrinsic methods participate in free callable lookup,
- whether reserved shells receive special collision priority,
- whether builtin shells belong under `@core:*` or `@sdk:*` by policy,
- and which phase owns failures related to builtin member lookup and canonical identity duplication.
Important fixed inputs already existed:
- reserved stdlib project spaces are resolved from the selected stdlib environment,
- source-visible builtin names resolve through imported builtin shell declarations,
- canonical builtin and host identities come from metadata rather than local spelling,
- builtin intrinsic methods are not imported as free functions,
- and host-owner namespace remains distinct from type, value, and callable namespaces.
## 2. Decision
PBS v1 adopts the following baseline for builtin shells and host-owner resolution:
1. Source-visible declarations exposed by reserved builtin shells are imported into their ordinary corresponding namespaces.
2. This means builtin-exposed types enter type lookup as imported type declarations, builtin-exposed constants enter value lookup as imported values, and host owners enter host-owner lookup as imported host-owner declarations.
3. `declare builtin type` itself remains a reserved stdlib/toolchain declaration form rather than ordinary user-authored source syntax.
4. Reserved-shell metadata exists to drive canonical identity and later lowering, not to create special source-level lookup priority.
5. Builtin simple types `int`, `float`, `bool`, and `str` remain separate always-available reserved type names and are not treated as ordinary imported builtin shells.
6. Builtin intrinsic methods never participate in free lookup.
7. Builtin intrinsic methods are resolved only through member lookup on a receiver already known to have the corresponding builtin type.
8. Reserved builtin shells and host owners follow the same collision policy as ordinary imported declarations: same visible name in the same namespace is an error unless another already-closed rule explicitly permits otherwise.
9. By policy, builtin shells are preferred under `@core:*`.
10. Member lookup failure on an already-typed builtin receiver belongs to static semantics.
11. Duplicate canonical builtin identities or duplicate canonical host identities in one resolved environment belong normatively to linking rather than to syntax or ordinary static semantics.
## 3. Reserved Shells As Imported Declarations
Reserved shells are source-visible through ordinary import and visibility rules.
This means:
- the user imports the shell from a reserved stdlib module,
- the imported shell becomes visible in the matching namespace,
- and source-level lookup treats that visible declaration like other imported declarations of the same namespace.
The compiler still recognizes the reserved metadata attached to those declarations, but that metadata does not create a parallel hidden namespace.
## 4. Builtin Simple Types Versus Imported Builtin Shells
PBS distinguishes:
- the tiny predeclared builtin simple-type set: `int`, `float`, `bool`, `str`,
- and imported builtin shells such as `Vec2`, `Color`, or similar stdlib-exposed types.
Rules:
- builtin simple types remain always available without import,
- imported builtin shells are not promoted to that same status,
- and the two categories must not be conflated in source-level lookup.
## 5. Intrinsic Member Lookup
Builtin intrinsic members are resolved only through receiver-member lookup.
Rules:
- they do not appear in top-level callable lookup,
- they are not introduced by import as free functions,
- and aliasing the owner builtin type changes only the local visible owner spelling, not the intrinsic's canonical identity.
This keeps member semantics uniform and avoids special free-function treatment for reserved surfaces.
## 6. Collision Policy
Reserved shells receive no special collision privilege.
Rules:
- if an imported builtin shell declaration and another visible declaration produce the same visible name in the same namespace, the program is rejected under the ordinary collision rules already chosen,
- if a host owner shares a spelling with a type or value, that alone is not a conflict because host-owner namespace remains distinct,
- and reserved-shell status does not authorize silent shadowing.
## 7. Reserved Project-Space Policy
For source-level policy:
- builtin shells are preferred under `@core:*`,
- host-facing capability surfaces remain the natural fit for `@sdk:*`.
This is a policy direction for clarity and separation of concerns.
It does not change the underlying ownership model governed by other specs.
## 8. Failure Ownership Baseline
The current baseline is:
- failure to resolve a reserved stdlib module remains manifest/import resolution,
- import of a non-exported reserved shell remains linking,
- member lookup failure on an already-typed builtin receiver remains static semantics,
- duplicate canonical builtin or host identities in one resolved environment remain linking failures.
Implementations may internally perform some of these checks during environment validation, but the normative external phase ownership is linking where the linking-phase decision assigns it.
## 9. Invariants
- Reserved-shell metadata does not create special source-level lookup priority.
- Builtin intrinsic methods are never free functions in source-level lookup.
- Builtin simple types remain separate from stdlib-delivered builtin shells.
- Host owners remain in the host-owner namespace only.
- Ordinary collision rules apply to reserved-shell imports unless a later explicit rule says otherwise.
- Canonical identity conflicts are linking problems, not syntax problems.
## 10. Explicit Non-Decisions
This decision record does not yet close:
- the full stdlib-surface policy of `18. Standard Library Surface Specification.md`,
- and the final lowering consequences in `13. Lowering IRBackend Specification.md`.
## 11. Spec Impact
This decision should feed at least:
- `docs/general/specs/14. Name Resolution and Module Linking Specification.md`
- `docs/general/specs/18. Standard Library Surface Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
It should also constrain future work in:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## 12. Validation Notes
The intended baseline is:
- reserved builtin shells are imported like ordinary declarations into the matching namespace,
- builtin methods are found only through receiver-member lookup,
- builtin simple types remain always available without import,
- `@core:*` is the preferred home for builtin shells,
- and duplicate canonical builtin or host identities are rejected at linking time.
Illustrative examples:
```pbs
import { Vec2 } from @core:math;
```
`Vec2` becomes an imported visible type declaration with builtin metadata.
```pbs
import { Vec2 } from @core:math;
Vec2.zero()
```
If `zero` is a builtin intrinsic member, it resolves through builtin member lookup on `Vec2`-typed receiver use and not through free callable lookup by the name `zero`.
```pbs
import { Vec2 } from @core:math;
declare const Vec2: int = 1;
```
This is rejected as an ordinary same-namespace collision rather than resolved by reserved-shell priority.
@@ -0,0 +1,173 @@
# Name Resolution - Callable Sets and Cross-Module Linking Decision
Status: Accepted (Implemented)
Cycle: Initial name-resolution closure pass
## 1. Context
PBS v1 needs a deterministic rule for how callable names cross module boundaries.
The open questions were:
- what exactly `import { f } from @project:path;` imports when `f` has multiple exported signatures,
- whether callable sets from different origins may merge,
- whether same-name imported callables from different origins are tolerated until callsite analysis,
- whether local and imported callable names may coexist under one visible function name,
- and how `mod.barrel` bounds the callable set that becomes importable.
Earlier closure already fixed important inputs:
- `mod.barrel` is the single source of module visibility,
- only `pub` names may be imported from another module,
- local function names and imported function names with the same visible name are already being treated as collisions in this closure pass,
- and callable identity is determined by callable shape rather than parameter-label spelling alone.
## 2. Decision
PBS v1 adopts the following baseline for callable sets and cross-module linking:
1. `import { f } from @project:path;` imports the exported callable set named `f` from the target module.
2. The imported callable set for `f` consists only of those overload signatures of `f` that are exported through that module's `mod.barrel`.
3. Non-exported overloads in the target module do not participate in the imported callable set.
4. Two imports of the same visible callable name are tolerated when they resolve to the same canonical underlying callable-set origin after module resolution.
5. Such same-origin duplicate imports are redundant but not errors.
6. Two imports of the same visible callable name from different canonical origins are rejected immediately.
7. The program must not wait until a callsite to reject different-origin callable-name collisions.
8. A module-local function name and an imported function name with the same visible name are rejected immediately.
9. Automatic merging of callable sets across different origins is not permitted in this closure pass.
10. Ordinary overload resolution occurs only after one unambiguous visible callable set has already been formed.
## 3. Imported Callable Set
The meaning of:
```pbs
import { f } from @project:path;
```
is:
- resolve the target module,
- collect the exported callable entries named `f` from that module,
- form the callable set consisting only of those exported overloads,
- and make that callable set visible locally under the imported visible name.
This import does not:
- reach non-exported overloads,
- merge with hidden module-internal overloads,
- or import one overload at a time independently from the exported callable name.
## 4. Same-Origin Versus Different-Origin Imports
### 4.1 Same origin
If the same visible callable name is imported more than once and both imports resolve to the same canonical underlying callable-set origin:
- the duplicate import is tolerated,
- but it remains redundant.
### 4.2 Different origin
If the same visible callable name is imported from different canonical origins:
- the program is rejected immediately,
- and one of the imports must be removed or aliased.
The implementation must not:
- merge the callable sets,
- defer the conflict to overload resolution,
- or allow callsite context to decide which imported origin wins.
## 5. Local Versus Imported Callable Names
If a module-local function name and an imported function name are the same visible callable name:
- the program is rejected immediately,
- and the implementation must not merge the local and imported callable sets.
This preserves deterministic visibility and keeps callable origin traceable.
## 6. Barrel Boundary
`mod.barrel` defines the exact boundary of the callable set that may cross module boundaries.
Rules:
- only overloads exported through `mod.barrel` are part of the importable callable set,
- overloads with the same source-level function name but not exported through `mod.barrel` are invisible to importing modules,
- and imported callable-set visibility is therefore a direct consequence of the source module's barrel contract.
## 7. Overload Resolution Boundary
This decision deliberately separates:
- callable-set formation,
- and overload resolution at a callsite.
The implementation must first form one unambiguous visible callable set.
Only then may ordinary overload resolution operate on the candidate signatures of that set.
Callsite context must not be used to resolve ambiguity between different imported callable origins.
## 8. Invariants
- Imported callable visibility is bounded by barrel export.
- Different callable origins must not merge automatically.
- Same-origin duplicate imports may be tolerated as redundancy, not as new callable contributions.
- Local and imported function names do not coexist under one merged visible callable name in this closure pass.
- Overload resolution happens after visible callable-set formation, not instead of it.
## 9. Explicit Non-Decisions
This decision record does not yet close:
- per-overload import syntax,
- aliasing policy for callable imports beyond the already-closed generic alias rules,
- and any lowering consequences in `13. Lowering IRBackend Specification.md`.
## 10. Spec Impact
This decision should feed at least:
- `docs/general/specs/14. Name Resolution and Module Linking Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `docs/general/specs/13. Conformance Test Specification.md`
It should also constrain future work in:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## 11. Validation Notes
The intended baseline is:
- callable imports operate on exported callable names,
- all exported overloads of that name come together from one module,
- same-origin duplicate imports are tolerated,
- different-origin same-name imports are rejected immediately,
- and local/import callable collisions are also rejected immediately.
Illustrative examples:
```pbs
import { f } from @a:m;
import { f } from @a:m;
```
This is tolerated as redundant same-origin duplication.
```pbs
import { f } from @a:m;
import { f } from @b:n;
```
This is rejected immediately because the visible callable names match but the canonical origins differ.
```pbs
fn f(a: int) -> int { ... }
import { f } from @a:m;
```
This is rejected as a local-versus-import callable collision.
@@ -0,0 +1,200 @@
# Name Resolution - Linking Phase Boundary Decision
Status: Accepted (Implemented)
Cycle: Initial name-resolution closure pass
## 1. Context
PBS v1 needs an explicit phase boundary around source-level name resolution so that:
- frontend implementation does not invent phase ownership,
- diagnostics can attribute failures consistently,
- conformance can test rejection classes coherently,
- and later lowering work does not have to guess whether a failure belongs to syntax, linking, or typing.
Earlier closure already established rules for:
- module scope construction,
- import naming and aliasing,
- builtin shell visibility,
- callable-set visibility across modules.
The remaining open question was how to classify the failure classes that arise while assembling visible declarations across files and modules.
## 2. Decision
PBS v1 adopts the following normative phase baseline for name resolution and related frontend failures:
1. `syntax` is a distinct normative phase.
2. `manifest/import resolution` is a distinct normative phase.
3. `linking` is a distinct normative phase.
4. `static semantics` is a distinct normative phase.
5. `syntax` owns malformed import grammar and other token-shape or grammar-shape failures.
6. `manifest/import resolution` owns failures to resolve project space, reserved stdlib space, dependency graph, module path, or environment source.
7. `linking` owns assembly of visible declarations across files and modules.
8. `linking` therefore owns:
- import of non-exported names,
- unresolved barrel entries against module declarations,
- collisions between visible imported names from different canonical origins,
- local-versus-import visibility collisions,
- callable-origin conflicts across module boundaries,
- and duplicate canonical builtin or host identities in one resolved environment.
9. `static semantics` owns declaration validity, type checking, member lookup once the receiver type is known, and overload resolution within an already-formed visible callable set.
10. Member lookup failure on an already-typed builtin receiver belongs to `static semantics`.
11. Ambiguity between different imported origins must be rejected in `linking` before any callsite analysis.
## 3. Phase Roles
### 3.1 Syntax
`syntax` owns failures that arise before module or declaration assembly.
Examples:
- malformed import declaration shape,
- malformed alias syntax,
- malformed declaration grammar,
- unexpected tokens.
### 3.2 Manifest and Import Resolution
`manifest/import resolution` owns failures of locating and loading the source of a module or reserved environment.
Examples:
- unresolved `@project:*` dependency target,
- unresolved reserved stdlib module,
- invalid project-space selection,
- failure to load the module source from the selected environment.
### 3.3 Linking
`linking` owns the assembly of the visible declaration space after modules have been found and loaded.
Examples:
- imported name is not exported by the target module,
- `mod.barrel` entry does not resolve against declarations of the module,
- two imports expose the same visible name from different canonical origins,
- a local visible declaration collides with an imported visible declaration,
- callable-origin conflicts across module boundaries,
- duplicate canonical builtin identities in one resolved environment,
- duplicate canonical host identities in one resolved environment.
### 3.4 Static Semantics
`static semantics` owns validation and typing of the already-linked visible program.
Examples:
- duplicate local declarations,
- invalid declaration validity conditions,
- type mismatch,
- member lookup on a known receiver type,
- overload resolution inside one already-visible callable set.
## 4. Linking As A Real Normative Phase
PBS keeps `linking` as a distinct normative phase rather than collapsing it fully into `static semantics`.
Reasoning:
- some failures arise only when assembling visible declarations across files and modules,
- those failures are neither pure grammar failures nor ordinary local typing failures,
- and naming `linking` gives diagnostics and conformance a stable vocabulary for them.
This does not require every implementation to expose one identical internal compiler pass graph.
It only requires the externally visible failure ownership to map back to this normative phase model.
## 5. Barrel Matching And Visible Assembly
`mod.barrel` matching belongs to `linking`.
This means:
- failure of a barrel item to resolve to a declaration of the module is not merely a syntax issue,
- and it is not deferred until later typing or lowering.
Barrel matching is part of assembling the module's visible declaration contract.
## 6. Imported-Origin Conflicts
Conflicts between different imported origins are rejected in `linking` immediately.
This means:
- the implementation must not wait for a specific callsite or use-site,
- overload resolution is not allowed to rescue ambiguity between different imported origins,
- and visible declaration conflicts are resolved structurally before later typing work proceeds.
## 7. Builtin Receiver Lookup
Member lookup on a builtin receiver whose type is already known remains `static semantics`.
The reason is:
- by that point the relevant shell visibility work has already completed,
- and the remaining question is ordinary typed member validity rather than module assembly.
## 8. Invariants
- The phase model exposed to users and conformance must remain deterministic.
- `linking` remains the phase for visible declaration assembly across module boundaries.
- Callsite analysis must not be used to resolve imported-origin conflicts.
- `static semantics` operates on an already-linked visible declaration space.
- Syntax and manifest/import resolution remain narrower than linking and do not absorb visible-name conflicts that arise only after module loading.
## 9. Explicit Non-Decisions
This decision record does not yet close:
- the full diagnostics-code taxonomy,
- whether implementations expose one explicit user-facing `linking` label or a mapped equivalent wording class,
- the final artifact-facing phase vocabulary after lowering and verification specs close,
- and the exact implementation architecture of one compiler pipeline.
## 10. Spec Impact
This decision should feed at least:
- `docs/general/specs/14. Name Resolution and Module Linking Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `docs/general/specs/13. Conformance Test Specification.md`
It should also constrain future work in:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/pbs/decisions/Name Resolution - Scope, Lookup, and Imports Decision.md`
- `docs/pbs/decisions/Name Resolution - Builtin Shells and Host Owners Decision.md`
- `docs/pbs/decisions/Name Resolution - Callable Sets and Cross-Module Linking Decision.md`
## 11. Validation Notes
The intended phase split is:
- `syntax` parses declaration and import shape,
- `manifest/import resolution` finds and loads modules,
- `linking` assembles visible names across modules and barrels,
- `static semantics` validates and types the already-linked visible program.
Illustrative examples:
```pbs
import { Missing } from @a:m;
```
If `@a:m` resolves successfully but does not export `Missing`, this is a `linking` failure.
```pbs
import { f } from @a:m;
import { f } from @b:n;
```
If the canonical origins differ, this is a `linking` failure and is rejected before any callsite analysis.
```pbs
import { Vec2 } from @core:math;
value.zero()
```
If `value` is already known to have builtin type `Vec2` and `.zero` is not a valid member on that receiver type, the failure is `static semantics`.
@@ -0,0 +1,270 @@
# Name Resolution - Scope, Lookup, and Imports Decision
Status: Accepted (Implemented)
Cycle: Initial name-resolution closure pass
## 1. Context
PBS v1 needs a deterministic frontend-visible rule for:
- how module scope is formed,
- how lookup works by namespace,
- what imports actually introduce into local scope,
- how collisions between local and imported names are handled,
- and which failures belong to syntax, manifest/import resolution, static semantics, or linking.
Existing specs already fix important inputs:
- `mod.barrel` is the single source of module visibility,
- imports target modules, not files,
- only `pub` names may be imported from another module,
- PBS has distinct type, value, callable, and host-owner namespaces,
- builtin simple types `int`, `float`, `bool`, and `str` are always available in type position,
- and reserved stdlib project spaces resolve only from the selected stdlib environment.
The remaining goal of this decision is to close the minimum name-resolution baseline needed for normative frontend work around ordinary scope construction, ordinary lookup, and import naming.
## 2. Decision
PBS v1 adopts the following baseline for scope construction, lookup, and imports:
1. Top-level declarations of a module are collected across all `.pbs` files in the module before visibility filtering is applied.
2. `mod.barrel` is a visibility filter over existing module declarations, not the source of declaration existence.
3. Module-internal top-level availability does not depend on source-file order.
4. Local block scopes nest normally over module scope.
5. In value position, lookup prefers the nearest lexical value binding before any module-level or imported value.
6. Parameters and local `let` bindings participate in the same nearest lexical value-scope layer for lookup purposes.
7. In type position, visible module-local type declarations are considered before imported type declarations, and builtin simple types remain always-available reserved type names outside ordinary import competition.
8. In callable position, visible module-local callable declarations are considered before imported callable declarations.
9. In host-owner position, visible module-local host owners are considered before imported host owners.
10. The local visible name introduced by an import is always the post-alias name when an alias is present.
11. `import { X } from @project:path;` introduces the imported exported name `X` into the matching namespace.
12. `import { X as Y } from @project:path;` introduces only the local visible name `Y` into the matching namespace.
13. Alias spelling changes only the local visible name, never canonical builtin identity or canonical host identity.
14. `import { * } from @project:path;` is the whole-module import form for bringing the target module's exported names into local visibility under their exported names.
15. A collision between a module-local declaration and an imported visible name in the same namespace is a deterministic error rather than silent shadowing.
16. A collision between two imported visible names in the same namespace is not an error only when both imports denote the same canonical underlying declaration after module resolution.
17. If two imported visible names in the same namespace come from different canonical underlying declarations, the program is rejected and one of the imports must be aliased or removed.
18. `import { * } from @project:path;` does not create a first-class module object, module namespace value, or other source-visible binding by itself; it only introduces the exported names of the target module.
19. A module-local function and an imported function with the same visible name produce a deterministic error in this closure pass.
20. Non-callable namespaces do not merge by name.
## 3. Scope Construction
### 3.1 Module collection
For one module:
- the compiler collects top-level declarations from all `.pbs` files in that module,
- forms one module-level declaration space,
- then applies `mod.barrel` to determine `mod` and `pub` visibility.
This means:
- declaration existence is not derived from barrel entries,
- and module-internal declaration availability is not ordered by file traversal.
### 3.2 Lexical scope
Inside executable bodies:
- lexical block scope is nested normally,
- nearest local bindings win within value lookup,
- and lexical nesting remains independent from cross-module visibility.
## 4. Lookup By Namespace
### 4.1 Value position
Value-position lookup follows this order:
1. nearest local lexical bindings,
2. parameters in the current lexical function scope,
3. visible module-local values,
4. visible imported values.
For lookup purposes, parameters and local `let` bindings are one nearest lexical value layer.
The distinction between them may still matter for diagnostics wording.
### 4.2 Type position
Type-position lookup follows this order:
1. visible module-local type declarations,
2. visible imported type declarations,
3. builtin simple types `int`, `float`, `bool`, and `str` as always-available reserved type names.
Builtin simple types are not treated as ordinary imported declarations and do not participate in ordinary import competition.
### 4.3 Callable position
Callable-position lookup follows this order:
1. visible module-local callables,
2. visible imported callables.
If a visible module-local function name and a visible imported function name are the same, the program is rejected in this closure pass rather than merged.
### 4.4 Host-owner position
Host-owner lookup follows this order:
1. visible module-local host owners,
2. visible imported host owners.
Host-owner lookup remains separate from type, value, and callable lookup.
## 5. Import Surface
### 5.1 Named import
`import { X } from @project:path;`:
- resolves the target module,
- checks that `X` is exported and importable from that module,
- and introduces `X` into the corresponding namespace locally.
### 5.2 Aliased import
`import { X as Y } from @project:path;`:
- resolves the same exported declaration as the non-aliased form,
- but introduces only `Y` as the local visible name.
Alias spelling does not change canonical identity governed elsewhere.
### 5.3 Whole-module import
`import { * } from @project:path;`:
- validates and resolves the target module,
- introduces the target module's exported visible names under their exported spellings,
- but does not create a module-valued binding,
- does not create a namespace object,
- and does not authorize qualified member access by itself.
If PBS later wants module-object or namespace-qualified source semantics, that must be added explicitly rather than inferred from this form.
## 6. Collision Policy
### 6.1 Local versus imported
If a module-local declaration and an imported declaration produce the same visible name in the same namespace:
- the program is rejected,
- and the implementation must not silently shadow the imported declaration or the local declaration.
This includes function names.
In this closure pass, a local function and an imported function with the same visible name are rejected rather than merged.
### 6.2 Imported versus imported
If two imports produce the same visible name in the same namespace:
- the program is not rejected if both imports resolve to the same canonical underlying declaration after module resolution,
- but the duplicate import is still redundant,
- and the program is rejected if the imports resolve to different canonical underlying declarations.
### 6.3 Namespace separation
Names in different namespaces do not collide merely by spelling.
For example:
- a host owner and a type declaration do not collide by spelling alone,
- because host-owner namespace remains distinct from type namespace.
## 7. Relationship To Later Name-Resolution Decisions
This decision is intentionally limited to:
- ordinary scope construction,
- ordinary namespace lookup,
- import naming,
- and ordinary collision policy.
Later name-resolution decisions close:
- reserved builtin shells and host owners,
- callable-set visibility across modules,
- and the final phase boundary between syntax, manifest/import resolution, linking, and static semantics.
## 8. Invariants
- Name lookup must be deterministic.
- Module-internal top-level declaration availability must not depend on file order.
- `mod.barrel` remains a visibility mechanism rather than a declaration source.
- Imports must not invent first-class module-object semantics accidentally.
- The effective visible name of an import is always the post-alias name when an alias is present.
- Builtin simple types remain a reserved always-available core type set, distinct from ordinary imported declarations.
- Implementations must not assume silent local-over-import shadowing.
- Implementations must not merge local and imported function names automatically.
## 9. Explicit Non-Decisions
This decision record does not yet close:
- reserved-shell-specific lookup and collision details,
- callable-set import behavior across module boundaries beyond the local-versus-import collision baseline,
- and backend-facing lowering consequences of the resolved lookup model.
## 10. Spec Impact
This decision should feed at least:
- `docs/general/specs/14. Name Resolution and Module Linking Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `docs/general/specs/13. Conformance Test Specification.md`
It should also constrain future work in:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/pbs/decisions/Name Resolution - Builtin Shells and Host Owners Decision.md`
- `docs/pbs/decisions/Name Resolution - Callable Sets and Cross-Module Linking Decision.md`
- `docs/pbs/decisions/Name Resolution - Linking Phase Boundary Decision.md`
## 11. Validation Notes
The intended baseline is:
- all top-level declarations in a module exist before barrel filtering,
- lookup is namespace-specific and deterministic,
- the effective visible import name is the alias name when an alias is present,
- whole-module import through `import { * } from @project:path;` introduces exported names rather than a module object,
- local/import collisions are rejected rather than shadowed,
- and builtin simple types remain reserved always-available names outside ordinary import competition.
Illustrative examples:
```pbs
import { Foo } from @a:m;
declare const Foo: int = 1;
```
This is rejected as a local-versus-import collision in the value namespace.
```pbs
import { f } from @a:m;
import { f } from @b:n;
```
This is rejected because the visible imported names match but the canonical origins differ.
```pbs
fn f(a: int) -> int { ... }
import { f } from @a:m;
```
This is rejected as a local-versus-import collision in callable position.
```pbs
import { * } from @a:m;
```
This introduces the exported visible names of `@a:m`, but does not introduce a source-visible module object in v1.
```pbs
import { A as aaa } from @a:m;
```
The visible local declaration name is `aaa`, not `A`.
+44
View File
@@ -0,0 +1,44 @@
# PBS Decisions
This directory contains PBS decision records.
## Purpose
A decision record is the bridge between agenda discussion and normative spec text.
Use this directory to capture:
- what was decided,
- why that direction was chosen,
- which constraints now apply,
- what remains intentionally out of scope,
- which specs must be updated.
Architecture and decisions must be resolved before implementation.
## Expected Format
A decision record should usually include:
1. Title
2. Status
3. Date or Cycle
4. Context
5. Decision
6. Invariants
7. Explicit Non-Decisions
8. Spec Impact
9. Validation Notes or Examples
## Writing Rules
- Write in stable, reviewable language.
- State the adopted decision first and clearly.
- Capture architectural constraints and invariants explicitly.
- Record what is still not decided so later implementation does not guess.
- Point to the exact specs that need integration.
## Implementation Rule
If implementation work exposes a missing decision, do not infer it.
Stop, surface the ambiguity, and return it to agenda or decision review.
@@ -0,0 +1,41 @@
# SPAWN-YIELD v1 Claim Rescope Decision
Status: Accepted
Cycle: Agenda 18 / PR-06.6
## Context
Os requisitos `G20-9.4.2` e `G20-9.4.3` estavam em estado `deferred` porque `SPAWN` e `YIELD` ainda nao fazem parte da superficie executavel v1 atualmente claimada pelo backend.
Sem uma decisao formal, o claim ficava ambiguo para auditoria externa.
## Decision
Adotamos oficialmente a **Trilha B**.
1. `SPAWN` e `YIELD` ficam fora do escopo do claim executavel `core-v1`.
2. O backend v1 deve tratar essas formas como nao-suportadas no escopo claimado.
3. Invariantes especificas de aridade/stack para `SPAWN` e `YIELD` ficam reservadas para um perfil futuro que as admita explicitamente.
## Invariants
1. Nenhum claim `core-v1` pode implicar suporte executavel a `SPAWN`/`YIELD`.
2. Se um perfil futuro admitir `SPAWN`/`YIELD`, deve publicar evidencias de conformidade dedicadas antes de claim de suporte.
3. Matriz de conformidade deve explicitar o rescope para evitar regressao silenciosa de claim.
## Spec Impact
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`:
- secao 9.4 passa a declarar `SPAWN`/`YIELD` fora do escopo de `core-v1`.
2. `docs/general/specs/17. Compatibility and Evolution Policy.md`:
- claims suportados devem explicitar superficies executaveis excluidas.
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`:
- linhas `G20-9.4.2` e `G20-9.4.3` saem de `deferred` para status alinhado ao rescope.
## Validation Notes
Validacao desta decisao e documental/policy:
1. testes de integridade de spec/matriz para `SPAWN`/`YIELD` claim rescope;
2. verificacao explicita de status e notas na matriz;
3. rastreabilidade via esta decision record.
@@ -0,0 +1,190 @@
# Value Representation and Identity Decision
Status: Accepted (Implemented)
Cycle: Initial value-representation closure pass
## 1. Context
PBS v1 needs a stable user-visible model for:
- which values are pure copied payloads,
- which values preserve shared runtime identity,
- which carriers merely wrap other values,
- and how callback values fit into the language without exposing general first-class functions or closures.
Earlier decisions already fixed important inputs:
- structs are reference-like in ordinary use,
- services are canonical singleton values,
- `bind(context, fn_name)` captures the same struct identity without copying it,
- `optional` and `result` remain explicit carriers rather than implicit effect-lifting mechanisms.
## 2. Decision
PBS v1 adopts the following value-representation baseline:
1. Pure scalar-like values are copied by value and do not carry user-visible identity.
2. Struct values are identity-bearing, heap-backed reference values.
3. Service values are identity-bearing canonical singleton values.
4. Host-backed resource values are identity-bearing values on the PBS side, even though their backing authority remains host-owned.
5. Tuple, `optional`, and `result` carriers do not introduce identity of their own.
6. Contract values do not introduce a new user-visible identity distinct from the underlying struct or service value.
7. Callback values are first-class callable values in PBS v1, but callback identity is not promoted as a user-visible identity concept.
8. Assignment, parameter passing, and return preserve aliasing for identity-bearing values and copy payload for pure value kinds.
## 3. Value Categories
### 3.1 Pure copied values
The following value kinds are pure copied values in the user model:
- `int`
- `float`
- `bool`
- enum values
- canonical `str`
Assignment, parameter passing, and return of these values copy the value itself.
### 3.2 Identity-bearing values
The following value kinds carry stable user-visible identity:
- struct values
- service values
- host-backed resource/handle values
Assignment, parameter passing, and return of these values preserve aliasing to the same runtime entity rather than copying an independent underlying object.
### 3.3 Carrier-only values
The following value kinds are carriers and do not create identity of their own:
- tuples
- `optional`
- `result`
They preserve the semantics of the values they contain.
If a carrier contains an identity-bearing payload, the carrier transports that same payload identity rather than inventing a new one.
## 4. Structs
Struct values are always reference-like in PBS v1.
Rules:
- `new Struct(...)` produces a fresh struct identity.
- Assignment of a struct value copies the reference, not the underlying field storage.
- Passing or returning a struct value preserves aliasing to the same struct instance.
- Mutation through one alias is observable through other aliases to that same struct instance.
## 5. Services
Service values are canonical module-owned singleton values.
Rules:
- A service value denotes the same singleton identity wherever it is used in the same resolved program.
- Assignment, parameter passing, and return preserve that same singleton identity.
- Service use does not create fresh service instances.
## 6. Contract Values
Contract values do not introduce a new user-visible entity.
A contract value is a runtime view over:
- an underlying struct identity or service singleton identity,
- together with the selected contract implementation used for dispatch.
For user-facing semantics:
- aliasing is defined by the underlying struct or service value,
- not by treating the contract wrapper as a separate identity-bearing object.
## 7. Callback Values
Callback values are first-class callable values in PBS v1.
This means they may be:
- assigned to variables,
- passed as arguments,
- and returned from functions.
However, PBS v1 does not promote callback identity as an explicit user-visible identity concept.
### 7.1 Plain callback values
When a callback value is formed from a compatible top-level `fn`, it denotes a callable value over that target function.
### 7.2 Bound callback values
When a callback value is formed through `bind(context, fn_name)`:
- the same struct context identity is captured,
- the context is not copied,
- the callback retains the target function together with that captured context,
- and invoking the callback behaves as if the target function is called with the captured context as its first argument.
### 7.3 User model
The language must explain callback behavior without requiring the user to reason about callback identity as if callbacks were ordinary heap objects.
It is sufficient to state that:
- callbacks are first-class callable values,
- bound callbacks retain their captured context,
- and copies of a callback value preserve the same callable meaning and retained context.
## 8. Copy Versus Aliasing Rule
The general rule for PBS v1 is:
- pure value kinds are copied by value,
- identity-bearing kinds preserve aliasing,
- carrier kinds preserve the semantics of their contained values and do not create identity of their own.
Examples:
- assigning an `int` copies the integer value,
- assigning a `Struct` value copies the reference to the same struct instance,
- assigning an `optional<Player>` that contains `some(player)` preserves the same `Player` identity inside the carrier,
- assigning a `result<E> Player` success payload preserves the same `Player` identity inside the carrier.
## 9. Beginner-Facing Model
The user-facing explanation should be:
- some values are plain data, so passing them passes the value,
- structs and services are shared entities, so passing them passes access to the same entity,
- tuples, `optional`, and `result` only package values and do not become new entities by themselves,
- callbacks are callable values, and bound callbacks keep the same captured context rather than copying it.
This wording is simple enough for beginners while still preserving the performance-relevant truth about aliasing and mutation.
## 10. Explicit Non-Decisions
This decision record does not yet close:
- the exact runtime layout of any heap object,
- collection value categories in detail,
- the final host-backed handle representation syntax,
- the final diagnostics wording for aliasing/copy visibility.
## 11. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/pbs/specs/4. Static Semantics Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
## 12. Validation Notes
The intended split is:
- structs, services, and host-backed resources behave like identity-bearing entities,
- tuples, `optional`, and `result` are carriers,
- callbacks are first-class callable values without promoted callback identity in the user model.
+197
View File
@@ -0,0 +1,197 @@
# PBS Frontend PR Sequence
Este indice organiza uma sequencia de PRs atomicas para levar `frontends/pbs` ao contrato das specs.
1. `PR-001-pbs-lexer-core-syntax-alignment.md`
2. `PR-002-pbs-ast-contract-v1.md`
3. `PR-003-pbs-parser-declarations-and-types.md`
4. `PR-004-pbs-parser-statements-and-control-flow.md`
5. `PR-005-pbs-parser-expressions-optional-result-apply.md`
6. `PR-006-pbs-barrel-and-module-visibility.md`
7. `PR-006.2-pbs-parser-ast-syntax-hardening.md`
8. `PR-006.3-pbs-syntax-completeness-and-module-hygiene.md`
9. `PR-007-pbs-static-semantics-declaration-validation.md`
10. `PR-008-pbs-static-semantics-call-resolution-and-flow.md`
11. `PR-009-pbs-diagnostics-contract-v1.md`
12. `PR-010-pbs-irbackend-lowering-contract.md`
13. `PR-011-pbs-gate-u-conformance-fixtures.md`
Cada documento e auto contido e inclui: `Briefing`, `Target`, `Method`, `Acceptance Criteria` e `Tests`.
## Non-Conformance Remediation PRs
14. `PR-012-pbs-byte-offset-spans.md`
15. `PR-013-pbs-import-unresolved-diagnostics.md`
16. `PR-014-pbs-switch-wildcard-rules.md`
17. `PR-015-pbs-this-self-context-validation.md`
18. `PR-016-pbs-assignment-target-and-field-access-semantics.md`
19. `PR-017-pbs-const-evaluation-and-dependency-rules.md`
20. `PR-018-pbs-result-flow-ok-err-handle-rules.md`
21. `PR-019-pbs-non-unit-fallthrough-diagnostics.md`
22. `PR-020-pbs-lowering-admission-gates.md`
23. `PR-021-pbs-handle-aware-fallthrough-completion.md`
24. `PR-022-pbs-source-kind-and-module-origin-pipeline.md`
25. `PR-023-pbs-stdlib-environment-resolver-and-loader.md`
26. `PR-024-pbs-parser-ast-interface-module-mode.md`
27. `PR-025-pbs-interface-module-semantics-and-linking.md`
28. `PR-026-pbs-sdk-minimal-core-color-and-gfx.md`
29. `PR-027-pbs-builtin-metadata-extraction-and-ir-lowering-admission.md`
30. `PR-028-pbs-gate-u-sdk-interface-module-fixtures.md`
31. `PR-029-pbs-builtin-slot-inference-and-layout-semantics.md`
32. `PR-030-pbs-host-admission-capability-gating.md`
33. `PR-031-pbs-dependency-scoped-fail-fast-admission.md`
## Backend VM Pipeline PR Sequence (Agenda 18)
Esta sequencia organiza implementacao atomica para `IRBackend -> IRVM -> OptimizeIRVM -> EmitBytecode`, com trilha de montagem do output para o input (bytecode ate IRBackend).
34. `PR-032-backend-bytecode-module-serializer-baseline.md`
35. `PR-033-backend-bytecode-function-layout-and-debug-minimum.md`
36. `PR-034-backend-emitter-hostcall-sysc-contract.md`
37. `PR-035-backend-emit-stage-pipeline-wiring.md`
38. `PR-036-backend-irvm-core-model-and-validator.md`
39. `PR-037-backend-optimize-irvm-noop-stage-and-guards.md`
40. `PR-038-irbackend-v2-executable-contract-model.md`
41. `PR-039-pbs-frontend-irbackend-v2-lowering.md`
42. `PR-040-backend-lower-to-irvm-stage-implementation.md`
43. `PR-041-backend-gate-i-runtime-compat-integration-fixtures.md`
## JVM-Grade Remediation Waves (Execution Plan)
Esta trilha organiza as PRs por ondas para execucao incremental com rollback simples por item.
### Onda O1 - Conformance and Correctness Hardening
1. `PR-O1.1-backend-diagnostics-taxonomy-and-attribution.md`
2. `PR-O1.2-irbackend-executable-contract-hardening.md`
3. `PR-O1.3-pbs-executable-lowering-fidelity.md`
4. `PR-O1.4-lower-to-irvm-callsite-prechecks.md`
5. `PR-O1.5-bytecode-debug-minimum-completeness.md`
6. `PR-O1.6-gate-su-safety-matrix-completion.md`
### Onda O2 - JVM-Inspired Verification and Linking Boundaries
1. `PR-O2.1-bytecode-link-precheck-stage.md`
2. `PR-O2.2-bytecode-preload-verifier.md`
3. `PR-O2.3-optimize-irvm-pass-manager-and-equivalence.md`
4. `PR-O2.4-gate-i-runtime-backed-compat-harness.md`
### Onda O3 - Evolution and Scale
1. `PR-O3.1-irvm-control-flow-lowering-label-resolution.md`
2. `PR-O3.2-bytecode-constpool-symbol-interning-determinism.md`
3. `PR-O3.3-irvm-profile-evolution-and-feature-gates.md`
### Onda O4 - JVM-Grade Uplift
1. `PR-O4.1-callable-signature-identity-and-dense-symbol-table.md`
2. `PR-O4.2-global-intrinsic-table-and-reindexing.md`
3. `PR-O4.3-semantic-lowering-cfg-and-stack-analysis.md`
4. `PR-O4.4-irvm-program-single-source-of-truth.md`
5. `PR-O4.5-vm-profile-end-to-end-pipeline.md`
6. `PR-O4.6-strict-bytecode-precheck-unknown-opcode-rejection.md`
7. `PR-O4.7-gate-i-runtime-backed-execution-adapter.md`
8. `PR-O4.8-jvm-grade-regression-matrix-and-golden-artifacts.md`
### Onda O5.0 - Dense Table Identity Foundation (Pre-O5)
1. `PR-05.0.1-frontend-phase-shared-name-table-context.md`
2. `PR-05.0.2-module-identity-dense-table-and-moduleid-wiring.md`
3. `PR-05.0.3-irbackend-typed-callable-and-intrinsic-ids.md`
4. `PR-05.0.4-callable-shape-and-signature-interning.md`
5. `PR-05.0.5-synthetic-stdlib-fileid-via-filetable.md`
6. `PR-05.0.6-host-binding-key-interning-and-capability-identity.md`
### Onda O5 - JVM-Grade Score Evolution (5.6 -> 8.5+)
Prerequisito de execucao: concluir a Onda O5.0.
1. `PR-05.1-pbs-frontend-semantic-executable-lowering-cfg.md`
2. `PR-05.2-irbackend-callsite-classification-by-semantic-identity.md`
3. `PR-05.3-irvm-deterministic-function-id-and-entrypoint-policy.md`
4. `PR-05.4-irvm-program-coherence-without-bypass.md`
5. `PR-05.5-irvm-validator-real-stack-effects-hostcall-intrinsic.md`
6. `PR-05.6-optimize-irvm-real-deterministic-passes.md`
7. `PR-05.7-gate-i-runtime-backed-mandatory-in-ci.md`
8. `PR-05.8-backend-spec-to-test-conformance-matrix.md`
### Onda O6 - JVM-Grade Score Evolution (8.0 -> 9.0+)
Foco: fechar `partial/deferred` relevantes da matriz normativa e endurecer evidencia de conformidade.
1. `PR-06.1-source-attribution-and-diagnostics-evidence-hardening.md`
2. `PR-06.2-optimize-irvm-semantic-equivalence-harness.md`
3. `PR-06.3-irvm-ext-contract-and-elimination-fixtures.md`
4. `PR-06.4-gate-i-runtime-line-repeatability-ci.md`
5. `PR-06.5-conformance-matrix-hard-gate-policy.md`
6. `PR-06.6-spawn-yield-v1-or-claim-rescope.md`
### Onda O7 - Partial Closure Before IDE Focus
Foco: eliminar os dois `partial` remanescentes na matriz backend antes de mover foco principal para IDE.
1. `PR-07.1-optimize-irvm-span-source-hook-preservation.md`
2. `PR-07.2-pbs-callsite-category-no-textual-heuristics-regression.md`
3. `PR-07.3-irvm-entrypoint-export-emission-for-runtime-loader.md`
### Onda O8 - Canonical Identity and Dense Addressing Hardening
Foco: fechar lacunas estruturais em identidade canonica de intrinsic/modulo/entrypoint e remover riscos de ambiguidade no handoff FE->BE.
1. `PR-08.1-intrinsic-resolution-canonical-identity-keying.md`
2. `PR-08.2-irbackend-moduleid-contract-and-modulepool.md`
3. `PR-08.3-qualified-entrypoint-identity-contract.md`
4. `PR-08.4-call-func-callee-module-identity-correctness.md`
5. `PR-08.5-intrinsic-registry-single-source-sync-with-runtime.md`
### Onda O9 - ModuleId-Only Contract Cutover
Foco: remover definitivamente `moduleKey` textual do contrato estrutural FE->BE, endurecer entrypoint qualificado e alinhar specs/matriz com o modelo `ModuleId`-only.
1. `PR-09.1-irbackend-modulekey-hard-removal-from-contract.md`
2. `PR-09.2-pbs-frontend-moduleid-only-lowering-and-import-surfaces.md`
3. `PR-09.3-lower-to-irvm-moduleid-only-ordering-and-strict-qualified-entrypoint.md`
4. `PR-09.4-specs-refresh-moduleid-only-entrypointref-and-bytecode-alignment.md`
5. `PR-09.5-hard-gates-no-modulekey-regression-and-migration-cleanup.md`
6. `PR-09.6-isa-intrinsic-registry-single-source-artifact.md`
7. `PR-09.7-compiler-normalization-to-isa-registry-artifact.md`
### Onda O10 - Parser Maintainability Refactor (No Functional Change)
Foco: reduzir complexidade estrutural de `PbsParser` sem alterar gramatica, AST, spans ou contrato de diagnosticos observavel.
1. `PR-10.1-pbs-parser-shared-context-and-safe-delegation.md`
2. `PR-10.2-pbs-parser-attribute-and-type-subparsers.md`
3. `PR-10.3-pbs-parser-top-level-declaration-decomposition.md`
4. `PR-10.4-pbs-parser-block-and-statement-decomposition.md`
5. `PR-10.5-pbs-parser-recovery-utilities-and-regression-hardening.md`
### Onda O11 - Expression Parser Maintainability Refactor (No Functional Change)
Foco: reduzir complexidade estrutural de `PbsExprParser` sem alterar precedence, AST, spans, recovery ou diagnosticos observaveis.
1. `PR-11.1-pbs-expr-parser-shared-context-and-precedence-spine.md`
2. `PR-11.2-pbs-expr-parser-control-flow-subparsers.md`
3. `PR-11.3-pbs-expr-parser-postfix-primary-and-construction-decomposition.md`
4. `PR-11.4-pbs-expr-parser-literals-patterns-and-shared-token-utilities.md`
5. `PR-11.5-pbs-expr-parser-regression-hardening-and-final-cleanup.md`
### Onda O12 - Flow Expression Analyzer Maintainability Refactor (No Functional Change)
Foco: reduzir complexidade estrutural de `PbsFlowExpressionAnalyzer` sem alterar inferencia, diagnosticos, matching de tipos ou comportamento observavel da analise semantica.
1. `PR-12.1-flow-expression-analyzer-context-and-dispatch-foundation.md`
2. `PR-12.2-flow-expression-analyzer-literal-and-structural-expression-splitting.md`
3. `PR-12.3-flow-expression-analyzer-call-and-member-resolution-decomposition.md`
4. `PR-12.4-flow-expression-analyzer-switch-and-handle-decomposition.md`
5. `PR-12.5-flow-expression-analyzer-regression-hardening-and-final-cleanup.md`
### Onda O13 - Flow Body Analyzer Maintainability Refactor (No Functional Change)
Foco: reduzir complexidade estrutural de `PbsFlowBodyAnalyzer` sem alterar regras de flow, completion, assignment checking ou diagnosticos observaveis.
1. `PR-13.1-flow-body-analyzer-context-and-entrypoint-foundation.md`
2. `PR-13.2-flow-body-analyzer-callable-body-and-completion-decomposition.md`
3. `PR-13.3-flow-body-analyzer-statement-analysis-splitting.md`
4. `PR-13.4-flow-body-analyzer-assignment-target-resolution-decomposition.md`
5. `PR-13.5-flow-body-analyzer-regression-hardening-and-final-cleanup.md`
@@ -0,0 +1,63 @@
# PR-05.0.1 - Frontend Phase Shared NameTable Context
## Briefing
Hoje o frontend PBS cria `NameTable` em componentes diferentes (linking, declarative semantics, rules), o que fragmenta identidade de nome por fase.
Esta PR centraliza `NameTable` no `FrontendPhaseContext` para toda a fase de frontend, com um ciclo de vida unico por compilacao.
## Motivation
### Dor que esta PR resolve
1. Mesma string pode receber `NameId` diferente dependendo da fase.
2. Dificulta evoluir para identidades tipadas cross-phase sem adaptadores de conversao.
3. Complica debug e rastreabilidade de diagnosticos semanticos entre linking e lowering.
## Target
Uniformizar identidade de nomes no FE inteiro, com `NameId` estavel durante a fase de frontend.
## Scope
1. `FrontendPhaseContext` passa a expor `NameTable`.
2. Validators e binders do PBS passam a receber `NameTable` do contexto, sem criar tabela local.
3. Ajuste de testes que dependem de instanciacao direta.
## Non-Goals
1. Nao altera regras semanticas.
2. Nao altera parser/AST.
## Method
### O que deve ser feito explicitamente
1. Adicionar `NameTable` ao contexto da fase de frontend.
2. Remover `new NameTable()` locais em linking/semantics.
3. Injetar o `NameTable` compartilhado em:
- `PbsModuleVisibilityValidator`,
- `PbsDeclarationSemanticsValidator`,
- `PbsDeclarationRuleValidator`,
- `PbsNamespaceBinder`.
4. Garantir que o ciclo de vida da tabela seja por execucao de fase, nao global estatico.
## Acceptance Criteria
1. Nao existe mais alocacao local de `NameTable` nas fases PBS do frontend.
2. Mesmo nome gera mesmo `NameId` em linking e semantica na mesma compilacao.
3. Testes de linking/semantica continuam passando sem regressao comportamental.
## Tests
1. Teste de identidade cruzada (linking vs declaration validation) para nomes iguais.
2. Teste de isolamento entre duas compilacoes diferentes (nao vazar IDs entre runs).
## Affected Documents
1. `docs/pbs/specs/11. AST Specification.md`
2. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,59 @@
# PR-05.0.2 - Module Identity Dense Table and ModuleId Wiring
## Briefing
O FE usa `String moduleKey` em varios mapas e no handoff para backend.
Esta PR introduz identidade densa de modulo (`ModuleTable` + `ModuleId`) e faz o FE operar internamente por ID, mantendo string apenas como representacao de borda quando necessario.
## Motivation
### Dor que esta PR resolve
1. Chaves string de modulo sao repetidas e suscetiveis a inconsistencia de normalizacao.
2. Custos de hash/string crescem com o grafo de modulos.
3. Dificuldade de garantir determinismo e joins estaveis em agregacao multi-modulo.
## Target
Substituir identidade interna de modulo baseada em string por `ModuleId` internado.
## Scope
1. Criacao de `ModuleTable` no core.
2. Uso de `ModuleId` em `PBSFrontendPhaseService` para mapas de modulo/dependencias.
3. Adaptacao de pontos de diagnostico e exibição para renderizar nome canônico quando preciso.
## Non-Goals
1. Nao altera sintaxe de import.
2. Nao altera formato de mensagens ao usuario final alem do necessario.
## Method
### O que deve ser feito explicitamente
1. Implementar `ModuleTable extends InternTable<ModuleId, ModuleRef>` (ou valor equivalente canonico).
2. Trocar `Map<String,...>` de modulo em `PBSFrontendPhaseService` por `Map<ModuleId,...>`.
3. Trocar grafo de dependencia de `String` para `ModuleId`.
4. Manter funcao unica de render de modulo para diagnostico.
## Acceptance Criteria
1. Fluxo principal do FE nao depende de `moduleKey` string para joins internos.
2. Dependencias e bloqueios por falha de modulo usam `ModuleId`.
3. Nao ha regressao funcional em linking/import gating.
## Tests
1. Teste de determinismo de IDs de modulo para mesmo grafo admitido.
2. Teste de propagacao de falha por dependencia usando IDs.
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,62 @@
# PR-05.0.3 - IRBackend Typed Callable and Intrinsic IDs
## Briefing
O contrato `IRBackendExecutableFunction` ainda carrega `callableId`, `calleeCallableId` e `intrinsicId` como `int/Integer`.
Esta PR tipa esses campos com `CallableId` e `IntrinsicId`, alinhando model com Dense Tables e reduzindo erro de classe de ID.
## Motivation
### Dor que esta PR resolve
1. Mistura acidental entre dominios de ID diferentes em tempo de desenvolvimento.
2. Validacoes repetitivas de faixa/semantica por usar primitivo nu.
3. API de backend menos segura para evolucao de lowering/remap.
## Target
Evoluir o contrato de FE->BE para IDs tipados em vez de inteiros crus.
## Scope
1. `IRBackendExecutableFunction` e metadados de instrucao.
2. `IRBackendAggregator` remap de callables e intrinsecos.
3. Ajustes de serializers/tests que assumem `int`.
## Non-Goals
1. Nao muda semantica de chamada.
2. Nao muda ordenacao de remap por si so.
## Method
### O que deve ser feito explicitamente
1. Trocar:
- `int callableId` -> `CallableId`,
- `Integer calleeCallableId` -> `CallableId` (nullable quando aplicavel),
- `int intrinsicId` -> `IntrinsicId`.
2. Atualizar construtores/guards para validar `.isNone()` e nao-negatividade via tipo.
3. Atualizar `IRBackendAggregator` para trabalhar com vetores/tabelas de IDs tipados.
4. Atualizar FE lowering PBS para emitir IDs tipados desde origem.
## Acceptance Criteria
1. Nao ha mais campos de callable/intrinsic ID como inteiro cru no contrato executavel.
2. Tentativas de misturar dominio de ID falham em compile-time.
3. Testes de remap e merge seguem verdes.
## Tests
1. Testes unitarios de construcao de instrucao com tipos corretos/incorretos.
2. Testes de agregacao multi-arquivo validando remap tipado.
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,62 @@
# PR-05.0.4 - Callable Shape and Signature Interning
## Briefing
O FE ainda monta chaves semanticas por concat string (`name#arity`, `signatureSurface`, `typeShape`).
Esta PR cria internacao para superfícies de assinatura/shape e remove concatenação textual como identidade primaria.
## Motivation
### Dor que esta PR resolve
1. Chave textual e fragil para evolucao de formato.
2. Custo de alocacao/hash desnecessario em caminhos quentes.
3. Risco de colisao logica por normalizacao incompleta.
## Target
Internar shapes de callable e superfícies de assinatura em tabela dedicada, com ID estavel.
## Scope
1. Estruturas de assinatura do linking e lowering.
2. `CallableSignatureRef` com suporte a referencia internada de shape.
3. Remocao gradual de `callableArityKey` e derivados string.
## Non-Goals
1. Nao altera regra de overload.
2. Nao altera formato externo de diagnostico.
## Method
### O que deve ser feito explicitamente
1. Introduzir tabela de shapes (ex.: `CallableShapeTable` / `TypeSurfaceTable`).
2. Representar identidade de callable por tupla tipada (`NameId`, aridade, `ShapeId`).
3. Atualizar:
- linking (`FunctionSymbolKey`),
- FE lowering executavel (`callableIdsByNameAndArity`),
- referencias em `CallableSignatureRef`.
4. Manter conversao para string apenas para logs/debug.
## Acceptance Criteria
1. Fluxo principal de resolução de callable nao depende de concat string.
2. Determinismo de shape/signature comprovado por ID internado.
3. Nenhuma regressao de resolução de overload/documentada.
## Tests
1. Teste de internacao idempotente para shape identico.
2. Testes de distinção para shapes diferentes com mesmo nome/arity.
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,59 @@
# PR-05.0.5 - Synthetic Stdlib FileId via FileTable
## Briefing
`InterfaceModuleLoader` hoje aloca `FileId` sintetico por `AtomicInteger`.
Esta PR move a alocacao de arquivos sinteticos para o `FileTable`, mantendo uma unica autoridade de identidade de arquivo.
## Motivation
### Dor que esta PR resolve
1. Risco de colisao/deriva de `FileId` fora da infraestrutura oficial.
2. Arquivos sinteticos ficam fora da trilha normal de metadata de source.
3. Diagnosticos e spans de stdlib perdem consistencia de origem no pipeline.
## Target
Fazer todo `FileId` (incluindo sintetico) vir do `FileTable`.
## Scope
1. `InterfaceModuleLoader`.
2. Contexto de carga de stdlib/interface para suportar registro no `FileTable`.
3. Source handle sintetico minimo para parser/diagnostico.
## Non-Goals
1. Nao altera conteudo dos modulos stdlib.
2. Nao altera parse mode de interface.
## Method
### O que deve ser feito explicitamente
1. Criar `SourceHandle` sintetico para fontes carregadas da stdlib/interface.
2. Registrar cada handle no `FileTable` e usar `FileId` retornado.
3. Remover contador `AtomicInteger` de `InterfaceModuleLoader`.
4. Preservar caminho lógico para mensagens (ex.: origem virtual stdlib).
## Acceptance Criteria
1. `InterfaceModuleLoader` nao usa mais `new FileId(...)`.
2. Todo `FileId` de stdlib/interface existe no `FileTable`.
3. Diagnosticos em fontes sinteticas mantem atribuicao consistente.
## Tests
1. Teste de carga de interface garantindo que `FileId` sintetico foi registrado no `FileTable`.
2. Teste de span/diagnostico para arquivo sintetico.
## Affected Documents
1. `docs/pbs/specs/11. AST Specification.md`
2. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,59 @@
# PR-05.0.6 - Host Binding Key Interning and Capability Identity
## Briefing
A validacao de host admission ainda usa chave composta em string (`module|method|version`) para deduplicacao e consistencia.
Esta PR troca chave textual por identidade internada de binding host e prepara capacidade para validacoes mais seguras.
## Motivation
### Dor que esta PR resolve
1. Concatenacao textual para chave critica de ABI e fragil.
2. Risco de bug por normalizacao inconsistente de partes da chave.
3. Menor clareza para evoluir validacao de capabilities por dominio tipado.
## Target
Internar identidade canonica de host binding em tabela dedicada e usar ID no validador de host admission.
## Scope
1. `PbsHostAdmissionValidator`.
2. Infra de tabela de binding host no core/frontend.
3. Ajustes em metadados reservados quando necessario.
## Non-Goals
1. Nao altera semantica de capability policy.
2. Nao altera contrato de host ABI no runtime.
## Method
### O que deve ser feito explicitamente
1. Introduzir valor canônico `HostBindingRef(module,name,version)` e tabela internada.
2. Substituir map com chave string por map com `HostBindingId` (ou `HostBindingRef` internado).
3. Manter normalizacao de capability separada da identidade de binding.
4. Preservar diagnosticos com referencias claras ao binding original.
## Acceptance Criteria
1. `PbsHostAdmissionValidator` nao usa mais chave formatada por string para binding.
2. Inconsistencia de capability para mesmo binding continua detectada de forma deterministica.
3. Nao ha regressao em cenarios conhecidos de host admission.
## Tests
1. Teste de deduplicacao de binding por identidade internada.
2. Teste de mismatch de capability para mesmo binding.
## Affected Documents
1. `docs/pbs/specs/6.2. Host ABI Binding and Loader Resolution Specification.md`
2. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,78 @@
# PR-05.1 - PBS Frontend Semantic Executable Lowering (CFG)
## Briefing
O frontend PBS ainda gera `IRBackendExecutableFunction` por varredura de callsites no AST, o que perde semântica de execução real.
Esta PR substitui esse caminho por lowering semântico baseado em fluxo de controle (CFG), preservando ordem de execução, terminadores e formas de desvio.
## Motivation
### Dor atual que esta PR resolve
1. Execução divergente entre programa fonte e artefato gerado em cenários com `if`, `while`, `for`, `switch`, `handle` e `return` antecipado.
2. Impossibilidade de elevar o backend para JVM-grade porque o contrato executável nasce semanticamente incompleto.
3. Falsos positivos de conformidade: testes passam para casos lineares, mas o modelo quebra em fluxo real.
## Target
Esta PR altera o frontend PBS para que `IRBackendExecutableFunction.instructions` represente fluxo executável real, não apenas uma lista de chamadas encontradas.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.1` (NameTable compartilhada por fase).
2. `PR-05.0.2` (identidade de modulo por `ModuleId`).
3. `PR-05.0.3` (IDs tipados de callable/intrinseco no contrato).
4. `PR-05.0.4` (internacao de shape/signature).
## Scope
1. Gerador de IR executável no frontend PBS.
2. Emissão de labels e jumps para estruturas de controle.
3. Recalculo de `maxStackSlots` com base no fluxo emitido.
4. Testes de fidelidade semântica do FE para IR executável.
## Non-Goals
1. Não introduz otimizações.
2. Não altera formato binário PBX.
3. Não altera runtime.
## Method
### O que deve ser feito explicitamente
1. Substituir o mecanismo de `collectCallsFrom*` por lowering orientado a nós semânticos de statements/expressions.
2. Emitir instruções de controle (`LABEL`, `JMP`, `JMP_IF_TRUE`, `JMP_IF_FALSE`, `RET`) para cada forma de fluxo suportada.
3. Garantir que `return` termine bloco/caminho e que caminhos alcançáveis terminem em instrução terminadora.
4. Preservar spans de origem em cada instrução emitida para diagnóstico.
5. Manter validação fail-fast quando existir forma semântica não lowerável em v1.
6. Atualizar análise de stack para operar sobre o programa realmente emitido.
7. Emitir referências de chamada via IDs tipados (`CallableId`/`IntrinsicId`) sem chave textual ad-hoc.
## Acceptance Criteria
1. `IRBackendExecutableFunction` deixa de ser construído por varredura cega de callsites.
2. Para casos com ramificação e laço, a ordem de execução no IR executável é semanticamente equivalente ao AST validado.
3. Funções com `return` antecipado não emitem execução espúria após ponto de saída.
4. `maxStackSlots` calculado bate com programa emitido e passa em validação backend.
5. Diagnósticos de lowering preservam fase e span corretamente.
6. Não há lookup de identidade de callsite baseado em concatenação string no caminho principal.
## Tests
1. Testes positivos com fixtures de `if/else`, `while`, `for`, `switch`, `handle`, `return` antecipado.
2. Testes negativos para caminhos sem terminador, labels inválidos e formas não suportadas.
3. Teste de regressão comparando resultado anterior vs novo para provar correção em casos não lineares.
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/19. Verification and Safety Checks Specification.md`
## Open Questions
Sem bloqueios arquiteturais. Implementação deve seguir decisões já fechadas na Agenda 18.
@@ -0,0 +1,73 @@
# PR-05.2 - IRBackend Callsite Classification by Semantic Identity
## Briefing
A classificação de callsites no frontend executável ainda depende de heurística textual de callee.
Esta PR torna obrigatória a classificação por identidade semântica resolvida no binding, eliminando inferência por nome/forma textual.
## Motivation
### Dor atual que esta PR resolve
1. Risco de classificar callsite no bucket errado (`CALL_FUNC`, `CALL_HOST`, `CALL_INTRINSIC`).
2. Ambiguidade em member/bind/group callee com nome coincidente.
3. Falta de robustez em evolução de sintaxe semântica do FE.
## Target
Fronteira `PBS FE -> IRBackend` com identidade de callsite estável e sem heurística textual para decisão de categoria.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.1` (NameTable compartilhada).
2. `PR-05.0.2` (ModuleId no FE).
3. `PR-05.0.3` (CallableId/IntrinsicId tipados no contrato).
4. `PR-05.0.4` (shape/signature internadas).
## Scope
1. Resultado de resolução semântica para chamadas.
2. Estrutura de lowering para carregar identidade resolvida.
3. Diagnósticos quando identidade não estiver resolvida no ponto exigido.
## Non-Goals
1. Não muda política de overload além do já definido em semântica.
2. Não introduz novas categorias de callsite.
## Method
### O que deve ser feito explicitamente
1. Propagar do analisador semântico para lowering um descritor explícito de destino de chamada.
2. O descritor deve carregar identidade canônica tipada (ao menos categoria + id alvo), sem depender de nome textual.
3. Remover dependência de `extractSimpleCalleeName` para classificação.
4. Exigir que cada callsite emitido em `IRBackend` esteja em exatamente uma categoria válida.
5. Emitir erro determinístico quando o FE não possuir identidade semântica suficiente para classificar o callsite.
6. Validar compatibilidade de metadados obrigatórios por categoria no ato de emissão.
## Acceptance Criteria
1. Classificação de callsite não depende de parsing textual de callee.
2. Cada callsite em `IRBackend` possui categoria única e metadados obrigatórios.
3. Casos ambíguos geram diagnóstico estável em fase correta, sem fallback heurístico.
4. Não há regressão em casos já válidos.
5. O payload de callsite no contrato executável é tipado por ID, não por inferência textual.
## Tests
1. Testes positivos para chamadas de função, host e intrínseco com diferentes formas sintáticas.
2. Testes negativos de ambiguidade e callee não resolvido.
3. Testes de estabilidade diagnóstica (code/phase/span).
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,70 @@
# PR-05.3 - IRVM Deterministic Function-ID and Entrypoint Policy
## Briefing
A regra de indexação de funções e seleção de entrypoint precisa ficar estritamente alinhada ao contrato normativo para evitar divergência entre builds equivalentes.
Esta PR fecha política determinística de `func_id` e entrypoint único explícito.
## Motivation
### Dor atual que esta PR resolve
1. Possível variação de `func_id` quando ordem de merge muda.
2. Risco de entrypoint implícito ou ambíguo.
3. Dificuldade para gerar artefatos reproduzíveis e goldens estáveis.
## Target
`LowerToIRVMService` com regra única e testável de ordenação/indexação/entrypoint.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.2` (identidade de modulo por `ModuleId`).
2. `PR-05.0.3` (IDs tipados de callable).
## Scope
1. Ordenação determinística de funções.
2. Política explícita de entrypoint.
3. Diagnóstico para ausência ou ambiguidade de entrypoint.
## Non-Goals
1. Não altera ABI de chamada.
2. Não altera layout binário do bytecode.
## Method
### O que deve ser feito explicitamente
1. Definir ordenação canônica apenas pelos campos normativos aprovados.
2. Tornar explícita a ordenação de módulo a partir do `ModuleId` canônico.
3. Exigir exatamente um entrypoint válido no grafo admitido.
4. Atribuir `func_id=0` ao entrypoint e indexar demais por ordem canônica.
5. Rejeitar determinísticamente casos sem entrypoint ou com entrypoint múltiplo.
6. Cobrir cenários de permutação de entrada com mesma saída de indexação.
## Acceptance Criteria
1. Mesma entrada admitida gera mesma tabela de `func_id` em execuções repetidas.
2. Mudança na ordem de merge dos módulos não altera indexação final.
3. Ausência ou ambiguidade de entrypoint falha com diagnóstico estável.
4. A ordenação não depende de string derivada não canônica de módulo.
## Tests
1. Teste de determinismo com permutação de ordem de merge.
2. Teste de entrypoint único válido.
3. Testes negativos para zero entrypoint e múltiplos entrypoints.
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/19. Verification and Safety Checks Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,68 @@
# PR-05.4 - IRVM Program Coherence Without Bypass
## Briefing
Existe bypass de coerência no `IRVMProgram` em presença de `RAW_SYSCALL` e derivação com placeholders (`__unknown__`).
Esta PR remove esses atalhos do fluxo canônico e endurece o contrato de coerência `IRVM <-> EmissionPlan`.
## Motivation
### Dor atual que esta PR resolve
1. Programa pode aparentar coerente e mesmo assim carregar informação inválida para emissão.
2. Brecha para mascarar erro estrutural antes do Gate de emissão/verificação.
3. Diagnóstico tardio e pouco preciso para falhas de marshaling.
## Target
`IRVMProgram` com coerência obrigatória, sem exceção silenciosa para formas proibidas no pipeline canônico.
## Dependencies
Prerequisito direto:
1. `PR-05.0.3` (payload de IDs tipados no contrato executável).
## Scope
1. Regras de coerência no construtor e no `coherentEmissionPlan()`.
2. Eliminação de placeholder de syscall desconhecida em caminho de derivação canônico.
3. Taxonomia de erro para incoerência estrutural.
## Non-Goals
1. Não muda verificador runtime.
2. Não muda decisão de proibir `RAW_SYSCALL` em pre-load.
## Method
### O que deve ser feito explicitamente
1. Remover condição que pula validação de coerência quando detecta `RAW_SYSCALL`.
2. Tornar inválido no caminho canônico qualquer plano com operação proibida para pre-load.
3. Remover geração de `HOSTCALL` com `SyscallDecl("__unknown__",...)` em derivação automática.
4. Falhar cedo com erro determinístico e mensagem orientada a ação.
## Acceptance Criteria
1. `IRVMProgram` nunca retorna plano incoerente no fluxo canônico.
2. Não existe mais derivação com placeholders desconhecidos para hostcall.
3. Erros de coerência aparecem antes da emissão binária.
4. Coerência valida vínculos de IDs de call/intrinsic com tipo correto de domínio.
## Tests
1. Testes negativos para `RAW_SYSCALL` no plano e para hostcall sem metadado válido.
2. Testes de regressão para caminhos válidos existentes.
3. Testes de estabilidade de códigos de erro.
## Affected Documents
1. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/19. Verification and Safety Checks Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,70 @@
# PR-05.5 - IRVM Validator Real Stack Effects for HOSTCALL and INTRINSIC
## Briefing
O validador IRVM hoje modela `HOSTCALL` e `INTRINSIC` com efeito de stack genérico insuficiente para rigor JVM-grade.
Esta PR passa a validar efeitos reais de stack por assinatura (`arg_slots`/`ret_slots`) nessas operações.
## Motivation
### Dor atual que esta PR resolve
1. Possíveis underflow/overflow não detectados em chamadas host/intrínseco.
2. Retorno efetivo divergente sem falha no precheck.
3. Confiança excessiva na emissão sem validação semântica de pilha completa.
## Target
`IRVMValidator` e metadados de operação com informação suficiente para calcular efeito real de stack.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.3` (IDs tipados de callable/intrinseco).
2. `PR-05.0.6` (identidade canônica de host binding).
## Scope
1. Modelo de metadados para chamadas host e intrínseco no estágio IRVM.
2. Regras de validação de stack baseadas em assinatura.
3. Diagnósticos determinísticos de mismatch.
## Non-Goals
1. Não define política de otimização.
2. Não altera opcode wire format.
## Method
### O que deve ser feito explicitamente
1. Introduzir acesso a `arg_slots`/`ret_slots` efetivos durante validação de `HOSTCALL`.
2. Introduzir contrato equivalente para `INTRINSIC` (a partir de tabela canônica no pipeline).
3. Aplicar stack effect real no data-flow do validador.
4. Rejeitar mismatch de altura de retorno em joins e `RET` final.
5. Preservar mensagens de erro estáveis na taxonomia `MARSHAL_VERIFY_PRECHECK_*`.
6. Consumir metadados canônicos por ID, sem lookup textual ad-hoc.
## Acceptance Criteria
1. `HOSTCALL` e `INTRINSIC` participam do cálculo real de pilha no validador.
2. Casos de mismatch de assinatura falham no precheck com erro determinístico.
3. Casos válidos seguem aprovando sem regressão.
4. O caminho de validação não depende de composição textual de chave de binding.
## Tests
1. Testes positivos com combinações de arg/ret slots para host e intrínsecos.
2. Testes negativos para underflow, overflow e retorno incompatível.
3. Testes de join mismatch com chamadas em blocos ramificados.
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/19. Verification and Safety Checks Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,75 @@
# PR-05.6 - OptimizeIRVM Real Deterministic Passes
## Briefing
A etapa `OptimizeIRVM` está corretamente posicionada no pipeline, mas ainda opera como `NoOp`.
Esta PR introduz o primeiro conjunto de passes reais, seguros e determinísticos, mantendo equivalência semântica e compatibilidade de perfil.
## Motivation
### Dor atual que esta PR resolve
1. Etapa de otimização existe formalmente, mas não entrega valor técnico.
2. Difícil sustentar evolução de performance e limpeza de IRVM sem regressão.
3. Falta de contrato de execução de pass manager com evidência forte.
## Target
`OptimizeIRVMService` com pass manager produtivo e baseline de passes v1.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.3` (IDs tipados no contrato executável).
2. `PR-05.0.4` (shape/signature internadas).
## Scope
1. Pass manager determinístico com ordem estável.
2. Passes iniciais semânticamente conservadores.
3. Validação antes/depois de cada pass.
## Non-Goals
1. Não inclui otimizações agressivas interprocedurais.
2. Não inclui JIT/runtime optimization.
## Method
### O que deve ser feito explicitamente
1. Implementar baseline de passes v1:
- eliminação de bloco inalcançável,
- normalização de labels redundantes,
- simplificação de salto para próximo PC.
2. Manter invariantes obrigatórias:
- sem mudança de `vm_profile`,
- sem introdução de opcode fora do perfil,
- sem alteração de contratos de slots/retorno observáveis.
3. Validar programa antes e após cada pass.
4. Registrar nome/ordem de pass para rastreabilidade de regressão.
## Acceptance Criteria
1. `OptimizeIRVM` deixa de ser apenas `NoOp` no caminho padrão.
2. Mesma entrada produz mesma saída otimizada (determinismo).
3. Testes de equivalência semântica passam para fixtures representativas.
4. Nenhum pass viola perfil de VM ou contrato de emissão.
5. Nenhum pass degrada identidade tipada para chave textual ad-hoc.
## Tests
1. Testes unitários por pass com entradas mínimas e edge cases.
2. Testes de pipeline comparando saída otimizada vs não otimizada para equivalência.
3. Testes negativos para pass que tenta alterar perfil/semântica.
## Affected Documents
1. `docs/general/specs/21. IRVM Optimization Pipeline Specification.md`
2. `docs/general/specs/19. Verification and Safety Checks Specification.md`
## Open Questions
Sem bloqueios arquiteturais para baseline v1.
@@ -0,0 +1,66 @@
# PR-05.7 - Gate I Runtime-Backed Mandatory in CI
## Briefing
O harness de compatibilidade runtime-backed pode cair para `local-fallback` quando comando não está configurado.
Esta PR separa modo dev e modo CI, tornando obrigatório runtime-backed real em CI para suportar claim forte de conformidade.
## Motivation
### Dor atual que esta PR resolve
1. Falsa sensação de conformidade quando ambiente cai para fallback local.
2. Regressões de integração com runtime real podem passar despercebidas.
3. Evidência de Gate I fica fraca para suporte externo.
## Target
Pipeline de testes com política explícita: em CI, fallback local não é aceito para Gate I.
## Dependencies
Dependencia recomendada:
1. `PR-05.8` para registrar o status do Gate I na matriz de conformidade.
## Scope
1. Política de execução do adapter runtime-backed.
2. Configuração de CI para `PROMETEU_RUNTIME_CHECK_CMD`.
3. Diagnóstico claro quando runtime-backed obrigatório não está ativo.
## Non-Goals
1. Não altera runtime.
2. Não remove adapter local para uso de desenvolvimento.
## Method
### O que deve ser feito explicitamente
1. Introduzir flag de modo estrito para Gate I em CI.
2. Em modo estrito, falhar teste se adapter entrar em `local-fallback`.
3. Publicar comando e contrato mínimo do check runtime em pipeline.
4. Preservar modo permissivo local para desenvolvimento fora de CI.
## Acceptance Criteria
1. CI falha se Gate I não executar em modo runtime-backed real.
2. Execução local mantém fallback disponível quando não for modo estrito.
3. Resultado de Gate I reporta claramente `adapterMode` e motivo.
## Tests
1. Teste de modo estrito com comando ausente deve falhar.
2. Teste de modo estrito com comando válido deve passar.
3. Regressão local em modo não estrito permanece funcional.
## Affected Documents
1. `docs/general/specs/19. Verification and Safety Checks Specification.md`
2. `docs/general/specs/13. Conformance Test Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,73 @@
# PR-05.8 - Backend Spec-to-Test Conformance Matrix
## Briefing
Falta uma matriz única ligando cada MUST normativo de backend aos testes que provam conformidade.
Esta PR cria a matriz de rastreabilidade para `18.1`, `18.2`, `18.3`, specs `19`, `20`, `21` e Gate I/S-U.
## Motivation
### Dor atual que esta PR resolve
1. Dificuldade de provar cobertura de conformidade por requisito.
2. Buracos de teste ficam escondidos por ausência de rastreabilidade.
3. Evolução de arquitetura sem visão clara de impacto em evidência.
## Target
Artefato de conformidade auditável que mapeia requisito -> teste positivo -> teste negativo -> status.
## Dependencies
Prerequisito de conteúdo:
1. Incorporar explicitamente a trilha `PR-05.0.X` como fundação de identidade/IDs.
## Scope
1. Matriz normativa de backend FE/BE.
2. Classificação de status por requisito (`pass`, `missing`, `partial`, `deferred`).
3. Regra de atualização obrigatória da matriz em toda PR backend relevante.
4. Seção dedicada para rastrear requisitos de identidade tipada e Dense Tables.
## Non-Goals
1. Não cria nova semântica de linguagem.
2. Não substitui specs normativas.
## Method
### O que deve ser feito explicitamente
1. Criar documento de matriz em `docs/general/specs` ou `docs/pbs/specs` com tabela por requisito normativo.
2. Para cada MUST, vincular explicitamente:
- teste(s) positivo(s),
- teste(s) negativo(s),
- módulo/classe de teste,
- status atual.
3. Adicionar quality gate de revisão: PR backend sem atualização da matriz deve ser rejeitada quando impactar conformidade.
4. Definir procedimento de manutenção para não deixar entradas órfãs.
## Acceptance Criteria
1. Todo MUST de `19`, `20`, `21` e addendum executável de `13` aparece na matriz.
2. Cada item tem referência concreta a teste ou marcação explícita de ausência.
3. Revisão de PR consegue identificar rapidamente gaps de conformidade.
4. A matriz explicita dependência e cobertura dos itens `PR-05.0.1` a `PR-05.0.6`.
## Tests
1. Não exige testes executáveis novos por si só.
2. Exige checagem de integridade da matriz em revisão CI/lint documental.
## Affected Documents
1. `docs/general/specs/19. Verification and Safety Checks Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/21. IRVM Optimization Pipeline Specification.md`
4. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,72 @@
# PR-06.1 - Source Attribution and Diagnostics Evidence Hardening
## Briefing
Ha cobertura parcial para preservacao de `source attribution` em rejeicoes backend e no handoff executavel.
Esta PR fecha os gaps de evidencia para requisitos de atribuicao de origem e estabilidade de diagnostico.
## Motivation
### Dor atual que esta PR resolve
1. Falta de prova forte de que erros backend preservam `file/start/end` quando acionaveis pelo usuario.
2. Parte da matriz marca `partial` para requisitos de atribuicao (`G20-11.3`, `PBS13-12.1.4`).
3. Revisao de regressao de spans depende de inspeccao manual.
## Target
Cobertura automatizada para atribuicao de origem em diagnosticos de falha backend e no contrato executavel.
## Dependencies
Prerequisitos recomendados:
1. `PR-05.5` (stack effects reais host/intrinsic).
2. `PR-05.8` (matriz de conformidade existente).
## Scope
1. Testes de atribuicao de origem para falhas deterministicas no `LowerToIRVM`.
2. Testes de atribuicao para falhas de pipeline (`BACKEND_LOWER_IRVM` e `BACKEND_EMIT_BYTECODE`) quando aplicavel.
3. Atualizacao da matriz para migrar `G20-11.3` e `PBS13-12.1.4` de `partial` para `pass` se houver cobertura completa.
## Non-Goals
1. Nao altera semantica de linguagem.
2. Nao introduz novas classes de diagnostico.
## Method
### O que deve ser feito explicitamente
1. Criar fixtures negativas onde erro e claramente source-actionable e verificar:
- `code` estavel,
- `phase` estavel,
- `file/start/end` presentes e coerentes.
2. Garantir que spans de instrucoes/callsites sejam propagadas ativamente para as mensagens de falha.
3. Atualizar a matriz com referencias exatas de teste.
## Acceptance Criteria
1. Falhas source-actionable do backend expõem atribuicao de origem valida.
2. Requisitos `G20-11.3` e `PBS13-12.1.4` saem de `partial` se cobertura completa for atingida.
3. Nenhuma regressao em testes existentes de taxonomia de erro.
## Tests
1. Novos testes unitarios/integracao para spans em diagnosticos de falha.
2. Reexecucao obrigatoria:
- `:prometeu-compiler:prometeu-build-pipeline:test`
- `:prometeu-compiler:prometeu-frontend-api:test`
## Affected Documents
1. `docs/general/specs/19. Verification and Safety Checks Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
4. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,75 @@
# PR-06.2 - OptimizeIRVM Semantic Equivalence Harness
## Briefing
A etapa `OptimizeIRVM` ja possui passes reais, mas a prova de equivalencia semantica ainda esta parcial.
Esta PR cria harness sistematico para validar comportamento observavel com `opt on/off`.
## Motivation
### Dor atual que esta PR resolve
1. Evidencia de equivalencia semantica ainda e fixture-level limitada.
2. Itens `G21-6.2`, `G21-7.1` e `G21-9.1` permanecem `partial`.
3. Risco de pass regressivo sem deteccao ampla.
## Target
Harness de equivalencia deterministica com corpus de CFG e chamadas host/intrinsic.
## Dependencies
Prerequisitos diretos:
1. `PR-05.6` (pass manager real).
2. `PR-05.7` (Gate I estrito em CI).
## Scope
1. Framework de comparacao `optimized` vs `non-optimized`.
2. Fixtures representativas:
- sequencias lineares,
- condicional com joins,
- loops simples,
- hostcall/intrinsic.
3. Assercoes de invariantes:
- semantica observavel equivalente,
- determinismo de output,
- contratos de slots preservados.
## Non-Goals
1. Nao inclui prova formal completa.
2. Nao adiciona otimizacoes agressivas interprocedurais.
## Method
### O que deve ser feito explicitamente
1. Expor no teste caminho `optimize on/off` para o mesmo `IRVMProgram`.
2. Comparar resultado observavel em nivel de artefato e checagens Gate I/S-U.
3. Cobrir casos negativos em que pass invalido deve falhar por perfil/contrato.
4. Atualizar a matriz para converter requisitos `partial` quando cobertos.
## Acceptance Criteria
1. Existe harness reutilizavel de equivalencia `opt on/off`.
2. Cobertura de CFG e chamadas host/intrinsic com assercao de equivalencia.
3. `G21-6.2`, `G21-7.1`, `G21-9.1` evoluem para `pass` se cobertura completa.
## Tests
1. Novos testes no pacote `backend/irvm` e/ou `integration`.
2. Reexecucao obrigatoria:
- `:prometeu-compiler:prometeu-build-pipeline:test`
## Affected Documents
1. `docs/general/specs/21. IRVM Optimization Pipeline Specification.md`
2. `docs/general/specs/19. Verification and Safety Checks Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,69 @@
# PR-06.3 - IRVM_EXT Contract and Elimination Fixtures
## Briefing
O contrato de `IRVM_EXT` esta parcialmente coberto apenas pelo `INTERNAL_EXT` atual.
Esta PR amplia cobertura para garantir metadados estruturais e eliminacao antes da emissao.
## Motivation
### Dor atual que esta PR resolve
1. Requisito `G20-6.2` permanece `partial`.
2. Falta evidencia para mais de um formato de extensao interna.
3. Dificuldade de evoluir extensoes com seguranca sem regressao de precheck.
## Target
Suite de fixtures para contrato de `IRVM_EXT` e precondicao de eliminacao no caminho de emissao.
## Dependencies
Prerequisitos diretos:
1. `PR-05.6` (otimizador ativo).
2. `PR-05.4` (coerencia de programa sem bypass).
## Scope
1. Fixtures com multiplas op variantes internas (ou metadados distintos equivalentes).
2. Validacao explicita de metadados estruturais (`pops/pushes/branch/terminator`).
3. Prova de rejeicao quando opcode interno residual chega ao emit.
## Non-Goals
1. Nao define novas extensoes de runtime.
2. Nao altera ISA core publicado.
## Method
### O que deve ser feito explicitamente
1. Adicionar cenarios de teste para `IRVM_EXT` alem do caso trivial existente.
2. Verificar que `OptimizeIRVM` elimina extensoes internas em caminho canônico.
3. Verificar que `EmitBytecode` falha deterministicamente quando extensao residual permanece.
4. Atualizar a matriz para `G20-6.2` conforme cobertura final.
## Acceptance Criteria
1. Contrato estrutural de `IRVM_EXT` fica provado por testes dedicados.
2. Caminho de eliminacao pre-emissao e coberto com positivo/negativo.
3. `G20-6.2` evolui para `pass` se cobertura completa.
## Tests
1. `IRVMValidatorTest` e `OptimizeIRVMServiceTest` com novos casos.
2. `EmitBytecodePipelineStageTest` para residual interno.
3. Reexecucao:
- `:prometeu-compiler:prometeu-build-pipeline:test`
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/21. IRVM Optimization Pipeline Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,68 @@
# PR-06.4 - Gate I Runtime-Line Repeatability in CI
## Briefing
Gate I ja suporta modo estrito runtime-backed, mas a prova de repetibilidade por runtime line ainda esta parcial.
Esta PR endurece CI para validar repetibilidade em mais de uma linha de runtime suportada.
## Motivation
### Dor atual que esta PR resolve
1. `G19-5.2.8` permanece `partial`.
2. Falta evidencia de comportamento repetivel entre linhas de runtime.
3. Claim de integracao forte fica fragil sem execucao multi-line.
## Target
Pipeline CI com Gate I estrito e validacao de repetibilidade em matrix de runtime line.
## Dependencies
Prerequisitos diretos:
1. `PR-05.7` (modo estrito runtime-backed).
2. disponibilidade de pelo menos duas linhas de runtime executaveis no CI.
## Scope
1. Configuracao CI para `PROMETEU_GATE_I_STRICT=true`.
2. Parametrizacao de `PROMETEU_RUNTIME_CHECK_CMD` por runtime line.
3. Registro de evidencia de execucao por linha (log/sumario de job).
## Non-Goals
1. Nao altera implementacao do runtime.
2. Nao define politica de suporte de longo prazo entre linhas.
## Method
### O que deve ser feito explicitamente
1. Adicionar jobs ou matrix de CI para linhas de runtime alvo.
2. Garantir falha obrigatoria quando runtime-backed nao estiver ativo.
3. Adicionar teste/documentacao que explicite `adapterMode`, `runtimeLine` e motivo.
4. Atualizar matriz de conformidade para `G19-5.2.8`.
## Acceptance Criteria
1. CI falha se Gate I cair em fallback em modo estrito.
2. CI executa Gate I em >= 2 linhas de runtime declaradas.
3. `G19-5.2.8` evolui para `pass` se repetibilidade multi-line for comprovada.
## Tests
1. Testes de adapter strict ja existentes continuam verdes.
2. Execucao obrigatoria de Gate I em matrix CI com runtime-backed real.
## Affected Documents
1. `docs/general/specs/13. Conformance Test Specification.md`
2. `docs/general/specs/19. Verification and Safety Checks Specification.md`
3. `docs/general/specs/17. Compatibility and Evolution Policy.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Definir oficialmente quais runtime lines entram na matrix minima obrigatoria.
@@ -0,0 +1,68 @@
# PR-06.5 - Conformance Matrix Hard-Gate Policy
## Briefing
A matriz de conformidade existe e possui lint basico, mas ainda nao bloqueia de forma forte PRs que degradam evidencia.
Esta PR transforma a matriz em hard gate processual para mudancas FE/BE com impacto de conformidade.
## Motivation
### Dor atual que esta PR resolve
1. Possibilidade de drift entre comportamento real e status da matriz.
2. Risco de PR alterar pipeline sem atualizar rastreabilidade normativa.
3. Revisao depende demais de disciplina manual.
## Target
Politica automatizada que rejeita PR backend sem atualizacao de matriz quando ha impacto de conformidade.
## Dependencies
Prerequisitos diretos:
1. `PR-05.8` (matriz + lint documental inicial).
## Scope
1. Regra de CI/revisao para detectar mudanca relevante em FE/BE backend.
2. Exigencia de atualizacao da matriz quando requisito normativo e impactado.
3. Politica clara para `partial/missing/deferred` e justificativa obrigatoria.
## Non-Goals
1. Nao substituir julgamento tecnico de revisao.
2. Nao bloquear PR puramente documental sem impacto tecnico.
## Method
### O que deve ser feito explicitamente
1. Definir regra objetiva de impacto (arquivos/pacotes gatilho).
2. Implementar verificacao automatica em CI para forcar update da matriz quando gatilho ocorrer.
3. Exigir no PR referencia explicita aos Requirement IDs alterados.
4. Atualizar docs de contribuicao/qualidade com o novo gate.
## Acceptance Criteria
1. PR com mudanca backend relevante e sem update de matriz e rejeitada.
2. PR que altera status de requisito exige justificativa e testes referenciados.
3. Processo de revisao fica reproduzivel e auditavel.
## Tests
1. Testes de lint/matriz existentes continuam passando.
2. Teste de politica (script/check) com cenarios:
- mudanca relevante sem matriz -> fail,
- mudanca relevante com matriz -> pass.
## Affected Documents
1. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
2. `docs/general/specs/13. Conformance Test Specification.md`
3. `docs/pbs/specs/2. Governance and Versioning.md`
## Open Questions
1. Definir lista final de caminhos de codigo que acionam hard gate de matriz.
@@ -0,0 +1,76 @@
# PR-06.6 - SPAWN/YIELD v1 or Claim Rescope
## Briefing
Os requisitos `G20-9.4.2` e `G20-9.4.3` estao `deferred` porque `SPAWN/YIELD` nao fazem parte do surface executavel v1 atual.
Esta PR fecha a pendencia por uma de duas trilhas exclusivas:
1. implementar `SPAWN/YIELD` em v1 com testes; ou
2. ajustar claim/perfil/spec para remover obrigacao deste escopo no v1 claimado.
## Motivation
### Dor atual que esta PR resolve
1. Nota JVM-grade fica penalizada por requisitos deferidos.
2. Claim de conformidade pode ficar ambiguo para auditoria externa.
3. Planejamento tecnico fica travado entre implementacao e re-scope.
## Target
Decisao implementada e test-backed para encerrar `deferred` com status claro.
## Dependencies
Prerequisitos variam por trilha:
1. Trilha A (implementar): depende de extensao do modelo `IRBackend/IRVM` para opcodes e verificacao.
2. Trilha B (re-scope): depende de alinhamento normativo com specs/decision.
## Scope
1. Trilha A:
- adicionar suporte `SPAWN/YIELD`,
- validar aridade e stack constraints,
- cobrir com testes positivos/negativos.
2. Trilha B:
- ajustar documentos para deixar explicito que nao e parte do profile v1 claimado,
- atualizar matriz e policy de claim.
## Non-Goals
1. Nao introduzir modelo completo de concorrencia/corrotina alem do minimo normativo.
2. Nao conflitar com autoridade de runtime/ISA.
## Method
### O que deve ser feito explicitamente
1. Escolher uma trilha oficial (A ou B) por decisao registrada.
2. Executar implementacao ou re-scope end-to-end (codigo + specs + matriz).
3. Garantir que `G20-9.4.2` e `G20-9.4.3` saiam de `deferred` para `pass` (A) ou status normativo explicitamente nao-aplicavel no claim v1 (B).
## Acceptance Criteria
1. Nao existe mais ambiguidade sobre `SPAWN/YIELD` no claim atual.
2. Matriz e specs refletem exatamente o comportamento implementado e claimado.
3. Gate de conformidade nao deixa regressao silenciosa nesses itens.
## Tests
1. Trilha A:
- testes de lowering/validator para `SPAWN` arg count e `YIELD` stack constraint.
2. Trilha B:
- testes de integridade documental/policy com checks de claim.
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
3. `docs/general/specs/17. Compatibility and Evolution Policy.md`
4. `docs/pbs/decisions/*` (decision de escopo, quando aplicavel)
## Open Questions
1. Qual trilha oficial deve ser adotada: implementacao v1 (A) ou re-scope de claim (B)?
@@ -0,0 +1,73 @@
# PR-07.1 - OptimizeIRVM Span and Source-Hook Preservation
## Briefing
A matriz de conformidade ainda marca `G21-7.5` como `partial`.
Hoje existe evidencia de spans no lowering, mas falta regressao dedicada provando que passes de `OptimizeIRVM` preservam hooks de atribuicao de origem (spans/source hooks) apos reescritas de instrucoes e remapeamento de saltos.
## Motivation
### Dor atual que esta PR resolve
1. Risco de regressao silenciosa em spans durante otimização.
2. Evidencia insuficiente para fechar `G21-7.5`.
3. Diagnosticos pos-otimizacao podem perder rastreabilidade sem prova dedicada.
## Target
Fechar `G21-7.5` com suite de regressao explicita para preservacao de source hooks/spans no caminho `LowerToIRVM -> OptimizeIRVM -> EmitBytecode`.
## Dependencies
Prerequisitos diretos:
1. `PR-06.2` (harness de equivalencia de otimizacao).
2. `PR-06.3` (passes reais de reescrita/remocao no optimizer).
## Scope
1. Testes dedicados para verificacao de span retention por pass:
- `UnreachableInstructionEliminationPass`,
- `NormalizeRedundantJumpTargetsPass`,
- `SimplifyJumpToNextPcPass`.
2. Assercoes de preservacao de `BytecodeEmitter.Operation.span` para operacoes sobreviventes.
3. Assercoes de preservacao de spans em operacoes de salto apos remapeamento de target.
4. Atualizacao da matriz para converter `G21-7.5` de `partial` para `pass`.
## Non-Goals
1. Nao introduz novo formato de source map.
2. Nao altera contrato de diagnostico fora do backend pipeline.
## Method
### O que deve ser feito explicitamente
1. Criar fixture IRVM com spans distintos por instrucao/op.
2. Executar optimize com passes reais e comparar mapeamento de spans esperado no output.
3. Incluir caso com salto reescrito para validar span do salto apos remap.
4. Incluir caso com eliminacao de instrucoes para validar que operacoes restantes mantem spans originais.
5. Atualizar matriz (`docs/general/specs/22...`) com referencias aos novos testes.
## Acceptance Criteria
1. Existe suite de teste dedicada para preservacao de spans/source hooks no optimizer.
2. Reescritas de salto preservam spans da operacao original.
3. Eliminacao de instrucoes nao corrompe spans das operacoes remanescentes.
4. `G21-7.5` evolui para `pass`.
## Tests
1. Novos testes em `backend/irvm` (ex.: `OptimizeIRVMSourceAttributionTest` ou equivalente).
2. Reexecucao obrigatoria:
- `:prometeu-compiler:prometeu-build-pipeline:test`
## Affected Documents
1. `docs/general/specs/21. IRVM Optimization Pipeline Specification.md`
2. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,74 @@
# PR-07.2 - PBS Callsite Category Without Textual Heuristics (Regression Fixtures)
## Briefing
A matriz de conformidade ainda marca `PBS13-12.2.2` como `partial`.
Ja existe enforce de metadados no contrato executavel, mas falta fixture regressiva dedicada para provar que o frontend/backend nao classifica callsite por heuristica textual quando identidades entram em colisao.
## Motivation
### Dor atual que esta PR resolve
1. Ambiguidade residual na evidencia de `CALL_FUNC/CALL_HOST/CALL_INTRINSIC`.
2. Risco de regressao para classificacao por nome textual em casos limítrofes.
3. `PBS13-12.2.2` permanece `partial` por falta de caso dedicado de identidade ambigua.
## Target
Fechar `PBS13-12.2.2` com fixtures explicitas de identidade e ambiguidade, garantindo que categoria de callsite e derivada de identidade semantica/admitida, nao de heuristica textual.
## Dependencies
Prerequisitos diretos:
1. `PR-05.2` (classificacao de callsite por identidade semantica).
2. `PR-05.0.1` e `PR-05.0.6` (name/host identity foundation).
## Scope
1. Fixture positiva:
- nome textual com "cara de host", mas identidade resolvida como callable local -> deve lower para `CALL_FUNC`.
2. Fixture positiva:
- nome textual sobreposto entre dominios, com identidade univoca admitida para host ou intrinsic -> deve lower categoria correta.
3. Fixture negativa dedicada:
- colisao real entre categorias (callable/host/intrinsic) para o mesmo callsite -> rejeicao deterministica por ambiguidade.
4. Atualizacao de matriz para converter `PBS13-12.2.2` de `partial` para `pass`.
## Non-Goals
1. Nao altera gramatica PBS.
2. Nao redefine regras de admission de host/intrinsics fora do escopo desta prova.
## Method
### O que deve ser feito explicitamente
1. Adicionar testes em `PbsFrontendCompilerTest` (ou suite semantica correlata) para os tres cenarios acima.
2. Assertar `InstructionKind` resultante (`CALL_FUNC`, `CALL_HOST`, `CALL_INTRINSIC`) em casos positivos.
3. Assertar codigo diagnostico deterministico em caso ambiguo.
4. Garantir que nao ha branch de fallback por string pattern no caminho de lowering executavel.
5. Atualizar matriz de conformidade com referencias dos novos testes.
## Acceptance Criteria
1. Existe fixture dedicada cobrindo ambiguidade de categoria por identidade.
2. Casos positivos provam classificacao correta mesmo quando nome textual engana.
3. Caso ambiguo falha deterministicamente com diagnostico estavel.
4. `PBS13-12.2.2` evolui para `pass`.
## Tests
1. Novos testes no frontend PBS:
- `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
2. Reexecucao obrigatoria de integracao backend:
- `:prometeu-compiler:prometeu-build-pipeline:test`
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
Sem bloqueios arquiteturais.
@@ -0,0 +1,77 @@
# PR-07.3 - IRVM Entrypoint Export Emission for Runtime Loader Compatibility
## Briefing
Hoje um cartridge pode compilar com `entrypoint: "frame"` no `manifest.json` e `pub fn frame()` no `mod.barrel`, mas ainda falhar em runtime com `EntrypointNotFound`.
A causa observada e que o `program.pbx` pode ser emitido sem secao `exports` (section kind `4`), enquanto o loader resolve entrypoint nominal usando `program.exports`.
## Motivation
### Dor atual que esta PR resolve
1. Build aparentemente valido, mas falha de bootstrap em runtime.
2. Divergencia entre contrato de manifesto (`entrypoint` nominal) e artefato PBX emitido.
3. Falta de evidencia automatizada para evitar regressao de exports no caminho `IRBackend -> IRVM -> Bytecode`.
## Target
Corrigir o pipeline backend para sempre emitir export nominal do entrypoint no PBX de preload, garantindo compatibilidade com o loader quando o `manifest.json` declara entrypoint por nome.
## Dependencies
Prerequisitos diretos:
1. `PR-05.3` (politica deterministica de entrypoint no indice `0`).
2. `PR-05.4` (coerencia unica entre IRVM e EmissionPlan).
## Scope
1. `LowerToIRVMService` deve preencher `EmissionPlan.exports` com o simbolo do entrypoint apontando para `func_idx = 0`.
2. Adicionar regressao dedicada para garantir que `coherentEmissionPlan()` preserva export do entrypoint.
3. Validar serializacao PBX com secao `exports` presente quando houver entrypoint nominal.
4. Cobrir cenario de integracao onde `manifest.entrypoint = "frame"` inicializa VM sem `EntrypointNotFound`.
## Non-Goals
1. Nao exportar toda a superficie de funcoes executaveis neste passo.
2. Nao alterar formato binario PBX alem da presenca correta da secao `exports`.
3. Nao mudar semantica de resolucao por indice numerico de entrypoint.
## Method
### O que deve ser feito explicitamente
1. No `LowerToIRVMService`, construir `BytecodeEmitter.EmissionPlan` com `exports` contendo, no minimo, `Export(entryPointCallableName, 0)`.
2. Garantir determinismo do export do entrypoint a partir da mesma politica que fixa `func_id = 0`.
3. Adicionar teste unitario em `LowerToIRVMServiceTest` para verificar export nominal do entrypoint no plano coerente.
4. Adicionar teste de emissao/link para verificar secao `exports` no modulo serializado.
5. Adicionar teste de integracao runtime-backed para falhar se regressar para `EntrypointNotFound` em cartridge com entrypoint nominal valido.
## Acceptance Criteria
1. Build de projeto PBS com entrypoint `frame` gera PBX com secao `exports`.
2. O simbolo `frame` aponta para `func_idx = 0` no artefato emitido.
3. Execucao de cartridge com `manifest.entrypoint = "frame"` nao falha por `EntrypointNotFound` quando o programa contem o entrypoint admitido.
4. Rebuilds equivalentes produzem mapping de export deterministico.
## Tests
1. Novos testes de backend:
- `:prometeu-compiler:prometeu-build-pipeline:test`
2. Reexecucao de compatibilidade runtime-backed:
- `:prometeu-compiler:prometeu-build-pipeline:test --tests *Runtime*`
3. Smoke local recomendado:
- `./runtime/prometeu build .`
- `./runtime/prometeu run cartridge`
## Affected Documents
1. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/pbs/specs/7. Cartridge Manifest and Runtime Capabilities Specification.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Em evolucao futura, devemos exportar apenas o entrypoint ou tambem funcoes explicitamente marcadas para linking externo?
@@ -0,0 +1,80 @@
# PR-08.1 - Intrinsic Resolution by Canonical Identity (Owner+Name+Version)
## Briefing
Hoje a resolucao de intrinsic no frontend PBS ainda depende de chave por `sourceMethodName` simples.
Isso permite ambiguidade quando existem metodos com o mesmo nome em owners diferentes e enfraquece o contrato de canonical addressing.
## Motivation
### Dor atual que esta PR resolve
1. Ambiguidade potencial de resolucao de intrinsic por nome de metodo sem owner.
2. Dependencia implícita de heuristica textual ao inves de identidade canonica.
3. Risco de regressao quando ampliar superficie de builtins/intrinsics stateful.
## Target
Tornar a resolucao de `CALL_INTRINSIC` no frontend semanticamente canonica e nao ambigua, usando chave composta deterministica:
1. `owner canonical`,
2. `intrinsic name canonical`,
3. `canonical version`.
## Dependencies
Prerequisitos diretos:
1. `PR-05.2` (classificacao de callsite sem heuristica textual).
2. `PR-07.2` (regressao contra heuristica textual de categoria).
## Scope
1. Substituir o map por `sourceMethodName` no lowering executavel por indice por identidade canonica.
2. Ajustar `PbsReservedMetadataExtractor`/surface helper para expor owner canonical explicitamente na chave de resolucao.
3. Tornar erro de ambiguidade explicito quando mais de uma intrinsic disputar o mesmo callsite apos resolver receiver/owner.
4. Cobrir cenarios com nomes repetidos em owners diferentes.
## Non-Goals
1. Nao alterar ids finais de intrinsics no bytecode/runtime nesta PR.
2. Nao introduzir novo opcode.
3. Nao expandir parser/sintaxe de `IntrinsicCall`.
## Method
### O que deve ser feito explicitamente
1. Introduzir chave tipada para intrinsic de lowering (ex.: `IntrinsicResolutionKey(ownerCanonical, nameCanonical, version)`).
2. Popular lookup de intrinsics com essa chave em vez de `sourceMethodName`.
3. Resolver owner canonical a partir do receiver sem fallback textual opaco.
4. Rejeitar deterministicamente callsite intrinsic sem mapeamento canonico univoco.
5. Adicionar testes positivos/negativos para:
- owners distintos com mesmo metodo,
- override de versao,
- callsite sem receiver compativel.
## Acceptance Criteria
1. Nenhum callsite intrinsic e resolvido apenas por `sourceMethodName`.
2. Colisao de metodo entre owners diferentes nao gera escolha implicita.
3. Diagnosticos de ambiguidade/nao resolucao sao estaveis e testados.
4. Build equivalente gera mesma classificacao e mesmo `intrinsicPool`.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
2. `:prometeu-compiler:prometeu-build-pipeline:test --tests *LowerToIRVMServiceTest*`
3. Regressao dedicada para callsites `input.pad.*` vs outros owners com nome coincidente.
## Affected Documents
1. `docs/pbs/specs/6.1. Intrinsics and Builtin Types Specification.md`
2. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
3. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. O contrato final deve expor owner canonico como campo separado em `IntrinsicSurface`, ou apenas como nome canonico fully-qualified?
@@ -0,0 +1,79 @@
# PR-08.2 - IRBackend Module Identity via Dense Table (ModuleId + ModulePool)
## Briefing
`moduleKey` hoje e string no contrato executavel e vira identificador estrutural em multiplos pontos.
Isso funciona, mas ainda nao aproveita plenamente a infraestrutura de dense tables ja existente (`ModuleTable`/`ModuleId`) para identidade canonica de modulo no handoff FE->BE.
## Motivation
### Dor atual que esta PR resolve
1. Identidade de modulo dependente de serializacao textual (`project:path`) no contrato.
2. Maior risco de drift/normalizacao inconsistente entre fronteiras.
3. Custo de comparacao/armazenamento pior do que id tipado em larga escala.
## Target
Evoluir o contrato `IRBackend` para carregar identidade de modulo tipada por dense table:
1. `ModuleId` nas entidades executaveis,
2. `modulePool` canonico no payload,
3. `moduleKey` textual mantido apenas como campo auxiliar/debug no periodo de transicao.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.2` (infra de `ModuleId` e `ModuleTable`).
2. `PR-05.0.3` (migração previa de ids tipados no contrato executavel).
## Scope
1. Introduzir `modulePool` no `IRBackend` e remapeamento na agregacao multi-arquivo.
2. Trocar referencias estruturais de modulo para `ModuleId` em executable/callable surfaces.
3. Adaptar sorting/canonical ordering para usar `ModuleId` + leitura canonica da tabela.
4. Preservar backward compatibility local durante migracao (camada de adaptacao).
## Non-Goals
1. Nao redefinir formato PBX nesta PR.
2. Nao alterar semantica de modulo no parser/linker.
3. Nao remover imediatamente todos os campos textuais de debug.
## Method
### O que deve ser feito explicitamente
1. Adicionar `modulePool: ReadOnlyList<ModuleReference>` em `IRBackend`.
2. Adicionar `moduleId` em `IRBackendExecutableFunction` e `CallableSignatureRef` (ou equivalente de assinatura).
3. Atualizar `IRBackendAggregator` para reindexar modulos via `ModuleTable` (dense table).
4. Atualizar FE PBS para emitir `moduleId` usando tabela canonica de modulos.
5. Atualizar BE (`LowerToIRVMService`) para ordenar por identidade de modulo canonica sem dependencia de concat textual.
6. Incluir testes de determinismo para remapeamento multi-modulo com ids estaveis.
## Acceptance Criteria
1. `IRBackend` possui pool canonico de modulos com ids densos.
2. Caminho estrutural nao depende de `moduleKey` string para identidade.
3. Merges de `IRBackendFile` preservam reindexacao deterministica de modulo.
4. Funcoes equivalentes em builds equivalentes recebem ids de modulo identicos.
## Tests
1. `:prometeu-compiler:prometeu-frontend-api:test`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
3. `:prometeu-compiler:prometeu-build-pipeline:test`
4. Novos testes de agregacao multi-modulo com colisao textual potencial.
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Fase de transicao deve manter `moduleKey` como shadow field por quantas ondas?
@@ -0,0 +1,80 @@
# PR-08.3 - Qualified Entrypoint Identity (No Name-Only Resolution)
## Briefing
A selecao de entrypoint no backend ainda filtra apenas por `callableName`.
Em projetos multi-modulo isso amplia risco de ambiguidade e cria acoplamento desnecessario a nomes globais.
## Motivation
### Dor atual que esta PR resolve
1. Ambiguidade de entrypoint quando existem callables homonimos.
2. Diagnostico tardio por nome sem contexto de modulo.
3. Divergencia potencial entre contrato de frontend e selecao real no backend.
## Target
Evoluir o contrato para entrypoint qualificado e deterministico:
1. `entryPointCallableName` + `entryPointModuleId` (ou `entryPointCallableId`),
2. resolucao backend por identidade qualificada,
3. politicas de erro claras para mismatch/ausencia.
## Dependencies
Prerequisitos diretos:
1. `PR-08.2` (ModuleId no contrato IRBackend).
2. `PR-05.3` (politica deterministica de indexacao e `func_id=0`).
## Scope
1. Expandir `FrontendSpec` e handoff FE para declarar entrypoint qualificado.
2. Atualizar `IRBackend` para carregar declaracao qualificada de entrypoint.
3. Atualizar `LowerToIRVMService` para selecionar entrypoint por identidade qualificada.
4. Preservar fallback de compatibilidade durante migracao (com warning deterministico).
## Non-Goals
1. Nao alterar semantica de `func_id=0`.
2. Nao mudar contrato de manifesto de cartridge nesta PR.
3. Nao introduzir multiple entrypoints por linguagem.
## Method
### O que deve ser feito explicitamente
1. Introduzir estrutura de entrada qualificada (ex.: `EntrypointRef(moduleId, callableName)`).
2. Popular estrutura no frontend PBS a partir do modulo de `frame`.
3. Modificar `orderFunctions` para usar referencia qualificada.
4. Em caso de fallback por nome, emitir diagnostico de deprecacao controlado.
5. Adicionar testes para:
- homonimos em modulos distintos,
- entrypoint valido qualificado,
- entrypoint ausente com erro estavel.
## Acceptance Criteria
1. Selecao de entrypoint nao depende apenas de nome.
2. Homonimos em modulos distintos nao geram ambiguidade quando entrypoint qualificado existe.
3. `func_id=0` continua pertencendo ao entrypoint declarado.
4. Rebuilds equivalentes mantem func ordering deterministico.
## Tests
1. `:prometeu-compiler:prometeu-frontend-api:test`
2. `:prometeu-compiler:prometeu-build-pipeline:test --tests *LowerToIRVMServiceTest*`
3. Testes de integracao com dois modulos contendo `frame`.
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Melhor contrato final: `EntrypointRef(moduleId, callableName)` ou `CallableId` global direto?
@@ -0,0 +1,72 @@
# PR-08.4 - CALL_FUNC Callee Module Identity Correctness
## Briefing
No lowering executavel PBS, instrucoes `CALL_FUNC` podem carregar `calleeModuleKey` do contexto local, e nao necessariamente do callable alvo.
Isso compromete rastreabilidade, debug e futuras validacoes de linking por modulo.
## Motivation
### Dor atual que esta PR resolve
1. Metadado de callsite incorreto para chamadas inter-modulo.
2. Dificulta diagnostico e verificacao de integridade no backend.
3. Introduz risco de regressao quando modulo vira identidade tipada no contrato.
## Target
Garantir que todo `CALL_FUNC` preserva identidade real do alvo (`callee module`) de forma deterministica, sem usar contexto local como proxy.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.4` (assinatura/callable internados).
2. `PR-08.2` (quando `ModuleId` tipado estiver ativo, usar id do alvo).
## Scope
1. Corrigir montagem de callsite para puxar modulo do `calleeCallableId` resolvido.
2. Ajustar modelos auxiliares de resolucao de callable para incluir modulo do alvo.
3. Expandir testes de lowering com chamadas cross-module.
## Non-Goals
1. Nao alterar categoria de callsite.
2. Nao introduzir linking dinamico de funcoes.
3. Nao alterar bytecode emitido para opcodes de chamada.
## Method
### O que deve ser feito explicitamente
1. Enriquecer lookup de callable para retornar identidade completa (`callableId + module identity`).
2. Em `CALL_FUNC`, preencher `callee module` com identidade do alvo real.
3. Adicionar validacao de consistencia em contrato executavel para evitar modulo invalido em chamada.
4. Criar regressao com:
- modulo A chamando funcao em modulo B,
- assert do modulo do callee no IRBackend.
## Acceptance Criteria
1. Nenhuma instrução `CALL_FUNC` usa modulo local quando alvo e externo.
2. Testes cross-module passam com metadado correto de callee.
3. Diagnosticos mantem atribuicao correta em falhas de resolucao.
4. Contrato segue deterministico em rebuilds equivalentes.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsFrontendCompilerTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PBSFrontendPhaseServiceTest*`
3. `:prometeu-compiler:prometeu-build-pipeline:test --tests *LowerToIRVMPipelineStageTest*`
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Durante a transicao, manter `calleeCallableName` textual para debug ou derivar sempre da assinatura por id?
@@ -0,0 +1,74 @@
# PR-08.5 - Intrinsic Registry Single Source of Truth (Compiler <-> Runtime)
## Briefing
O compiler backend hoje possui `IRVMIntrinsicRegistry` hardcoded e o runtime possui registry propio em `builtins.rs`.
Mesmo estando alinhados agora, a manutencao manual em dois lugares cria risco alto de drift.
## Motivation
### Dor atual que esta PR resolve
1. Duplicacao de source-of-truth para ids finais de intrinsic.
2. Risco de regressao silenciosa quando runtime evoluir surface intrinsic.
3. Custo operacional para garantir paridade manual em cada mudanca.
## Target
Estabelecer uma fonte unica versionada para mapeamento canonico de intrinsics (`canonicalName@version -> finalId`) e consumir isso em compiler + runtime com teste de paridade automatizado.
## Dependencies
Prerequisitos diretos:
1. `PR-08.1` (resolucao canonica consistente no frontend).
2. `PR-05.7` (caminho de verificacao runtime-backed robusto).
## Scope
1. Definir artefato de registry canonico (ex.: JSON/TOML) sob controle de versionamento.
2. Gerar/consumir mapeamento no compiler (`IRVMIntrinsicRegistry`) a partir desse artefato.
3. Adicionar checagem de paridade em teste para impedir divergencia com runtime.
4. Documentar fluxo de evolucao de intrinsic id sem quebra de compatibilidade.
## Non-Goals
1. Nao reescrever todas as implementacoes de intrinsic do runtime nesta PR.
2. Nao alterar semantica de execucao de `INTRINSIC`.
3. Nao migrar para discovery dinamico em tempo de execucao.
## Method
### O que deve ser feito explicitamente
1. Introduzir arquivo canonico de registry em local acordado (`docs` ou `shared metadata`).
2. Criar utilitario de leitura/geracao para preencher `IRVMIntrinsicRegistry` no compiler.
3. Adicionar teste no compiler que compara mapeamento esperado com runtime (snapshot/paridade).
4. Adicionar regra de CI para falhar em desvio de paridade.
5. Atualizar docs de contribuicao para fluxo de adicao/upgrade de intrinsics.
## Acceptance Criteria
1. Existe uma unica fonte versionada de mapeamento de intrinsic ids finais.
2. Compiler nao depende de lista manual duplicada para esse mapeamento.
3. CI falha quando runtime e compiler divergem em identidade/ID de intrinsic.
4. Inclusao de nova intrinsic segue workflow documentado e testavel.
## Tests
1. `:prometeu-compiler:prometeu-build-pipeline:test --tests *Intrinsic*`
2. Teste de paridade compiler-runtime dedicado.
3. Smoke runtime-backed com intrinsic valido e id invalido.
## Affected Documents
1. `docs/pbs/specs/6.1. Intrinsics and Builtin Types Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
4. `../runtime/docs/runtime/specs/06-input-peripheral.md`
5. `../runtime/docs/runtime/specs/02-vm-instruction-set.md`
## Open Questions
1. Melhor local da fonte unica: repo `runtime`, repo `studio`, ou pacote compartilhado dedicado?
@@ -0,0 +1,81 @@
# PR-09.1 - IRBackend Contract Cut: Remove `moduleKey` and `calleeModuleKey` (String)
## Briefing
O contrato executavel ainda carrega `moduleKey` textual como trilha de compatibilidade.
Isso mantem dupla identidade (`ModuleId` + string) em area critica de handoff.
## Motivation
### Dor atual que esta PR resolve
1. Identidade estrutural ainda pode cair em fallback textual.
2. Contrato permite dados redundantes e potencialmente divergentes.
3. A transicao para dense-only ainda nao esta fechada.
## Target
Encerrar a transicao no contrato FE->BE:
1. remover `moduleKey` de `IRBackendExecutableFunction`,
2. remover `calleeModuleKey` de instrucoes executaveis,
3. remover `moduleKey` de `CallableSignatureRef`,
4. eliminar parsing/fallback textual em `IRBackendAggregator`.
## Dependencies
Prerequisitos diretos:
1. `PR-08.2`
2. `PR-08.3`
3. `PR-08.4`
## Scope
1. Atualizar modelos em `prometeu-frontend-api` e `prometeu-compiler-core`.
2. Remover construtores de compatibilidade que aceitam `moduleKey` string.
3. Atualizar agregacao para reindexar apenas por `ModuleId` + `modulePool`.
4. Atualizar todos os testes afetados.
## Non-Goals
1. Nao alterar formato PBX nesta PR.
2. Nao mudar semantica de host/intrinsic callsites.
## Method
### O que deve ser feito explicitamente
1. Em `IRBackendExecutableFunction`:
- remover campo `moduleKey`,
- remover `calleeModuleKey`,
- manter apenas `ModuleId` estrutural.
2. Em `CallableSignatureRef`:
- remover `moduleKey`,
- manter `moduleId` + assinatura.
3. Em `IRBackend` agregador:
- remover `moduleReferenceFromKey(...)` e qualquer fallback textual.
4. Em testes:
- converter fixtures para `ModuleId` + `modulePool`.
## Acceptance Criteria
1. Nao existe mais `moduleKey` string em contratos estruturais FE/BE.
2. Reindexacao multi-file usa somente dense tables.
3. Build/test passam sem camadas de compatibilidade textual.
## Tests
1. `:prometeu-compiler:prometeu-compiler-core:test`
2. `:prometeu-compiler:prometeu-frontend-api:test`
3. `:prometeu-compiler:prometeu-build-pipeline:test`
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Nenhuma. Esta PR fecha corte de transicao.
@@ -0,0 +1,68 @@
# PR-09.2 - PBS Frontend Lowering: ModuleId-Only (No `moduleKey` in lowering surfaces)
## Briefing
Mesmo apos o contrato aceitar `ModuleId`, o lowering PBS ainda trafega `moduleKey` em estruturas internas (`ImportedCallableSurface`, indices auxiliares e fixtures).
## Motivation
### Dor atual que esta PR resolve
1. FE ainda acopla resolucao de callable/import a string de modulo.
2. A remocao de `moduleKey` no contrato quebra se FE nao migrar totalmente.
3. Risco de divergencia entre metadado textual e identidade internada.
## Target
Migrar lowering PBS para `ModuleId` como identidade unica:
1. `ImportedCallableSurface` sem `moduleKey`,
2. callsite/callable lookup por ids internados,
3. diagnosticos e logs usando renderizacao derivada de `modulePool` apenas quando necessario.
## Dependencies
Prerequisito direto:
1. `PR-09.1`
## Scope
1. Atualizar `PbsFrontendCompiler` para operar com `ModuleId` nas superfices de import/callable.
2. Atualizar `PBSFrontendPhaseService` para fornecer metadados densos sem string estrutural.
3. Atualizar testes PBS e artifacts golden.
## Non-Goals
1. Nao alterar parser PBS.
2. Nao alterar admission de host capabilities.
## Method
### O que deve ser feito explicitamente
1. Remover `moduleKey` de `ImportedCallableSurface`.
2. Em `collect/lower callsites`, propagar `calleeModuleId` via assinatura internada.
3. Ajustar renderizacao de debug para usar `modulePool` quando mostrar modulo.
4. Atualizar golden printer para mostrar `moduleId` (e opcionalmente nome renderizado derivado).
## Acceptance Criteria
1. FE PBS nao depende de `moduleKey` string para resolver/importar/lower callables.
2. Todas as callsites `CALL_FUNC` carregam `calleeModuleId` coerente.
3. Testes PBS passam sem acessos estruturais a chave textual.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
2. `:prometeu-compiler:prometeu-frontend-api:test --tests *IRBackendExecutableContractTest*`
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/14. Name Resolution and Module Linking Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Nenhuma. Regra fica `ModuleId`-only para identidade estrutural.
@@ -0,0 +1,72 @@
# PR-09.3 - LowerToIRVM: ModuleId-Only Ordering + Strict Qualified Entrypoint
## Briefing
`LowerToIRVMService` ainda possui fallback para `moduleKey` textual e fallback de entrypoint por nome quando `entryPointModuleId` nao e informado.
## Motivation
### Dor atual que esta PR resolve
1. Ordenacao de funcoes ainda pode depender de string legado.
2. Entrypoint pode cair em selecao name-only, mantendo ambiguidade residual.
3. Contrato qualificado existe, mas nao e estrito.
## Target
Tornar lowering estritamente orientado por identidade:
1. ordenacao por `ModuleId -> modulePool` somente,
2. entrypoint obrigatoriamente qualificado (`entryPointModuleId + callableName`),
3. remover fallback textual/heuristico.
## Dependencies
Prerequisitos diretos:
1. `PR-09.1`
2. `PR-09.2`
## Scope
1. Atualizar `LowerToIRVMService` para eliminar `fallbackModuleKey`.
2. Validar presenca obrigatoria de `entryPointModuleId` para entrada executavel.
3. Atualizar testes de ordenacao, ambiguidades e erros deterministas.
## Non-Goals
1. Nao alterar regra `func_id=0` (continua entrypoint).
2. Nao alterar emissao de opcodes.
## Method
### O que deve ser feito explicitamente
1. Substituir `moduleSortKey(...)` textual por leitura canonica direta do `modulePool` indexado por `ModuleId`.
2. Em `orderFunctions`, rejeitar entrada sem `entryPointModuleId`.
3. Remover caminho de erro/controle baseado em entrypoint name-only.
4. Cobrir com testes:
- entrypoint qualificado valido,
- entrypoint qualificado ausente,
- homonimos em modulos distintos com qualificacao.
## Acceptance Criteria
1. Nenhum fallback para `moduleKey` no LowerToIRVM.
2. Entrypoint e sempre resolvido por identidade qualificada.
3. Determinismo preservado em rebuild equivalente.
## Tests
1. `:prometeu-compiler:prometeu-build-pipeline:test --tests *LowerToIRVMServiceTest*`
2. `:prometeu-compiler:prometeu-build-pipeline:test --tests *BackendSafetyGateSUTest*`
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Nenhuma. Esta PR fecha o fallback de entrypoint name-only.
@@ -0,0 +1,84 @@
# PR-09.4 - Specs Refresh: ModuleId-Only + EntrypointRef Normative Alignment
## Briefing
Com a remocao estrutural de `moduleKey`, as specs normativas precisam refletir:
1. identidade de modulo densa (`ModuleId`),
2. entrypoint qualificado (`EntrypointRef`),
3. ausencia de fallback textual.
## Motivation
### Dor atual que esta PR resolve
1. Specs ainda descrevem partes name-only/text-based em pontos criticos.
2. Matriz pode afirmar `pass` sem refletir contratos mais estritos.
3. Risco de regressao por lacuna documento->implementacao.
## Target
Atualizar o baseline normativo para o modelo final:
1. `IRBackend` estrutural sem `moduleKey`,
2. `EntrypointRef(moduleId, callableName)` obrigatorio em handoff executavel,
3. ordenacao/lowering sem dependencias textuais.
## Dependencies
Prerequisitos diretos:
1. `PR-09.1`
2. `PR-09.2`
3. `PR-09.3`
## Scope
1. Revisar e atualizar specs:
- PBS 13 (Lowering IRBackend),
- General 20 (IRBackend -> IRVM),
- General 15 (Bytecode mapping entrypoint linkage),
- General 22 (matriz de conformidade).
2. Registrar decisao de corte definitivo (`moduleKey` removido).
## Non-Goals
1. Nao alterar implementação de runtime nesta PR.
2. Nao introduzir novo formato de arquivo para `program.pbx`.
## Method
### O que deve ser feito explicitamente
1. Em PBS13 e G20:
- trocar obrigacoes name-only por `EntrypointRef` qualificado,
- declarar `ModuleId` como identidade estrutural unica.
2. Em G15:
- manter `func_id=0` como entrypoint selecionado por `EntrypointRef`.
3. Em G22:
- adicionar/ajustar requirement rows para:
- no-moduleKey structural identity,
- strict qualified entrypoint,
- moduleid-only ordering.
## Acceptance Criteria
1. Nenhuma spec normativa relevante menciona `moduleKey` como identidade estrutural.
2. Matriz de conformidade cobre explicitamente obrigações novas.
3. `BackendConformanceMatrixSpecTest` e gate hard-policy permanecem verdes.
## Tests
1. `:prometeu-compiler:prometeu-build-pipeline:test --tests *BackendConformanceMatrixSpecTest*`
2. `:prometeu-compiler:prometeu-build-pipeline:test --tests *BackendClaimScopeSpecTest*`
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Nenhuma. Esta PR e de alinhamento normativo.
@@ -0,0 +1,76 @@
# PR-09.5 - Hard Gates: No-`moduleKey` Regression + Migration Cleanup
## Briefing
Depois do corte `ModuleId`-only, precisamos impedir reintroducao acidental de `moduleKey` estrutural e limpar residuos de migracao.
## Motivation
### Dor atual que esta PR resolve
1. Sem gate dedicado, regressao textual pode voltar por conveniencia.
2. Testes/golden antigos ainda podem carregar nomenclatura de transicao.
3. Confianca de manutencao cai sem verificacao automatica de proibicao.
## Target
Fechar o ciclo de migracao:
1. adicionar gate anti-regressao (`moduleKey` proibido em contratos estruturais),
2. atualizar fixtures/golden para contrato final,
3. consolidar notas de migracao e contribuicao.
## Dependencies
Prerequisitos diretos:
1. `PR-09.1`
2. `PR-09.2`
3. `PR-09.3`
4. `PR-09.4`
## Scope
1. Criar teste/lint de proibicao para `moduleKey` em pacotes de contrato/lowering.
2. Atualizar `golden` de frontend/backend para `ModuleId`-only.
3. Atualizar docs de contribuicao para adicao de callables/modulos sem chave textual.
## Non-Goals
1. Nao alterar semantica de parser/lexer PBS.
2. Nao introduzir novo gate externo ao gradle test.
## Method
### O que deve ser feito explicitamente
1. Adicionar teste de policy:
- falha se campos/assinaturas estruturais de FE/BE usarem `moduleKey`.
2. Atualizar snapshots golden e testes que assumiam debug key textual.
3. Registrar checklist de migracao final:
- FE lowering,
- IRBackend contract,
- LowerToIRVM,
- docs/matriz.
## Acceptance Criteria
1. Nao existe `moduleKey` em contratos estruturais FE/BE.
2. Gate automatizado falha ao tentar reintroduzir o campo.
3. Testes/golden passam no modo novo sem artefatos legados.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
2. `:prometeu-compiler:prometeu-frontend-api:test`
3. `:prometeu-compiler:prometeu-build-pipeline:test`
## Affected Documents
1. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
2. `docs/pbs/pull-requests/INDEX.md`
3. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## Open Questions
1. Nenhuma. PR de fechamento e anti-regressao.
@@ -0,0 +1,84 @@
# PR-09.6 - ISA-Scoped Intrinsic Registry as Single Source of Truth
## Briefing
Hoje o mapeamento `canonicalName@version -> finalId` ainda e mantido em dois lugares (compiler e runtime), com teste de paridade.
Isso reduz risco, mas ainda nao elimina dual-authoring.
## Motivation
### Dor atual que esta PR resolve
1. Fonte duplicada para IDs finais de intrinsic.
2. Risco operacional de drift entre compiler e runtime.
3. Evolucao de intrinsics depende de sincronizacao manual.
## Target
Definir um artefato unico, versionado e vinculado ao profile ISA para o registry de intrinsics:
1. artefato canonico de registry (`intrinsic-registry-v1`),
2. ownership normativo no boundary ISA/profile,
3. consumo por compiler e runtime a partir da mesma fonte.
## Dependencies
Prerequisitos diretos:
1. `PR-08.5` (paridade compiler-runtime existente)
2. `PR-09.7` (normalizacao de consumo no compiler)
## Scope
1. Definir formato normativo do artefato (CSV/TOML/JSON) no boundary ISA.
2. Definir local canonico e versionamento do artefato.
3. Definir contrato de evolucao:
- adicao de intrinsic,
- deprecacao,
- compatibilidade de IDs.
4. Definir gate de paridade contra consumidores.
## Non-Goals
1. Nao alterar semantica de opcode `INTRINSIC`.
2. Nao redesenhar toda a arquitetura de builtins do runtime nesta PR.
## Method
### O que deve ser feito explicitamente
1. Criar documento de formato canonico do registry:
- chave canonica,
- versao canonica,
- final id,
- constraints de unicidade.
2. Declarar ownership do artefato no profile ISA.
3. Definir pipeline de validacao:
- parser estrito,
- check de unicidade de identity e final id,
- check de ordenacao deterministica.
4. Definir workflow de manutencao para adicao de intrinsic.
## Acceptance Criteria
1. Existe uma unica fonte versionada para IDs finais de intrinsic.
2. Runtime e compiler referenciam formalmente essa fonte.
3. Processo de evolucao de intrinsics fica deterministico e auditavel.
## Tests
1. Testes de parser/validacao do artefato canonico.
2. Testes de paridade de consumidores contra o artefato.
3. Gate de CI que falha em divergia do mapping.
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
3. `docs/pbs/specs/6.1. Intrinsics and Builtin Types Specification.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
5. Runtime specs correspondentes (ajuste posterior no repo runtime).
## Open Questions
1. Local canonico final do artefato: `runtime` (recomendado) ou `shared-metadata` dedicado. runtime
@@ -0,0 +1,76 @@
# PR-09.7 - Compiler Normalization to ISA Intrinsic Registry Artifact
## Briefing
Apos estabelecer o artefato unico do registry (PR-09.6), o compiler precisa consumir exclusivamente esse artefato e remover caminhos residuais de dual-authoring.
## Motivation
### Dor atual que esta PR resolve
1. Compiler ainda pode depender de representacao local paralela.
2. Teste de paridade atual com parse de `builtins.rs` e acoplamento fragil de formato.
3. Falta um caminho de consumo unico no pipeline backend.
## Target
Normalizar o lado compiler para source-of-truth unico:
1. `IRVMIntrinsicRegistry` carregando apenas o artefato canonico ISA,
2. remover/encapsular validacoes que dependem de parsing textual de runtime internals,
3. reforcar gate de consistencia do consumidor compiler.
## Dependencies
Prerequisito direto:
1. `PR-09.6`
## Scope
1. Ajustar `IRVMIntrinsicRegistry` para modo canonical-only.
2. Revisar testes de paridade:
- principal: paridade com artefato canonico,
- opcional/informativo: runtime-backed check separado.
3. Garantir mensagens de erro e diagnostico estaveis para registry invalido.
## Non-Goals
1. Nao alterar implementacao de intrinsics no runtime.
2. Nao mover ownership de docs runtime nesta PR.
## Method
### O que deve ser feito explicitamente
1. Consolidar parser/loader do registry no compiler com contrato estrito.
2. Substituir assercoes hardcoded por fixtures derivadas do artefato.
3. Separar teste de compatibilidade runtime:
- nao bloquear desenvolvimento local quando runtime repo ausente,
- bloquear em modo strict/CI quando configurado.
4. Atualizar docs de contribuicao do compiler para fluxo de update de intrinsics.
## Acceptance Criteria
1. Compiler nao tem mais fonte duplicada de mapping de intrinsic IDs.
2. `LowerToIRVMService` resolve IDs finais exclusivamente via artefato canonico.
3. Suite de testes backend cobre:
- carregamento valido,
- invalid registry,
- mismatch detectavel em strict mode.
## Tests
1. `:prometeu-compiler:prometeu-build-pipeline:test --tests *IRVMIntrinsicRegistry*`
2. `:prometeu-compiler:prometeu-build-pipeline:test --tests *LowerToIRVMServiceTest*`
3. `:prometeu-compiler:prometeu-build-pipeline:test --tests *BackendConformanceMatrixSpecTest*`
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
3. `docs/pbs/pull-requests/INDEX.md`
## Open Questions
1. Nenhuma bloqueante para lado compiler.
@@ -0,0 +1,69 @@
# PR-10.1 - PBS Parser Shared Context and Safe Delegation
## Briefing
`PbsParser` concentra estado compartilhado (`cursor`, `diagnostics`, `fileId`, `parseMode`, `loopDepth`) e responsabilidades de parsing em uma unica classe.
Esta PR introduz uma fundacao estrutural para decomposicao, sem alterar comportamento: um contexto compartilhado e pontos de delegacao seguros, mantendo `PbsParser` como fachada publica.
## Motivation
### Dor atual que esta PR resolve
1. Extracoes futuras dependem de copiar estado ou expor detalhes internos do parser.
2. O acoplamento entre navegação, diagnostico e parse impede quebrar a classe sem risco alto.
3. A refatoracao fica mais segura se a infraestrutura de compartilhamento vier antes da movimentacao de logica.
## Target
Estabelecer a base de refactor sem mudar funcionalidade:
1. Introduzir um contexto compartilhado para parser.
2. Encapsular helpers comuns de span/report/consume no contexto ou utilitarios proximos.
3. Permitir delegacao gradual para subparsers mantendo `PbsParser.parse(...)` como API unica.
## Dependencies
Nenhuma.
## Scope
1. Criar `ParserContext` ou equivalente com acesso a `cursor`, `diagnostics`, `fileId`, `parseMode` e `loopDepth`.
2. Mover helpers estruturais triviais para o contexto onde isso nao altere semantica.
3. Adaptar `PbsExprParser` bootstrap para consumir o mesmo contexto, ou uma visao compatível, sem mudar seu comportamento.
## Non-Goals
1. Nao alterar gramatica PBS.
2. Nao mover ainda parsing de tipos, atributos, blocos ou declaracoes para classes separadas.
3. Nao alterar mensagens, codigos de erro ou spans.
## Method
### O que deve ser feito explicitamente
1. Introduzir um objeto de contexto pequeno e explicito.
2. Manter `PbsParser` como orquestrador/fachada durante toda a PR.
3. Preservar o contrato de `parse(...)` e a ordem de consumo de tokens.
4. Validar que a nova camada e puramente estrutural.
## Acceptance Criteria
1. `PbsParser` continua sendo o unico entrypoint publico de parse.
2. Nenhum teste de parser, semantica ou frontend muda comportamento esperado.
3. Nao ha alteracao observavel em AST, spans ou diagnosticos.
4. A PR reduz acoplamento e prepara extracoes futuras sem mover regras complexas ainda.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. O `loopDepth` deve viver no contexto mutavel compartilhado ou em um helper especializado de block parsing? Esta PR pode manter no contexto; a decisao final pode vir na `PR-10.4`.
@@ -0,0 +1,70 @@
# PR-10.2 - PBS Parser Attribute and Type Subparsers
## Briefing
`PbsParser` ainda centraliza parsing de atributos, `typeRef` e `returnSpec`, que sao superficies coesas e amplamente reutilizadas.
Esta PR extrai essas responsabilidades para subparsers dedicados, sem alterar sintaxe aceita, AST produzido ou diagnosticos.
## Motivation
### Dor atual que esta PR resolve
1. `PbsParser` mistura topo de arquivo, declaracoes, blocos, atributos e tipos.
2. `parseTypeRef`, `parseAttribute*` e `parseCallableReturnSpec` sao hotspots claros de complexidade e reuso.
3. Sem extrair essa camada, as PRs seguintes continuam dependendo de uma classe central grande demais.
## Target
Separar parsing de tipos e atributos em colaboradores dedicados:
1. `PbsAttributeParser` ou equivalente.
2. `PbsTypeParser` ou equivalente.
3. Delegacao explicita a partir de `PbsParser`.
## Dependencies
Prerequisito direto:
1. `PR-10.1`
## Scope
1. Extrair `parseAttributeList`, `parseAttribute`, `parseAttributeArguments`, `parseAttributeArgument`, `parseAttributeValue`.
2. Extrair `parseTypeRef`, `parseNamedTupleTypeFields`, `parseCallableReturnSpec`, `parseReturnSpecFromMarker`, `isTypeStart`.
3. Preservar integralmente `PbsAst` e `ParseErrors`.
## Non-Goals
1. Nao alterar regras de atributos em modos `ORDINARY` e `INTERFACE_MODULE`.
2. Nao alterar aridade de named tuple.
3. Nao alterar recuperacao de erro alem do necessario para manter equivalencia.
## Method
### O que deve ser feito explicitamente
1. Mover parsing de atributos e tipos para classes pequenas, focadas e package-private.
2. Reusar o contexto compartilhado introduzido na PR anterior.
3. Manter `PbsParser` apenas como delegador nessas superficies.
4. Adicionar regressao para spans e diagnosticos de tipos/atributos se ainda nao houver cobertura suficiente.
## Acceptance Criteria
1. `PbsParser` deixa de implementar diretamente a maior parte do parsing de atributos e tipos.
2. AST e diagnosticos dessas superficies permanecem equivalentes.
3. A cobertura existente de parser continua verde sem mudancas semanticas.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsInterfaceModuleSemanticsTest*`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. Se `returnSpec` deve ficar no parser de tipos ou em um parser de callable surface. A recomendacao desta PR e manter em `PbsTypeParser`, porque o contrato de retorno depende diretamente de `typeRef`.
@@ -0,0 +1,73 @@
# PR-10.3 - PBS Parser Top-Level Declaration Decomposition
## Briefing
O maior concentrador de branching restante em `PbsParser` e a montagem de topo de arquivo e o dispatch de `declare ...`.
Esta PR extrai o parsing de declaracoes top-level e de corpos declarativos para colaboradores especificos, mantendo a mesma gramatica e o mesmo comportamento observavel.
## Motivation
### Dor atual que esta PR resolve
1. `parseFile` e `parseDeclareTopDecl` acumulam roteamento de muitas formas de declaracao.
2. Declaracoes como `host`, `builtin type`, `struct`, `contract`, `service`, `enum` e `implements` convivem no mesmo arquivo e elevam acoplamento.
3. Essa parte do parser muda com frequencia e hoje tem custo alto de manutencao.
## Target
Separar a camada de declaracoes top-level:
1. parsing de imports,
2. dispatch de `declare`,
3. parsing de corpos declarativos,
4. roteamento por `ParseMode`.
## Dependencies
Prerequisitos diretos:
1. `PR-10.1`
2. `PR-10.2`
## Scope
1. Extrair `parseFile` em conjunto com o dispatch de topo para um colaborador dedicado.
2. Extrair `parseDeclareTopDecl` e parsers correlatos (`host`, `builtin type`, `struct`, `contract`, `service`, `error`, `enum`, `callback`, `const`, `implements`).
3. Preservar o comportamento atual de atributos permitidos/proibidos por tipo de declaracao.
## Non-Goals
1. Nao alterar a ordem de imports/declarations no AST.
2. Nao alterar as regras de `INTERFACE_MODULE`.
3. Nao reescrever `PbsExprParser`.
## Method
### O que deve ser feito explicitamente
1. Criar um `PbsTopLevelParser` e um `PbsDeclarationParser`, ou divisao equivalente.
2. Manter em `PbsParser` apenas a montagem final da fachada e o fio de chamada principal.
3. Extrair por familias coesas de declaracao, evitando uma nova classe monolitica.
4. Preservar sincronia/recovery de topo no mesmo fluxo observavel.
## Acceptance Criteria
1. `parseFile` e `parseDeclareTopDecl` deixam de concentrar o dispatch completo de todas as declaracoes.
2. O parse de topo continua deterministico e equivalente ao estado anterior.
3. Testes de parser e frontend continuam verdes sem necessidade de atualizar fixtures por mudanca funcional.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsBarrelParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsInterfaceModuleSemanticsTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `implements` deve ficar junto de declaracoes top-level gerais ou em um parser especializado de contract/service surfaces? A recomendacao e mantê-lo no parser top-level por depender fortemente do roteamento de arquivo.
@@ -0,0 +1,74 @@
# PR-10.4 - PBS Parser Block and Statement Decomposition
## Briefing
Depois de extrair tipos/atributos e declaracoes top-level, o maior hotspot restante de `PbsParser` passa a ser parsing de blocos e statements.
Esta PR separa `block`, `statement`, `assignment`, `loop` e controle de fluxo em um parser dedicado, sem alterar a funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. `parseBlock`, `parseStatement`, `parseIfStatement`, `parseForStatement` e correlatos mantem alta complexidade e forte acoplamento com `loopDepth`.
2. A mistura de statement parsing com helpers de token/erro dificulta evolucao e leitura.
3. O parser de blocos e o ponto mais sensivel para regressao e precisa de uma fronteira estrutural clara.
## Target
Extrair a superficie de blocos e statements para um colaborador dedicado:
1. blocos,
2. statements estruturados,
3. assignment detection,
4. controle de `loopDepth`.
## Dependencies
Prerequisitos diretos:
1. `PR-10.1`
2. `PR-10.2`
3. `PR-10.3`
## Scope
1. Extrair `parseBlock`, `parseStatement`, `parseLetStatement`, `parseAssignStatement`, `parseLValue`.
2. Extrair `parseIfStatement`, `parseForStatement`, `parseWhileStatement`, `parseBreakStatement`, `parseContinueStatement`, `parseReturnStatement`.
3. Extrair `isAssignmentStatementStart` e helpers locais associados.
## Non-Goals
1. Nao alterar regras de tail expression.
2. Nao alterar precedence de expressoes.
3. Nao alterar as mensagens atuais de erro para loop control e assignment targets.
## Method
### O que deve ser feito explicitamente
1. Introduzir um `PbsBlockParser` ou equivalente.
2. Encapsular `loopDepth` dentro do contexto compartilhado ou de uma API pequena de entrada/saida de loop.
3. Reutilizar `PbsExprParser` como dependencia, sem alterar seu contrato.
4. Preservar spans e forma de recovery dentro de blocos.
## Acceptance Criteria
1. `PbsParser` deixa de conter a maior parte do parsing de blocos e statements.
2. `loopDepth` continua correto para `break` e `continue`.
3. Nenhum teste de parser, semantica de flow ou lowering sofre alteracao funcional.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserStatementsTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsFallthroughTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `isAssignmentStatementStart` deve permanecer no parser de bloco ou virar helper de cursor/lookahead. A recomendacao e mantê-lo no parser de bloco nesta PR e avaliar extração posterior apenas se necessário.
@@ -0,0 +1,80 @@
# PR-10.5 - PBS Parser Recovery Utilities and Regression Hardening
## Briefing
As PRs anteriores reduzem a complexidade estrutural de `PbsParser`. Esta PR fecha a trilha com consolidacao de recovery/utilitarios e endurecimento de regressao, ainda sem alterar funcionalidade.
O objetivo e evitar que a decomposicao introduza pequenas divergencias em diagnosticos, spans ou pontos de reinicio.
## Motivation
### Dor atual que esta PR resolve
1. Recovery e helpers de consumo sao sensiveis e podem ficar duplicados apos a extracao.
2. Sem cobertura adicional, uma refatoracao estrutural grande pode preservar testes principais e ainda mudar detalhes de parser.
3. O parser precisa terminar menor, mas tambem com fronteiras de manutencao claras.
## Target
Consolidar a etapa final do refactor:
1. recovery de topo e de atributos,
2. helpers de consumo/report,
3. regressao de spans/diagnosticos,
4. limpeza final de `PbsParser`.
## Dependencies
Prerequisitos diretos:
1. `PR-10.1`
2. `PR-10.2`
3. `PR-10.3`
4. `PR-10.4`
## Scope
1. Consolidar `consume`, `consumeForToken`, `consumeDeclarationTerminator`, `consumeBalancedBraces`, `synchronizeTopLevel` e recovery de atributo em utilitarios coesos.
2. Remover duplicacao residual entre subparsers.
3. Adicionar ou endurecer testes de regressao para:
- spans,
- erros esperados,
- recovery em topo e em bloco,
- modos `ORDINARY` e `INTERFACE_MODULE`.
## Non-Goals
1. Nao alterar taxonomia de `ParseErrors`.
2. Nao introduzir novas construcoes sintaticas.
3. Nao reescrever o lexer ou `PbsExprParser`.
## Method
### O que deve ser feito explicitamente
1. Fazer uma passada final de consolidacao estrutural.
2. Eliminar helpers obsoletos ou duplicados apos as extracoes.
3. Verificar equivalencia observavel com foco em spans e recovery.
4. Encerrar a trilha com `PbsParser` como fachada pequena e clara.
## Acceptance Criteria
1. `PbsParser` fica restrito a composicao/orquestracao e nao volta a concentrar logica de parse pesado.
2. Recovery e consumo de token ficam centralizados e sem duplicacao relevante.
3. Suite do frontend PBS passa integralmente.
4. Nao ha mudanca funcional observavel em parse, AST ou diagnosticos.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserStatementsTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. Nenhuma de arquitetura. A partir desta PR, qualquer mudanca adicional deve ser tratada como evolucao funcional separada, nao como parte do refactor estrutural.
@@ -0,0 +1,68 @@
# PR-11.1 - PBS Expr Parser Shared Context and Precedence Spine
## Briefing
`PbsExprParser` hoje concentra estado compartilhado, helpers basicos e toda a espinha de precedence em uma unica classe.
Esta PR introduz a fundacao estrutural para decompor o parser de expressoes sem alterar comportamento: contexto compartilhado, helpers comuns e uma organizacao mais clara da cadeia de precedence.
## Motivation
### Dor atual que esta PR resolve
1. Extracoes futuras dependem de duplicar acesso a `cursor`, `diagnostics`, `fileId` e `blockParserDelegate`.
2. A cadeia de precedence existe, mas toda a infraestrutura esta acoplada a uma unica classe.
3. Refatorar primeiro a fundacao reduz risco antes de mover control-flow e postfix/primary.
## Target
Estabelecer uma base segura para o refactor de `PbsExprParser`:
1. contexto compartilhado,
2. helpers de span/report/consume reutilizaveis,
3. espinha de precedence claramente separada do restante.
## Dependencies
Nenhuma.
## Scope
1. Introduzir `ExprParserContext` ou equivalente.
2. Encapsular `cursor`, `diagnostics`, `fileId` e `blockParserDelegate` nessa camada.
3. Reorganizar a espinha de precedence (`parseExpression`, `parseApply`, `parseOr`, `parseAnd`, `parseEquality`, `parseComparison`, `parseAs`, `parseTerm`, `parseFactor`, `parseUnary`) sem mudar a ordem semantica.
## Non-Goals
1. Nao alterar associatividade ou precedence.
2. Nao mover ainda parsing de `if/switch/handle`.
3. Nao alterar `PbsParser` nem `PbsTokenCursor`.
## Method
### O que deve ser feito explicitamente
1. Criar um contexto compartilhado pequeno e explicito.
2. Manter `PbsExprParser` como entrypoint package-private.
3. Preservar a ordem atual de chamadas na chain de precedence.
4. Validar que esta PR e puramente estrutural.
## Acceptance Criteria
1. `PbsExprParser` continua com o mesmo contrato de entrada/saida.
2. Precedence e associatividade permanecem equivalentes.
3. Nao ha mudanca observavel em AST, spans ou diagnosticos de expressoes.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `blockParserDelegate` deve continuar como callback simples ou migrar para interface mais rica de surface parsing? Nesta PR, manter callback simples minimiza risco.
@@ -0,0 +1,72 @@
# PR-11.2 - PBS Expr Parser Control-Flow Subparsers
## Briefing
As formas de expressao com maior branching em `PbsExprParser` sao `if`, `switch`, `handle` e `else`.
Esta PR extrai essas construcoes para subparsers dedicados, mantendo a mesma sintaxe, mesmos diagnosticos e o mesmo AST.
## Motivation
### Dor atual que esta PR resolve
1. `if/switch/handle` compartilham recovery, parsing de blocos e recursion, elevando bastante a complexidade local.
2. Essas formas sao semanticamente coesas e podem viver fora do parser principal de precedence.
3. Sem essa extracao, `PbsExprParser` continua grande mesmo apos separar a fundacao.
## Target
Separar parsing de expressoes de controle de fluxo:
1. `handle`,
2. `else`,
3. `if expression`,
4. `switch expression`.
## Dependencies
Prerequisito direto:
1. `PR-11.1`
## Scope
1. Extrair `parseHandle`, `parseHandlePattern`, `parseElse`, `parseIfExpression`, `parseIfExpressionFromToken`, `parseSwitchExpression`, `parseSwitchPattern`.
2. Preservar uso de `parseSurfaceBlock` para blocos de expressao.
3. Manter exatamente a precedence atual dessas superficies.
## Non-Goals
1. Nao alterar a regra de `if expression` exigir `else`.
2. Nao alterar curingas de `switch`.
3. Nao alterar formatos aceitos de `handle` e remapeamento de erro.
## Method
### O que deve ser feito explicitamente
1. Introduzir subparsers pequenos por familia de construcao.
2. Reusar o contexto compartilhado da PR anterior.
3. Garantir que `parseExpression()` continue entrando pela mesma superficie sintatica.
4. Proteger a equivalencia com testes focados em control-flow expressions.
## Acceptance Criteria
1. A logica de `if/switch/handle/else` nao fica mais centralizada em `PbsExprParser`.
2. ASTs gerados para essas construcoes permanecem equivalentes.
3. Diagnosticos de formas invalidas continuam com o mesmo contrato observavel.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserStatementsTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsResultFlowRulesTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `else` deve viver junto do control-flow parser ou continuar na espinha de precedence. A recomendacao e movê-lo junto porque a associatividade e as mensagens de erro fazem parte do mesmo cluster conceitual.
@@ -0,0 +1,74 @@
# PR-11.3 - PBS Expr Parser Postfix, Primary and Construction Decomposition
## Briefing
O segundo grande concentrador de complexidade em `PbsExprParser` esta nas superficies de `postfix` e `primary`: chamadas, membros, propagate, tuplas, blocos, `new`, `bind`, `some/ok/err`.
Esta PR separa essas familias em colaboradores menores, sem alterar a funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. `parsePostfix`, `parsePrimary` e `parseParenthesizedPrimary` misturam muitas formas sintaticas distintas.
2. Tuple literals, grouped expressions e construction surfaces compartilham lookahead delicado.
3. A manutencao dessas regras num unico metodo torna alto o custo de qualquer evolucao futura.
## Target
Separar parsing de superficies primarias e postfix:
1. postfix chaining,
2. primary literals/identifiers/blocks,
3. tuple/group handling,
4. construction/result surfaces (`new`, `bind`, `some`, `ok`, `err`).
## Dependencies
Prerequisitos diretos:
1. `PR-11.1`
2. `PR-11.2`
## Scope
1. Extrair `parsePostfix`.
2. Extrair `parsePrimary`, `parseParenthesizedPrimary`, `parseTupleItems`, `parseTupleItem`.
3. Extrair `parseNewExpression`, `parseBindExpression`, `parseSomeExpression`, `parseOkExpression`, `parseErrExpression`.
4. Preservar recovery atual para `?`, tuple malformed e parens.
## Non-Goals
1. Nao alterar a aridade de tuple literal.
2. Nao alterar mixed labeled/unlabeled tuple validation.
3. Nao alterar o formato aceito de `new Vec.zero(...)` e `bind(ctx, fn)`.
## Method
### O que deve ser feito explicitamente
1. Introduzir subparsers por familia sintatica em vez de criar um novo monolito.
2. Manter a ordem atual de postfix chaining.
3. Preservar lookahead de tuple/group exatamente como hoje.
4. Reforcar testes de tupla, construction e propagate operator invalido.
## Acceptance Criteria
1. `parsePostfix` e `parsePrimary` deixam de concentrar todas as superficies primarias.
2. Tuplas, grupos, constructions e postfix chains continuam equivalentes.
3. Nao ha mudanca funcional em AST, spans ou diagnosticos.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsOptionalResultTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsApplyResolutionTest*`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. O parsing de tuple/group deve ficar junto de primary ou em helper especializado de parenthesized surfaces. A recomendacao e extrair para helper especializado, porque esse e o trecho com lookahead mais sensivel.
@@ -0,0 +1,73 @@
# PR-11.4 - PBS Expr Parser Literals, Patterns and Shared Token Utilities
## Briefing
Depois de extrair control-flow e primary/postfix, restam em `PbsExprParser` alguns clusters menores mas sensiveis: parsing de literais/padroes, `error path`, consumo de tokens e utilitarios de parse numerico/string.
Esta PR consolida esses pontos em utilitarios dedicados, ainda sem mudanca funcional.
## Motivation
### Dor atual que esta PR resolve
1. Parsing de literal aparece em mais de um lugar (`primary` e switch pattern).
2. `error path`, `consumeMemberName`, `parseLong/Int/DoubleOrDefault` e `unescapeString` sao infra compartilhada e hoje permanecem acoplados ao parser principal.
3. Sem consolidar essa base, o parser termina menor, mas ainda com detalhes mecanicos espalhados.
## Target
Extrair infra compartilhada de expressao:
1. parsing de literais,
2. parsing de `error path`,
3. parsing de patterns simples,
4. token utilities e decode helpers.
## Dependencies
Prerequisitos diretos:
1. `PR-11.1`
2. `PR-11.2`
3. `PR-11.3`
## Scope
1. Extrair `parseLiteralPatternExpression`, `parseErrorPath`, `parseHandlePattern` e helpers correlatos.
2. Consolidar `consume`, `consumeMemberName`, `span`, `report`.
3. Consolidar `parseLongOrDefault`, `parseIntOrDefault`, `parseDoubleOrDefault`, `unescapeString`.
## Non-Goals
1. Nao alterar as regras de literal recovery.
2. Nao alterar o decode de strings.
3. Nao alterar a estrutura de `PbsAst.ErrorPath`.
## Method
### O que deve ser feito explicitamente
1. Reunir parsing de literal/pattern em componente reutilizavel.
2. Mover utilitarios mecanicos para helpers claros e pequenos.
3. Garantir que toda chamada mantenha a mesma atribuicao de spans e diagnosticos.
4. Evitar criar uma util-class genérica demais; manter helpers focados no dominio de expression parsing.
## Acceptance Criteria
1. `PbsExprParser` deixa de concentrar parsing repetido de literais/padroes e utilitarios basicos.
2. Parsing de strings, numeros e `error path` permanece equivalente.
3. A suite de parser continua verde sem atualizar comportamento esperado.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsDeclarationsTest*`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. Nenhuma de arquitetura. Esta PR e de consolidacao local.
@@ -0,0 +1,75 @@
# PR-11.5 - PBS Expr Parser Regression Hardening and Final Cleanup
## Briefing
As PRs anteriores reduzem a complexidade estrutural de `PbsExprParser`. Esta PR fecha a trilha com limpeza final, eliminacao de duplicacao residual e endurecimento de regressao, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. Refactors estruturais em parser de expressao podem mudar detalhes finos sem quebrar imediatamente todos os testes.
2. Ao final da decomposicao, costuma restar duplicacao pequena e helpers obsoletos.
3. O fechamento da trilha precisa garantir equivalencia observavel e uma fachada final pequena.
## Target
Concluir a trilha de refactor do parser de expressoes:
1. limpeza estrutural final,
2. consolidacao dos helpers remanescentes,
3. cobertura de regressao para precedence, postfix, tuples e control-flow expressions.
## Dependencies
Prerequisitos diretos:
1. `PR-11.1`
2. `PR-11.2`
3. `PR-11.3`
4. `PR-11.4`
## Scope
1. Remover codigo duplicado ou caminhos obsoletos apos as extracoes.
2. Garantir que `PbsExprParser` fique reduzido a composicao/orquestracao.
3. Expandir regressao quando necessario para spans, diagnosticos e precedence.
## Non-Goals
1. Nao alterar gramatica de expressoes.
2. Nao introduzir novas formas sintaticas.
3. Nao alterar `PbsAst` ou `ParseErrors`.
## Method
### O que deve ser feito explicitamente
1. Fazer uma passada final de consolidacao.
2. Verificar equivalencia com foco em:
- precedence,
- associatividade,
- tuple/group lookahead,
- control-flow expression recovery.
3. Encerrar a trilha com um `PbsExprParser` pequeno, claro e estavel.
## Acceptance Criteria
1. `PbsExprParser` termina como fachada/orquestrador, nao como concentrador de todas as regras.
2. Nao ha mudanca funcional observavel em AST, spans ou diagnosticos.
3. Suite do frontend PBS passa integralmente.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserStatementsTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. Nenhuma. A partir desta PR, qualquer ajuste restante deve ser tratado como mudanca funcional separada.
@@ -0,0 +1,69 @@
# PR-12.1 - Flow Expression Analyzer Context and Dispatch Foundation
## Briefing
`PbsFlowExpressionAnalyzer` concentra estado compartilhado e um dispatch grande de `Expression -> semantic analysis` em uma unica classe.
Esta PR introduz a base estrutural para decomposicao sem alterar funcionalidade: contexto compartilhado, helpers comuns e uma fronteira clara entre fachada e implementacoes especializadas.
## Motivation
### Dor atual que esta PR resolve
1. A classe combina orquestracao, recursion, block delegation e regras semanticas detalhadas.
2. Extracoes futuras ficam arriscadas sem um contexto compartilhado explicito.
3. O maior hotspot da classe e o dispatch principal de `analyzeExpressionInternal`, que hoje depende de muitos parametros repetidos.
## Target
Estabelecer uma fundacao segura para o refactor:
1. contexto compartilhado para analise de expressao,
2. encapsulamento de argumentos recorrentes,
3. fachada pequena em `PbsFlowExpressionAnalyzer`.
## Dependencies
Nenhuma.
## Scope
1. Introduzir um contexto/request object para `scope`, `expectedType`, `returnType`, `resultErrorName`, `receiverType`, `model`, `diagnostics`, `use` e `valueContext`.
2. Encapsular a dependencia de `BlockAnalyzer` nessa camada.
3. Reorganizar o dispatch principal sem mover ainda regras complexas para outras classes.
## Non-Goals
1. Nao alterar inferencia de tipos.
2. Nao alterar diagnosticos ou spans.
3. Nao reescrever `PbsFlowTypeOps` ou `PbsFlowBodyAnalyzer`.
## Method
### O que deve ser feito explicitamente
1. Criar um contexto pequeno e explicito para a analise recursiva.
2. Manter `PbsFlowExpressionAnalyzer` como entrypoint package-private.
3. Preservar a ordem atual de recursion e emissao de diagnosticos.
4. Garantir que esta PR seja puramente estrutural.
## Acceptance Criteria
1. `PbsFlowExpressionAnalyzer` continua com o mesmo contrato observavel.
2. A quantidade de parametros repetidos no dispatch recursivo e reduzida.
3. Nao ha mudanca funcional em inferencia, erros ou comportamento da suite.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsDeclarationsTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsAssignmentTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsApplyResolutionTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. O contexto deve ser imutavel por chamada recursiva ou permitir derivacao incremental. A recomendacao e usar derivacao imutavel leve para reduzir risco de regressao.
@@ -0,0 +1,71 @@
# PR-12.2 - Flow Expression Analyzer Literal and Structural Expression Splitting
## Briefing
Grande parte do dispatch de `PbsFlowExpressionAnalyzer` cobre formas literais e estruturais de expressao: literais, `this`, identificadores, grupos, tuplas, blocos, unarios, binarios, `none/some`, `new`, `as`, `ok/err`.
Esta PR extrai essas familias para componentes menores, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. O dispatch principal mistura casos triviais com regras mais complexas de call/member/switch/handle.
2. Formas estruturais simples podem ser separadas com risco baixo e alta reducao de complexidade.
3. Sem esse corte, o dispatch central continua inchado mesmo com contexto compartilhado.
## Target
Separar a analise de expressoes literais e estruturais:
1. literais e identificadores,
2. grupos, tuplas e blocos,
3. unario/binario,
4. `none/some`, `new`, `bind`-independent simple forms, `as`, `ok/err`.
## Dependencies
Prerequisito direto:
1. `PR-12.1`
## Scope
1. Extrair casos simples de `analyzeExpressionInternal` para helpers/colaboradores dedicados.
2. Manter o resultado em `ExprResult` exatamente como hoje.
3. Preservar todas as chamadas a `typeOps` e `blockAnalyzer`.
## Non-Goals
1. Nao alterar regras de callback/bind.
2. Nao alterar member access ou overload resolution.
3. Nao alterar switch/handle/result propagation.
## Method
### O que deve ser feito explicitamente
1. Mover primeiro os casos com menor acoplamento semantico.
2. Manter o dispatch principal apenas como roteador.
3. Preservar a ordem atual de recursion para evitar mudanca em diagnosticos acumulados.
## Acceptance Criteria
1. Casos literais e estruturais deixam de ficar todos dentro do dispatch principal.
2. AST/semantics observados pela suite permanecem equivalentes.
3. O hotspot principal da classe reduz tamanho e branching sem alterar comportamento.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsOptionalResultTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsDeclarationsTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `BindExpr` deve entrar aqui ou junto de call resolution. A recomendacao e mantê-lo para `PR-12.3`, porque ele depende de matching de callback/callable.
@@ -0,0 +1,72 @@
# PR-12.3 - Flow Expression Analyzer Call and Member Resolution Decomposition
## Briefing
`analyzeCallExpression`, `analyzeApplyExpression`, `resolveCallableApplication`, `analyzeMemberExpression` e parte de `BindExpr` concentram a logica de resolucao mais sensivel do analisador.
Esta PR extrai essa superficie para colaboradores menores, sem alterar regras de overload, bare method extraction, acesso a campos ou matching de callback.
## Motivation
### Dor atual que esta PR resolve
1. Member access e callable resolution sao os clusters mais densos depois do dispatch principal.
2. A classe mistura regras de acesso a tuple/struct/service/contract com overload resolution e bind matching.
3. Qualquer ajuste nessas regras hoje exige tocar um arquivo muito central e com alta chance de regressao.
## Target
Separar a analise de resolucao:
1. member access,
2. call/apply overload resolution,
3. bind-to-callback matching,
4. field access permission checks.
## Dependencies
Prerequisitos diretos:
1. `PR-12.1`
2. `PR-12.2`
## Scope
1. Extrair `analyzeCallExpression`, `analyzeApplyExpression`, `resolveCallableApplication`.
2. Extrair `analyzeMemberExpression` e `canReadStructField`.
3. Mover a parte especifica de `BindExpr` para o mesmo cluster de resolucao.
## Non-Goals
1. Nao alterar diagnosticos de overload ambiguous/unresolved.
2. Nao alterar regras de leitura de campo privado/publico.
3. Nao alterar a proibicao de bare method extraction.
## Method
### O que deve ser feito explicitamente
1. Criar um resolver focado em call/member semantics.
2. Preservar o mesmo uso de `TypeView`, `CallableSymbol` e `ExprResult`.
3. Garantir que o order of checks permaneça equivalente, especialmente em erros e narrowing por `expectedType`.
## Acceptance Criteria
1. Call/member resolution deixa de ficar concentrada em `PbsFlowExpressionAnalyzer`.
2. Bare method extraction, field access e overload matching permanecem equivalentes.
3. Suite semantica continua verde sem mudancas funcionais.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsApplyResolutionTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsAssignmentTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsFrontendCompilerTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `BindExpr` deve compartilhar exatamente o mesmo narrowing path de `call/apply` ou ficar em helper proprio. A recomendacao e helper proprio dentro do mesmo resolver, para evitar acoplamento artificial.
@@ -0,0 +1,73 @@
# PR-12.4 - Flow Expression Analyzer Switch and Handle Decomposition
## Briefing
`switch` e `handle` sao as maiores superfices especializadas restantes em `PbsFlowExpressionAnalyzer`, com regras de exaustividade, pattern typing, matching de erro e arm typing.
Esta PR separa essas construcoes em analisadores dedicados, mantendo exatamente o comportamento atual.
## Motivation
### Dor atual que esta PR resolve
1. `analyzeSwitchExpression` e `analyzeHandleExpression` concentram regras de alto branching e recovery semantico.
2. Essas regras sao semanticamente coesas e merecem fronteiras proprias.
3. Sem esse corte, a classe principal continua com os hotspots mais caros de manutencao.
## Target
Extrair a analise especializada de:
1. `switch expression`,
2. `switch pattern typing/keying`,
3. `handle expression`,
4. `handle block arm` e matching de error targets.
## Dependencies
Prerequisitos diretos:
1. `PR-12.1`
2. `PR-12.2`
3. `PR-12.3`
## Scope
1. Extrair `analyzeSwitchExpression`, `switchPatternKey`, `switchPatternType`.
2. Extrair `analyzeHandleExpression`, `analyzeHandleBlockArm`, `matchesTargetError`, `unwrapGroup`.
3. Preservar a interacao com `blockAnalyzer`, `typeOps` e `model`.
## Non-Goals
1. Nao alterar regras de exaustividade de switch em value position.
2. Nao alterar regras de wildcard/default duplication.
3. Nao alterar regras de `handle` para `ok(...)` / `err(...)` terminais.
## Method
### O que deve ser feito explicitamente
1. Criar analisadores especializados por construcao.
2. Preservar ordem de validacoes e diagnosticos.
3. Reusar o contexto compartilhado para evitar nova explosao de parametros.
## Acceptance Criteria
1. `switch` e `handle` deixam de ficar implementados diretamente na classe principal.
2. Exaustividade, arm typing e error matching permanecem equivalentes.
3. Nenhum teste de result flow, control flow ou optional/result muda comportamento esperado.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsResultFlowRulesTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsOptionalResultTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `switchPatternKey` e `switchPatternType` devem ficar juntos no mesmo colaborador. A recomendacao e sim, porque ambos definem a semantica da superficie de pattern.
@@ -0,0 +1,77 @@
# PR-12.5 - Flow Expression Analyzer Regression Hardening and Final Cleanup
## Briefing
As PRs anteriores reduzem a complexidade estrutural de `PbsFlowExpressionAnalyzer`. Esta PR fecha a trilha com consolidacao final, limpeza de duplicacao residual e endurecimento de regressao, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. Refactors estruturais em analise semantica podem preservar casos principais e ainda mudar detalhes finos de diagnostico.
2. Ao final da decomposicao, tendem a restar helpers redundantes ou caminhos duplicados.
3. O fechamento da trilha precisa garantir equivalencia observavel e uma fachada final pequena.
## Target
Concluir a trilha de refactor:
1. limpeza estrutural final,
2. consolidacao dos helpers remanescentes,
3. cobertura de regressao para inferencia e diagnosticos.
## Dependencies
Prerequisitos diretos:
1. `PR-12.1`
2. `PR-12.2`
3. `PR-12.3`
4. `PR-12.4`
## Scope
1. Remover duplicacao residual apos as extracoes.
2. Garantir que `PbsFlowExpressionAnalyzer` fique reduzido a composicao/orquestracao.
3. Reforcar testes de regressao para call/member resolution, result flow, switch e handle.
## Non-Goals
1. Nao alterar taxonomia de `PbsSemanticsErrors`.
2. Nao alterar `TypeView`, `ExprResult` ou `PbsFlowTypeOps`.
3. Nao introduzir novas regras semanticas.
## Method
### O que deve ser feito explicitamente
1. Fazer uma passada final de consolidacao.
2. Verificar equivalencia com foco em:
- inferencia de tipos,
- overload resolution,
- access checks,
- switch/handle exhaustiveness e matching,
- diagnosticos emitidos.
3. Encerrar a trilha com uma fachada pequena e clara.
## Acceptance Criteria
1. `PbsFlowExpressionAnalyzer` termina como orquestrador, nao como concentrador de toda a logica.
2. Nao ha mudanca funcional observavel em analise, tipos inferidos ou diagnosticos.
3. Suite do frontend PBS passa integralmente.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsApplyResolutionTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsResultFlowRulesTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsOptionalResultTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
5. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. Nenhuma. A partir desta PR, qualquer mudanca adicional deve ser tratada como evolucao funcional separada.
@@ -0,0 +1,67 @@
# PR-13.1 - Flow Body Analyzer Context and Entrypoint Foundation
## Briefing
`PbsFlowBodyAnalyzer` concentra montagem de contexto, iteracao de callables e delegacao recursiva de block/statement analysis em uma unica classe.
Esta PR introduz a base estrutural para decomposicao sem alterar funcionalidade: contexto compartilhado, encapsulamento dos argumentos recorrentes e uma fachada mais clara para a classe.
## Motivation
### Dor atual que esta PR resolve
1. A classe repassa muitos parametros repetidos entre `validate`, `validateCallableBody`, `analyzeBlock` e `analyzeStatement`.
2. Extracoes futuras ficam arriscadas sem um contexto comum explicito.
3. A fundacao estrutural reduz risco antes de mover regras de completion, statements e assignment resolution.
## Target
Estabelecer uma base segura para o refactor:
1. contexto compartilhado de body analysis,
2. encapsulamento de `returnType`, `resultErrorName`, `receiverType`, `model` e `diagnostics`,
3. fachada pequena para `validate(...)`.
## Dependencies
Nenhuma.
## Scope
1. Introduzir um contexto/request object para analise de corpo.
2. Reorganizar `validate` e `validateCallableBody` sem mover ainda regras complexas.
3. Preservar a relacao atual com `PbsFlowExpressionAnalyzer`.
## Non-Goals
1. Nao alterar inferencia de tipos ou diagnosticos.
2. Nao alterar `Model.from(...)`.
3. Nao mover ainda completion analysis ou assignment target resolution para classes separadas.
## Method
### O que deve ser feito explicitamente
1. Criar um contexto pequeno e explicito para analise recursiva de blocos/callables.
2. Manter `PbsFlowBodyAnalyzer` como entrypoint package-private.
3. Preservar a ordem atual de validacao e emissao de erros.
## Acceptance Criteria
1. `PbsFlowBodyAnalyzer` continua com o mesmo contrato observavel.
2. A quantidade de parametros repetidos nas chamadas internas e reduzida.
3. Nao ha mudanca funcional em flow analysis, completion ou diagnosticos.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsDeclarationsTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. O contexto deve ser derivado imutavelmente por bloco ou mutado localmente. A recomendacao e derivacao leve para reduzir risco de vazamento entre branches.
@@ -0,0 +1,71 @@
# PR-13.2 - Flow Body Analyzer Callable Body and Completion Decomposition
## Briefing
As regras de entrada de callable e de completion/fallthrough em `PbsFlowBodyAnalyzer` formam um cluster coeso, mas hoje ficam misturadas com statement analysis e assignment resolution.
Esta PR extrai essa superficie para colaboradores dedicados, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. `validateCallableBody`, `validateCallableCompletion`, `blockAlwaysReturns`, `statementAlwaysReturns`, `expressionAlwaysReturns`, `switchAlwaysReturns` e `handleAlwaysReturns` concentram regras de completion com alto branching.
2. Completion analysis e statement analysis sao preocupacoes diferentes e hoje dividem a mesma classe.
3. Essa parte e muito sensivel e merece uma fronteira estrutural propria.
## Target
Separar a camada de body entry/completion:
1. bootstrap de callable body,
2. validacao de fallthrough/completion,
3. regras de `always returns`,
4. exaustividade relevante para completion.
## Dependencies
Prerequisito direto:
1. `PR-13.1`
## Scope
1. Extrair `validateCallableBody`.
2. Extrair `validateCallableCompletion`, `blockAlwaysReturns`, `statementAlwaysReturns`, `expressionAlwaysReturns`.
3. Extrair `switchAlwaysReturns`, `switchIsExhaustive`, `handleAlwaysReturns`, `handleArmAlwaysReturns`, `isKnownErrorPath`.
## Non-Goals
1. Nao alterar as regras atuais de fallthrough para result/plain non-unit.
2. Nao alterar a semantica de exaustividade usada apenas para completion.
3. Nao alterar statement analysis ou assignment checks.
## Method
### O que deve ser feito explicitamente
1. Introduzir um analisador de completion ou divisao equivalente.
2. Manter `PbsFlowBodyAnalyzer` como orquestrador do processo.
3. Preservar rigorosamente a ordem atual de checks e codigos de diagnostico.
## Acceptance Criteria
1. A logica de completion/fallthrough deixa de ficar centralizada em `PbsFlowBodyAnalyzer`.
2. As regras de `always returns` permanecem equivalentes.
3. Nenhum teste de fallthrough, control flow ou result flow muda comportamento esperado.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsFallthroughTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsResultFlowRulesTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `switch`/`handle` completion deve ficar junto do completion analyzer ou reaproveitar colaboradores do expression analyzer. A recomendacao e manter local ao completion analyzer para evitar acoplamento indevido entre analise de tipo e analise de terminacao.
@@ -0,0 +1,72 @@
# PR-13.3 - Flow Body Analyzer Statement Analysis Splitting
## Briefing
Depois de separar entry/completion, o maior hotspot restante em `PbsFlowBodyAnalyzer` passa a ser `analyzeBlock` e `analyzeStatement`, com tratamento de `let`, `return`, `if`, `for`, `while`, expression statement e delegacao para `PbsFlowExpressionAnalyzer`.
Esta PR extrai essa superficie para colaboradores menores, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. `analyzeStatement` concentra varias formas de statement com regras semanticas distintas.
2. Loops, `if` e `return` usam os mesmos parametros e diagnosticos, mas pertencem a clusters semanticos diferentes.
3. A manutencao dessa logica em um unico metodo torna a classe dificil de evoluir.
## Target
Separar a analise de statements:
1. blocos e escopos,
2. `let` e expression statements,
3. `return` flow,
4. `if/for/while`.
## Dependencies
Prerequisitos diretos:
1. `PR-13.1`
2. `PR-13.2`
## Scope
1. Extrair `analyzeBlock` e o dispatch de `analyzeStatement`.
2. Extrair regras de `let`, `if`, `for`, `while` e expression statement para helpers/colaboradores dedicados.
3. Deixar `return` bootstrap pronto para corte proprio, sem ainda mexer em assignment target resolution.
## Non-Goals
1. Nao alterar mutabilidade de escopo local.
2. Nao alterar validacao de tipos de condicao ou bounds de loop.
3. Nao alterar assignment resolution.
## Method
### O que deve ser feito explicitamente
1. Introduzir um statement analyzer ou divisao equivalente por familias.
2. Reusar o contexto compartilhado da `PR-13.1`.
3. Preservar a ordem atual de chamadas ao `expressionAnalyzer`.
## Acceptance Criteria
1. `analyzeStatement` deixa de concentrar todas as formas de statement.
2. Scoping, condition checks e loop bound checks permanecem equivalentes.
3. Suite semantica continua verde sem mudanca funcional.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsAssignmentTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsDeclarationsTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `return` deve ficar no statement analyzer ou em um colaborador proprio de result flow. A recomendacao e deixar o corte final para a PR seguinte se isso simplificar mais a classe.
@@ -0,0 +1,72 @@
# PR-13.4 - Flow Body Analyzer Assignment Target Resolution Decomposition
## Briefing
`resolveAssignmentTarget` e a logica correlata de assignment compatibility concentram um dos trechos mais densos e sensiveis de `PbsFlowBodyAnalyzer`.
Esta PR extrai a resolucao de assignment target e as regras de acesso/leitura/escrita de campo para colaboradores dedicados, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. Assignment resolution mistura lookup de locals, `this`, singleton services, consts e navegação em campos de struct.
2. Regras de leitura e escrita de campo estao acopladas ao fluxo do statement analyzer.
3. A superficie e densa e merece um resolver proprio com foco em diagnósticos de assignability.
## Target
Separar a camada de assignment semantics:
1. resolucao de assignment target,
2. assignability de roots conhecidos,
3. leitura/escrita de campos,
4. type compatibility por operador de atribuicao.
## Dependencies
Prerequisitos diretos:
1. `PR-13.1`
2. `PR-13.2`
3. `PR-13.3`
## Scope
1. Extrair `analyzeAssignmentStatement`.
2. Extrair `resolveAssignmentTarget`, `assignmentCompatible`, `canReadStructField`, `canWriteStructField`, `isKnownNonAssignableRoot`.
3. Manter `AssignmentTargetResolution` ou mover para um modelo focado de assignment.
## Non-Goals
1. Nao alterar regras de mutabilidade/local const.
2. Nao alterar regras de acesso a campos privados/publicos.
3. Nao alterar o mapeamento de operadores compostos para inferencia binaria.
## Method
### O que deve ser feito explicitamente
1. Criar um resolver dedicado para assignment targets.
2. Preservar exatamente os mesmos erros emitidos para target nao resolvido, nao assignable ou field access denied.
3. Reusar `PbsFlowTypeOps` sem alterar sua logica.
## Acceptance Criteria
1. Assignment target resolution deixa de ficar centralizada em `PbsFlowBodyAnalyzer`.
2. Regras de assignability e field access permanecem equivalentes.
3. Nenhum teste de assignment ou control flow muda comportamento esperado.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsAssignmentTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsDeclarationsTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `AssignmentTargetResolution` deve permanecer como record local ou migrar para um modelo package-private dedicado. A recomendacao e mover para o resolver de assignment para reduzir acoplamento.
@@ -0,0 +1,77 @@
# PR-13.5 - Flow Body Analyzer Regression Hardening and Final Cleanup
## Briefing
As PRs anteriores reduzem a complexidade estrutural de `PbsFlowBodyAnalyzer`. Esta PR fecha a trilha com consolidacao final, limpeza de duplicacao residual e endurecimento de regressao, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. Refactors estruturais em flow/body analysis podem preservar casos principais e ainda mudar detalhes finos de diagnostico ou scoping.
2. Ao final da decomposicao, tendem a restar helpers redundantes ou caminhos duplicados.
3. O fechamento da trilha precisa garantir equivalencia observavel e uma fachada final pequena.
## Target
Concluir a trilha de refactor:
1. limpeza estrutural final,
2. consolidacao dos helpers remanescentes,
3. cobertura de regressao para completion, statements e assignment semantics.
## Dependencies
Prerequisitos diretos:
1. `PR-13.1`
2. `PR-13.2`
3. `PR-13.3`
4. `PR-13.4`
## Scope
1. Remover duplicacao residual apos as extracoes.
2. Garantir que `PbsFlowBodyAnalyzer` fique reduzido a composicao/orquestracao.
3. Reforcar testes de regressao para fallthrough, return flow, loops e assignments.
## Non-Goals
1. Nao alterar taxonomia de `PbsSemanticsErrors`.
2. Nao alterar `PbsFlowTypeOps` ou `PbsFlowExpressionAnalyzer`.
3. Nao introduzir novas regras semanticas.
## Method
### O que deve ser feito explicitamente
1. Fazer uma passada final de consolidacao.
2. Verificar equivalencia com foco em:
- completion/fallthrough,
- scoping local,
- return result flow,
- assignment target resolution,
- field access diagnostics.
3. Encerrar a trilha com uma fachada pequena e clara.
## Acceptance Criteria
1. `PbsFlowBodyAnalyzer` termina como orquestrador, nao como concentrador da logica completa.
2. Nao ha mudanca funcional observavel em flow analysis ou diagnosticos.
3. Suite do frontend PBS passa integralmente.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsFallthroughTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsAssignmentTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsResultFlowRulesTest*`
5. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. Nenhuma. A partir desta PR, qualquer mudanca adicional deve ser tratada como evolucao funcional separada.
+78
View File
@@ -0,0 +1,78 @@
# PBS Pull Requests
This directory contains self-contained PBS change proposals for review.
## Purpose
A pull request document packages a proposed change so it can be reviewed as a coherent unit before final integration.
Use this directory when a change:
- touches multiple documents,
- changes architecture or semantics,
- needs explicit review criteria,
- or should be assessed before editing the final normative corpus.
Architecture and decisions come before implementation.
## Required Properties
Every pull request document must be self-contained.
A reviewer should be able to understand the proposal without reconstructing context from chat history or scattered notes.
## Required Sections
Each pull request should include, at minimum:
1. Briefing
2. Target
3. Method
4. Acceptance Criteria
5. Tests, when needed
Recommended additional sections:
6. Motivation
7. Scope
8. Non-Goals
9. Affected Documents
10. Open Questions
## Section Expectations
### Briefing
Summarize the problem and the proposed change in a short, readable form.
### Target
State exactly what documents, behaviors, or contracts the proposal changes.
### Method
Explain the architectural and editorial approach.
If the proposal depends on prior decisions, name them explicitly.
### Acceptance Criteria
List the conditions that must be true for the proposal to be accepted.
These should be specific and reviewable.
### Tests
Include tests when the change affects executable behavior, conformance, verification, lowering, or observable runtime semantics.
If tests are not necessary, say why.
## Writing Rules
- Keep the proposal self-contained.
- Prefer explicit architectural reasoning over implementation detail.
- Do not bury acceptance criteria inside prose.
- Do not assume unresolved details.
- If a required decision is missing, stop and raise the question instead of inferring an answer.
## Review Rule
A pull request may propose implementation consequences, but it must not smuggle in unresolved architectural choices as implementation details.
@@ -0,0 +1,94 @@
# PBS Language Charter
Status: Draft v1
Applies to: Prometeu Base Script (PBS) language design
## 1. Mission
PBS exists to make 2D game development on Prometeu intuitive for beginners and reliable for experienced developers, without sacrificing deterministic runtime behavior.
## 2. Product Vision
PBS is a game-first language for a logical, evolving hardware platform.
It must feel fluid for frame-driven gameplay code while remaining strict enough to produce stable, verifiable bytecode for a closed VM target.
## 3. Target Users
- Beginner creators building their first playable 2D games.
- Intermediate developers shipping complete games with predictable behavior.
- Advanced developers who need explicit control of architecture and performance costs.
## 4. Core Principles
1. Game-first ergonomics: common gameplay patterns must be concise.
2. Determinism first: same program + same inputs/events => same behavior.
3. Explicit boundaries: host interaction, costs, and side effects must be visible.
4. Safe defaults: simple code paths should be hard to misuse.
5. Progressive power: advanced control is opt-in, not mandatory.
6. Compatibility discipline: language evolution must not silently break cartridges.
## 5. Scope of PBS v1
- Stable core syntax and grammar contract.
- Static and dynamic semantics for deterministic game code.
- Toolchain-managed host binding model aligned with syscall/capability model.
- Module visibility and import model suitable for multi-file game projects.
- Diagnostics and conformance requirements for interoperable implementations.
## 6. Out of Scope for PBS v1
- New VM opcodes as a language requirement.
- Non-deterministic async execution models.
- Mandatory custom allocator model replacing runtime GC.
- Explicit lifetime-control syntax before an explicit future design and profile activation.
- User-authored declaration of canonical host primitive bindings outside reserved SDK/toolchain `declare host` surfaces.
## 7. Non-Negotiable Constraints
- Runtime and bytecode authority override language preferences.
- Closed VM compatibility is mandatory.
- `FRAME_SYNC`-based execution semantics are preserved.
- Host API usage remains capability-gated and versioned.
- Canonical host primitive bindings remain reserved to SDK/toolchain-controlled `declare host` surfaces.
## 8. Evolution Commitments
- Additive-first evolution for minor releases.
- Incompatible changes only in major lines with migration guidance.
- Canonical host primitive versioning by `(module, name, version)`.
- User-facing host-backed APIs evolve through SDK/stdlib surfaces, not direct user-authored host-binding declarations outside reserved `declare host` modules.
- Deterministic loader rejection when target contracts are unsupported.
## 9. Quality Bar
PBS is considered healthy only if:
- newcomers can produce a working 2D game loop quickly,
- generated behavior is deterministic and replayable,
- diagnostics are stable and actionable,
- performance risks are visible in tooling,
- older supported cartridges keep running across updates.
## 10. Required Spec Set Before Implementation
Before implementation starts, PBS must define at least:
1. Core Syntax Specification.
2. Static Semantics Specification.
3. Dynamic Semantics Specification.
4. Memory and Lifetime Specification.
5. Host ABI Binding Specification.
6. Module/Package Specification.
7. AST Specification.
8. Diagnostics Specification.
9. Lowering IRBackend Specification.
10. Shared acceptance specs in `docs/general/specs` (Conformance, Compatibility, Verification).
## 11. Decision Rule
When trade-offs appear, decisions must prioritize, in order:
1. Determinism and compatibility.
2. Clarity for beginners.
3. Fluency for real game workflows.
4. Performance transparency for advanced users.
@@ -0,0 +1,341 @@
# PBS Memory and Lifetime Specification
Status: Draft v1 (Temporary)
Applies to: runtime memory spaces, value representation classes, identity, aliasing, GC baseline, host-memory boundaries, and cost visibility in PBS core
## 1. Purpose
This document defines the authoritative PBS memory and lifetime model for v1.
Its purpose is to make the language's runtime storage model explicit enough that:
- implementations agree on the current core value categories,
- identity and aliasing are not left implicit,
- GC remains compatible with deterministic execution,
- the VM heap and host-owned memory boundary stay understandable,
- tooling can surface runtime-visible memory and allocation costs consistently.
## 2. Scope
This document defines:
- runtime memory spaces relevant to PBS user semantics,
- value categories and their representation classes,
- identity, aliasing, and copy behavior,
- baseline GC guarantees and non-guarantees,
- host-memory boundary rules,
- memory-related safety invariants and remaining runtime failure boundaries,
- hooks that later diagnostics and tooling may rely on for cost reporting.
This document does not define:
- exact GC algorithm internals,
- general-purpose allocator APIs,
- future explicit lifetime syntax activation,
- final IR lowering details,
- subsystem-specific host resource APIs.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `1. Language Charter.md`
4. `3. Core Syntax Specification.md`
5. `4. Static Semantics Specification.md`
6. `9. Dynamic Semantics Specification.md`
7. This document
If a rule here conflicts with higher authority, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `1. Language Charter.md`
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `9. Dynamic Semantics Specification.md`
This document integrates the following accepted decisions:
- `docs/pbs/decisions/Value Representation and Identity Decision.md`
- `docs/pbs/decisions/GC and Reachability Decision.md`
- `docs/pbs/decisions/Host Memory Boundary Decision.md`
- `docs/pbs/decisions/Allocation and Cost Visibility Decision.md`
- `docs/pbs/decisions/Lifetime Control and Future Profiles Decision.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- 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.
- Core PBS v1 does not expose explicit lifetime-control syntax in ordinary user code.
## 6. Runtime Memory Spaces
PBS v1 distinguishes, at minimum:
1. VM-managed runtime storage used for GC-managed values and retained runtime state.
2. Stack-like transient value flow used for ordinary value exchange during evaluation.
3. Host-owned memory and resources that remain outside ordinary PBS userland memory semantics.
The VM heap and host-owned memory remain distinct in the user model.
Cross-boundary host/userland interaction is value-based rather than memory-sharing-based.
## 7. Value Representation Classes
### 7.1 Pure copied values
The following value kinds are pure copied values in the user model:
- `int`
- `float`
- `bool`
- enum values
- canonical `str`
Assignment, parameter passing, and return of these values copy the value itself.
### 7.2 Identity-bearing values
The following value kinds carry stable user-visible identity:
- struct values
- service values
- host-backed resource values on the PBS side
Assignment, parameter passing, and return of these values preserve aliasing to the same runtime entity rather than copying an independent underlying object.
### 7.3 Carrier-only values
The following value kinds are carriers and do not introduce identity of their own:
- tuples
- `optional`
- `result`
If a carrier contains an identity-bearing payload, the carrier transports that same payload identity rather than inventing a new one.
### 7.4 Contract values
Contract values do not introduce a new user-visible identity distinct from the underlying struct or service value.
They are runtime views over an underlying identity-bearing value together with the selected contract implementation used for dispatch.
### 7.5 Callback values
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.
## 8. Identity, Aliasing, and Copy Behavior
### 8.1 Structs
Struct values are always reference-like in PBS v1.
Rules:
- `new Struct(...)` produces a fresh struct identity.
- Assignment of a struct value copies the reference, not the underlying field storage.
- Passing or returning a struct value preserves aliasing to the same struct instance.
- Mutation through one alias is observable through other aliases to that same struct instance.
### 8.2 Services
Service values denote the same canonical singleton identity wherever used in the same resolved program.
Assignment, parameter passing, and return preserve that same singleton identity.
### 8.3 Carriers
`optional`, `result`, and tuples preserve the semantics of their contained values.
Examples:
- assigning an `optional<Player>` that contains `some(player)` preserves the same `Player` identity inside the carrier,
- assigning a `result<E> Player` success payload preserves the same `Player` identity inside the carrier.
### 8.4 General rule
The general rule for PBS v1 is:
- pure value kinds are copied by value,
- identity-bearing kinds preserve aliasing,
- carrier kinds preserve the semantics of their contained values and do not create identity of their own.
## 9. GC Baseline
### 9.1 Reachability
GC is the baseline runtime model for VM-owned memory in PBS core.
For GC-managed VM-owned values, liveness is defined by reachability from the runtime roots that matter to PBS semantics.
At minimum, those roots include:
- currently active local/frame state,
- reachable fields of reachable struct instances,
- service singleton roots,
- retained callback state that remains reachable,
- and any other runtime roots required to preserve already-observable PBS behavior.
If a GC-managed value remains reachable through the normative runtime state, the implementation must preserve its continued semantic availability.
### 9.2 Reclamation
PBS v1 guarantees eventual reclamation, not prompt reclamation.
The language does not promise:
- immediate reclamation,
- reclamation at a specific frame boundary,
- or a semantic event when reclamation occurs.
### 9.3 Safepoint relationship
`FRAME_SYNC` is the only normative safepoint in PBS v1.
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.
### 9.4 Observability
User code cannot observe reclamation directly.
PBS v1 provides no user-visible mechanism for:
- detecting that a value was collected,
- registering a callback on reclamation,
- forcing immediate collection,
- sequencing user code against collector timing.
PBS v1 defines no user-authored finalizers or destructor-like reclamation hooks.
## 10. Host Memory Boundary
The host/userland boundary in PBS v1 is value-based rather than memory-sharing-based.
Cross-boundary interaction between host and PBS userland is restricted to stack-only values.
PBS userland does not expose host memory as ordinary language values.
PBS v1 does not expose:
- raw host pointers,
- borrowed host-memory views,
- pinning,
- zero-copy transfer,
- shared heap objects spanning host memory and VM memory.
Long-lived host resources, if later exposed, must be specified by subsystem contract rather than inferred from a general host-memory-handle model in core PBS.
## 11. Cost Visibility Hooks
### 11.1 Normatively relevant cost facts
The normatively relevant cost facts in PBS v1 are:
- whether an operation may allocate VM-owned runtime storage,
- whether an operation retains state beyond the current evaluation,
- whether an operation copies payload versus preserves aliasing,
- whether an operation crosses the host boundary,
- whether an operation may trap.
### 11.2 `bind`
`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.
### 11.3 Non-allocation-bearing surfaces by themselves
The following constructs are not allocation-bearing by themselves in PBS v1:
- `optional`
- `result`
- `handle`
- `!`
- `if`
- `switch`
- `apply`
If allocation or retention occurs while evaluating one of these constructs, that cost arises from:
- subexpression evaluation,
- called targets,
- payload formation already defined elsewhere,
- or runtime behavior outside the surface itself.
### 11.4 Quantitative reporting
The language does not normatively guarantee:
- exact byte counts,
- exact object counts,
- exact collector timing,
- exact host-side allocation volume,
- precise performance ranking.
Those belong to diagnostics/profiling quality rather than to the core language contract.
## 12. Future Lifetime Control Policy
PBS v1 adopts the following policy:
- no dormant lifetime-control keyword is preserved merely for speculative future use,
- advanced memory workflows should default to library/tooling-first exploration,
- future explicit lifetime-oriented syntax, if introduced at all, must be profile-gated and justified by real need rather than by historical inertia.
Core PBS v1 does not promise future activation of legacy RC/HIP-style syntax.
## 13. Beginner-Facing Model
The user-facing explanation should be:
- some values are plain data, so passing them passes the value,
- structs and services are shared entities, so passing them passes access to the same entity,
- tuples, `optional`, and `result` only package values and do not become new entities by themselves,
- the runtime keeps reachable GC-managed values alive,
- the program does not directly hold or manipulate host memory.
## 14. TODO
The following items remain editorial or adjacent-spec integration tasks rather than open memory-model agenda questions:
- subsystem-specific wording for long-lived host resources if those are later introduced,
- diagnostics-specific wording for cost warnings and notes,
- future profile mechanics if an explicit lifetime profile is ever proposed.
## 15. Non-Goals
- Designing full pool, arena, or weak-reference libraries in this pass.
- Reintroducing mandatory user-authored lifetime syntax in core v1.
- Defining exact collector implementation strategy.
- Rewriting already-settled source syntax beyond what is required for consistency with accepted decisions.
## 16. Exit Criteria
This document is ready to move beyond temporary draft status only when:
1. every current core value category has explicit representation and aliasing wording,
2. GC guarantees and non-guarantees are separated clearly,
3. the VM heap versus host-memory boundary is normatively described,
4. memory-related cost facts are specified well enough for diagnostics/tooling hooks,
5. the remaining TODO items are reduced to editorial integration or future optional work rather than semantic uncertainty.
@@ -0,0 +1,160 @@
# PBS AST Specification
Status: Draft v1
Applies to: canonical AST contract emitted by PBS parser/frontend before IRBackend lowering
## 1. Purpose
This document defines the mandatory AST contract between PBS parsing and frontend lowering to `IRBackend`.
The contract is obligations-first: implementations may choose any internal representation, but must expose equivalent observable AST behavior and invariants.
## 2. Scope
This document defines:
- AST root and ordering invariants,
- mandatory node families for declarations, statements, and expressions in the supported v1 slice,
- mandatory node attribution and declaration metadata,
- deterministic rejection and recovery boundaries,
- and Gate U evidence obligations for AST conformance.
This document does not define:
- static-semantics algorithms,
- runtime/bytecode/verifier behavior,
- or `IRBackend -> IRVM` lowering.
## 3. Authority and Precedence
Normative precedence:
1. `3. Core Syntax Specification.md`
2. `4. Static Semantics Specification.md`
3. `12. Diagnostics Specification.md`
4. This document
5. `13. Lowering IRBackend Specification.md`
If a rule here conflicts with a higher-precedence source, the higher-precedence rule wins.
## 4. Normative Inputs
This document depends on:
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `12. Diagnostics Specification.md`
- `13. Lowering IRBackend Specification.md`
## 5. AST Contract Model
The AST contract is defined by required observable behavior, not by one mandatory class hierarchy or parser architecture.
Conformance is implementation-language agnostic.
## 6. Root and Structural Invariants
Parser output must satisfy all of the following:
1. exactly one AST root per source file;
2. deterministic child ordering consistent with source order;
3. preserved declaration and lexical block hierarchy;
4. parent/child span integrity (no structurally impossible attribution relationships);
5. no post-parse AST rewrite that changes source-observable parse meaning.
## 7. Mandatory Attribution and Declaration Metadata
Every node consumed by diagnostics or lowering must carry stable source attribution:
- `file`,
- `start`,
- `end`.
Mandatory declaration metadata on required declaration nodes includes:
1. declaration name,
2. declared signature/surface when applicable (parameters/return),
3. declaration-level syntactic flags/attributes required by later phases,
4. stable `file/start/end` attribution.
Missing required attribution or metadata on mandatory nodes is non-conformant.
## 8. Mandatory Declaration Families
The v1 AST must represent, at minimum, declaration families for:
- imports,
- top-level `fn`,
- `struct`,
- `contract`,
- `service`,
- `error`,
- `enum`,
- `callback`,
- `declare const`,
- and declaration nodes required by barrel/linking flow.
Declaration identity must be preserved at AST boundary; implementations must not prematurely merge/collapse declarations (including overload sets).
## 9. Mandatory Statement and Expression Families
The v1 AST must represent statement/expression families for the supported core syntax slice, including at minimum:
- statements: `block`, `let`, `return`, expression statement;
- expressions: `identifier`, literals, `unary`, `binary`, `call`, `group`.
Additional supported forms required by `3` are also in scope for explicit node representation.
## 10. Precedence, Associativity, and Rejection
Precedence and associativity outcomes are normative through AST shape.
Rules:
1. accepted forms must preserve parse outcome explicitly in AST shape;
2. non-associative or forbidden chained forms are deterministic reject with stable diagnostics;
3. unsupported forms outside the active source slice are deterministic reject;
4. unsupported/invalid forms must not be masked by permissive synthetic nodes that imply accepted semantics.
## 11. Recovery and Diagnostics Integration
Parser recovery may continue after syntax errors for diagnostic collection, but recovered AST must remain:
- structurally coherent,
- attribution-consistent,
- and non-permissive (must not fabricate valid semantics that hide required rejection).
AST-facing diagnostics must follow `12` identity and attribution rules.
For conformance, required diagnostic identity is keyed by stable machine fields, not rendered sentence text.
## 12. Conformance and Gate U Evidence
AST conformance evidence is provided through Gate U fixtures as defined in `docs/general/specs/13. Conformance Test Specification.md`.
At minimum, Gate U must include:
1. representative valid AST fixtures for mandatory declaration/statement/expression families;
2. malformed/recovery fixtures with deterministic rejection assertions;
3. attribution assertions (`file/start/end`) on required nodes;
4. precedence/associativity shape assertions for representative expressions;
5. mandatory negative families:
- unexpected token in declaration context,
- missing required closer (`)`, `}`, or `;`) as applicable,
- forbidden non-associative chains,
- unsupported forms outside the active syntax slice.
## 13. Non-Goals
- Freezing one parser implementation architecture.
- Replacing static semantics/linking decisions with AST-only rules.
- Defining backend/runtime/bytecode/verifier behavior.
## 14. Exit Criteria
This document is healthy when:
1. mandatory AST families and metadata are explicit,
2. recovery/rejection invariants are explicit and test-backed,
3. attribution invariants are explicit and test-backed,
4. lowering preconditions consumed by `13` are unambiguous.
@@ -0,0 +1,243 @@
# PBS Diagnostics Specification
Status: Draft v1
Applies to: deterministic diagnostics emitted by PBS-facing tooling across parsing, static analysis, manifest/import resolution, linking, host-admission checks, and load-facing validation surfaces
## 1. Purpose
This document defines the PBS diagnostics baseline for v1.
Its purpose is to make diagnostics stable enough that:
- conforming tools report failures in the same phases,
- users receive deterministic and actionable source-facing feedback,
- diagnostics remain machine-identifiable even when rendered in different locales,
- conformance can validate rejection class and attribution,
- and frontend, linking, manifest, and load-facing validation remain aligned.
## 2. Scope
This document defines:
- the required external diagnostic phases,
- the minimum machine-readable identity of a PBS-facing diagnostic,
- the minimum source-facing payload and attribution baseline,
- the boundary between normative diagnostic fields and implementation-defined rendering,
- the boundary between PBS-facing diagnostics and artifact/tooling failures,
- and the warning/cost-diagnostics boundary for v1.
This document does not define:
- a full runtime trap catalog,
- UI presentation or IDE styling,
- one exact localized sentence for every diagnostic,
- one transport-specific schema such as LSP field mapping,
- one standardized source-map or artifact-offset format,
- or profiling/reporting formats.
## 3. Authority and Precedence
Normative precedence:
1. `1. Language Charter.md`
2. `3. Core Syntax Specification.md`
3. `4. Static Semantics Specification.md`
4. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
5. `6.2. Host ABI Binding and Loader Resolution Specification.md`
6. `7. Cartridge Manifest and Runtime Capabilities Specification.md`
7. `9. Dynamic Semantics Specification.md`
8. `10. Memory and Lifetime Specification.md`
9. `13. Lowering IRBackend Specification.md`
10. This document
If a diagnostic rule here contradicts a normative acceptance/rejection rule in a higher-precedence document, the higher-precedence document wins.
## 4. Normative Inputs
This document depends on, at minimum:
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `5. Manifest, Stdlib, and SDK Resolution Specification.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `7. Cartridge Manifest and Runtime Capabilities Specification.md`
- `9. Dynamic Semantics Specification.md`
- `10. Memory and Lifetime Specification.md`
- `13. Lowering IRBackend Specification.md`
Relevant backend-facing integration points also include:
- `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
- `docs/general/specs/16. Runtime Execution and Initialization Specification.md`
- `docs/general/specs/19. Verification and Safety Checks Specification.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- The syntax specification already enumerates minimum required syntax diagnostics.
- The static semantics specification already enumerates minimum required static diagnostics.
- Manifest/import resolution failures are required to be deterministic compile-time errors.
- Loader failures around malformed or unauthorized host usage are required to be deterministic.
- Stable source span metadata is required at the token level and must remain useful to later diagnostics.
- Traps are fatal runtime outcomes rather than a recoverable userland diagnostic flow.
- Qualitative cost facts such as retention-bearing operations and host-boundary crossings are normative, but quantitative performance metrics are not.
## 6. Required Diagnostic Phases
PBS-facing tooling must distinguish at least the following external diagnostic phases:
1. `syntax`,
2. `static semantics`,
3. `manifest/import resolution`,
4. `linking`,
5. `host-binding/capability admission`,
6. `load-facing rejection` when directly attributable to malformed or unauthorized PBS-facing artifact usage.
`linking` is a first-class phase in the external diagnostics contract and must not be collapsed away into a generic resolution bucket.
This document does not require one finer-grained public phase split for verifier internals, artifact offsets, or transport-specific backend stages beyond what is stated here.
## 7. Required Diagnostic Identity, Payload, and Attribution
Every PBS-facing diagnostic must expose a stable machine-readable identity.
At minimum, every required source-facing diagnostic must include:
1. `diagnostic code`,
2. `severity`,
3. `phase`,
4. `primary file`,
5. `primary span/location`,
6. `message template id`,
7. stable named placeholders for that template when applicable,
8. and a rendered human-readable message.
The stable identity of a diagnostic is carried primarily by:
- `diagnostic code`,
- stable phase attribution,
- `message template id`,
- primary attribution,
- and the rejection-class semantics represented by the code/template pair.
Human wording alone is not the identity of the diagnostic.
Conformance assertions must key diagnostics by stable machine fields (`code`, `phase`, `message template id`, attribution), not by localized rendered sentence text.
## 8. Cross-File Attribution, Notes, and Hint Surface
Cross-file attribution follows an action-first rule.
Rules:
- import failures must point primarily to the importing site,
- barrel failures must point primarily to the barrel site or entry that triggered the failure,
- linking and cross-module lookup failures must point primarily to the use or reference site that could not be resolved,
- related sites may be attached when known,
- and `duplicate` or `conflict` diagnostics must include at least one related site.
`notes` are optional by default in v1 except where another rule explicitly requires related-location reporting.
The stable visible categories currently reserved are:
- `error`,
- `warning`,
- `note`,
- `hint`.
`hint` is part of the diagnostics model in v1, but hint content is not mandatory.
## 9. Wording, Templates, and Localization
Rendered wording does not need to be byte-for-byte identical across implementations or locales.
However:
- the rendered message must preserve the same normative rejection meaning,
- the rendered message must not contradict the governing spec rule,
- and the code/template/placeholder contract must remain stable.
This allows implementations to localize diagnostics while preserving conformance-friendly identity.
Human-readable messages may be rendered from locale-specific templates, but template/token identity remains stable across locales.
Implementations should preserve the ability to render an English default or fallback message for future interoperability-oriented transports such as a possible LSP integration, even when the local product surface renders another language by default.
Examples in this specification are illustrative unless explicitly marked normative.
`help` or guided remediation is outside the minimum mandatory contract in v1.
## 10. Required Diagnostic Coverage and Backend-Originated Failures
At minimum, the PBS diagnostics baseline must cover:
1. syntax errors already required by `3. Core Syntax Specification.md`,
2. static-semantics errors already required by `4. Static Semantics Specification.md`,
3. deterministic manifest and import-resolution failures required by `5. Manifest, Stdlib, and SDK Resolution Specification.md`,
4. linking failures required by source-level name-resolution and module-linking rules,
5. malformed, unauthorized, or capability-rejected host usage required by `6.2. Host ABI Binding and Loader Resolution Specification.md` and `7. Cartridge Manifest and Runtime Capabilities Specification.md`,
6. source-attributable backend-originated failures that remain user-actionable under normative lowering or load-facing rules.
7. dependency-scoped fail-fast admission at frontend boundary: when one module is rejected, modules that import it (directly or transitively) must not be emitted, while diagnostics collection for independent modules must continue.
At minimum, host-admission diagnostics must cover missing or malformed host capability metadata and unknown or undeclared capability names.
Only backend-originated failures that remain source-attributable and user-actionable belong to the PBS-facing diagnostics contract.
This means:
- lowering failures remain in scope when they reflect a normative source-facing lowering rule or impossibility,
- verifier or loader failures remain in scope when they are directly attributable to malformed or unauthorized PBS-facing artifact usage already within the PBS contract,
- and purely internal compiler exceptions, artifact corruption, or backend-internal failures with no stable user-facing source attribution remain outside the PBS-facing diagnostics contract.
When a backend-originated failure remains in scope for PBS-facing diagnostics, v1 requires at least one source location but does not require one standardized source-map, artifact-offset, or verifier-trace format.
Dynamic-semantics traps are not source-level recoverable diagnostics in the ordinary PBS userland model. This document therefore does not require a compile-time diagnostic surface for every possible fatal runtime trap.
Dependency-scoped fail-fast admission is not equivalent to global build abort.
When failures exist, implementations must still preserve deterministic diagnostic identity and attribution for unaffected independent modules processed in the same build.
## 11. Cost Diagnostics and Warning Policy
Warnings are supported and recommended in v1, but they are not part of the minimum mandatory conformance baseline.
Tooling may surface qualitative cost facts as warnings or notes, especially for:
- retention-bearing `bind`,
- observable copy-versus-alias semantics,
- and host-boundary crossings.
The choice between `warning` and `note` is implementation-defined in v1.
This document does not make a detailed warning taxonomy normative and does not require a warning at every such site.
Quantitative metrics such as exact byte counts, exact allocation counts, collector timing, or performance ranking remain outside the diagnostics contract and belong to profiling/tooling rather than to language conformance.
## 12. Current Limits
The v1 diagnostics contract intentionally leaves the following items outside the currently standardized surface:
- transport-specific wire formats,
- one exact source-map format,
- one exact verifier/loader internal reporting shape,
- one mandatory warning catalog,
- and one mandatory remediation/help-content policy.
These are not licenses to weaken the required external fields defined above.
## 13. Non-Goals
- Mandating one UI or IDE presentation style.
- Freezing one exact localization strategy or locale set.
- Turning every optimization hint into a normative diagnostic.
- Replacing the acceptance/rejection rules already defined elsewhere.
- Standardizing profiler output as if it were language law.
## 14. Exit Criteria
This document is ready to move beyond temporary status only when:
1. every required rejection in the current spec set is mapped to a diagnostic phase,
2. diagnostic identity, metadata, and attribution rules are explicit enough for conformance, including locale-agnostic token/template identity,
3. the backend-originated failure boundary is explicit enough that PBS-facing diagnostics can be distinguished from internal tool failures,
4. and cost/warning expectations are explicit where they are intended to be normative for v1.
@@ -0,0 +1,210 @@
# PBS Lowering IRBackend Specification
Status: Draft v1 (Frontend Scope + Backend Handoff Addendum)
Applies to: first lowering boundary from bound PBS frontend model into `IRBackend`/`IRBackendFile`, plus executable-backend handoff obligations at this boundary
## 1. Purpose
This document defines the normative frontend lowering contract from PBS source semantics to `IRBackend`.
Its purpose is to keep the first lowering deterministic and shared across implementations while PBS and backend design evolve.
## 2. Scope
This document defines:
- required preconditions before lowering starts,
- AST invariants that lowering may assume as hard contract,
- semantic obligations preserved in `IRBackend`,
- deterministic rejection behavior for unsupported frontend-lowering forms,
- diagnostics attribution obligations for lowering failures in frontend scope,
- and executable-backend handoff obligations at the `IRBackend` boundary.
This document does not define:
- VM lowering (`IRVM`),
- bytecode/PBX mapping,
- runtime execution behavior,
- verifier/loader internals.
Those concerns belong to shared acceptance specs under `docs/general/specs`.
## 3. Authority and Precedence
Normative precedence:
1. `3. Core Syntax Specification.md`
2. `4. Static Semantics Specification.md`
3. `11. AST Specification.md`
4. `12. Diagnostics Specification.md`
5. This document
If a lowering rule here conflicts with higher-precedence syntax/semantics rules, the higher-precedence rule wins.
## 4. Normative Inputs
This document depends on:
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `11. AST Specification.md`
- `12. Diagnostics Specification.md`
- `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
## 5. Lowering Preconditions
Frontend lowering into `IRBackend` may start only when:
1. source has been tokenized and parsed,
2. required syntax diagnostics have been emitted,
3. AST output satisfies `11` required invariants for this source unit, including:
- one root per file,
- deterministic child ordering,
- mandatory node attribution (`file/start/end`) on nodes consumed by lowering,
- mandatory declaration metadata on declaration nodes required by the active source slice,
- and structural coherence after any parser recovery.
4. linking/name-resolution outcomes required for the current lowering slice are available,
5. and no unresolved semantic ambiguity is deferred to lowering.
Lowering must not invent unresolved semantic answers that belong to syntax/static/linking phases.
## 6. IRBackend Preserved Obligations
For each admitted source unit and callable in the current lowering slice, `IRBackend` must preserve at minimum:
1. callable identity (name/category as applicable),
2. callable arity,
3. declared return surface information,
4. source attribution anchor (`file + span`) for diagnostics and traceability,
5. source-observable parse intent for statement/expression structure (including precedence/associativity outcome already fixed by AST shape).
6. deterministic `requiredCapabilities` derived from admitted host-binding metadata for packer/runtime-manifest assistance.
7. frontend-declared executable `EntrypointRef` (`entryPointCallableName` + `entryPointModuleId`) for backend handoff.
Lowering must not collapse source categories in a way that erases required declaration/callable identity needed by downstream diagnostics or conformance assertions.
The normative contract is obligation-based, not tied to one mandatory in-memory class graph.
## 7. Deterministic Rejection Policy
If a source form is outside current frontend-lowering support:
1. rejection must be deterministic,
2. diagnostics must expose stable `code`, `severity`, `phase`, `message template id`, and primary attribution,
3. and unsupported forms must not silently degrade into different valid lowered behavior.
Lowering must not convert a required syntax/static rejection into accepted lowered behavior.
For multi-module builds, lowering admission must apply dependency-scoped fail-fast:
1. a module rejected in syntax, static semantics, linking, host-admission, or load-facing gates must not be emitted;
2. any module that imports a rejected module (directly or transitively) must also be excluded from `IRBackend` emission;
3. modules independent from the rejected dependency subgraph may continue to lower and emit in the same build.
## 8. Conformance Boundary
`IRBackend` is the first lowering boundary (frontend responsibility).
Conformance-valid claims at this boundary require Gate U evidence from `docs/general/specs/13. Conformance Test Specification.md`.
For this frontier, Gate U evidence is expected to cover at minimum:
- lexer behavior for covered inputs,
- parser behavior and AST shape invariants required by `11`,
- lowering outcomes at `IRBackend` boundary,
- and deterministic diagnostics identity/attribution for rejection cases.
Conformance at this boundary may be claimed only when the full claimed PBS source surface is implemented at `IRBackend` level.
## 9. Explicit Deferrals
The following are intentionally out of scope for this document:
- `IRBackend -> IRVM` lowering,
- artifact encoding and binary layout,
- runtime lifecycle behavior,
- verifier and loader checks.
## 10. Non-Goals
- Freezing one optimizer strategy.
- Freezing one compiler architecture.
- Repeating runtime or bytecode authority.
## 11. Exit Criteria
This document is healthy when:
1. lowering preconditions are explicit,
2. preserved `IRBackend` obligations are explicit,
3. deterministic rejection policy is explicit and test-backed,
4. and scope boundaries with general/backend acceptance specs are explicit.
## 12. Executable Backend Handoff Addendum (v1)
For executable backends, the `IRBackend` output from this frontend boundary must satisfy the additional handoff obligations below.
### 12.1 Callable obligations
For each executable callable admitted into `IRBackend`, the frontend must preserve:
1. stable callable identity in the current build graph,
2. observable callable signature (input arity and return shape),
3. callable category needed by downstream lowering,
4. source attribution anchor (`fileId`, `start`, `end`),
5. and executable body representation that is backend-lowerable.
### 12.2 Callsite classification obligations
Each executable callsite in `IRBackend` must be classified into exactly one category:
1. `CALL_FUNC`,
2. `CALL_HOST`,
3. `CALL_INTRINSIC`.
Backend lowering must not infer this category by textual heuristics.
### 12.3 Host-backed metadata obligations
Each host-backed callsite admitted at this boundary must preserve canonical host identity:
1. `module`,
2. `name`,
3. `version`.
When available at this boundary, declared host ABI shape (`arg_slots`, `ret_slots`) must also be preserved for downstream validation.
### 12.4 VM-owned metadata obligations
VM-owned intrinsic callsites admitted at this boundary must preserve canonical intrinsic identity:
1. `canonicalName`,
2. `canonicalVersion`.
VM-owned builtin projections/constants/intrinsics must not be reclassified as host bindings.
### 12.5 Deterministic capability obligations
`requiredCapabilities` derived at this boundary must be deterministic for the same admitted input graph.
### 12.6 Boundary with backend lowering specs
This addendum defines obligations preserved at the `IRBackend` boundary only.
It does not replace:
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`,
2. `docs/general/specs/21. IRVM Optimization Pipeline Specification.md`,
3. or `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`.
### 12.7 FrontendSpec Entry Point Obligation
For executable language frontends, `FrontendSpec` must declare one canonical qualified entrypoint reference (`EntrypointRef`):
1. `entryPointCallableName`,
2. `entryPointModuleId`.
At `IRBackend` emission time:
1. frontend must copy this declaration into `IRBackend.entryPointCallableName` and `IRBackend.entryPointModuleId`,
2. both values must be non-blank/non-none and deterministic for the same language/spec version,
3. and backend stages must treat this qualified reference as authoritative for entrypoint selection instead of name-only fallbacks or hardcoded language-agnostic names.
@@ -0,0 +1,153 @@
# PBS Governance and Versioning
Status: Draft v1
Applies to: PBS language, profiles, and related specifications
## 1. Purpose
This document defines how PBS decisions are made and how versions evolve without breaking the ecosystem unpredictably.
## 2. Scope
This policy governs:
- language specification changes,
- profile changes (for example, Core/Game),
- standard library specification changes,
- compatibility policy updates,
- release and deprecation decisions.
## 3. Governance Model
PBS uses a spec-first governance model.
No implementation change is considered normative until the relevant spec change is accepted.
### 3.1 Roles
- Maintainers: approve/reject RFCs and cut releases.
- Editors: keep specs coherent, complete, and cross-referenced.
- Implementers: provide feasibility feedback and conformance evidence.
- Community contributors: propose RFCs and review drafts.
### 3.2 Authority Rule
If a governance decision conflicts with runtime/bytecode authority, runtime/bytecode authority wins.
## 4. Decision Process (RFC)
All non-trivial changes MUST go through RFC.
### 4.1 RFC Lifecycle
1. Draft: problem, proposal, alternatives, migration impact.
2. Review: open feedback period.
3. Decision: `Accepted`, `Rejected`, or `Deferred`.
4. Spec Merge: normative documents updated.
5. Implementation: only after spec merge.
6. Conformance: tests and diagnostics updated before release.
### 4.2 Fast-Track
Fast-track is allowed only for:
- critical correctness fixes,
- security/capability violations,
- deterministic behavior regressions.
Fast-track changes still require post-merge RFC backfill.
## 5. Version Domains
PBS versioning is separated by domain to avoid ambiguity.
1. Language Version (`pbs_lang`): syntax + semantics.
2. Profile Version (`pbs_profile`): profile-specific surface (Core/Game).
3. Stdlib Version (`pbs_stdlib`): standard library contract.
4. Compatibility Policy Version (`pbs_compat`): evolution/deprecation policy text.
Host primitives remain versioned by canonical identity `(module, name, version)`.
Direct declaration of canonical host primitive bindings is reserved to SDK/toolchain-managed `declare host` surfaces, not ordinary user-authored PBS modules.
User-facing PBS and stdlib APIs over host primitives MAY evolve independently from those bindings as long as canonical host identity, capability policy, and compatibility commitments remain preserved.
## 6. Versioning Scheme
Each domain uses semantic versioning:
- `MAJOR`: incompatible changes.
- `MINOR`: backward-compatible additions.
- `PATCH`: clarifications/fixes with no intended behavior break.
## 7. Change Classification
### 7.1 Patch Changes
- wording fixes,
- unambiguous typo corrections,
- diagnostics wording adjustments without code/behavior contract changes.
### 7.2 Minor Changes
- additive syntax behind explicit profile gates,
- new stdlib APIs,
- new host primitive versions added without removing old supported versions.
### 7.3 Major Changes
- behavior changes that can alter valid program outcomes,
- removal of previously supported constructs,
- incompatible type or resolution rule changes.
## 8. Compatibility Rules
- Supported old versions MUST continue to compile/link/run as declared by the compatibility window.
- A release MUST publish a compatibility matrix for language/profile/stdlib domains.
- Toolchains MUST reject unsupported targets deterministically with explicit diagnostics.
## 9. Deprecation and Removal Policy
Deprecation stages:
1. Introduce deprecation notice in specs and tooling.
2. Keep feature functional during declared support window.
3. Remove only in a subsequent major version.
Every deprecation MUST include:
- replacement path,
- migration notes,
- timeline (first deprecated version, last supported version, removal version).
## 10. Release Requirements
Before any version release:
1. Specs for changed domains are updated.
2. Changelog is published with change classification.
3. Conformance suite is updated and passing.
4. Compatibility matrix is published.
5. Migration guide is provided for any major-impact changes.
## 11. Documentation Contract
Every accepted change MUST update, when relevant:
- normative spec sections,
- examples,
- diagnostics documentation,
- conformance tests,
- compatibility matrix/changelog.
- For executable FE/BE conformance-relevant code changes, the backend conformance matrix (`docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`) MUST be updated and pass hard-gate policy checks.
## 12. Conflict Resolution
When maintainers disagree, the tie-breaker is:
1. determinism and compatibility,
2. clarity for beginners,
3. implementation feasibility and tooling stability.
## 13. Non-Goals
- Replacing runtime authority with governance-only decisions.
- Defining subsystem-specific API semantics in this document.
- Granting implementation behavior override over normative specs.

Some files were not shown because too many files have changed in this diff Show More