clean up
This commit is contained in:
@@ -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.
|
||||
@@ -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.
|
||||
+168
@@ -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.
|
||||
+173
@@ -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`.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
+59
@@ -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.
|
||||
+62
@@ -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.
|
||||
+59
@@ -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.
|
||||
+78
@@ -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.
|
||||
+73
@@ -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.
|
||||
+70
@@ -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.
|
||||
+70
@@ -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.
|
||||
+72
@@ -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)?
|
||||
+73
@@ -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.
|
||||
+74
@@ -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.
|
||||
+77
@@ -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?
|
||||
+80
@@ -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?
|
||||
+72
@@ -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?
|
||||
+74
@@ -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?
|
||||
+81
@@ -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.
|
||||
+68
@@ -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.
|
||||
+72
@@ -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.
|
||||
+84
@@ -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.
|
||||
+76
@@ -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.
|
||||
+84
@@ -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
|
||||
+76
@@ -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.
|
||||
+69
@@ -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`.
|
||||
+73
@@ -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.
|
||||
+74
@@ -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.
|
||||
+80
@@ -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.
|
||||
+68
@@ -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.
|
||||
+74
@@ -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.
|
||||
+73
@@ -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.
|
||||
+75
@@ -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.
|
||||
+69
@@ -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.
|
||||
+71
@@ -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.
|
||||
+72
@@ -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.
|
||||
+73
@@ -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.
|
||||
+77
@@ -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.
|
||||
+67
@@ -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.
|
||||
+71
@@ -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.
|
||||
+72
@@ -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.
|
||||
+72
@@ -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.
|
||||
+77
@@ -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.
|
||||
@@ -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.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,772 @@
|
||||
# PBS Static Semantics Specification
|
||||
|
||||
Status: Draft v1 (Normative)
|
||||
Scope: binding, callable formation, type checking, and deterministic function application
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
This document defines the static semantics of PBS core language.
|
||||
|
||||
It is intended to:
|
||||
|
||||
- give deterministic meaning to declarations accepted by the syntax specification,
|
||||
- define callable identity and application rules,
|
||||
- make type checking stable across implementations,
|
||||
- preserve beginner-facing clarity without hidden callable behavior.
|
||||
|
||||
## 2. Core Semantic Model
|
||||
|
||||
### 2.1 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. `3. Core Syntax Specification.md`
|
||||
4. This document
|
||||
|
||||
If a rule here conflicts with higher authority, it is invalid.
|
||||
|
||||
### 2.2 Semantic namespaces
|
||||
|
||||
PBS distinguishes at least:
|
||||
|
||||
- type namespace,
|
||||
- value namespace,
|
||||
- callable namespace.
|
||||
- host-owner namespace.
|
||||
|
||||
Rules:
|
||||
|
||||
- `declare struct`, `declare service`, `declare contract`, `declare error`, `declare enum`, `declare callback`, and `declare builtin type` introduce names in the type namespace.
|
||||
- `declare host` introduces names in the host-owner namespace.
|
||||
- `let`, parameters, and `declare const` introduce names in the value namespace.
|
||||
- `declare service Name` also introduces the canonical singleton value `Name` in the value namespace.
|
||||
- Top-level `fn`, service methods, and host methods participate in the callable namespace.
|
||||
- `fn` declarations are not first-class values in v1 core and therefore do not become ordinary value expressions.
|
||||
- `bind(...)` is a callback-formation construct, not a general function-value construct.
|
||||
- `declare host` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source.
|
||||
- `declare builtin type` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source.
|
||||
- A host owner name is not an ordinary value expression in v1 core; it is used only as a qualified host-call owner.
|
||||
- The builtin simple types `int`, `float`, `bool`, and `str` are always present in the type namespace.
|
||||
- Builtin simple types are resolved without import or declaration.
|
||||
- User-authored type declarations must not reuse builtin simple type names.
|
||||
|
||||
### 2.3 Attribute metadata
|
||||
|
||||
Attributes are compile-time metadata attached to declaration surfaces.
|
||||
|
||||
Rules:
|
||||
|
||||
- An attribute has no value-level or type-level meaning by itself.
|
||||
- Attributes are not first-class values and are not reflectable in v1 core.
|
||||
- Attributes do not automatically survive into runtime or bytecode artifacts.
|
||||
- An attribute affects runtime artifacts only when another specification defines an explicit lowering for its semantic effect.
|
||||
- In v1 core, the normative reserved attributes are `Host`, `Capability`, `BuiltinType`, `BuiltinConst`, and `IntrinsicCall`.
|
||||
- `Host` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
|
||||
- `Capability` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
|
||||
- `Host` is invalid on ordinary user-authored modules, top-level `fn`, struct methods, service methods, callbacks, contracts, and constants.
|
||||
- `Host` metadata is consumed by the compiler during host-binding lowering.
|
||||
- The `Host` attribute syntax itself is not exported as runtime metadata; instead, its canonical identity participates in PBX host-binding emission as defined by the Host ABI Binding specification.
|
||||
- `BuiltinType` is valid only on a reserved top-level `declare builtin type` declaration.
|
||||
- `BuiltinConst` is valid only on a reserved top-level `declare const` declaration that omits an initializer.
|
||||
- `IntrinsicCall` is valid only on a method signature declared directly inside a reserved `declare builtin type` body.
|
||||
- Builtin metadata is consumed by the compiler during VM-owned builtin and intrinsic lowering rather than by host-binding lowering.
|
||||
|
||||
### 2.4 Tuple shapes
|
||||
|
||||
Static checking uses tuple shapes as semantic objects.
|
||||
|
||||
Definitions:
|
||||
|
||||
- Input tuple shape: ordered sequence of zero or more input slots.
|
||||
- Output tuple shape: ordered sequence of zero or more output slots.
|
||||
- Each slot has a type and a stable label.
|
||||
|
||||
Rules:
|
||||
|
||||
- Tuple shapes in PBS core are always named, except for unit `()`.
|
||||
- Input slot labels come from parameter names and are local frame names.
|
||||
- Output slot labels come from return annotations and are visible for multi-slot member projection.
|
||||
- Tuple-shape identity for overload and resolution ignores labels.
|
||||
- Tuple-shape compatibility requires matching arity and positional slot types.
|
||||
- Labels must still be preserved as part of declaration surface and projection metadata.
|
||||
- A single-slot tuple shape has a distinguished carrier value type equal to its slot type.
|
||||
- In value positions, single-slot tuple values collapse to their carrier value type.
|
||||
- Single-slot tuple shapes have no dedicated tuple-literal surface in v1 core.
|
||||
|
||||
## 3. Functions and `apply`
|
||||
|
||||
### 3.1 Canonical function model
|
||||
|
||||
Every callable `fn` in PBS is modeled statically as:
|
||||
|
||||
```text
|
||||
Fn : InputTuple -> OutputTuple
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `fn f(a: A, b: B)` has input tuple shape `(a: A, b: B)`.
|
||||
- `fn f()` has empty input tuple shape `()`.
|
||||
- `-> void`, `-> ()`, and omitted return annotation all denote empty output tuple shape `()`.
|
||||
- `-> T` denotes a single-slot output tuple shape `(value: T)`.
|
||||
- `-> (x: T)` denotes a single-slot output tuple shape `(x: T)`.
|
||||
- `-> (x: T, y: U)` denotes a two-slot output tuple shape `(x: T, y: U)`.
|
||||
- `-> T` and `-> (x: T)` are identical for overload identity and differ only in preserved label metadata.
|
||||
- `optional T` is a regular value type and may appear in parameters, locals, fields, and plain returns.
|
||||
- `optional T` with single-slot payload is internally normalized to `optional<(value: T)>`.
|
||||
- `optional` and `optional void` are invalid type surfaces.
|
||||
- `-> result<E> T` denotes a result return surface over payload shape `T` and error type `E`.
|
||||
- `-> result<E> T` with single-slot payload is internally normalized to `result<E, (value: T)>`.
|
||||
- `-> result<E>` is valid and denotes a result return surface with unit payload.
|
||||
- A function return surface may be plain or `result<E>`.
|
||||
- A function return surface must not combine `optional` and `result` in the same declaration.
|
||||
- `result<E>` wraps the declared success payload; the payload itself may be scalar or a named tuple shape.
|
||||
|
||||
### 3.2 Callable categories
|
||||
|
||||
The following constructs are callable in v1 core:
|
||||
|
||||
- top-level `fn`,
|
||||
- struct methods on concrete receivers,
|
||||
- contract values,
|
||||
- callback values,
|
||||
- service methods,
|
||||
- host methods on declared host owners,
|
||||
- builtin intrinsic methods on declared builtin types.
|
||||
|
||||
Rules:
|
||||
|
||||
- All callable categories use the same input/output tuple model.
|
||||
- A struct method is identified by `(struct type, method name, input tuple shape excluding the receiver slot, output tuple shape)`.
|
||||
- A contract value is identified at the type level by its contract type and at runtime by an underlying concrete struct instance or service singleton value plus its selected implementation.
|
||||
- A callback declaration defines a nominal callable type with exactly one input/output tuple shape.
|
||||
- A service method is identified by `(service name, method name, input tuple shape, output tuple shape)`.
|
||||
- A host method is identified by `(host owner name, method name, input tuple shape, output tuple shape)` within the PBS declaration surface.
|
||||
- A builtin intrinsic method is identified within PBS declaration surface by `(builtin type name, method name, input tuple shape, output tuple shape)` and lowers further by canonical builtin/intrinsic metadata.
|
||||
- A top-level `fn` is identified by `(name, input tuple shape, output tuple shape)`.
|
||||
- A callback value is identified at the type level by its declared callback type and signature.
|
||||
- Contract signatures and barrel signatures must preserve the same callable shape.
|
||||
- Canonical host primitive identity and binding are governed by the Host ABI Binding specification rather than by ordinary v1 core declaration identity alone.
|
||||
|
||||
### 3.3 Declaration validity
|
||||
|
||||
Rules:
|
||||
|
||||
- Parameter names in a single `ParamList` must be unique.
|
||||
- Output labels in a named tuple return annotation must be unique.
|
||||
- Error case labels in a single `declare error` body must be unique.
|
||||
- Enum case labels in a single `declare enum` must be unique.
|
||||
- Enum case integer identifiers in a single `declare enum` must be unique.
|
||||
- Two declarations with the same callable name and the same input/output tuple shape are duplicates.
|
||||
- Changing only parameter names does not create a new callable.
|
||||
- Changing only input labels in `ParamList` does not create a new callable.
|
||||
- Changing only output labels does not create a new callable.
|
||||
- `mod.barrel` function entries are matched by callable identity, ignoring labels.
|
||||
- Barrel labels may differ from implementation labels.
|
||||
- Any return surface that combines `optional` and `result` is statically invalid.
|
||||
- Any payload-less `optional` type surface is statically invalid.
|
||||
- Any `optional void` type surface is statically invalid.
|
||||
- A host method signature in a reserved stdlib/interface module MUST carry exactly one `Host` attribute.
|
||||
- A host method signature in a reserved stdlib/interface module MUST carry exactly one `Capability` attribute.
|
||||
- A `Host` attribute MUST declare exactly the named arguments `module`, `name`, and `version`.
|
||||
- `Host.module` and `Host.name` MUST be non-empty string literals.
|
||||
- `Host.version` MUST be a positive integer literal.
|
||||
- A `Capability` attribute MUST declare exactly the named argument `name`.
|
||||
- `Capability.name` MUST be a non-empty lowercase capability identifier.
|
||||
- Two host methods in the same resolved stdlib environment MUST NOT lower to the same canonical `(module, name, version)` unless they denote the same host method declaration after project/module resolution.
|
||||
- A `declare const` declaration must include an explicit type annotation.
|
||||
- A `declare const` declaration without `BuiltinConst` metadata must include an initializer.
|
||||
- A `declare const` declaration with `BuiltinConst` metadata must omit the initializer.
|
||||
- A non-builtin `declare const` initializer must be a constant expression.
|
||||
- `declare const` dependency resolution is module-wide and must not depend on source-file processing order.
|
||||
- `declare const` dependencies must form an acyclic graph.
|
||||
- A `BuiltinType` attribute MUST declare exactly the named arguments `name` and `version`.
|
||||
- `BuiltinType.name` MUST be a non-empty string literal.
|
||||
- `BuiltinType.version` MUST be a positive integer literal.
|
||||
- Two builtin type declarations in the same resolved stdlib environment MUST NOT lower to the same canonical `(name, version)` unless they denote the same builtin declaration after project/module resolution.
|
||||
- A builtin field type must be builtin-layout-admissible as defined by the builtin/intrinsics specification.
|
||||
- Builtin field slot offsets are inferred by the compiler from canonical field order and flattened builtin layout width.
|
||||
- Builtin layout composition must be acyclic.
|
||||
- A builtin field that depends on a builtin layout with unresolved flattened width is statically invalid.
|
||||
- `IntrinsicCall` MUST declare exactly the named argument `name` and MAY additionally declare `version`.
|
||||
- `IntrinsicCall.name` MUST be a non-empty string literal.
|
||||
- `IntrinsicCall.version`, when present, MUST be a positive integer literal.
|
||||
- Two builtin methods in the same canonical builtin owner/version line MUST NOT lower to the same canonical intrinsic `(owner, name, version)` unless they denote the same builtin method declaration after project/module resolution.
|
||||
- `BuiltinConst` MUST declare exactly the named arguments `target`, `name`, and `version`.
|
||||
- `BuiltinConst.target` and `BuiltinConst.name` MUST be non-empty string literals.
|
||||
- `BuiltinConst.version` MUST be a positive integer literal.
|
||||
- Two builtin constant declarations in the same resolved stdlib environment MUST NOT lower to the same canonical `(target, name, version)` unless they denote the same builtin constant declaration after project/module resolution.
|
||||
|
||||
### 3.4 Constant expressions
|
||||
|
||||
PBS core v1 restricts top-level constant evaluation to a deterministic compile-time subset.
|
||||
|
||||
Rules:
|
||||
|
||||
- A non-builtin `declare const` initializer is evaluated at compile time.
|
||||
- A non-builtin `declare const` may depend only on previously resolved visible `declare const` declarations and enum case values.
|
||||
- Cross-file constant resolution within a module is defined by dependency analysis, not source-file order.
|
||||
- Constant evaluation fails if the dependency graph contains a cycle.
|
||||
- The allowed constant-expression forms in v1 core are:
|
||||
- scalar literals: `IntLit`, `FloatLit`, `StringLit`, `BoolLit`,
|
||||
- enum case paths `EnumName.caseName`,
|
||||
- a reference to another visible `declare const`,
|
||||
- unary `-` applied to an integer or float constant expression,
|
||||
- unary `not` or `!` applied to a boolean constant expression,
|
||||
- binary arithmetic operators over numeric constant expressions,
|
||||
- binary comparison operators over compatible constant expressions,
|
||||
- binary boolean operators over boolean constant expressions.
|
||||
- A non-builtin `declare const` initializer must not use:
|
||||
- callable application or call sugar,
|
||||
- `new`,
|
||||
- `bind(...)`,
|
||||
- `some(...)` or `none`,
|
||||
- tuple expressions,
|
||||
- block expressions,
|
||||
- `if`, `switch`, `handle`, `else` extraction, or `!` result propagation,
|
||||
- method calls or member access except enum case paths.
|
||||
- For non-builtin `declare const`, the initializer type must be compatible with the declared `const` type.
|
||||
- A `BuiltinConst` declaration is not part of ordinary compile-time constant evaluation and lowers through VM-owned builtin constant materialization instead.
|
||||
- A `declare const` exported through `mod.barrel` may be imported from another module only through ordinary module import rules.
|
||||
- A `declare const` does not introduce mutable runtime storage; implementations may inline, fold, or materialize it as an immutable constant as long as observable semantics remain unchanged.
|
||||
|
||||
### 3.5 Enum declarations and values
|
||||
|
||||
Rules:
|
||||
|
||||
- `declare enum Name(case1, case2, ...);` introduces a nominal enum type `Name`.
|
||||
- `declare enum Name(case1 = n1, case2 = n2, ...);` introduces explicit integer identifiers for enum cases.
|
||||
- If no enum case uses an explicit identifier, identifiers are assigned as `0..n-1` in declaration order.
|
||||
- If any enum case uses an explicit identifier, then every enum case in that declaration must use an explicit identifier.
|
||||
- `Name.case` is a valid enum value surface only when `Name` resolves to a declared enum type and `case` resolves to a declared case of that enum.
|
||||
- The static type of `Name.case` is the enum type `Name`.
|
||||
- Error labels are not enum cases and must not be used where enum case values are required.
|
||||
|
||||
### 3.6 Structs, services, methods, and contracts
|
||||
|
||||
Rules:
|
||||
|
||||
- Struct values are heap-backed reference values in v1 core.
|
||||
- Service values are canonical module-owned singleton values in v1 core.
|
||||
- `new Struct(args...)` allocates a new struct instance of the declared struct type.
|
||||
- `new Struct.ctorName(args...)` invokes a named constructor declared in the enclosing struct body and produces a new struct instance of that type.
|
||||
- Struct construction arguments are matched positionally to the declared struct field order.
|
||||
- Assigning a struct value copies the reference, not the underlying field storage.
|
||||
- Assigning a service value copies the same canonical singleton identity; it does not create a new instance.
|
||||
- A struct field with no access modifier is readable and writable only from methods and `ctor` bodies of its enclosing struct.
|
||||
- A `pub` struct field is externally readable but remains externally non-assignable.
|
||||
- A `pub mut` struct field is externally readable and externally assignable.
|
||||
- An assignment target `expr.name` to a struct field is valid only when the access site is permitted to write that field.
|
||||
- Writes to a private struct field are valid only through `this.name` inside methods and `ctor` bodies of the enclosing struct.
|
||||
- A struct method declared in a struct body has an implicit receiver binding `this` of type `Self`.
|
||||
- A service method declared in a service body has an implicit receiver binding `this` of type `Self`.
|
||||
- `this` is valid only inside struct method, service method, and `ctor` bodies.
|
||||
- `Self` is valid only in struct method, service method, and `ctor` declarations and denotes the enclosing owner type.
|
||||
- The enclosing struct name is in scope inside its own field declarations, enabling self-referential field types.
|
||||
- A named `ctor` declared in a struct body is not a method, but it does introduce an implicit under-construction `this`.
|
||||
- A `ctor` has no declared return annotation and is not a `fn`.
|
||||
- A `ctor` completes by falling off the end of its body after initializing the enclosing struct instance.
|
||||
- Every field of the enclosing struct must be definitely assigned on every completing `ctor` path.
|
||||
- Named constructors participate in overload resolution by name plus parameter signature.
|
||||
- `return;` and `return expr;` are both invalid inside `ctor` bodies.
|
||||
- Methods declared in a struct body belong to the direct method namespace of that concrete struct type.
|
||||
- Methods declared in a service body belong to the direct method namespace of that concrete service type.
|
||||
- `receiver.method(...)` on a concrete struct receiver resolves only against methods declared directly in that struct body.
|
||||
- `receiver.method(...)` on a service receiver resolves only against methods declared directly in that service body.
|
||||
- `receiver.ctorName(...)` is never valid on a concrete struct value.
|
||||
- Service values are ordinary value expressions and may be assigned, passed, and returned under their declared service type.
|
||||
- Services do not have fields.
|
||||
- Services do not declare named constructors and are never targets of `new`.
|
||||
- Contract implementations do not inject their methods into the direct method namespace of the concrete struct or service.
|
||||
- `implements Contract for Owner using s { ... }` is unique per `(Contract, Owner)` pair, where `Owner` is a declared struct or service.
|
||||
- A contract for a struct or service may be implemented only in the module where that owner itself is declared.
|
||||
- Contracts may be declared in other modules and implemented for the local struct or service in its owner module.
|
||||
- An `implements` block has no independent visibility; its observability follows the visibility of the owner declaration, and the contract must also be nameable at the use site.
|
||||
- Methods declared directly inside a struct or service follow the visibility of their enclosing owner declaration; they do not have independent visibility.
|
||||
- A struct value or service singleton value may be coerced to a contract value when exactly one visible `implements Contract for Owner ...` applies.
|
||||
- Contract coercion may happen by explicit `expr as ContractType` or by contextual typing in assignments, parameter passing, and returns.
|
||||
- `as` in expression position is reserved for explicit contract coercion only; no other cast semantics exist in v1 core.
|
||||
- The contract name in `expr as ContractName` must be a simple visible identifier resolved through ordinary scope and import rules.
|
||||
- A contract value carries the underlying struct reference or service singleton value together with the selected contract implementation for runtime dispatch.
|
||||
- Calling `contractValue.method(...)` uses dynamic dispatch through the contract value.
|
||||
- Calling `structValue.contractMethod(...)` is not valid unless that method is also declared directly on the struct.
|
||||
- Calling `serviceValue.contractMethod(...)` is not valid unless that method is also declared directly on the service.
|
||||
- Structs do not have static methods in v1 core; named constructors are their only type-qualified callable members.
|
||||
- Services are accessed through their canonical singleton value, not through `new` or static method declarations.
|
||||
|
||||
Example:
|
||||
|
||||
```pbs
|
||||
declare contract StasisProcess {
|
||||
fn stasis() -> int;
|
||||
}
|
||||
|
||||
declare struct Struct(pub a: int) {
|
||||
fn compute() -> int {
|
||||
return this.a;
|
||||
}
|
||||
|
||||
ctor createWithSomethingSpecial(x: int) {
|
||||
this.a = x;
|
||||
}
|
||||
}
|
||||
|
||||
implements StasisProcess for Struct using s {
|
||||
fn stasis() -> int {
|
||||
return s.compute();
|
||||
}
|
||||
}
|
||||
|
||||
fn demo() -> int {
|
||||
let s = new Struct(1);
|
||||
let s2 = new Struct.createWithSomethingSpecial(2);
|
||||
let sp: StasisProcess = s;
|
||||
let sp2 = s as StasisProcess;
|
||||
let a = s.a;
|
||||
let _ = s2.compute();
|
||||
let b = sp.stasis();
|
||||
let c = sp2.stasis();
|
||||
return a + b + c;
|
||||
}
|
||||
```
|
||||
|
||||
### 3.7 Nominal callbacks
|
||||
|
||||
Rules:
|
||||
|
||||
- `declare callback Name(params...) -> R;` introduces a nominal callback type `Name`.
|
||||
- A callback type is not a `fn`, and a `fn` declaration does not implicitly define a callback type.
|
||||
- A value of callback type may be formed only from a compatible top-level `fn` in v1 core.
|
||||
- A value of callback type may also be formed by `bind(context, fn_name)` when the surrounding static type context expects a callback type.
|
||||
- Service methods are not assignable to callback values in v1 core.
|
||||
- Host methods are not assignable to callback values in v1 core.
|
||||
- Callback values do not capture local environment implicitly.
|
||||
- Assignment of a top-level `fn` to a callback type succeeds only when exactly one visible overload matches the callback signature.
|
||||
- `bind(context, fn_name)` succeeds only when exactly one visible top-level `fn` overload matches after consuming the first parameter with `context`.
|
||||
- Valid expected callback contexts for `bind(context, fn_name)` include variable initialization with an explicit callback type, assignment to an explicitly typed callback location, argument passing to a callback-typed parameter, and return from a callback-typed function.
|
||||
- The context expression in `bind(context, fn_name)` is evaluated once at bind time and stored explicitly in the resulting callback value.
|
||||
- When that stored context is identity-bearing, the resulting callback preserves the same captured identity rather than copying an independent underlying object.
|
||||
- `bind(context, fn_name)` does not introduce general closures; it is explicit partial binding of the first parameter only.
|
||||
- Callback compatibility ignores labels and compares ordered input/output slot types plus the return-surface kind.
|
||||
|
||||
Example:
|
||||
|
||||
```pbs
|
||||
declare callback TickCb(dt: int) -> void;
|
||||
|
||||
fn on_tick(dt: int) -> void {
|
||||
}
|
||||
|
||||
fn install_tick() -> void {
|
||||
let cb: TickCb = on_tick;
|
||||
let _ = cb;
|
||||
}
|
||||
```
|
||||
|
||||
Bound example:
|
||||
|
||||
```pbs
|
||||
declare callback UpdateCb(dt: int) -> void;
|
||||
|
||||
declare struct Enemy(hp: int);
|
||||
|
||||
fn update_enemy(self: Enemy, dt: int) -> void {
|
||||
}
|
||||
|
||||
fn install_update(enemy: Enemy) -> void {
|
||||
let cb: UpdateCb = bind(enemy, update_enemy);
|
||||
let _ = cb;
|
||||
}
|
||||
```
|
||||
|
||||
Ambiguous overload example:
|
||||
|
||||
```pbs
|
||||
declare callback TickCb(dt: int) -> void;
|
||||
|
||||
fn tick(dt: int) -> void {
|
||||
}
|
||||
|
||||
fn tick(time: int) -> void {
|
||||
}
|
||||
|
||||
fn install_tick() -> void {
|
||||
let cb: TickCb = tick; // error: ambiguous overloaded fn assignment
|
||||
}
|
||||
```
|
||||
|
||||
### 3.8 Canonical application
|
||||
|
||||
The canonical surface form for function application is:
|
||||
|
||||
```pbs
|
||||
callee apply arg
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `apply` is an infix operator that is right-associative.
|
||||
- `f1 apply f2 apply x` is defined as `f1 apply (f2 apply x)`.
|
||||
- `f1 apply f2 apply f3 apply params` is defined as `f1 apply (f2 apply (f3 apply params))`.
|
||||
- The left operand of `apply` must resolve to one of: a callable candidate set, a bound struct method target, a bound service method target, a contract-method target, or a callback value.
|
||||
- The right operand of `apply` is an argument expression.
|
||||
- If the callable input arity is `0`, the argument expression must be `()`.
|
||||
- If the callable input arity is `1`, the argument expression is checked against the carrier type of the single input slot.
|
||||
- If the callable input arity is `2..6`, the argument expression must have a named tuple shape with matching arity and positional types.
|
||||
- Input labels are not used for compatibility.
|
||||
- No single-slot tuple argument literal is required or recognized in surface syntax.
|
||||
- There is no partial application in v1 core.
|
||||
- There is no currying in v1 core.
|
||||
- Chained `apply` is nested ordinary application, not callable composition as a first-class value.
|
||||
- Callback values, service methods, host methods, struct methods, and contract-method targets use the same `apply` rules as top-level `fn`.
|
||||
|
||||
### 3.9 Call sugar
|
||||
|
||||
The surface form:
|
||||
|
||||
```pbs
|
||||
callee(arg1, arg2, ..., argN)
|
||||
```
|
||||
|
||||
desugars to the canonical `apply` surface according to arity.
|
||||
|
||||
Rules:
|
||||
|
||||
- The desugaring is purely syntactic.
|
||||
- `f()` is exact sugar for `f apply ()`.
|
||||
- `f(x)` is exact sugar for `f apply x`.
|
||||
- `f(x1, x2, ..., xn)` for `n >= 2` is exact sugar for `f apply (x1, x2, ..., xn)`.
|
||||
- No semantic distinction exists between direct call sugar and its canonical `apply` form.
|
||||
- When `(arg1, ..., argN)` is used as positional tuple sugar, the callee input tuple shape supplies the effective labels.
|
||||
- All overload resolution, diagnostics, and type checking are defined on the canonical `apply` form.
|
||||
|
||||
### 3.10 Result type of application
|
||||
|
||||
Rules:
|
||||
|
||||
- If the selected callable output arity is `0`, the result of `apply` is unit.
|
||||
- If the selected callable output arity is `1`, the result of `apply` is the carrier type of the single output slot.
|
||||
- If the selected callable output arity is `2..6`, the result of `apply` has the named output tuple shape of the selected callable.
|
||||
- Multi-slot output tuple results expose their labels for member projection.
|
||||
- If the selected callable is a callback value, the visible multi-slot output labels come from the callback type rather than from the original source `fn`.
|
||||
- If the selected callable returns `()`, the application result is unit.
|
||||
|
||||
Example:
|
||||
|
||||
```pbs
|
||||
fn func(a: int, b: int) -> (c: int, d: float) {
|
||||
return (c: a + b, d: 2.0);
|
||||
}
|
||||
|
||||
fn demo_apply() -> int {
|
||||
let params: (a: int, b: int) = (1, 2);
|
||||
let r = func apply params;
|
||||
let c = r.c;
|
||||
let d = r.d;
|
||||
let _ = d;
|
||||
return c;
|
||||
}
|
||||
```
|
||||
|
||||
In the example above:
|
||||
|
||||
- `func` has input tuple shape `(a: int, b: int)`,
|
||||
- `func` has output tuple shape `(c: int, d: float)`,
|
||||
- `r` has named output tuple type `(c: int, d: float)`,
|
||||
- `r.c` has type `int`,
|
||||
- `r.d` has type `float`.
|
||||
|
||||
Single-slot example:
|
||||
|
||||
```pbs
|
||||
fn plus_one(x: int) -> int {
|
||||
return x + 1;
|
||||
}
|
||||
|
||||
fn demo_single() -> void {
|
||||
let r = plus_one apply 1;
|
||||
if r == 2 {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In the example above:
|
||||
|
||||
- `plus_one` has input tuple shape `(x: int)`,
|
||||
- the argument `1` is accepted directly as the carrier value for the single input slot,
|
||||
- `plus_one` has output tuple shape `(value: int)`,
|
||||
- the value produced by `plus_one apply 1` has carrier type `int`,
|
||||
- `r.value` is not required and should not be used.
|
||||
|
||||
### 3.11 Overload resolution
|
||||
|
||||
Rules:
|
||||
|
||||
- Overload resolution starts from the visible callable candidates with the selected name.
|
||||
- Candidate filtering first uses callable kind and input tuple arity.
|
||||
- Remaining candidates are filtered by positional input type compatibility.
|
||||
- If exactly one candidate remains, resolution succeeds.
|
||||
- If multiple candidates remain, expected output types or expected multi-slot output tuple shapes may be used as a tie-breaker when statically available.
|
||||
- If multiple candidates still remain, the `apply` is ambiguous and compilation fails.
|
||||
- If no candidate remains, the `apply` is unresolved and compilation fails.
|
||||
- Overloads that differ only by labels are duplicates and are forbidden.
|
||||
- Overloads that differ only by output positional types are permitted, but uncontextualized `apply` sites may become ambiguous.
|
||||
|
||||
### 3.12 Member access and projection
|
||||
|
||||
Rules:
|
||||
|
||||
- `TypeName.case` is valid when `TypeName` resolves to a declared enum type and `case` resolves to one of its declared enum cases.
|
||||
- `TypeName.case` has static type `TypeName`.
|
||||
- `expr.name` is valid when the static type of `expr` is a declared `struct` containing field `name` and the access site is permitted to read that field.
|
||||
- For `struct` field access, the projected member type is the declared field type.
|
||||
- Reads of a private struct field are valid only through `this.name` inside methods and `ctor` bodies of the enclosing struct.
|
||||
- `expr.method` is a valid method-call target when the static type of `expr` is a concrete struct type declaring method `method`.
|
||||
- `expr.method` over a concrete struct receiver does not search visible contract implementations.
|
||||
- `expr.method` is a valid method-call target when the static type of `expr` is a concrete service type declaring method `method`.
|
||||
- `expr.method` over a concrete service receiver does not search visible contract implementations.
|
||||
- `HostName.method` is a valid method-call target when `HostName` resolves to a visible declared host owner whose body declares method `method`.
|
||||
- `TypeName.ctorName` is not a general member access surface; named constructors are entered only through `new TypeName.ctorName(...)`.
|
||||
- `expr.method` is a valid method-call target when the static type of `expr` is a contract value whose contract declares method `method`.
|
||||
- Bare extraction of a struct, service, host, builtin, or contract method as a value is invalid in v1 core because methods are not first-class.
|
||||
- `expr.name` is valid when the static type of `expr` is a multi-slot named output tuple containing label `name`.
|
||||
- For named output tuples, the projected member type is the type of the corresponding output slot.
|
||||
- Projection is label-based, not position-based.
|
||||
- `expr.name` is valid when the static type of `expr` is a builtin type declaring projection field `name`.
|
||||
- For builtin projection fields, the projected member type is the declared builtin field type.
|
||||
- `expr.method` is a valid method-call target when the static type of `expr` is a builtin type declaring intrinsic member `method`.
|
||||
- `expr.hasSome()` and `expr.hasNone()` are valid intrinsic method-call surfaces when the static type of `expr` is `optional<P>`.
|
||||
- `expr.hasSome()` and `expr.hasNone()` both have static type `bool`.
|
||||
- `expr.name()` and `expr.key()` are valid intrinsic method-call surfaces when the static type of `expr` is an enum type.
|
||||
- `expr.name()` has static type `str`.
|
||||
- `expr.key()` has static type `int`.
|
||||
- Access to a missing output label is a compile-time error.
|
||||
- Access to a missing struct field is a compile-time error.
|
||||
- Read access to an inaccessible private struct field is a compile-time error.
|
||||
- Write access to an inaccessible or non-`pub mut` struct field is a compile-time error.
|
||||
- Access to a missing struct method is a compile-time error.
|
||||
- Access to a missing service method is a compile-time error.
|
||||
- Access to a missing host method is a compile-time error.
|
||||
- Access to a missing contract method is a compile-time error.
|
||||
- Access to a missing builtin projection field is a compile-time error.
|
||||
- Access to a missing builtin intrinsic member is a compile-time error.
|
||||
- Member projection is not defined for single-slot collapsed carrier values.
|
||||
|
||||
### 3.13 Block expressions and function fallthrough
|
||||
|
||||
Rules:
|
||||
|
||||
- A block expression with a `TailExpr` has the static type of that final expression.
|
||||
- A block expression without a `TailExpr` has static type unit.
|
||||
- Only the final unsemicoloned expression in a block contributes to the block result.
|
||||
- A function body does not implicitly return its trailing `TailExpr`; explicit `return` and ordinary control-flow rules still apply.
|
||||
- Reaching the end of a plain non-unit function is a compile-time error unless all control-flow paths are proven to return explicitly.
|
||||
- Reaching the end of a `void` or `()` function is valid and yields unit.
|
||||
- Reaching the end of an `optional P` function yields `none`.
|
||||
- Reaching the end of a `result<E>` function is a compile-time error.
|
||||
|
||||
### 3.14 Loop forms
|
||||
|
||||
Rules:
|
||||
|
||||
- `while cond { ... }` requires `cond` to have static type `bool`.
|
||||
- `for i: T from start until end { ... }` is the declarative counted loop form in v1 core.
|
||||
- `for i: T from start until end step s { ... }` is the explicit-step counted loop form in v1 core.
|
||||
- In `for`, the declared iteration variable `i` introduces a loop-local binding of type `T`.
|
||||
- `start`, `end`, and `step` expressions in `for` must be type-compatible with the declared iteration type `T`.
|
||||
- If `step` is omitted, the loop uses the integer value `1` of the iteration type domain.
|
||||
- `for` iteration proceeds by evaluating `start`, `end`, and optional `step` once before loop entry.
|
||||
- `for ... until ...` uses an exclusive upper bound.
|
||||
- `continue` inside `while` transfers control to the next condition check.
|
||||
- `continue` inside `for` transfers control to the step update and then to the next bound check.
|
||||
- `break` exits the nearest enclosing loop.
|
||||
|
||||
### 3.15 `if` and `switch` conditional expressions
|
||||
|
||||
Rules:
|
||||
|
||||
- In `if cond { a } else { b }`, `cond` must have static type `bool`.
|
||||
- Only the selected branch is evaluated at runtime.
|
||||
- The branch expressions `a` and `b` must have the same static type, subject only to ordinary contextual typing already defined elsewhere in the language.
|
||||
- The static result type of the `if` expression is that shared static type.
|
||||
- In `switch selector { pattern: { ... }, ... }`, the selector expression is evaluated once.
|
||||
- `switch` accepts enum selectors and literal-comparable scalar selectors; `error` selectors are invalid.
|
||||
- Each non-wildcard `switch` arm pattern must be unique within the same `switch`.
|
||||
- Each non-wildcard `switch` arm pattern must be type-compatible with the selector expression.
|
||||
- Enum-case switch patterns must resolve to declared cases of the selector's enum type.
|
||||
- Error labels are not valid switch patterns.
|
||||
- `default` and `_` are equivalent wildcard spellings for `switch`.
|
||||
- At most one wildcard arm may appear in a `switch`.
|
||||
- A `switch` must not mix `default` and `_` in the same arm set.
|
||||
- The blocks of all `switch` arms must have the same static type, subject only to ordinary contextual typing already defined elsewhere in the language.
|
||||
- The static result type of the `switch` expression is that shared static type.
|
||||
- A `switch` used as an `ExprStmt` is valid when the selected arm blocks evaluate to unit.
|
||||
- A `switch` expression used in a value-required position must be exhaustive, either by a wildcard arm or by another statically proven exhaustive case set.
|
||||
|
||||
### 3.16 `optional` construction and extraction
|
||||
|
||||
Rules:
|
||||
|
||||
- `some(expr)` forms an `optional<P>` value where `P` is the static type of `expr`, unless an expected `optional<Q>` context is present and constrains `expr` to be compatible with `Q`.
|
||||
- `some(expr)` is invalid when the payload normalizes to `void`.
|
||||
- `none` is valid only when an expected `optional<P>` type is available from context.
|
||||
- `opt else fallback` requires the left operand to have static type `optional<P>`.
|
||||
- In `opt else fallback`, the `fallback` expression must be compatible with payload shape `P`.
|
||||
- The static result type of `opt else fallback` is the carrier value type for single-slot payloads and the named tuple payload shape for multi-slot payloads.
|
||||
- `opt else fallback` does not introduce implicit mutation or unwrapping side effects beyond normal expression evaluation.
|
||||
|
||||
### 3.17 `result<E>` return flow and handling
|
||||
|
||||
Rules:
|
||||
|
||||
- `return ok(expr);` is valid only inside a function whose declared return surface is `result<E> P`.
|
||||
- In `return ok(expr);`, `expr` must be compatible with the declared success payload shape `P`.
|
||||
- `return err(E.label);` is valid only inside a function whose declared return surface is `result<E> P`.
|
||||
- In `return err(E.label);`, the error path must resolve to a declared case of the same error type `E`.
|
||||
- `ok(...)` and `err(...)` are special result-flow forms rather than ordinary value expressions.
|
||||
- `expr!` requires `expr` to have static type `result<E> P`.
|
||||
- `expr!` is valid only when the enclosing function returns `result<E> Q` for the same error type `E`.
|
||||
- The static result type of `expr!` is the extracted success payload shape `P`, collapsed to its carrier value when single-slot.
|
||||
- `handle expr { ... }` requires `expr` to have static type `result<E1> P`.
|
||||
- `handle expr { ... }` is valid only when the enclosing function returns `result<E2> Q` for some payload `Q`.
|
||||
- Each non-wildcard `handle` arm must match a distinct declared case of `E1`.
|
||||
- `handle` arms must be exhaustive over `E1`, either by naming all cases exactly once or by providing `_`.
|
||||
- The static result type of `handle expr { ... }` is the extracted success payload shape `P`, collapsed to its carrier value when single-slot.
|
||||
- A short `handle` arm `E1.case -> E2.case` is valid only when `E2.case` resolves to a declared case of the target error type `E2`.
|
||||
- A block `handle` arm must terminate with either `ok(payload)` or `err(E2.case)`.
|
||||
- In a `handle` arm, `ok(payload)` is valid only when `payload` is compatible with the success payload shape `P`.
|
||||
- In a `handle` arm, `err(E2.case)` is valid only when `E2.case` resolves to a declared case of the target error type `E2`.
|
||||
- In a `handle` arm, `ok(payload)` yields the value of the `handle` expression, while `err(E2.case)` performs immediate enclosing-function return.
|
||||
|
||||
### 3.18 Required static diagnostics
|
||||
|
||||
At minimum, deterministic static diagnostics are required for:
|
||||
|
||||
- duplicate parameter names in `fn` declarations,
|
||||
- duplicate declaration names in the same namespace/scope,
|
||||
- duplicate output labels in named tuple returns,
|
||||
- duplicate error case labels in `declare error`,
|
||||
- duplicate enum case labels in `declare enum`,
|
||||
- duplicate enum case identifiers in `declare enum`,
|
||||
- invalid mixed implicit/explicit enum case identifiers,
|
||||
- invalid `this` usage outside struct method, service method, or `ctor` body,
|
||||
- invalid `Self` type usage outside struct method, service method, or `ctor` declarations,
|
||||
- invalid struct method declaration shape,
|
||||
- invalid service method declaration shape,
|
||||
- invalid host declaration shape,
|
||||
- invalid host method declaration shape,
|
||||
- invalid attribute surface,
|
||||
- invalid `Host` attribute target,
|
||||
- invalid `Capability` attribute target,
|
||||
- invalid `BuiltinType` attribute target,
|
||||
- invalid `BuiltinConst` attribute target,
|
||||
- invalid `IntrinsicCall` attribute target,
|
||||
- duplicate `Host` attribute on one host method,
|
||||
- missing required `Host` attribute on a reserved host method,
|
||||
- malformed `Host(module=..., name=..., version=...)` argument set,
|
||||
- invalid empty `Host.module` or `Host.name`,
|
||||
- invalid non-positive `Host.version`,
|
||||
- malformed `Capability(name=...)` argument set,
|
||||
- invalid empty or non-canonical `Capability.name`,
|
||||
- invalid builtin declaration shape,
|
||||
- invalid builtin method declaration shape,
|
||||
- missing required `BuiltinType` attribute on a reserved builtin declaration,
|
||||
- malformed `BuiltinType(name=..., version=...)` argument set,
|
||||
- invalid empty `BuiltinType.name`,
|
||||
- invalid non-positive `BuiltinType.version`,
|
||||
- malformed `IntrinsicCall(name=..., version=...)` argument set,
|
||||
- invalid empty `IntrinsicCall.name`,
|
||||
- invalid non-positive `IntrinsicCall.version`,
|
||||
- malformed `BuiltinConst(target=..., name=..., version=...)` argument set,
|
||||
- invalid empty `BuiltinConst.target` or `BuiltinConst.name`,
|
||||
- invalid non-positive `BuiltinConst.version`,
|
||||
- builtin field type not builtin-layout-admissible,
|
||||
- cyclic builtin layout composition,
|
||||
- unresolved flattened builtin layout width,
|
||||
- duplicate canonical builtin type identity,
|
||||
- duplicate canonical builtin intrinsic identity,
|
||||
- duplicate canonical builtin constant identity,
|
||||
- invalid `ctor` declaration shape,
|
||||
- invalid `return` inside `ctor`,
|
||||
- incomplete field initialization on a completing `ctor` path,
|
||||
- duplicate `implements Contract for Owner` pair,
|
||||
- `implements` declared outside the owner module of the struct or service,
|
||||
- incompatible or missing contract method implementation,
|
||||
- invalid contract coercion from concrete struct or service value,
|
||||
- unresolved barrel function signature after label-insensitive matching,
|
||||
- unresolved host barrel entry,
|
||||
- unresolved callback barrel entry,
|
||||
- invalid enum case path,
|
||||
- invalid enum intrinsic member call,
|
||||
- invalid named constructor target,
|
||||
- unresolved named constructor overload,
|
||||
- ambiguous named constructor overload,
|
||||
- incompatible top-level `fn` assignment to callback type,
|
||||
- ambiguous overloaded top-level `fn` assignment to callback type,
|
||||
- attempted assignment of service method to callback type,
|
||||
- attempted assignment of host method to callback type,
|
||||
- use of `bind(...)` without an expected callback type,
|
||||
- incompatible `bind(...)` context type for callback target,
|
||||
- ambiguous overloaded top-level `fn` target in `bind(...)`,
|
||||
- `apply` on a non-callable target,
|
||||
- arity mismatch in `apply`,
|
||||
- argument type mismatch in `apply`,
|
||||
- `apply` chain with incompatible intermediate carrier/tuple shape,
|
||||
- ambiguous overload resolution,
|
||||
- unresolved callable application,
|
||||
- possible fallthrough of plain non-unit function,
|
||||
- non-boolean `while` condition,
|
||||
- invalid `for` iteration type,
|
||||
- incompatible `for` bound or step type,
|
||||
- non-boolean `if` expression condition,
|
||||
- incompatible `if` expression branch types,
|
||||
- duplicate `switch` arm pattern,
|
||||
- mixed `default` and `_` wildcard arms in `switch`,
|
||||
- invalid `switch` selector type,
|
||||
- selector-pattern type mismatch in `switch`,
|
||||
- invalid enum case switch pattern,
|
||||
- incompatible `switch` arm block types,
|
||||
- non-exhaustive `switch` expression in value position,
|
||||
- invalid mixed `optional`/`result` return surface,
|
||||
- invalid payload-less `optional` type surface,
|
||||
- invalid `optional void` type surface,
|
||||
- invalid reuse of a builtin simple type name for a user-authored type declaration,
|
||||
- missing explicit type annotation on `declare const`,
|
||||
- missing initializer on non-builtin `declare const`,
|
||||
- non-constant `declare const` initializer,
|
||||
- incompatible `declare const` initializer type,
|
||||
- cyclic dependency among `declare const` declarations,
|
||||
- unresolved referenced `declare const` in constant evaluation,
|
||||
- invalid `none` usage without expected optional type,
|
||||
- invalid `else` extraction over non-optional operand,
|
||||
- fallback type mismatch in `else` extraction,
|
||||
- invalid `some(...)` construction form,
|
||||
- use of `ok(...)` or `err(...)` outside allowed result-flow positions,
|
||||
- invalid `ok(...)` construction form,
|
||||
- invalid `err(...)` construction form,
|
||||
- invalid error label in `err(...)`,
|
||||
- invalid `!` propagation on non-result expression,
|
||||
- mismatched error type in `!` propagation,
|
||||
- invalid `handle` on non-result expression,
|
||||
- non-exhaustive `handle` mapping,
|
||||
- duplicate `handle` mapping arm,
|
||||
- invalid mapped error label in `handle`,
|
||||
- invalid `ok(...)` payload in `handle`,
|
||||
- invalid terminal form of a `handle` arm block,
|
||||
- attempted use of a single-slot tuple literal where no such surface form exists,
|
||||
- member access on a missing struct field,
|
||||
- read access to an inaccessible private struct field,
|
||||
- write access to an inaccessible or non-`pub mut` struct field,
|
||||
- member access on a missing struct method,
|
||||
- member access on a missing service method,
|
||||
- member access on a missing host method,
|
||||
- member access on a missing contract method,
|
||||
- member access on a missing builtin projection field,
|
||||
- member access on a missing builtin intrinsic member,
|
||||
- bare method extraction from a struct, service, host, builtin, or contract value,
|
||||
- member projection on a single-slot carrier value,
|
||||
- invalid optional intrinsic member call,
|
||||
- invalid builtin intrinsic member call,
|
||||
- member projection on a missing named output label.
|
||||
@@ -0,0 +1,452 @@
|
||||
# PBS Manifest, Module, Stdlib, and SDK Resolution Specification
|
||||
|
||||
Status: Draft v2 (Normative)
|
||||
Applies to: `prometeu.json`, project and module terminology, workspace dependency resolution, stdlib selection, reserved stdlib projects, interface-module loading, and compile-time SDK metadata
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
This document defines the normative compile-time model for:
|
||||
|
||||
- project manifests,
|
||||
- project and module identity,
|
||||
- import resolution,
|
||||
- stdlib selection,
|
||||
- reserved stdlib project spaces,
|
||||
- stdlib interface modules,
|
||||
- and the compile-time lifecycle of SDK host-binding metadata.
|
||||
|
||||
This document is the authority for how the compiler discovers and loads:
|
||||
|
||||
- ordinary project modules,
|
||||
- reserved stdlib modules such as `@sdk:gfx`,
|
||||
- compile-time reserved metadata attached to those reserved modules,
|
||||
- and interface-only service facades that wrap host surfaces for source ergonomics.
|
||||
|
||||
This document does not define runtime load behavior.
|
||||
PBX host-binding emission and loader-side syscall resolution are defined by the Host ABI Binding and Loader Resolution Specification.
|
||||
|
||||
## 2. Scope
|
||||
|
||||
This document defines:
|
||||
|
||||
- the role of `language` in `prometeu.json`,
|
||||
- the role of `stdlib` in `prometeu.json`,
|
||||
- the distinction between projects, modules, and imports,
|
||||
- the distinction between ordinary project dependencies and the stdlib environment,
|
||||
- root-project ownership of the effective stdlib line of a build,
|
||||
- reserved project spaces such as `@sdk:*` and `@core:*`,
|
||||
- the source model for stdlib interface modules,
|
||||
- the compile-time role of reserved attributes such as `[Host(...)]`.
|
||||
|
||||
This document does not define:
|
||||
|
||||
- PBX binary layout,
|
||||
- loader-side syscall resolution,
|
||||
- cartridge capability policy,
|
||||
- package registry protocol details,
|
||||
- runtime reflection over attributes.
|
||||
|
||||
## 3. Core Terms
|
||||
|
||||
### 3.1 Project
|
||||
|
||||
A project is the unit described by `prometeu.json`.
|
||||
|
||||
Rules:
|
||||
|
||||
- A project has a `name`, `version`, `language`, `stdlib`, and `dependencies`.
|
||||
- A project is the unit resolved by the workspace dependency graph.
|
||||
- A project is the unit selected by a dependency declaration.
|
||||
- A project is the unit published and versioned by ordinary dependency resolution.
|
||||
- A project contains one or more modules.
|
||||
|
||||
### 3.2 Module
|
||||
|
||||
A module is the unit of source import inside a project.
|
||||
|
||||
Rules:
|
||||
|
||||
- Every `.pbs` source file belongs to exactly one module.
|
||||
- Every module belongs to exactly one project.
|
||||
- Imports select modules, not whole projects.
|
||||
- A module is addressed by a project name plus a module path.
|
||||
|
||||
### 3.3 Canonical module address
|
||||
|
||||
The canonical PBS module address format is:
|
||||
|
||||
```text
|
||||
@project:path/to/module
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `project` identifies the owning project space.
|
||||
- `path/to/module` identifies the module path inside that project.
|
||||
- Module path segments are directory-style segments separated by `/`.
|
||||
- The syntax is Java-like in organization and JavaScript-like in import surface.
|
||||
|
||||
Examples:
|
||||
|
||||
- `@game:player/state`
|
||||
- `@physics:collision/shapes`
|
||||
- `@sdk:gfx`
|
||||
- `@core:math/vector`
|
||||
|
||||
### 3.4 Reserved project spaces
|
||||
|
||||
The following project spaces are reserved:
|
||||
|
||||
- `@sdk:*`
|
||||
- `@core:*`
|
||||
|
||||
Rules:
|
||||
|
||||
- Reserved project spaces belong to the selected stdlib environment.
|
||||
- Ordinary user-authored projects MUST NOT publish modules into reserved project spaces.
|
||||
- Ordinary dependency resolution MUST NOT satisfy `@sdk:*` or `@core:*` imports from user projects.
|
||||
- Reserved project spaces are resolved only from the selected stdlib environment.
|
||||
|
||||
## 4. `prometeu.json`
|
||||
|
||||
### 4.1 Required fields
|
||||
|
||||
The manifest format relevant to this document is:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "main",
|
||||
"version": "1.0.0",
|
||||
"language": "pbs",
|
||||
"stdlib": "1",
|
||||
"dependencies": [
|
||||
{ "name": "dep1", "version": "1.0.0" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `name` identifies the project.
|
||||
- `version` identifies the project version.
|
||||
- `language` identifies the frontend language.
|
||||
- `stdlib` identifies the selected stdlib major line.
|
||||
- `dependencies` declare ordinary project dependencies only.
|
||||
|
||||
### 4.2 `language`
|
||||
|
||||
Rules:
|
||||
|
||||
- `language` selects the compiler frontend.
|
||||
- All projects in one resolved workspace MUST use the same `language`.
|
||||
- Unknown `language` values are compile-time errors.
|
||||
|
||||
### 4.3 `stdlib`
|
||||
|
||||
Rules:
|
||||
|
||||
- `stdlib` is required in every manifest.
|
||||
- `stdlib` uses major-only version syntax in v1.
|
||||
- The manifest surface for `stdlib` is a string containing a positive decimal integer.
|
||||
- Examples of valid values: `"1"`, `"2"`.
|
||||
- Examples of invalid values: `"0"`, `"01"`, `"1.0"`, `"v1"`, `""`.
|
||||
- Implementations SHOULD normalize `stdlib` internally to an integer major version.
|
||||
|
||||
Diagnostics:
|
||||
|
||||
- Missing `stdlib` is a manifest error.
|
||||
- Invalid major-only format is a manifest error.
|
||||
|
||||
## 5. Ordinary Dependencies vs Stdlib Environment
|
||||
|
||||
### 5.1 Ordinary dependencies
|
||||
|
||||
Rules:
|
||||
|
||||
- `dependencies` model ordinary project relationships only.
|
||||
- A dependency may be local or registry-based according to the compiler's dependency resolver.
|
||||
- Dependencies contribute source projects, modules, and project-graph edges.
|
||||
- `dependencies` do not declare stdlib projects.
|
||||
|
||||
### 5.2 Stdlib environment
|
||||
|
||||
Rules:
|
||||
|
||||
- The stdlib environment is not declared through `dependencies`.
|
||||
- The stdlib environment is selected through `stdlib`.
|
||||
- `@sdk:*` and `@core:*` imports resolve against the stdlib environment selected for the build.
|
||||
- The presence of stdlib modules does not imply automatic visibility in source.
|
||||
- User code MUST still import stdlib modules explicitly through ordinary import syntax.
|
||||
|
||||
Example:
|
||||
|
||||
```pbs
|
||||
import { Gfx, color } from @sdk:gfx;
|
||||
|
||||
let c: color = color.red;
|
||||
Gfx.draw_pixel(1, 1, c);
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `Gfx` is not implicitly in scope.
|
||||
- `Gfx` becomes visible only through `import`.
|
||||
- The compiler accepts that import because the selected stdlib environment exposes `@sdk:gfx`.
|
||||
|
||||
## 6. Effective Stdlib of the Build
|
||||
|
||||
The root project owns the effective stdlib line of the build.
|
||||
|
||||
Rules:
|
||||
|
||||
- The resolved workspace has exactly one effective stdlib major version.
|
||||
- The effective stdlib major version is taken from the root project manifest.
|
||||
- All projects in the workspace compile under that same effective stdlib line.
|
||||
- Dependency projects do not activate separate stdlib environments for themselves.
|
||||
|
||||
This means:
|
||||
|
||||
- `stdlib` on a dependency is a compatibility declaration,
|
||||
- not an instruction to switch the compiler into another stdlib mode for that dependency.
|
||||
|
||||
## 7. Stdlib Compatibility Across Dependency Projects
|
||||
|
||||
Let:
|
||||
|
||||
- `R` be the root project's `stdlib` major,
|
||||
- `D` be a dependency project's `stdlib` major.
|
||||
|
||||
Rules:
|
||||
|
||||
- If `D > R`, dependency resolution MUST fail with a deterministic compile-time error.
|
||||
- If `D <= R`, dependency resolution MAY proceed.
|
||||
- `D <= R` does not guarantee semantic compatibility of all APIs used by the dependency; it only means the dependency is not asking for a newer stdlib line than the root selected.
|
||||
|
||||
Rationale:
|
||||
|
||||
- the build target is chosen by the root project,
|
||||
- dependency projects may target the same or an older stdlib line,
|
||||
- dependency projects must not force the build to silently adopt a newer stdlib than the root requested.
|
||||
|
||||
Example:
|
||||
|
||||
- root `stdlib = "1"`, dependency `stdlib = "2"`: error.
|
||||
- root `stdlib = "2"`, dependency `stdlib = "1"`: allowed.
|
||||
- root `stdlib = "1"`, dependency `stdlib = "1"`: allowed.
|
||||
|
||||
## 8. Import Resolution
|
||||
|
||||
### 8.1 Resolution sources
|
||||
|
||||
The compiler resolves imports against exactly two sources:
|
||||
|
||||
1. the selected stdlib environment,
|
||||
2. the resolved ordinary project dependency graph.
|
||||
|
||||
Rules:
|
||||
|
||||
- `@sdk:*` and `@core:*` are resolved only against the stdlib environment,
|
||||
- all other `@project:*` imports are resolved only against the ordinary dependency graph,
|
||||
- there is no fallback from reserved stdlib resolution to ordinary dependencies,
|
||||
- there is no fallback from ordinary dependency resolution to reserved stdlib spaces.
|
||||
|
||||
### 8.2 Resolution algorithm
|
||||
|
||||
For an import:
|
||||
|
||||
```pbs
|
||||
import { X } from @project:path/to/module;
|
||||
```
|
||||
|
||||
the compiler MUST:
|
||||
|
||||
1. parse the project space and module path,
|
||||
2. determine whether the project space is reserved,
|
||||
3. if reserved, resolve the module from the selected stdlib environment,
|
||||
4. otherwise, resolve the module from the root project or its dependency graph,
|
||||
5. load the target module,
|
||||
6. resolve the requested exported names from that module.
|
||||
|
||||
Failure at any step is a deterministic compile-time error.
|
||||
|
||||
## 9. Stdlib Interface Modules
|
||||
|
||||
### 9.1 Interface-module model
|
||||
|
||||
The selected stdlib environment MUST provide its modules as PBS-like interface modules.
|
||||
|
||||
Rules:
|
||||
|
||||
- Stdlib modules are `.pbs` modules loaded by the compiler.
|
||||
- Stdlib interface modules use the same parser surface as ordinary PBS modules.
|
||||
- Stdlib interface modules are interpreted in interface-module mode.
|
||||
- Interface-module mode is non-executable and compile-time only.
|
||||
- Interface modules participate in import resolution and type checking.
|
||||
- Interface modules do not emit executable bytecode by themselves.
|
||||
|
||||
### 9.2 Allowed role
|
||||
|
||||
At minimum, an interface module may provide:
|
||||
|
||||
- exported names,
|
||||
- types,
|
||||
- enums,
|
||||
- host owners,
|
||||
- method signatures,
|
||||
- compile-time metadata such as canonical host-binding attributes.
|
||||
|
||||
This list fixes the currently required declarative role of interface modules, but does not by itself freeze the final complete declaration set allowed in interface-module mode.
|
||||
|
||||
An interface module is not runtime code.
|
||||
|
||||
### 9.3 Interface-module restrictions
|
||||
|
||||
At minimum, an interface module MUST remain declarative.
|
||||
|
||||
Rules:
|
||||
|
||||
- Interface modules MUST NOT contain top-level executable statements.
|
||||
- Interface modules MUST NOT require runtime initialization.
|
||||
- Interface modules MUST NOT introduce executable method bodies that would emit bytecode.
|
||||
- `declare host` is permitted only in reserved stdlib/toolchain interface modules.
|
||||
- Reserved attributes such as `[Host(...)]` are permitted only where another specification explicitly allows them.
|
||||
|
||||
### 9.4 Example interface module
|
||||
|
||||
Illustrative stdlib interface module:
|
||||
|
||||
```pbs
|
||||
declare enum color(red, green, blue);
|
||||
|
||||
declare host Gfx {
|
||||
[Host(module = "gfx", name = "draw_pixel", version = 1)]
|
||||
fn draw_pixel(x: int, y: int, c: color);
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- This module is valid only in a reserved stdlib/interface-module context.
|
||||
- It contributes compile-time symbols and metadata.
|
||||
- It does not produce executable bytecode by itself.
|
||||
|
||||
## 10. Compiler Loading of the Stdlib Environment
|
||||
|
||||
The compiler loads the stdlib environment from the stdlib line selected by the root project.
|
||||
|
||||
Required model:
|
||||
|
||||
1. Read the root `prometeu.json`.
|
||||
2. Determine the effective stdlib major line.
|
||||
3. Mount or select the matching stdlib environment.
|
||||
4. Expose its reserved project spaces such as `@sdk:*` and `@core:*`.
|
||||
5. Load interface modules from that environment on demand during import resolution.
|
||||
6. Parse those modules with the ordinary PBS parser.
|
||||
7. Validate them under interface-module semantic rules.
|
||||
8. Populate the compiler's symbol graph from their exported declarations and attributes.
|
||||
|
||||
Rules:
|
||||
|
||||
- The compiler MUST behave as if it were loading real modules, not hardcoded symbol tables.
|
||||
- The physical storage format of the stdlib environment is an implementation detail.
|
||||
- The compiler MAY load the stdlib environment from disk, embedded resources, a virtual filesystem, or another implementation-defined source with equivalent behavior.
|
||||
- For the Studio PBS frontend, embedding stdlib interface modules under frontend `resources` is a valid implementation strategy.
|
||||
|
||||
## 11. Reserved Attributes and Metadata Lifecycle
|
||||
|
||||
### 11.1 General rule
|
||||
|
||||
Attributes are compile-time metadata, not runtime objects.
|
||||
|
||||
Rules:
|
||||
|
||||
- Attributes are parsed as part of the source module.
|
||||
- Attributes participate in declaration validation and compiler metadata extraction.
|
||||
- Attributes are not exported as ordinary values, types, or runtime-reflectable objects.
|
||||
- Attributes do not automatically survive into bytecode, PBX, or runtime metadata.
|
||||
|
||||
### 11.2 `Host` attribute
|
||||
|
||||
The canonical reserved host-binding attribute is:
|
||||
|
||||
```pbs
|
||||
[Host(module = "gfx", name = "draw_pixel", version = 1)]
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `Host` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
|
||||
- `Host` provides the canonical host primitive identity used by compiler lowering.
|
||||
- `module` and `name` are string literals.
|
||||
- `version` is a positive integer literal.
|
||||
- The attribute surface itself is compile-time only.
|
||||
|
||||
### 11.3 Lowering effect
|
||||
|
||||
Although the attribute syntax itself is compile-time only, its semantic effect may be lowered.
|
||||
|
||||
Rules:
|
||||
|
||||
- The compiler consumes `Host` metadata while resolving host-backed SDK members.
|
||||
- The compiler uses that metadata to emit runtime-facing host-binding declarations as defined by the Host ABI Binding specification.
|
||||
- The compiler does not export the raw `[Host(...)]` syntax into runtime as a source-level attribute object.
|
||||
|
||||
In other words:
|
||||
|
||||
- the attribute is compile-time metadata,
|
||||
- the lowered host-binding declaration is runtime-facing artifact metadata,
|
||||
- they are not the same thing.
|
||||
|
||||
## 12. Relationship to `declare host`
|
||||
|
||||
Rules:
|
||||
|
||||
- `declare host` remains reserved to SDK/toolchain-controlled modules.
|
||||
- Ordinary user-authored project modules do not declare canonical host bindings directly.
|
||||
- User code consumes SDK exports through normal imports.
|
||||
- SDK-facing surfaces such as `Gfx.draw_pixel(...)` are resolved by the compiler against the selected stdlib environment.
|
||||
- Canonical host identity comes from reserved host-binding metadata such as `[Host(...)]`, not from the source spelling of the imported owner.
|
||||
|
||||
## 13. Project Publication and Distribution
|
||||
|
||||
Rules:
|
||||
|
||||
- Ordinary publication and dependency resolution operate at project granularity.
|
||||
- A published project version contains one or more modules.
|
||||
- Imports consume modules from a resolved project.
|
||||
- The stdlib environment is distributed separately from ordinary project dependencies.
|
||||
- The stdlib environment is selected by `stdlib`, not by `dependencies`.
|
||||
|
||||
## 14. Non-Goals
|
||||
|
||||
- Making stdlib modules implicitly visible without `import`.
|
||||
- Treating the stdlib as an ordinary dependency in the workspace graph.
|
||||
- Allowing each dependency project to activate its own stdlib line.
|
||||
- Hardcoding stdlib symbols directly into the compiler without a module model.
|
||||
- Runtime reflection over source-level attributes.
|
||||
|
||||
## 15. Open Items Deferred
|
||||
|
||||
The following remain intentionally deferred:
|
||||
|
||||
1. Exact on-disk distribution format of stdlib environment packs.
|
||||
2. Registry/publication protocol details for ordinary projects.
|
||||
3. Final diagnostics catalog for all import-resolution failures.
|
||||
4. Full list of declarations allowed inside interface modules beyond the already-fixed reserved host surfaces.
|
||||
|
||||
## 16. Current Decision Summary
|
||||
|
||||
The current PBS design direction is:
|
||||
|
||||
1. `prometeu.json` declares `language` and `stdlib` separately.
|
||||
2. A project is the unit described by `prometeu.json` and selected by `dependencies`.
|
||||
3. A module is the unit selected by `import`.
|
||||
4. Canonical module addresses use `@project:path/to/module`.
|
||||
5. `@sdk:*` and `@core:*` are reserved stdlib project spaces.
|
||||
6. The root project selects the effective stdlib line for the whole build.
|
||||
7. Dependency projects with a higher stdlib requirement than the root are rejected.
|
||||
8. Stdlib modules are loaded as PBS-like interface modules, not as ordinary dependencies.
|
||||
9. Interface modules are compile-time-only in packaging terms: they may carry declarative service facades with method bodies for source-level API ergonomics, but they still do not emit executable bytecode as standalone modules.
|
||||
10. `declare host` remains reserved to stdlib/toolchain interface modules.
|
||||
11. Reserved attributes such as `[Host(...)]` are compile-time metadata, not runtime objects.
|
||||
12. The compiler consumes `Host` metadata to produce runtime-facing host-binding artifacts defined elsewhere.
|
||||
@@ -0,0 +1,377 @@
|
||||
# VM-owned vs Host-backed
|
||||
|
||||
Status: Draft v1 (Temporary)
|
||||
Applies to: ownership classification of PBS-visible operations, runtime boundary selection, and the normative distinction between VM-defined semantics and host-provided services
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
This document defines the normative distinction between:
|
||||
|
||||
- VM-owned operations,
|
||||
- host-backed operations,
|
||||
- and user-defined program operations.
|
||||
|
||||
Its purpose is to prevent semantic drift between:
|
||||
|
||||
- builtin language behavior,
|
||||
- VM execution behavior,
|
||||
- host/platform integration,
|
||||
- and source-level surfaces that may look similar while belonging to different ownership domains.
|
||||
|
||||
This document exists because PBS must distinguish at least three different kinds
|
||||
of callable behavior:
|
||||
|
||||
- program-owned functions,
|
||||
- VM-owned intrinsic behavior,
|
||||
- host-backed services.
|
||||
|
||||
Without this distinction, the language would conflate:
|
||||
|
||||
- builtin semantics with syscalls,
|
||||
- source-level shells with runtime authority,
|
||||
- and VM contracts with host capability-gated services.
|
||||
|
||||
## 2. Scope
|
||||
|
||||
This document defines:
|
||||
|
||||
- the ownership model for callable behavior visible to PBS programs,
|
||||
- the normative difference between VM-owned and host-backed operations,
|
||||
- the runtime boundary crossed by each operation category,
|
||||
- the relationship between ownership and lowering form,
|
||||
- the relationship between ownership and determinism,
|
||||
- the relationship between ownership and capability checks,
|
||||
- the relationship between ownership and loader resolution,
|
||||
- and the classification rule used to decide whether a surface belongs to the VM or to the host.
|
||||
|
||||
This document does not define:
|
||||
|
||||
- the full parser grammar for builtin declarations,
|
||||
- the full intrinsic registry binary format,
|
||||
- the final PBX section numbering for intrinsic metadata,
|
||||
- subsystem-specific host APIs such as GFX or AUDIO,
|
||||
- or the complete dynamic semantics of every builtin type.
|
||||
|
||||
## 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. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
|
||||
7. `6.2. Host ABI Binding and Loader Resolution Specification.md`
|
||||
8. This document
|
||||
|
||||
If a rule here conflicts with higher-precedence authority, the higher-precedence
|
||||
authority wins.
|
||||
|
||||
## 4. Normative Inputs
|
||||
|
||||
This document depends on, at minimum:
|
||||
|
||||
- `1. Language Charter.md`
|
||||
- `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`
|
||||
|
||||
## 5. Core Ownership Model
|
||||
|
||||
PBS distinguishes three ownership categories for callable behavior.
|
||||
|
||||
### 5.1 Program-owned function
|
||||
|
||||
A program-owned function is authored by the program and compiled from a PBS body.
|
||||
|
||||
Properties:
|
||||
|
||||
- semantic ownership belongs to the program,
|
||||
- execution stays inside the VM,
|
||||
- source definition includes an executable body,
|
||||
- runtime dispatch uses ordinary function-call machinery,
|
||||
- authority does not depend on host capability grants.
|
||||
|
||||
### 5.2 VM-owned operation
|
||||
|
||||
A VM-owned operation is part of the semantic contract of the PBS platform.
|
||||
|
||||
Properties:
|
||||
|
||||
- semantic ownership belongs to the VM platform,
|
||||
- execution stays inside the VM,
|
||||
- behavior is not defined by user-authored PBS bodies,
|
||||
- behavior is not resolved against host registries,
|
||||
- behavior is not granted or denied by host capabilities,
|
||||
- and behavior is expected to remain semantically canonical across conforming implementations.
|
||||
|
||||
VM-owned operations include, at minimum:
|
||||
|
||||
- intrinsic operations over builtin types,
|
||||
- compiler-recognized intrinsic method-call surfaces over core semantic forms,
|
||||
- and other future VM-defined semantic helpers explicitly designated by spec.
|
||||
|
||||
### 5.3 Host-backed operation
|
||||
|
||||
A host-backed operation is provided by the runtime environment outside the VM's
|
||||
closed semantic domain.
|
||||
|
||||
Properties:
|
||||
|
||||
- semantic authority belongs to the host platform,
|
||||
- execution crosses the VM-to-host boundary,
|
||||
- resolution uses canonical host identity,
|
||||
- loader validation and capability checks are required before execution,
|
||||
- and the final executable form is numeric host dispatch.
|
||||
|
||||
Host-backed operations are the domain of `declare host`, PBX `SYSC`, loader
|
||||
resolution, and final `SYSCALL`.
|
||||
|
||||
## 6. The Boundary Question
|
||||
|
||||
The normative classification question is:
|
||||
|
||||
```text
|
||||
Does this operation belong to the VM's semantic contract, or does it require a
|
||||
service owned by the external host platform?
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- If the operation expresses builtin language or VM semantics, it is VM-owned.
|
||||
- If the operation requires host-provided authority, devices, or platform services, it is host-backed.
|
||||
- If the operation is implemented by ordinary source code in the current program, it is program-owned.
|
||||
|
||||
Heuristic:
|
||||
|
||||
- if the operation must still have a complete meaning in a host-minimal VM, it is VM-owned,
|
||||
- if the operation loses meaning without external platform service, it is host-backed.
|
||||
|
||||
Examples:
|
||||
|
||||
- `Vec2.dot(other)` is VM-owned,
|
||||
- `Color.rgb(r, g, b)` is VM-owned,
|
||||
- `optional.hasSome()` is VM-owned,
|
||||
- `enumValue.name()` is VM-owned,
|
||||
- `Gfx.draw_pixel(x, y, c)` is host-backed,
|
||||
- `Input.is_pressed(button)` is host-backed.
|
||||
|
||||
## 7. Runtime Boundary and Resolution Model
|
||||
|
||||
### 7.1 VM-owned operations
|
||||
|
||||
VM-owned operations do not cross the host boundary.
|
||||
|
||||
Rules:
|
||||
|
||||
- they do not resolve through the host syscall registry,
|
||||
- they do not emit `SYSC`,
|
||||
- they do not require loader-side capability checks,
|
||||
- they are not represented by `declare host`,
|
||||
- and they execute through VM-owned machinery such as intrinsic dispatch or other VM-defined execution paths.
|
||||
|
||||
### 7.2 Host-backed operations
|
||||
|
||||
Host-backed operations cross the VM boundary and require host authority.
|
||||
|
||||
Rules:
|
||||
|
||||
- they resolve by canonical host identity `(module, name, version)`,
|
||||
- they are represented in source through reserved host-binding surfaces,
|
||||
- they emit PBX host-binding metadata,
|
||||
- they are validated against authoritative host metadata during load,
|
||||
- and they execute in final form through `SYSCALL`.
|
||||
|
||||
## 8. Semantic Authority
|
||||
|
||||
The semantic owner of an operation is the layer that defines its normative
|
||||
meaning.
|
||||
|
||||
### 8.1 VM-owned semantic authority
|
||||
|
||||
For VM-owned operations:
|
||||
|
||||
- the VM platform defines the operation's meaning,
|
||||
- the frontend may expose shell declarations but does not define behavior,
|
||||
- the host runtime must not redefine the operation's language-level semantics,
|
||||
- and the HAL may consume produced values but must not own their semantic definition.
|
||||
|
||||
### 8.2 Host-backed semantic authority
|
||||
|
||||
For host-backed operations:
|
||||
|
||||
- the host platform defines the authoritative service identity and ABI,
|
||||
- the frontend exposes a compile-time shell only,
|
||||
- the loader resolves the shell's canonical identity against the host registry,
|
||||
- and the VM executes only the numeric form after loader patching.
|
||||
|
||||
## 9. Determinism and Environmental Dependence
|
||||
|
||||
Determinism requirements differ by ownership category.
|
||||
|
||||
### 9.1 VM-owned operations
|
||||
|
||||
VM-owned operations must not derive meaning from host service behavior.
|
||||
|
||||
Rules:
|
||||
|
||||
- a VM-owned operation must not call the host as part of its semantic definition,
|
||||
- a VM-owned operation must not require host capability grants,
|
||||
- a VM-owned operation must not depend on wall-clock time unless a higher-precedence authority explicitly allows it,
|
||||
- a VM-owned operation must not depend on frontend-generated helper algorithms for its canonical behavior,
|
||||
- and the VM contract must be specific enough that conformance can test its behavior.
|
||||
|
||||
This does not require every VM-owned operation to be mathematically pure.
|
||||
It does require the operation's meaning to be owned and specified by the VM
|
||||
contract rather than delegated to the host.
|
||||
|
||||
### 9.2 Host-backed operations
|
||||
|
||||
Host-backed operations may depend on host state, devices, permissions, or
|
||||
platform policy.
|
||||
|
||||
Rules:
|
||||
|
||||
- host-backed operations may be denied by capability policy,
|
||||
- host-backed operations may vary by platform implementation within their ABI contract,
|
||||
- and host-backed operations are not reclassified as VM-owned merely because the source surface resembles an ordinary method call.
|
||||
|
||||
## 10. Artifact Implications
|
||||
|
||||
Ownership classification determines artifact form.
|
||||
|
||||
### 10.1 Program-owned function artifact direction
|
||||
|
||||
Program-owned functions lower to ordinary program call machinery.
|
||||
|
||||
### 10.2 VM-owned artifact direction
|
||||
|
||||
VM-owned operations lower to VM-facing artifacts.
|
||||
|
||||
Illustrative forms:
|
||||
|
||||
- direct intrinsic ids such as `INTRINSIC <id>`,
|
||||
- temporary intrinsic declaration tables plus pre-resolution callsites,
|
||||
- or other VM-internal runtime forms explicitly defined by future spec.
|
||||
|
||||
Rules:
|
||||
|
||||
- VM-owned operations must not be encoded as host-binding metadata merely because they are not authored in user code,
|
||||
- and VM-owned operations must not require host registry lookup.
|
||||
|
||||
### 10.3 Host-backed artifact direction
|
||||
|
||||
Host-backed operations lower to host-facing artifacts.
|
||||
|
||||
Rules:
|
||||
|
||||
- host-backed operations emit host-binding declarations into `SYSC`,
|
||||
- host-backed callsites use `HOSTCALL <sysc_index>` before load,
|
||||
- the loader resolves and patches those callsites,
|
||||
- and final execution uses `SYSCALL <id>`.
|
||||
|
||||
## 11. Source Surface Similarity Does Not Collapse Ownership
|
||||
|
||||
Two source surfaces may look similar while belonging to different ownership
|
||||
domains.
|
||||
|
||||
Examples:
|
||||
|
||||
- `Vec2.length()` may be VM-owned,
|
||||
- `Gfx.clear(color)` may be host-backed,
|
||||
- `value.name()` over an enum may be VM-owned,
|
||||
- and `service.method()` may be program-owned or service-owned ordinary PBS behavior.
|
||||
|
||||
Rules:
|
||||
|
||||
- source-level method-call syntax does not determine ownership,
|
||||
- declaration shape does not determine ownership,
|
||||
- ownership is determined by semantic authority and runtime boundary,
|
||||
- and toolchain metadata must classify the operation explicitly where ambiguity could arise.
|
||||
|
||||
## 12. Relationship to `declare host`
|
||||
|
||||
`declare host` is reserved exclusively for host-backed surfaces.
|
||||
|
||||
Rules:
|
||||
|
||||
- `declare host` must not be reused to model VM-owned builtin semantics,
|
||||
- host attributes such as `Host(module, name, version)` must not be used to identify VM-owned intrinsic behavior,
|
||||
- and a source surface that represents VM-owned behavior must use VM-specific metadata and lowering rules.
|
||||
|
||||
Rationale:
|
||||
|
||||
- `declare host` communicates external service ownership,
|
||||
- host attributes communicate loader-facing canonical identity,
|
||||
- and reusing them for VM-owned behavior would incorrectly imply host resolution, capability gating, and host semantic authority.
|
||||
|
||||
## 13. Relationship to Builtin Types and Intrinsics
|
||||
|
||||
Builtin types are VM-facing semantic types.
|
||||
|
||||
Rules:
|
||||
|
||||
- builtin types are not host APIs,
|
||||
- builtin type operations that belong to the builtin domain are VM-owned,
|
||||
- builtin constants, projections, constructors, and intrinsic methods are classified by VM semantics rather than by host service ownership,
|
||||
- and builtin values may later be passed to host-backed operations without transferring semantic ownership of the type itself.
|
||||
|
||||
Example:
|
||||
|
||||
- `Color` is VM-owned as a semantic type,
|
||||
- `Color.rgb(...)` is VM-owned,
|
||||
- `Pixel` may contain `Color` in its builtin layout,
|
||||
- `Gfx.draw_pixel(x, y, c)` is host-backed even when `c` has a VM-owned builtin type.
|
||||
|
||||
## 14. Relationship to `stdlib` and SDK Surfaces
|
||||
|
||||
`stdlib` and SDK packaging expose compile-time surfaces.
|
||||
|
||||
Rules:
|
||||
|
||||
- SDK or stdlib shells may expose both VM-owned and host-backed surfaces,
|
||||
- shell placement alone does not determine runtime ownership,
|
||||
- the runtime-facing artifact contract must preserve the true ownership category,
|
||||
- and compile-time convenience must not collapse VM-owned and host-backed operations into the same runtime mechanism.
|
||||
|
||||
## 15. Classification Checklist
|
||||
|
||||
When introducing a new callable surface, the spec author or toolchain author
|
||||
must answer at least these questions:
|
||||
|
||||
1. Who owns the semantic meaning of this operation?
|
||||
2. Does the operation require host-provided authority, devices, or policy?
|
||||
3. Must the loader resolve the operation against an external registry?
|
||||
4. Can the operation be denied by capabilities?
|
||||
5. Should the operation continue to exist with complete meaning in a host-minimal VM?
|
||||
6. Is the operation part of builtin language semantics rather than platform service integration?
|
||||
|
||||
Classification rule:
|
||||
|
||||
- If answers 2, 3, or 4 are yes, the operation is host-backed.
|
||||
- If answer 6 is yes and 2, 3, and 4 are no, the operation is VM-owned.
|
||||
- Otherwise the operation is program-owned unless another spec defines a distinct category.
|
||||
|
||||
## 16. Conformance Expectations
|
||||
|
||||
Conforming implementations must preserve the ownership boundary.
|
||||
|
||||
Rules:
|
||||
|
||||
- an implementation must not lower VM-owned builtin semantics through the host syscall pipeline,
|
||||
- an implementation must not treat host-backed operations as if they were VM-defined intrinsic semantics,
|
||||
- an implementation must preserve the loader-facing host-binding contract for host-backed surfaces,
|
||||
- and an implementation must preserve VM-facing semantic ownership for builtin and intrinsic operations.
|
||||
|
||||
## 17. Current Decision Summary
|
||||
|
||||
The current model is:
|
||||
|
||||
1. Program-authored functions are program-owned and execute through ordinary call machinery.
|
||||
2. Builtin semantics and intrinsic behavior are VM-owned.
|
||||
3. External platform services are host-backed.
|
||||
4. VM-owned behavior must not be modeled as `declare host`.
|
||||
5. Host-backed behavior must continue to use canonical host identity, `SYSC`, loader resolution, and final `SYSCALL`.
|
||||
6. Ownership is determined by semantic authority and runtime boundary, not by source-level syntax resemblance.
|
||||
@@ -0,0 +1,560 @@
|
||||
# Intrinsics and Builtin Types Specification
|
||||
|
||||
Status: Draft v1 (Temporary)
|
||||
Applies to: builtin type declarations, builtin constants, intrinsic member surfaces, builtin layout metadata, lowering direction, and artifact-facing intrinsic contracts
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
This document defines the PBS-facing contract for:
|
||||
|
||||
- VM-owned builtin types,
|
||||
- VM-owned intrinsic operations,
|
||||
- and source-level shells that expose those features to PBS programs.
|
||||
|
||||
Its purpose is to let the frontend expose builtin semantic types such as
|
||||
`Vec2`, `Color`, and `Pixel` as first-class language types while preserving
|
||||
three invariants:
|
||||
|
||||
- semantic ownership remains with the VM,
|
||||
- builtin values have canonical stack layout,
|
||||
- and builtin domain behavior does not drift into host bindings or frontend helper code.
|
||||
|
||||
## 2. Scope
|
||||
|
||||
This document defines:
|
||||
|
||||
- the source-level shell model for `declare builtin type`,
|
||||
- the canonical metadata carried by builtin type declarations,
|
||||
- builtin constants declared through reserved metadata,
|
||||
- builtin field layout and projection rules,
|
||||
- admissible field types for builtin layouts,
|
||||
- intrinsic member metadata and owner inheritance,
|
||||
- lowering categories for builtin declarations and members,
|
||||
- the runtime-facing artifact direction for intrinsic operations,
|
||||
- and canonical intrinsic registry ownership at ISA/profile boundary.
|
||||
|
||||
This document does not define:
|
||||
|
||||
- the full final parser grammar integration into `3. Core Syntax Specification.md`,
|
||||
- the final PBX section numbering for intrinsic declarations,
|
||||
- the full VM intrinsic registry binary format,
|
||||
- user-extensible builtin types,
|
||||
- or heap-backed builtin layouts.
|
||||
|
||||
## 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. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
|
||||
7. `6.2. Host ABI Binding and Loader Resolution Specification.md`
|
||||
8. `6. VM-owned vs Host-backed.md`
|
||||
9. This document
|
||||
|
||||
If a rule here conflicts with higher-precedence authority, the higher-precedence
|
||||
authority wins.
|
||||
|
||||
## 4. Normative Inputs
|
||||
|
||||
This document depends on, at minimum:
|
||||
|
||||
- `1. Language Charter.md`
|
||||
- `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`
|
||||
- `6. VM-owned vs Host-backed.md`
|
||||
- `13. Lowering IRBackend Specification.md`
|
||||
- `15. Bytecode and PBX Mapping Specification.md`
|
||||
|
||||
## 5. Core Model
|
||||
|
||||
### 5.1 Builtin type
|
||||
|
||||
A builtin type is a VM-owned semantic type whose language-visible identity is
|
||||
not authored by ordinary user code.
|
||||
|
||||
Properties:
|
||||
|
||||
- the type is first-class in the PBS type system,
|
||||
- the type has canonical layout metadata,
|
||||
- the type may expose field-like projection surfaces,
|
||||
- the type may expose intrinsic member-call surfaces,
|
||||
- and the type's semantic meaning is owned by the VM rather than by `stdlib`, SDK packaging, or the host.
|
||||
|
||||
### 5.2 Builtin declaration shell
|
||||
|
||||
`declare builtin type` is a reserved shell declaration.
|
||||
|
||||
Properties:
|
||||
|
||||
- it exists for binding, checking, lowering, and artifact emission,
|
||||
- it has no user-authored executable body,
|
||||
- and it does not transfer semantic ownership away from the VM registry.
|
||||
|
||||
### 5.3 Builtin constant
|
||||
|
||||
A builtin constant is a VM-owned named value exposed to source through a
|
||||
reserved top-level `declare const` shell carrying builtin metadata.
|
||||
|
||||
### 5.4 Intrinsic operation
|
||||
|
||||
An intrinsic operation is a VM-owned callable behavior with canonical
|
||||
definition in the VM contract.
|
||||
|
||||
### 5.5 Canonical intrinsic registry artifact
|
||||
|
||||
Final intrinsic ids are owned by one canonical ISA-scoped registry artifact.
|
||||
|
||||
Rules:
|
||||
|
||||
- compiler and runtime consumers must derive final intrinsic ids from that same artifact,
|
||||
- dual-authoring of compiler-local and runtime-local intrinsic-id maps is forbidden,
|
||||
- strict CI mode must fail on parity mismatch between consumer snapshots and canonical artifact.
|
||||
|
||||
## 6. Reserved Surface Forms
|
||||
|
||||
This document temporarily defines the intended source-level shell shape.
|
||||
Final parser integration belongs to `3. Core Syntax Specification.md`.
|
||||
|
||||
### 6.1 Builtin type shell
|
||||
|
||||
Illustrative form:
|
||||
|
||||
```pbs
|
||||
[BuiltinType(name="vec2", version=1)]
|
||||
declare builtin type Vec2(
|
||||
pub x: float,
|
||||
pub y: float,
|
||||
) {
|
||||
[IntrinsicCall(name="dot")]
|
||||
fn dot(other: Vec2) -> float;
|
||||
|
||||
[IntrinsicCall(name="length")]
|
||||
fn length() -> float;
|
||||
}
|
||||
```
|
||||
|
||||
### 6.2 Builtin constant shell
|
||||
|
||||
Illustrative form:
|
||||
|
||||
```pbs
|
||||
[BuiltinConst(target="vec2", name="zero", version=1)]
|
||||
declare const ZERO: Vec2;
|
||||
```
|
||||
|
||||
## 7. `BuiltinType` Metadata
|
||||
|
||||
`BuiltinType` declares the canonical VM-facing identity of a builtin type.
|
||||
|
||||
Required fields:
|
||||
|
||||
- `name`
|
||||
- `version`
|
||||
|
||||
Rules:
|
||||
|
||||
- the declaration name after `declare builtin type` is the PBS-visible type name,
|
||||
- `BuiltinType.name` is the canonical VM identity name,
|
||||
- `BuiltinType.version` is the canonical semantic version of that builtin contract,
|
||||
- the VM identity name need not equal the PBS-visible type name,
|
||||
- and the pair `(name, version)` is the canonical builtin type identity in v1.
|
||||
|
||||
Example:
|
||||
|
||||
- source-visible name: `Vec2`
|
||||
- canonical builtin identity: `("vec2", 1)`
|
||||
|
||||
## 8. Declaration Form and Structural Rules
|
||||
|
||||
`declare builtin type` uses a field-list surface similar to nominal aggregate
|
||||
declarations.
|
||||
|
||||
Rules:
|
||||
|
||||
- `declare builtin type` is reserved to SDK/toolchain-controlled modules,
|
||||
- ordinary user-authored modules must reject it,
|
||||
- the declaration introduces a type name in the type namespace,
|
||||
- the parenthesized member list declares builtin field projections,
|
||||
- the body may contain signatures only,
|
||||
- the body must not contain executable PBS statements,
|
||||
- builtin members must not declare PBS bodies,
|
||||
- and builtin declarations must not be used to encode ordinary user-defined structs.
|
||||
|
||||
This surface is intentionally shell-like.
|
||||
The declaration is not the implementation authority for builtin behavior.
|
||||
|
||||
## 9. Builtin Fields Are Projections, Not Ordinary Storage Fields
|
||||
|
||||
The field-like entries in a builtin declaration describe named projections over a
|
||||
canonical VM layout.
|
||||
|
||||
Rules:
|
||||
|
||||
- they are not ordinary user-defined struct fields,
|
||||
- their names are visible for projection syntax such as `value.x`,
|
||||
- they describe a canonical flattened layout order,
|
||||
- and their meaning is projection over VM-owned builtin value representation.
|
||||
|
||||
Consequences:
|
||||
|
||||
- a builtin field declaration does not imply ordinary mutability semantics,
|
||||
- a builtin field declaration does not imply that builtin values are structs,
|
||||
- and a builtin field declaration does not allow user code to provide storage-level implementation bodies.
|
||||
|
||||
## 10. Builtin Slot Inference
|
||||
|
||||
Builtin field slot offsets are inferred by the compiler, not authored in source.
|
||||
|
||||
Rules:
|
||||
|
||||
- slot offsets are zero-based and deterministic,
|
||||
- offsets are computed from declaration order plus flattened widths of field types,
|
||||
- nested builtin fields contribute their full flattened width to subsequent offsets,
|
||||
- and source-level `Slot(...)` metadata is forbidden in v1.
|
||||
|
||||
## 11. Builtin Layout Admissibility
|
||||
|
||||
Builtin field types are restricted.
|
||||
|
||||
A type is builtin-layout-admissible when it has:
|
||||
|
||||
- fixed width in slots,
|
||||
- finite flattened layout,
|
||||
- stack-only representation in this feature set,
|
||||
- and canonical VM-owned layout metadata.
|
||||
|
||||
In v1 temporary scope, builtin-layout-admissible types are:
|
||||
|
||||
- predeclared builtin scalar types whose runtime contract defines fixed slot width,
|
||||
- and declared builtin types whose own layout is fixed, finite, and stack-only.
|
||||
|
||||
The following are not builtin-layout-admissible unless a future spec explicitly
|
||||
changes the rule:
|
||||
|
||||
- user-declared structs,
|
||||
- services,
|
||||
- contracts,
|
||||
- callbacks,
|
||||
- `optional`,
|
||||
- `result`,
|
||||
- and any type with runtime-variable or heap-defined width.
|
||||
|
||||
## 12. Nested Builtin Layout and Flattening
|
||||
|
||||
Builtin fields may refer to other builtin-layout-admissible types.
|
||||
|
||||
Rules:
|
||||
|
||||
- nested builtin field types flatten recursively into the enclosing layout,
|
||||
- the enclosing builtin layout is the concatenation of its fields' flattened layouts in slot order,
|
||||
- a nested field retains its nominal field identity for projection purposes,
|
||||
- and verifier-facing slot widths are computed from the fully flattened layout.
|
||||
|
||||
Example:
|
||||
|
||||
```pbs
|
||||
[BuiltinType(name="color", version=1)]
|
||||
declare builtin type Color(
|
||||
pub raw: int,
|
||||
);
|
||||
|
||||
[BuiltinType(name="pixel", version=1)]
|
||||
declare builtin type Pixel(
|
||||
pub x: int,
|
||||
pub y: int,
|
||||
pub color: Color,
|
||||
);
|
||||
```
|
||||
|
||||
Canonical semantic layout:
|
||||
|
||||
```text
|
||||
Pixel -> [int, int, Color]
|
||||
```
|
||||
|
||||
Canonical flattened slot layout:
|
||||
|
||||
```text
|
||||
Pixel -> [int, int, int]
|
||||
```
|
||||
|
||||
## 13. Member Categories
|
||||
|
||||
Builtin members belong to one of the following semantic categories:
|
||||
|
||||
1. projection surface,
|
||||
2. builtin constant surface,
|
||||
3. layout-only constructor or factory surface,
|
||||
4. intrinsic call surface.
|
||||
|
||||
This document normatively defines projection, builtin constants, and intrinsic
|
||||
call surfaces.
|
||||
Layout-only constructors may be introduced by future syntax or by existing
|
||||
constructor lowering rules, but their implementation remains VM-facing rather
|
||||
than host-backed.
|
||||
|
||||
## 14. `IntrinsicCall` Metadata
|
||||
|
||||
`IntrinsicCall` identifies a VM-owned callable member over builtin semantics.
|
||||
|
||||
Required fields:
|
||||
|
||||
- `name`
|
||||
|
||||
Optional fields:
|
||||
|
||||
- `version`
|
||||
|
||||
Rules:
|
||||
|
||||
- `IntrinsicCall` is valid only on method signatures declared inside a `declare builtin type` body,
|
||||
- the enclosing `BuiltinType` provides the default intrinsic owner identity,
|
||||
- `IntrinsicCall.name` is the canonical intrinsic operation name within that owner,
|
||||
- if `IntrinsicCall.version` is omitted, it inherits the enclosing builtin type version,
|
||||
- if `IntrinsicCall.version` is present, it overrides only the operation version,
|
||||
- and `IntrinsicCall` must not be interpreted as host-binding metadata.
|
||||
|
||||
Canonical intrinsic identity in v1 is:
|
||||
|
||||
```text
|
||||
(owner, name, version)
|
||||
```
|
||||
|
||||
where:
|
||||
|
||||
- `owner` is inherited from `BuiltinType.name`,
|
||||
- `name` is taken from `IntrinsicCall.name`,
|
||||
- and `version` is inherited or overridden as above.
|
||||
|
||||
Example:
|
||||
|
||||
```pbs
|
||||
[BuiltinType(name="vec2", version=1)]
|
||||
declare builtin type Vec2(
|
||||
pub x: float,
|
||||
pub y: float,
|
||||
) {
|
||||
[IntrinsicCall(name="dot")]
|
||||
fn dot(other: Vec2) -> float;
|
||||
}
|
||||
```
|
||||
|
||||
declares canonical intrinsic identity:
|
||||
|
||||
```text
|
||||
("vec2", "dot", 1)
|
||||
```
|
||||
|
||||
## 15. `BuiltinConst` Metadata
|
||||
|
||||
`BuiltinConst` identifies a VM-owned named constant surface.
|
||||
|
||||
Required fields:
|
||||
|
||||
- `target`
|
||||
- `name`
|
||||
- `version`
|
||||
|
||||
Rules:
|
||||
|
||||
- `BuiltinConst` is valid only on reserved top-level `declare const` shells,
|
||||
- `target` identifies the canonical builtin owner name,
|
||||
- `name` identifies the canonical constant name within that builtin owner,
|
||||
- `version` identifies the constant contract version,
|
||||
- the declared PBS constant name is source-visible and may differ from the canonical constant name,
|
||||
- and builtin constants are VM-owned declarations, not host bindings.
|
||||
|
||||
Example:
|
||||
|
||||
```pbs
|
||||
[BuiltinConst(target="vec2", name="zero", version=1)]
|
||||
declare const ZERO: Vec2;
|
||||
```
|
||||
|
||||
declares a source-visible constant `ZERO` whose canonical builtin constant
|
||||
identity is:
|
||||
|
||||
```text
|
||||
("vec2", "zero", 1)
|
||||
```
|
||||
|
||||
## 16. Static Semantics
|
||||
|
||||
The following static rules apply.
|
||||
|
||||
### 16.1 Namespace rules
|
||||
|
||||
Rules:
|
||||
|
||||
- `declare builtin type` introduces a nominal type name in the type namespace,
|
||||
- builtin type names participate in visibility and import rules like other reserved type declarations,
|
||||
- ordinary user-authored type declarations must not redeclare visible builtin type names in the same scope,
|
||||
- and builtin constants declared through `declare const` introduce names in the value namespace.
|
||||
|
||||
### 16.2 Member lookup rules
|
||||
|
||||
Rules:
|
||||
|
||||
- `expr.field` is valid when `expr` has a builtin type declaring a projection field named `field`,
|
||||
- the projected type is the field's declared type,
|
||||
- `expr.method()` is valid when the builtin type declares a matching intrinsic member surface,
|
||||
- and missing builtin fields or members are compile-time errors.
|
||||
|
||||
### 16.3 Body restrictions
|
||||
|
||||
Rules:
|
||||
|
||||
- builtin declarations have no executable member bodies,
|
||||
- builtin methods are signature-only shells,
|
||||
- builtin constants are declaration-only shells,
|
||||
- and ordinary user code must not implement builtin semantics in PBS bodies.
|
||||
|
||||
## 17. Lowering Model
|
||||
|
||||
Builtin shells guide lowering; they do not supply executable implementation.
|
||||
|
||||
### 17.1 Projection lowering
|
||||
|
||||
Projection over builtin fields lowers to canonical projection over flattened
|
||||
layout.
|
||||
|
||||
Rules:
|
||||
|
||||
- field projection does not imply host interaction,
|
||||
- field projection does not emit `SYSC`,
|
||||
- field projection may lower to direct stack projection, reshaping operations, or another VM-owned form,
|
||||
- and the projected semantics are determined by builtin layout metadata.
|
||||
|
||||
### 17.2 Builtin constant lowering
|
||||
|
||||
Builtin constants lower to VM-owned constant materialization.
|
||||
|
||||
Rules:
|
||||
|
||||
- builtin constants must not lower through host binding resolution,
|
||||
- builtin constants may lower to direct value materialization, VM-owned constant pool lookup, or intrinsic-like constant fetch,
|
||||
- and the canonical constant identity determines which VM-owned value is materialized.
|
||||
|
||||
### 17.3 Intrinsic method lowering
|
||||
|
||||
Intrinsic methods lower to VM-owned intrinsic call behavior.
|
||||
|
||||
Rules:
|
||||
|
||||
- intrinsic methods must not lower through `SYSC`,
|
||||
- intrinsic methods must not emit `HOSTCALL`,
|
||||
- intrinsic method identities lower from `(owner, name, version)` metadata,
|
||||
- and the runtime-facing call form is VM-facing rather than host-facing.
|
||||
|
||||
## 18. Artifact Direction
|
||||
|
||||
This feature requires a distinct intrinsic artifact path.
|
||||
|
||||
Illustrative final executable form:
|
||||
|
||||
```text
|
||||
INTRINSIC <id>
|
||||
```
|
||||
|
||||
Illustrative optional pre-resolution form:
|
||||
|
||||
```text
|
||||
INTRCALL <decl_index>
|
||||
```
|
||||
|
||||
with declaration metadata carrying:
|
||||
|
||||
```text
|
||||
(owner, name, version)
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- implementations may emit final `INTRINSIC <id>` directly when intrinsic ids are stable for the targeted VM contract,
|
||||
- implementations may emit declaration-based intrinsic callsites when a preload resolution step is desired,
|
||||
- any such intrinsic declaration path remains VM-facing and must not reuse host-binding metadata,
|
||||
- and intrinsic artifacts are distinct from `SYSC`, `HOSTCALL`, and `SYSCALL`.
|
||||
|
||||
## 19. Verifier Obligations
|
||||
|
||||
The verifier must treat intrinsics and builtin layouts as first-class structural
|
||||
facts.
|
||||
|
||||
Rules:
|
||||
|
||||
- each builtin type has a known flattened slot width,
|
||||
- each intrinsic has known argument and result layouts,
|
||||
- verifier stack effects are computed from flattened layouts rather than only from source spellings,
|
||||
- and verifier reasoning must preserve nominal builtin type identity even when two builtin layouts occupy the same slot width.
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
Vec2.dot(Vec2, Vec2) -> float
|
||||
```
|
||||
|
||||
If `Vec2` flattens to two float-width slots, the verifier-facing stack effect is:
|
||||
|
||||
```text
|
||||
pop 4, push 1
|
||||
```
|
||||
|
||||
## 20. Determinism and Ownership Rules
|
||||
|
||||
Builtin and intrinsic semantics are VM-owned.
|
||||
|
||||
Rules:
|
||||
|
||||
- builtin operations must not rely on host registry resolution,
|
||||
- builtin operations must not require runtime capability grants,
|
||||
- builtin operations must not be specified merely as frontend helper code,
|
||||
- and builtin operations must remain within the VM-owned category defined by `6. VM-owned vs Host-backed.md`.
|
||||
|
||||
## 21. Relationship to `stdlib` and SDK Packaging
|
||||
|
||||
`stdlib` and SDK packaging may expose builtin declarations as compile-time
|
||||
surfaces.
|
||||
|
||||
Rules:
|
||||
|
||||
- packaging location does not make builtin semantics host-backed,
|
||||
- source modules may import builtin shells from reserved stdlib surfaces,
|
||||
- the shell remains descriptive rather than semantically authoritative,
|
||||
- and the VM contract remains the owner of builtin identities, layouts, constants, and intrinsic behavior.
|
||||
|
||||
## 22. Deterministic Static Errors
|
||||
|
||||
At minimum, a conforming implementation must reject:
|
||||
|
||||
1. `declare builtin type` in an ordinary user-authored module,
|
||||
2. missing required `BuiltinType` metadata on a builtin declaration,
|
||||
3. duplicate builtin field names within one declaration,
|
||||
4. source-level `Slot(...)` usage in builtin declarations,
|
||||
5. builtin field types that are not builtin-layout-admissible,
|
||||
6. `IntrinsicCall` used outside a builtin declaration body,
|
||||
7. `BuiltinConst` used outside a reserved top-level `declare const` shell,
|
||||
8. duplicate canonical builtin type identities in the same compilation environment,
|
||||
9. duplicate intrinsic canonical identities within the same builtin owner and version line,
|
||||
10. cyclic or unresolved flattened builtin layout composition,
|
||||
11. executable member bodies inside builtin declarations,
|
||||
12. any lowering that routes VM-owned builtin operations through the host-binding pipeline.
|
||||
|
||||
## 23. Current Decision Summary
|
||||
|
||||
The current temporary contract is:
|
||||
|
||||
1. Builtin types are VM-owned semantic types exposed through reserved shell declarations.
|
||||
2. `BuiltinType(name, version)` maps source-visible type names to canonical VM builtin identities.
|
||||
3. Builtin fields describe projection surfaces over canonical flattened layout.
|
||||
4. Builtin field types must be builtin-layout-admissible and stack-only in this feature set.
|
||||
5. Builtin types may contain other builtin-layout-admissible types, including nested builtin composition such as `Pixel` containing `Color`.
|
||||
6. `IntrinsicCall(name, version?)` identifies VM-owned intrinsic member behavior and inherits owner identity from the enclosing builtin type.
|
||||
7. `BuiltinConst(target, name, version)` exposes VM-owned builtin constants through reserved top-level `declare const` shells.
|
||||
8. Builtin projections, constants, and intrinsic calls must not lower through `SYSC`, `HOSTCALL`, or `SYSCALL`.
|
||||
9. Runtime-facing intrinsic artifacts are distinct from host-binding artifacts.
|
||||
@@ -0,0 +1,428 @@
|
||||
# Host ABI Binding and Loader Resolution Specification
|
||||
|
||||
Status: Draft v1 (Temporary)
|
||||
Applies to: PBX host-binding metadata, cartridge load, canonical syscall resolution, and loader-side capability gating
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
This document defines the current contract between:
|
||||
|
||||
- the PBS compiler/toolchain,
|
||||
- the PBX program artifact,
|
||||
- the cartridge loader,
|
||||
- and the host syscall registry.
|
||||
|
||||
Its purpose is to let compiler and runtime work in parallel without diverging on the most critical boundary:
|
||||
how host-backed SDK calls become load-time-resolved numeric syscalls.
|
||||
|
||||
This document is intentionally narrower than a full PBX or VM specification.
|
||||
It focuses on loader behavior and the minimum artifact contract the loader must consume.
|
||||
|
||||
## 2. Scope
|
||||
|
||||
This document defines:
|
||||
|
||||
- the canonical identity of a host binding,
|
||||
- the relationship between `declare host` and canonical host bindings,
|
||||
- the minimum PBX metadata required for load-time host resolution,
|
||||
- the pre-load opcode form used for host-backed call sites,
|
||||
- the required loader algorithm,
|
||||
- the required loader patching step from pre-load host callsites to numeric syscalls,
|
||||
- the division of responsibility between loader-side ABI checks and verifier-side stack checks,
|
||||
- capability checks required during load,
|
||||
- deterministic loader failures for malformed or unauthorized host usage,
|
||||
- the requirement that VM execution remains numeric-only.
|
||||
|
||||
This document does not define:
|
||||
|
||||
- the full PBX module format,
|
||||
- the exact in-memory patching strategy used by the loader,
|
||||
- the publication format of stdlib SDK packs,
|
||||
- the semantics of individual subsystems such as GFX or AUDIO.
|
||||
|
||||
## 3. Normative Inputs
|
||||
|
||||
This document follows two prior decisions:
|
||||
|
||||
1. Canonical host identity is defined by the hardware ABI as `(module, name, version)`.
|
||||
2. User code does not declare host bindings directly; SDK/toolchain-controlled modules expose reserved `declare host` surfaces and the compiler lowers those usages into PBX host-binding metadata.
|
||||
|
||||
This document therefore treats:
|
||||
|
||||
- `declare host Gfx { fn draw_pixel(...); }`
|
||||
|
||||
as compile-time surface only, and treats:
|
||||
|
||||
- `("gfx", "draw_pixel", 1)`
|
||||
|
||||
as the normative runtime-facing identity.
|
||||
|
||||
## 4. Core Model
|
||||
|
||||
The host-binding pipeline is:
|
||||
|
||||
1. User code imports SDK surfaces such as `Gfx` from `@sdk:gfx`.
|
||||
2. The compiler resolves those surfaces against the selected stdlib line.
|
||||
3. The compiler maps each host-backed SDK member to a canonical identity `(module, name, version)`.
|
||||
4. The compiler emits those required canonical identities into the PBX `SYSC` table.
|
||||
5. The compiler emits pre-load host call sites as `HOSTCALL <sysc_index>`.
|
||||
6. At cartridge load time, the loader resolves `SYSC` entries against the host syscall registry.
|
||||
7. The loader verifies ABI compatibility and capabilities before execution starts.
|
||||
8. The loader rewrites every `HOSTCALL <sysc_index>` into `SYSCALL <id>`.
|
||||
9. The VM executes only numeric syscall identifiers.
|
||||
|
||||
The loader never resolves host bindings from source-level names such as `Gfx.draw_pixel`.
|
||||
It resolves only canonical identities declared in the PBX.
|
||||
|
||||
## 5. Canonical Host Binding Identity
|
||||
|
||||
Every host binding is identified by the triple:
|
||||
|
||||
```text
|
||||
(module, name, version)
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `module` is the canonical host subsystem namespace, such as `gfx` or `audio`.
|
||||
- `name` is the canonical host operation name within that module.
|
||||
- `version` is the canonical ABI version of that host operation.
|
||||
- This identity is stable across source languages and SDK naming styles.
|
||||
- This identity is the only identity used by the loader for host resolution.
|
||||
|
||||
Source-level owners such as `Gfx` are SDK-facing aliases.
|
||||
They are not loader-facing identities.
|
||||
|
||||
## 6. Relationship to `declare host`
|
||||
|
||||
`declare host` is a reserved SDK/toolchain surface used to expose host-backed APIs to source programs.
|
||||
|
||||
Rules:
|
||||
|
||||
- User-authored project modules do not declare canonical host bindings directly.
|
||||
- `declare host` exists to define compile-time interface shape, not executable PBS bodies.
|
||||
- The compiler is responsible for mapping each host-backed member to its canonical host identity.
|
||||
- The PBX must not depend on source spellings such as `Gfx` for runtime resolution.
|
||||
|
||||
Example:
|
||||
|
||||
```pbs
|
||||
import { Gfx, color } from @sdk:gfx;
|
||||
|
||||
let c: color = color.red;
|
||||
Gfx.draw_pixel(1, 1, c);
|
||||
```
|
||||
|
||||
The source-level call may originate from an SDK declaration such as:
|
||||
|
||||
```pbs
|
||||
declare host Gfx {
|
||||
[Host(module = "gfx", name = "draw_pixel", version = 1)]
|
||||
[Capability(name = "gfx")]
|
||||
fn draw_pixel(x: int, y: int, c: color);
|
||||
}
|
||||
```
|
||||
|
||||
but the PBX-facing declaration is canonical, for example:
|
||||
|
||||
```text
|
||||
("gfx", "draw_pixel", 1)
|
||||
```
|
||||
|
||||
## 7. PBX Host Binding Section
|
||||
|
||||
### 7.1 Temporary section contract
|
||||
|
||||
Until the full PBX host-binding format is stabilized elsewhere, the loader contract uses a dedicated PBX section for declared host bindings.
|
||||
|
||||
Temporary section identifier:
|
||||
|
||||
- `SYSC`
|
||||
|
||||
Meaning:
|
||||
|
||||
- the list of canonical host bindings required by the program.
|
||||
|
||||
This section is metadata only.
|
||||
It does not define the executable opcode stream itself.
|
||||
|
||||
### 7.2 Temporary binary layout
|
||||
|
||||
The current temporary layout is:
|
||||
|
||||
```text
|
||||
u32 count
|
||||
repeat count times:
|
||||
u16 module_len
|
||||
[module_len bytes UTF-8]
|
||||
u16 name_len
|
||||
[name_len bytes UTF-8]
|
||||
u16 version
|
||||
u16 arg_slots
|
||||
u16 ret_slots
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- strings are UTF-8,
|
||||
- `module_len` and `name_len` are byte lengths,
|
||||
- `arg_slots` is the slot count the compiler expects the host binding to consume,
|
||||
- `ret_slots` is the slot count the compiler expects the host binding to produce,
|
||||
- duplicate `(module, name, version)` entries are invalid,
|
||||
- malformed lengths or invalid UTF-8 are load errors.
|
||||
|
||||
The `SYSC` table is:
|
||||
|
||||
- unique per program,
|
||||
- deduplicated by canonical identity,
|
||||
- ordered by first occurrence in the compiled program.
|
||||
|
||||
The loader MUST preserve the table order as emitted.
|
||||
|
||||
### 7.3 Presence requirements
|
||||
|
||||
The `SYSC` section is mandatory for every valid PBX artifact.
|
||||
|
||||
Rules:
|
||||
|
||||
- every valid `program.pbx` MUST contain a `SYSC` section,
|
||||
- the loader MUST inspect `SYSC` before execution begins,
|
||||
- an empty `SYSC` section is valid and means the program requires no host bindings,
|
||||
- absence of `SYSC` is a deterministic load error,
|
||||
- malformed or duplicate `SYSC` declarations are deterministic load errors.
|
||||
|
||||
Rationale:
|
||||
|
||||
- the Prometeu runtime is always host-aware,
|
||||
- PBX structural uniformity is preferred over optional host-binding metadata,
|
||||
- loader simplicity and deterministic testability take priority over omitting an empty section.
|
||||
|
||||
## 8. Loader Resolution Algorithm
|
||||
|
||||
The loader must perform host-binding resolution before VM execution starts.
|
||||
|
||||
Required algorithm:
|
||||
|
||||
1. Read the PBX header and section table.
|
||||
2. Locate and parse the `SYSC` section before launching the VM.
|
||||
3. Decode the declared canonical identities in source order.
|
||||
4. Reject duplicate identities.
|
||||
5. Resolve each identity against the host syscall registry.
|
||||
6. For each resolved entry, verify that declared `arg_slots` and `ret_slots` match the authoritative host metadata.
|
||||
7. Verify that the granted capability set covers every resolved binding.
|
||||
8. Scan the executable bytecode for every `HOSTCALL <sysc_index>` instruction.
|
||||
9. Reject any `HOSTCALL` whose `sysc_index` is out of bounds.
|
||||
10. Reject any `SYSC` entry that is never referenced by a `HOSTCALL`.
|
||||
11. Rewrite every `HOSTCALL <sysc_index>` into `SYSCALL <syscall_id>`.
|
||||
12. Reject the loaded image if any `HOSTCALL` remains after the rewrite pass.
|
||||
13. Produce the final executable program image.
|
||||
14. Abort load deterministically if any step fails.
|
||||
|
||||
The loader must not defer canonical-name resolution until the first call site executes.
|
||||
|
||||
## 9. Host Registry Resolution
|
||||
|
||||
The host maintains a canonical syscall registry:
|
||||
|
||||
```text
|
||||
(module, name, version) -> syscall_id + metadata
|
||||
```
|
||||
|
||||
That metadata includes, at minimum:
|
||||
|
||||
- numeric syscall identifier,
|
||||
- canonical identity,
|
||||
- argument slot count,
|
||||
- return slot count,
|
||||
- required capabilities.
|
||||
|
||||
Rules:
|
||||
|
||||
- the loader resolves only against this canonical registry,
|
||||
- unknown identities are load errors,
|
||||
- successful resolution yields numeric syscall identifiers and associated metadata,
|
||||
- the resolved metadata is authoritative for capability gating and later runtime verification.
|
||||
|
||||
## 10. Pre-Load Callsite Form
|
||||
|
||||
The compiler emits host-backed call sites in pre-load form as:
|
||||
|
||||
```text
|
||||
HOSTCALL <sysc_index>
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `sysc_index` is a zero-based index into the program's `SYSC` table,
|
||||
- every host-backed call site in PBX code must use `HOSTCALL`, not `SYSCALL`,
|
||||
- `HOSTCALL` exists only in the pre-load artifact form,
|
||||
- `HOSTCALL` must not remain in the final executable image passed to the VM.
|
||||
|
||||
Rationale:
|
||||
|
||||
- the compiler does not know final numeric syscall identifiers,
|
||||
- the loader resolves by canonical identity and materializes the numeric form,
|
||||
- the verifier and VM can stay numeric-only after the patch step.
|
||||
|
||||
## 11. Loader-Side ABI Validation
|
||||
|
||||
Load-time ABI validation is mandatory.
|
||||
|
||||
Rules:
|
||||
|
||||
- every `SYSC` entry declares `arg_slots` and `ret_slots`,
|
||||
- the loader resolves the entry to authoritative host metadata,
|
||||
- the loader MUST reject the image if declared `arg_slots` differs from host metadata,
|
||||
- the loader MUST reject the image if declared `ret_slots` differs from host metadata.
|
||||
|
||||
This validation is not a replacement for bytecode verification.
|
||||
It exists to detect mismatches between:
|
||||
|
||||
- the compiler's emitted host-binding contract,
|
||||
- and the host registry contract actually present in the runtime.
|
||||
|
||||
## 12. Capability Gating
|
||||
|
||||
Capability gating is mandatory during load.
|
||||
|
||||
Rules:
|
||||
|
||||
- every resolved host binding declares required capabilities,
|
||||
- frontend/build host-admission computes deterministic `requiredCapabilities` from host binding metadata for packer assistance,
|
||||
- the cartridge manifest declares requested capabilities using a nominal capability list,
|
||||
- the loader derives or receives the granted capability set from the cartridge/platform policy environment,
|
||||
- if a required capability is not granted, load fails,
|
||||
- the loader must fail before the program begins execution.
|
||||
|
||||
The compiler may infer which capabilities are required by the emitted `SYSC` table, but it does not grant authority.
|
||||
Authority belongs to the cartridge/platform loading environment.
|
||||
|
||||
Runtime capability checks may still exist defensively in the VM, but they do not replace mandatory load-time validation.
|
||||
|
||||
## 13. Verifier Interaction
|
||||
|
||||
The loader and the verifier validate different layers of the contract.
|
||||
|
||||
Loader responsibilities:
|
||||
|
||||
- validate canonical host identity resolution,
|
||||
- validate `SYSC`-declared ABI shape against host metadata,
|
||||
- validate capabilities,
|
||||
- patch `HOSTCALL <sysc_index>` into `SYSCALL <id>`.
|
||||
|
||||
Verifier responsibilities:
|
||||
|
||||
- run on the already-patched executable image,
|
||||
- validate stack safety and control-flow safety,
|
||||
- treat `SYSCALL <id>` exactly like any other final numeric instruction,
|
||||
- derive stack effects from authoritative runtime syscall metadata.
|
||||
|
||||
This is intentional and not considered harmful duplication:
|
||||
|
||||
- the loader checks interface compatibility,
|
||||
- the verifier checks structural correctness of the final program.
|
||||
|
||||
## 14. Execution Model After Load
|
||||
|
||||
After successful load:
|
||||
|
||||
- the VM executes numeric syscall identifiers only,
|
||||
- runtime dispatch must not depend on canonical strings,
|
||||
- canonical names exist only in PBX metadata and loader-side resolution,
|
||||
- the runtime-facing execution form remains `SYSCALL <id>`.
|
||||
|
||||
This preserves the hardware contract:
|
||||
|
||||
- canonical identity is used for declaration and linking,
|
||||
- numeric identity is used for execution.
|
||||
|
||||
## 15. Deterministic Loader Errors
|
||||
|
||||
The loader must fail deterministically for at least the following cases:
|
||||
|
||||
1. missing `SYSC` section,
|
||||
2. malformed `SYSC` payload,
|
||||
3. invalid UTF-8 in canonical names,
|
||||
4. duplicate `(module, name, version)` declarations,
|
||||
5. unknown canonical identity,
|
||||
6. ABI mismatch between `SYSC` declaration and host registry metadata,
|
||||
7. capability mismatch,
|
||||
8. `HOSTCALL` references an out-of-bounds `sysc_index`,
|
||||
9. a declared `SYSC` entry is unused by all `HOSTCALL` instructions,
|
||||
10. a `HOSTCALL` remains in the executable image after loader patching,
|
||||
11. any internal inconsistency between parsed host-binding metadata and the loader's host registry contract.
|
||||
|
||||
Diagnostics should identify the failing canonical identity whenever available.
|
||||
|
||||
## 16. Relationship to `stdlib`
|
||||
|
||||
`stdlib` selection is a compile-time concern that determines which SDK surfaces and host-backed declarations the compiler may use.
|
||||
|
||||
Rules:
|
||||
|
||||
- the loader does not resolve source imports such as `@sdk:gfx`,
|
||||
- the loader only consumes canonical host-binding metadata emitted into the PBX,
|
||||
- `stdlib` affects the loader indirectly through what the compiler emitted,
|
||||
- the loader must not attempt to reconstruct SDK/module semantics from the PBX.
|
||||
|
||||
In other words:
|
||||
|
||||
- `stdlib` selects the compile-time SDK contract,
|
||||
- `SYSC` carries the runtime-facing host-binding contract.
|
||||
|
||||
## 17. Relationship to Cartridge Manifest Capabilities
|
||||
|
||||
The cartridge manifest is the current declarative source for requested runtime capabilities.
|
||||
|
||||
Rules:
|
||||
|
||||
- cartridge capability declarations are external to `program.pbx`,
|
||||
- capability declarations are serializable nominal identifiers such as `gfx` or `audio`,
|
||||
- the loader converts that nominal declaration into the internal capability flag set used by the runtime,
|
||||
- the loader MUST NOT infer granted authority solely from the presence of `SYSC` entries.
|
||||
|
||||
This keeps authority separate from code generation:
|
||||
|
||||
- PBX declares what the program needs,
|
||||
- cartridge packaging declares what the cartridge requests,
|
||||
- the loader/runtime environment decides what is granted.
|
||||
|
||||
## 18. Current Implementation Direction
|
||||
|
||||
This document aligns with the current Prometeu direction:
|
||||
|
||||
- SDK/toolchain-controlled `declare host` surfaces define host-backed APIs,
|
||||
- the compiler emits canonical host-binding declarations into PBX `SYSC`,
|
||||
- the compiler emits `HOSTCALL <sysc_index>` in pre-load code,
|
||||
- the loader resolves those declarations at cartridge load,
|
||||
- the loader patch-rewrites host calls to numeric syscalls,
|
||||
- the VM continues to execute numeric syscalls only.
|
||||
|
||||
## 19. Open Items Deferred
|
||||
|
||||
The following remain deferred:
|
||||
|
||||
1. final PBX section numbering and chunk registry policy,
|
||||
2. exact binary opcode allocation for `HOSTCALL`,
|
||||
3. whether the loader patches bytecode in place or rebuilds a fresh executable image buffer,
|
||||
4. final cartridge policy model when platform-level grants differ from manifest requests,
|
||||
5. final chunk numbering and binary compatibility policy for PBX versions that predate mandatory `SYSC`,
|
||||
6. final integration shape with `ProgramImage` or another loaded-program container.
|
||||
|
||||
## 20. Current Decision Summary
|
||||
|
||||
The current temporary contract is:
|
||||
|
||||
1. Host bindings are identified canonically by `(module, name, version)`.
|
||||
2. `declare host` is reserved to SDK/toolchain modules and is compile-time surface only.
|
||||
3. The compiler emits a unique, deduplicated `SYSC` table ordered by first occurrence.
|
||||
4. Each `SYSC` entry carries `module`, `name`, `version`, `arg_slots`, and `ret_slots`.
|
||||
5. The compiler emits host-backed call sites as `HOSTCALL <sysc_index>`.
|
||||
6. The loader parses `SYSC` before execution.
|
||||
7. The loader resolves canonical identities against the host registry during load.
|
||||
8. The loader validates `arg_slots` and `ret_slots` against authoritative host metadata.
|
||||
9. The loader enforces capability gating during load.
|
||||
10. The loader rejects out-of-bounds and unused `SYSC` references.
|
||||
11. The loader rewrites every `HOSTCALL <sysc_index>` into `SYSCALL <id>`.
|
||||
12. The verifier runs after patching and validates the final numeric program.
|
||||
13. The VM executes numeric syscall identifiers only.
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
# Cartridge Manifest and Runtime Capabilities Specification
|
||||
|
||||
Status: Draft v1 (Temporary)
|
||||
Applies to: `manifest.json` in Prometeu cartridges, runtime capability declaration, and loader capability input
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
This document defines the current cartridge manifest contract relevant to runtime loading.
|
||||
|
||||
Its purpose is to stabilize:
|
||||
|
||||
- the JSON surface consumed by the cartridge loader,
|
||||
- the declaration of cartridge-requested runtime capabilities,
|
||||
- the boundary between cartridge packaging and loader authority,
|
||||
- the conversion from manifest-facing capability names to runtime capability flags.
|
||||
|
||||
This document is intentionally temporary and limited.
|
||||
It does not define cartridge publishing, signing, or store policy.
|
||||
|
||||
## 2. Scope
|
||||
|
||||
This document defines:
|
||||
|
||||
- the role of `manifest.json` in cartridge loading,
|
||||
- the current required manifest fields,
|
||||
- the new `capabilities` field,
|
||||
- the nominal capability enumeration used in JSON,
|
||||
- the mapping from nominal capabilities to runtime `CapFlags`,
|
||||
- the role of the loader when combining manifest capabilities with PBX `SYSC`.
|
||||
|
||||
This document does not define:
|
||||
|
||||
- the full package format beyond the current directory cartridge contract,
|
||||
- policy UI or permission prompts,
|
||||
- cartridge signing or trust chains,
|
||||
- final platform grant policy when the host wants to reduce requested capabilities.
|
||||
|
||||
## 3. Current Cartridge Manifest Role
|
||||
|
||||
The cartridge manifest is an external load-time descriptor for a cartridge.
|
||||
|
||||
It is not compiled from PBS source directly.
|
||||
It is produced by cartridge packaging tooling and consumed by the runtime loader.
|
||||
|
||||
The manifest currently carries:
|
||||
|
||||
- cartridge identity and metadata,
|
||||
- app entry information,
|
||||
- asset metadata,
|
||||
- preload metadata.
|
||||
|
||||
This document adds runtime capability declaration to that same manifest.
|
||||
|
||||
## 4. Manifest Shape
|
||||
|
||||
The current manifest shape relevant to this document is:
|
||||
|
||||
```json
|
||||
{
|
||||
"magic": "PMTU",
|
||||
"cartridge_version": 1,
|
||||
"app_id": 1001,
|
||||
"title": "Example",
|
||||
"app_version": "1.0.0",
|
||||
"app_mode": "game",
|
||||
"entrypoint": "frame",
|
||||
"capabilities": ["gfx", "input"],
|
||||
"asset_table": [],
|
||||
"preload": []
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `magic` identifies a Prometeu cartridge manifest,
|
||||
- `cartridge_version` identifies the cartridge manifest format line,
|
||||
- `entrypoint` identifies the runtime entrypoint,
|
||||
- for PBS v1, `entrypoint` should align with frontend-declared callable (`frame`),
|
||||
- `capabilities` declares the cartridge's requested runtime capabilities,
|
||||
- `asset_table` and `preload` remain separate concerns.
|
||||
|
||||
## 5. `capabilities`
|
||||
|
||||
### 5.1 General rules
|
||||
|
||||
`capabilities` is a manifest-facing nominal list.
|
||||
|
||||
Rules:
|
||||
|
||||
- `capabilities` is optional,
|
||||
- when omitted, it behaves as an empty list,
|
||||
- capability names are canonical lowercase identifiers,
|
||||
- duplicate entries are invalid,
|
||||
- unknown capability names are manifest errors.
|
||||
|
||||
### 5.2 Nominal capability set
|
||||
|
||||
The current nominal capability set is:
|
||||
|
||||
- `system`
|
||||
- `gfx`
|
||||
- `input`
|
||||
- `audio`
|
||||
- `fs`
|
||||
- `log`
|
||||
- `asset`
|
||||
- `bank`
|
||||
|
||||
These names are the normative manifest-facing representation.
|
||||
|
||||
## 6. Relationship to Runtime `CapFlags`
|
||||
|
||||
The runtime may continue to represent capabilities internally as a bitflag set.
|
||||
|
||||
That internal representation is an implementation detail.
|
||||
|
||||
The normative external model is:
|
||||
|
||||
- a nominal capability enum in the manifest,
|
||||
- deterministic conversion by the loader into runtime flags.
|
||||
|
||||
Canonical mapping:
|
||||
|
||||
- `system` -> `SYSTEM`
|
||||
- `gfx` -> `GFX`
|
||||
- `input` -> `INPUT`
|
||||
- `audio` -> `AUDIO`
|
||||
- `fs` -> `FS`
|
||||
- `log` -> `LOG`
|
||||
- `asset` -> `ASSET`
|
||||
- `bank` -> `BANK`
|
||||
|
||||
This means the recommended runtime design is:
|
||||
|
||||
1. deserialize `capabilities` into a nominal enum or equivalent validated representation,
|
||||
2. convert that validated set into internal `CapFlags`,
|
||||
3. use those flags during host-binding resolution.
|
||||
|
||||
## 7. Loader Semantics
|
||||
|
||||
The loader consumes both:
|
||||
|
||||
- the cartridge manifest,
|
||||
- and the PBX `SYSC` table.
|
||||
|
||||
Required behavior:
|
||||
|
||||
1. parse `manifest.json`,
|
||||
2. parse `capabilities`,
|
||||
3. convert the nominal capability list to internal capability flags,
|
||||
4. parse `program.pbx`,
|
||||
5. resolve each `SYSC` entry against the host registry,
|
||||
6. obtain required capabilities from resolved syscall metadata,
|
||||
7. fail if required capabilities are not granted by the manifest/policy environment.
|
||||
|
||||
The manifest alone does not make a program valid.
|
||||
The manifest must be consistent with the actual syscalls required by the PBX.
|
||||
|
||||
## 8. Requested vs Granted Authority
|
||||
|
||||
The manifest declares requested cartridge capabilities.
|
||||
|
||||
The loader/runtime environment is the authority that decides what is granted.
|
||||
|
||||
Current direction:
|
||||
|
||||
- in the initial runtime model, the manifest may act as the immediate source of granted capabilities,
|
||||
- a future platform policy layer may reduce or deny requested capabilities before final load.
|
||||
|
||||
Normative rule:
|
||||
|
||||
- the compiler does not grant capabilities,
|
||||
- the PBX does not grant capabilities,
|
||||
- cartridge/runtime loading is the authority boundary.
|
||||
|
||||
## 9. Relationship to Compiler and Packer
|
||||
|
||||
Responsibilities are split as follows:
|
||||
|
||||
Compiler:
|
||||
|
||||
- compiles source to PBX,
|
||||
- emits `SYSC`,
|
||||
- emits `HOSTCALL <sysc_index>`,
|
||||
- computes deterministic `requiredCapabilities` from admitted host bindings for packer tooling,
|
||||
- does not grant authority.
|
||||
|
||||
Packer:
|
||||
|
||||
- produces the cartridge manifest,
|
||||
- declares requested runtime capabilities,
|
||||
- packages `manifest.json`, `program.pbx`, and assets.
|
||||
|
||||
Loader:
|
||||
|
||||
- reads the manifest,
|
||||
- derives or receives granted capability flags,
|
||||
- validates those capabilities against PBX host requirements.
|
||||
|
||||
## 10. Validation Rules
|
||||
|
||||
The cartridge manifest must fail validation if:
|
||||
|
||||
1. `capabilities` contains an unknown name,
|
||||
2. `capabilities` contains duplicates,
|
||||
3. `capabilities` is not an array of strings or nominal enum values under the chosen serialization form.
|
||||
|
||||
Cartridge load must fail if:
|
||||
|
||||
1. the manifest omits a capability required by a resolved `SYSC` entry,
|
||||
2. a future platform policy denies a capability required by a resolved `SYSC` entry.
|
||||
|
||||
## 11. Serialization Guidance
|
||||
|
||||
The recommended manifest-facing model is a nominal enum list, not numeric masks.
|
||||
|
||||
Recommended JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"capabilities": ["gfx", "input", "audio"]
|
||||
}
|
||||
```
|
||||
|
||||
Rejected as normative surface:
|
||||
|
||||
- raw integer bitmasks,
|
||||
- hex masks,
|
||||
- unnamed positional arrays.
|
||||
|
||||
Rationale:
|
||||
|
||||
- nominal capability names are readable,
|
||||
- manifest diffs remain understandable,
|
||||
- packer and tooling validation is straightforward,
|
||||
- runtime may still use bitflags internally after conversion.
|
||||
|
||||
## 12. Current Decision Summary
|
||||
|
||||
The current temporary contract is:
|
||||
|
||||
1. `manifest.json` is the cartridge-facing load descriptor.
|
||||
2. `capabilities` is declared in `manifest.json`, not in `prometeu.json`.
|
||||
3. `capabilities` uses nominal canonical names such as `gfx` and `audio`.
|
||||
4. The runtime may keep using internal `CapFlags`.
|
||||
5. The loader converts nominal manifest capabilities into internal flags.
|
||||
6. PBX `SYSC` declares required host bindings, not authority.
|
||||
7. Loader validation fails if PBX host requirements exceed granted cartridge capabilities.
|
||||
@@ -0,0 +1,251 @@
|
||||
# PBS Stdlib Environment Packaging and Loading Specification
|
||||
|
||||
Status: Draft v1 (Temporary)
|
||||
Applies to: Studio PBS frontend stdlib packaging, stdlib environment discovery, reserved stdlib project spaces, and compiler-side stdlib loading abstractions
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
This document defines a practical packaging and loading model for the PBS stdlib environment inside the Studio compiler frontend.
|
||||
|
||||
Its purpose is to make the stdlib:
|
||||
|
||||
- available to the compiler without hardcoded symbol tables,
|
||||
- structured as real PBS interface modules,
|
||||
- versioned by stdlib major line,
|
||||
- and loadable through explicit compiler abstractions.
|
||||
|
||||
This document complements the normative language-level model in:
|
||||
|
||||
- [5. Manifest, Stdlib, and SDK Resolution Specification.md](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/docs/specs/pbs/5.%20Manifest,%20Stdlib,%20and%20SDK%20Resolution%20Specification.md)
|
||||
|
||||
## 2. Scope
|
||||
|
||||
This document defines:
|
||||
|
||||
- the recommended Studio packaging layout for stdlib interface modules,
|
||||
- the logical mapping between stdlib line, reserved project space, and module path,
|
||||
- the minimum compiler abstractions required to load stdlib modules,
|
||||
- the relationship between `resources` packaging and the logical stdlib environment.
|
||||
|
||||
This document does not define:
|
||||
|
||||
- runtime loader behavior,
|
||||
- PBX emission,
|
||||
- registry publication of stdlib packs,
|
||||
- final external distribution of stdlib outside Studio.
|
||||
|
||||
## 3. Core Model
|
||||
|
||||
The compiler must load stdlib modules as real interface modules, not as hardcoded built-ins.
|
||||
|
||||
Rules:
|
||||
|
||||
- the stdlib is selected by the root project's `stdlib` major,
|
||||
- each stdlib line defines one stdlib environment,
|
||||
- a stdlib environment exposes reserved project spaces such as `@sdk:*` and `@core:*`,
|
||||
- each reserved project space contains one or more modules,
|
||||
- each module is represented as PBS source plus `mod.barrel`.
|
||||
|
||||
## 4. Recommended Studio Packaging Layout
|
||||
|
||||
The recommended Studio layout is:
|
||||
|
||||
```text
|
||||
prometeu-compiler/frontends/prometeu-frontend-pbs/
|
||||
src/main/resources/
|
||||
stdlib/
|
||||
1/
|
||||
sdk/
|
||||
gfx/
|
||||
main.pbs
|
||||
mod.barrel
|
||||
audio/
|
||||
main.pbs
|
||||
mod.barrel
|
||||
core/
|
||||
math/
|
||||
main.pbs
|
||||
mod.barrel
|
||||
```
|
||||
|
||||
Interpretation:
|
||||
|
||||
- `stdlib/1` selects stdlib major line `1`,
|
||||
- `sdk` and `core` are reserved project spaces,
|
||||
- `gfx`, `audio`, `math` are module paths within those reserved spaces,
|
||||
- `main.pbs` and `mod.barrel` form the interface module contents.
|
||||
|
||||
## 5. Logical Mapping
|
||||
|
||||
The compiler must treat the physical layout as a logical stdlib environment.
|
||||
|
||||
Required mapping:
|
||||
|
||||
- `stdlib/<N>/sdk/gfx` -> `@sdk:gfx`
|
||||
- `stdlib/<N>/sdk/audio` -> `@sdk:audio`
|
||||
- `stdlib/<N>/core/math` -> `@core:math`
|
||||
- `stdlib/<N>/core/math/vector` -> `@core:math/vector`
|
||||
|
||||
Rules:
|
||||
|
||||
- physical storage is an implementation detail,
|
||||
- logical module identity is authoritative,
|
||||
- callers of the resolver should work with logical addresses such as `@sdk:gfx`, not resource paths.
|
||||
|
||||
## 6. Module File Convention
|
||||
|
||||
For the Studio implementation, each stdlib module should follow the same structural convention as ordinary PBS modules:
|
||||
|
||||
- one or more `.pbs` files,
|
||||
- exactly one `mod.barrel`.
|
||||
|
||||
Recommended minimum convention:
|
||||
|
||||
- `main.pbs`
|
||||
- `mod.barrel`
|
||||
|
||||
Rules:
|
||||
|
||||
- `main.pbs` is a convention, not a language-level requirement,
|
||||
- the module remains an ordinary PBS module from the parser's perspective,
|
||||
- it is interpreted under interface-module semantics because it lives in a reserved stdlib project space.
|
||||
|
||||
## 7. Required Compiler Abstractions
|
||||
|
||||
The compiler should not reach directly into `resources` paths throughout the frontend.
|
||||
|
||||
At minimum, the PBS frontend should define abstractions equivalent to:
|
||||
|
||||
### 7.1 `StdlibEnvironment`
|
||||
|
||||
Responsibility:
|
||||
|
||||
- represent the selected stdlib line for one compilation,
|
||||
- expose reserved project spaces,
|
||||
- provide access to interface modules by logical module address.
|
||||
|
||||
Minimum operations:
|
||||
|
||||
- select stdlib major line,
|
||||
- answer whether a reserved project space exists,
|
||||
- open a module by logical address.
|
||||
|
||||
### 7.2 `StdlibModuleResolver`
|
||||
|
||||
Responsibility:
|
||||
|
||||
- resolve logical imports in reserved project spaces,
|
||||
- map `@sdk:*` and `@core:*` imports to concrete interface module sources,
|
||||
- reject unknown stdlib modules deterministically.
|
||||
|
||||
Minimum operations:
|
||||
|
||||
- `resolve(@sdk:gfx)`
|
||||
- `resolve(@core:math/vector)`
|
||||
|
||||
### 7.3 `StdlibModuleSource`
|
||||
|
||||
Responsibility:
|
||||
|
||||
- represent the source files of one stdlib module,
|
||||
- provide access to the module's `.pbs` files and `mod.barrel`,
|
||||
- hide whether content came from disk, `resources`, or another source.
|
||||
|
||||
Minimum contents:
|
||||
|
||||
- module address
|
||||
- list of `.pbs` source texts or streams
|
||||
- `mod.barrel` source text or stream
|
||||
|
||||
### 7.4 `InterfaceModuleLoader`
|
||||
|
||||
Responsibility:
|
||||
|
||||
- parse a stdlib module source using the normal PBS parser,
|
||||
- validate it in interface-module mode,
|
||||
- return compiler-facing symbols and metadata.
|
||||
|
||||
Minimum outputs:
|
||||
|
||||
- exported symbols
|
||||
- declared types
|
||||
- host owners
|
||||
- host method signatures
|
||||
- reserved attribute metadata such as `[Host(...)]`
|
||||
|
||||
## 8. Loading Algorithm
|
||||
|
||||
The recommended Studio compiler flow is:
|
||||
|
||||
1. read the root `prometeu.json`,
|
||||
2. parse and normalize `stdlib`,
|
||||
3. construct `StdlibEnvironment` for that stdlib major,
|
||||
4. create a `StdlibModuleResolver`,
|
||||
5. when an import targets a reserved project space, resolve it through the stdlib resolver,
|
||||
6. obtain a `StdlibModuleSource`,
|
||||
7. parse the module with the standard PBS parser,
|
||||
8. validate it under interface-module semantic rules,
|
||||
9. cache the resulting interface module graph for the duration of the compilation.
|
||||
|
||||
Rules:
|
||||
|
||||
- reserved stdlib modules must not be handled through ordinary dependency resolution,
|
||||
- ordinary dependency modules must not be handled through the stdlib resolver,
|
||||
- a failed stdlib import is a deterministic compile-time error.
|
||||
|
||||
## 9. Attributes and Interface Metadata
|
||||
|
||||
Stdlib interface modules may contain reserved compile-time attributes such as:
|
||||
|
||||
```pbs
|
||||
declare host Gfx {
|
||||
[Host(module = "gfx", name = "draw_pixel", version = 1)]
|
||||
fn draw_pixel(x: int, y: int, c: color);
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- the parser reads the attribute as part of the interface module source,
|
||||
- the interface-module loader validates that the attribute is legal in that position,
|
||||
- the compiler stores the extracted metadata in its interface graph,
|
||||
- the raw attribute surface is not treated as a runtime object,
|
||||
- later lowering stages may consume the extracted metadata to produce PBX host-binding declarations.
|
||||
|
||||
## 10. Resources as an Implementation Strategy
|
||||
|
||||
For the Studio PBS frontend, packaging stdlib interface modules in frontend `resources` is a valid implementation strategy.
|
||||
|
||||
Rules:
|
||||
|
||||
- `resources` packaging is implementation-level, not language-level,
|
||||
- the compiler should still access stdlib modules through `StdlibEnvironment` and related abstractions,
|
||||
- code outside the stdlib loader should not depend on resource path layout directly.
|
||||
|
||||
Rationale:
|
||||
|
||||
- `resources` gives a simple bootstrap path,
|
||||
- stdlib evolves as real source artifacts,
|
||||
- the frontend avoids hardcoded built-ins,
|
||||
- the implementation remains replaceable later.
|
||||
|
||||
## 11. Caching and Reuse
|
||||
|
||||
The compiler may cache stdlib interface modules within one compilation or across compilations.
|
||||
|
||||
Rules:
|
||||
|
||||
- caching must not change observable semantics,
|
||||
- cache keys should include at least the stdlib major line and logical module address,
|
||||
- cached modules must preserve the same parsed declarations and attribute metadata as uncached loads.
|
||||
|
||||
## 12. Current Decision Summary
|
||||
|
||||
The current Studio direction is:
|
||||
|
||||
1. the stdlib environment is loaded as real PBS interface modules,
|
||||
2. the initial implementation may live under frontend `resources`,
|
||||
3. the logical model remains `stdlib line -> reserved project space -> module path`,
|
||||
4. the compiler should use explicit abstractions such as `StdlibEnvironment` and `StdlibModuleResolver`,
|
||||
5. stdlib interface modules are parsed with the normal PBS parser and validated in interface-module mode,
|
||||
6. reserved attributes such as `[Host(...)]` are extracted as compile-time metadata for later lowering.
|
||||
@@ -0,0 +1,356 @@
|
||||
# PBS Dynamic Semantics Specification
|
||||
|
||||
Status: Draft v1 (Temporary)
|
||||
Applies to: runtime-observable behavior of PBS core programs
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
This document defines the normative dynamic semantics of PBS core.
|
||||
|
||||
Its purpose is to make runtime behavior convergent across implementations by fixing:
|
||||
|
||||
- execution ordering,
|
||||
- runtime evaluation of expressions and statements,
|
||||
- abrupt completion and propagation behavior,
|
||||
- runtime behavior of effect surfaces such as `optional` and `result`,
|
||||
- the execution boundary between ordinary PBS code, callbacks, contract calls, and host-backed calls.
|
||||
|
||||
## 2. Scope
|
||||
|
||||
This document defines:
|
||||
|
||||
- the observable execution model of PBS core,
|
||||
- evaluation order for expressions, statements, and blocks,
|
||||
- runtime branch selection for `if` and `switch`,
|
||||
- runtime application behavior for `apply`, call sugar, methods, contracts, callbacks, and host-backed call surfaces,
|
||||
- runtime behavior of `optional`, `result<E>`, `else`, `!`, and `handle`,
|
||||
- abrupt completion (`return`, `break`, `continue`) and trap propagation,
|
||||
- determinism requirements that affect execution behavior.
|
||||
|
||||
This document does not define:
|
||||
|
||||
- static typing or overload resolution rules,
|
||||
- GC algorithm internals,
|
||||
- exact IR shape or lowering passes,
|
||||
- diagnostics catalog wording,
|
||||
- the full PBX binary format.
|
||||
|
||||
## 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. `3. Core Syntax Specification.md`
|
||||
4. `4. Static Semantics Specification.md`
|
||||
5. 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`
|
||||
- `5. Manifest, Stdlib, and SDK Resolution Specification.md`
|
||||
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
|
||||
|
||||
This document integrates the following accepted decisions:
|
||||
|
||||
- `docs/pbs/decisions/Dynamic Semantics - Execution Model Decision.md`
|
||||
- `docs/pbs/decisions/Dynamic Semantics - Effect Surfaces Decision.md`
|
||||
- `docs/pbs/decisions/Dynamic Semantics - Branch Selection Decision.md`
|
||||
- `docs/pbs/decisions/Host Memory Boundary Decision.md`
|
||||
|
||||
## 5. Already-Settled Inputs
|
||||
|
||||
The following inputs are already fixed elsewhere and must not be contradicted here:
|
||||
|
||||
- PBS prioritizes determinism and compatibility over ergonomics when the two conflict.
|
||||
- `FRAME_SYNC`-based execution semantics remain preserved.
|
||||
- No non-deterministic async execution model is part of PBS v1.
|
||||
- Function application is defined on the canonical `apply` surface, with call sugar desugaring to `apply`.
|
||||
- `optional T` function fallthrough yields `none`.
|
||||
- `result<E>` function fallthrough is a compile-time error.
|
||||
- `ok(...)` and `err(...)` are special result-flow forms rather than ordinary first-class runtime constructors.
|
||||
|
||||
## 6. Execution Baseline
|
||||
|
||||
PBS execution is single-threaded per program instance in v1.
|
||||
|
||||
User-visible execution is deterministic and does not expose concurrent interleaving.
|
||||
|
||||
User-visible sequencing is defined by:
|
||||
|
||||
- evaluation order,
|
||||
- branch selection,
|
||||
- abrupt completion,
|
||||
- result propagation,
|
||||
- trap propagation,
|
||||
- and host-call boundaries.
|
||||
|
||||
VM-internal frame layout, temporary storage, and lowering steps are not observable unless they change one of the semantic effects above.
|
||||
|
||||
`FRAME_SYNC` is the only normative safepoint in PBS v1.
|
||||
|
||||
## 7. Evaluation Order and Single Evaluation
|
||||
|
||||
### 7.1 Default rule
|
||||
|
||||
The default evaluation rule is strict left-to-right unless a construct explicitly states otherwise.
|
||||
|
||||
### 7.2 Call evaluation
|
||||
|
||||
For application:
|
||||
|
||||
1. form the call target,
|
||||
2. evaluate any receiver or callable artifact needed for target formation exactly once,
|
||||
3. evaluate arguments in source order from left to right,
|
||||
4. invoke the resolved target,
|
||||
5. produce one of:
|
||||
- normal return,
|
||||
- explicit `result<E>` propagation,
|
||||
- or `trap`.
|
||||
|
||||
This rule applies to canonical `apply` and to direct-call sugar that desugars to `apply`.
|
||||
|
||||
`apply` chains are parsed right-associatively, but their observable evaluation still follows the left-to-right rule above.
|
||||
|
||||
### 7.3 Exactly-once guarantees
|
||||
|
||||
The following expressions are evaluated exactly once where they appear:
|
||||
|
||||
- `if` condition,
|
||||
- `switch` selector,
|
||||
- the left operand of `opt else fallback`,
|
||||
- the payload expression of `some(expr)`,
|
||||
- the operand of `expr!`,
|
||||
- the operand of `handle expr { ... }`,
|
||||
- the context expression of `bind(context, fn_name)`,
|
||||
- call receivers, callees, and argument expressions as required by the call rule above.
|
||||
|
||||
## 8. Blocks and Abrupt Completion
|
||||
|
||||
Statements in a block execute in source order.
|
||||
|
||||
Only the final unsemicoloned expression in a block contributes to the block result.
|
||||
|
||||
Abrupt completion terminates the current construct immediately and prevents later sibling evaluation.
|
||||
|
||||
At minimum, the following are abrupt-completion forms:
|
||||
|
||||
- `return`,
|
||||
- `break`,
|
||||
- `continue`,
|
||||
- `!` on an error path,
|
||||
- `trap`.
|
||||
|
||||
## 9. `optional`
|
||||
|
||||
### 9.1 Runtime model
|
||||
|
||||
`optional` has exactly two runtime states:
|
||||
|
||||
- `some(payload)`
|
||||
- `none`
|
||||
|
||||
`none` is the canonical absence of payload.
|
||||
|
||||
### 9.2 Construction
|
||||
|
||||
`some(expr)` evaluates `expr` eagerly and exactly once before forming the `some(payload)` carrier.
|
||||
|
||||
### 9.3 Extraction
|
||||
|
||||
`opt else fallback`:
|
||||
|
||||
1. evaluates the left operand exactly once,
|
||||
2. yields the extracted payload if that operand evaluates to `some(payload)`,
|
||||
3. otherwise evaluates `fallback` and yields its value.
|
||||
|
||||
`else` is extraction with fallback, not error handling.
|
||||
|
||||
### 9.4 Trap behavior
|
||||
|
||||
`optional` is trap-free by itself.
|
||||
|
||||
Any trap associated with `some(expr)` or `opt else fallback` arises only from evaluating the relevant subexpressions.
|
||||
|
||||
## 10. `result<E>`
|
||||
|
||||
### 10.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`.
|
||||
|
||||
Expected, recoverable failures belong to `result<E>`, not to `trap`.
|
||||
|
||||
### 10.2 `!`
|
||||
|
||||
`expr!`:
|
||||
|
||||
1. evaluates `expr` exactly once,
|
||||
2. yields the extracted success payload if `expr` succeeds,
|
||||
3. performs immediate enclosing-function return with the same `err(...)` if `expr` yields error.
|
||||
|
||||
`!` does not:
|
||||
|
||||
- remap errors,
|
||||
- intercept traps,
|
||||
- or continue ordinary evaluation after the propagated error path is chosen.
|
||||
|
||||
### 10.3 `handle`
|
||||
|
||||
`handle expr { ... }`:
|
||||
|
||||
1. evaluates `expr` exactly once,
|
||||
2. yields the extracted success payload directly if `expr` succeeds,
|
||||
3. selects exactly one matching arm if `expr` yields error,
|
||||
4. executes that arm,
|
||||
5. requires the arm to terminate with either `ok(payload)` or `err(E2.case)`.
|
||||
|
||||
`ok(payload)` in a `handle` arm recovers locally and makes the `handle` expression yield `payload`.
|
||||
|
||||
`err(E2.case)` in a `handle` arm performs immediate enclosing-function return with `err(E2.case)`.
|
||||
|
||||
For the remap-only case, a short form such as `E1.case -> E2.case` is sugar for an arm block that returns `err(E2.case)`.
|
||||
|
||||
`handle` may execute user-defined logic inside an arm, but it remains specific to modeled `result` errors.
|
||||
|
||||
`handle` does not intercept or convert traps.
|
||||
|
||||
## 11. `apply`, Call Sugar, and `bind`
|
||||
|
||||
### 11.1 Canonical role of `apply`
|
||||
|
||||
`apply` is the canonical universal call surface in PBS v1.
|
||||
|
||||
The same observable call model applies to:
|
||||
|
||||
- top-level functions,
|
||||
- struct methods,
|
||||
- service methods,
|
||||
- contract calls,
|
||||
- callback calls,
|
||||
- host-backed calls.
|
||||
|
||||
Callable-specific dispatch may differ internally, but it does not change the user-visible sequencing model defined in this document.
|
||||
|
||||
### 11.2 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 processing remains explicit through `!` or `handle`.
|
||||
|
||||
### 11.3 `bind`
|
||||
|
||||
`bind(context, fn_name)` is the explicit callback-formation mechanism in PBS v1.
|
||||
|
||||
It:
|
||||
|
||||
- evaluates `context` exactly once,
|
||||
- captures the same struct context identity without copying it,
|
||||
- attaches that context to the resolved top-level function target,
|
||||
- produces a callback value whose invocation behaves as if the target function were called with the captured context as its first argument.
|
||||
|
||||
At the language-semantics level, `bind` is trap-free.
|
||||
|
||||
Incompatible binding shape remains a compile-time matter rather than a runtime failure mode.
|
||||
|
||||
Retention and storage consequences of `bind` belong to `Memory and Lifetime Specification.md`.
|
||||
|
||||
## 12. Branch Selection
|
||||
|
||||
### 12.1 `if`
|
||||
|
||||
`if` evaluates its condition exactly once.
|
||||
|
||||
If the condition is `true`, only the selected `then` branch executes.
|
||||
If the condition is `false`, only the selected `else` branch executes.
|
||||
|
||||
The non-selected branch is not evaluated, even partially.
|
||||
|
||||
### 12.2 `switch`
|
||||
|
||||
`switch` evaluates its selector exactly once and executes exactly one selected arm.
|
||||
|
||||
The non-selected arms are not evaluated.
|
||||
|
||||
`switch` is restricted to statically discriminable selector categories in v1:
|
||||
|
||||
- literal-comparable scalar values,
|
||||
- enum values,
|
||||
- canonical `str` values,
|
||||
- and any other selector category admitted elsewhere by explicit specification.
|
||||
|
||||
`switch` does not accept:
|
||||
|
||||
- `result`,
|
||||
- `error`,
|
||||
- structs,
|
||||
- string object/reference types distinct from canonical `str`,
|
||||
- heap-backed selector categories.
|
||||
|
||||
Matching is exact and deterministic:
|
||||
|
||||
- enum selectors match by canonical enum-case identity,
|
||||
- scalar selectors match by the exact equality rule for that scalar category,
|
||||
- `str` selectors match by canonical static string identity.
|
||||
|
||||
`switch` does not perform structural matching, guard evaluation, or user-defined equality dispatch.
|
||||
|
||||
## 13. Trap, Determinism, and Host Interaction
|
||||
|
||||
### 13.1 Trap boundary
|
||||
|
||||
`trap` is reserved for failures that are:
|
||||
|
||||
- outside the ordinary userland contract,
|
||||
- not suitably representable as the declared `result<E>` 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.
|
||||
|
||||
Any trap aborts the current PBS program execution rather than returning control to ordinary userland flow.
|
||||
|
||||
Control then transfers to runtime or firmware crash handling outside the ordinary language model.
|
||||
|
||||
### 13.2 Host interaction
|
||||
|
||||
Host calls must not introduce user-visible reordering of already-defined PBS evaluation order.
|
||||
|
||||
Expected operational failures of host-backed surfaces should be modeled through their declared contract rather than through ad hoc trap usage.
|
||||
|
||||
Cross-boundary host/userland interaction remains stack-value-based as defined by the host-boundary decision track; direct host-memory manipulation is not part of PBS userland semantics.
|
||||
|
||||
## 14. TODO
|
||||
|
||||
The following items remain editorial or cross-spec integration tasks rather than open semantic agenda questions:
|
||||
|
||||
- the final wording split between this document and `16. Runtime Execution and Initialization Specification.md` for crash handoff after trap,
|
||||
- the final wording split between this document and `10. Memory and Lifetime Specification.md` for retention/allocation facts that arise during ordinary execution,
|
||||
- conformance-oriented example coverage once `13. Conformance Test Specification.md` is expanded.
|
||||
|
||||
## 15. Non-Goals
|
||||
|
||||
- Reopening grammar or static typing unless current text is impossible to execute normatively.
|
||||
- Defining exact GC collection strategy.
|
||||
- Designing future async, actor, or scheduler models.
|
||||
- Specifying backend optimization policy.
|
||||
|
||||
## 16. Exit Criteria
|
||||
|
||||
This document is ready to move beyond temporary draft status only when:
|
||||
|
||||
1. every runtime-observable core construct has deterministic evaluation wording,
|
||||
2. trap versus status-value behavior is explicit for every effect-bearing construct,
|
||||
3. host-call interaction rules are stated without relying on informal prose elsewhere,
|
||||
4. the document can drive runtime conformance tests without decision backfill,
|
||||
5. the remaining TODO items are reduced to editorial integration rather than semantic uncertainty.
|
||||
@@ -0,0 +1,59 @@
|
||||
# PBS Specs
|
||||
|
||||
This directory contains the normative PBS specification set.
|
||||
|
||||
## Purpose
|
||||
|
||||
Specs define the official PBS language/frontend contract.
|
||||
|
||||
They exist to make behavior, constraints, and interfaces stable across implementations and reviews.
|
||||
|
||||
Cross-language acceptance rules are not defined here.
|
||||
Those are maintained in `docs/general/specs`.
|
||||
|
||||
## Expected Format
|
||||
|
||||
The exact structure may vary by document, but a spec should usually contain:
|
||||
|
||||
1. Title
|
||||
2. Status
|
||||
3. Scope or Applies To
|
||||
4. Purpose
|
||||
5. Authority and Precedence
|
||||
6. Normative Inputs
|
||||
7. Core Rules
|
||||
8. Non-Goals
|
||||
9. Exit Criteria
|
||||
|
||||
Some specs may also include:
|
||||
|
||||
- already-settled inputs,
|
||||
- initial section targets,
|
||||
- `TODO` sections for tracked unresolved items,
|
||||
- cross-references to adjacent specs.
|
||||
|
||||
## Writing Rules
|
||||
|
||||
- Write in normative language.
|
||||
- Integrate only decisions that have already been closed.
|
||||
- Keep debate history and exploratory alternatives out of the spec body.
|
||||
- Preserve clear boundaries between adjacent specs.
|
||||
- Use `TODO` only for explicitly tracked unresolved items, not as a substitute for agenda work.
|
||||
|
||||
## Upstream Rule
|
||||
|
||||
Specs should normally be fed by:
|
||||
|
||||
1. agendas that frame the open topic,
|
||||
2. decisions that close the architectural question,
|
||||
3. then spec integration.
|
||||
|
||||
If a spec edit would require guessing an unresolved design choice, the correct action is to stop and surface the missing decision first.
|
||||
|
||||
## Current Chapter Focus
|
||||
|
||||
The active PBS chapter focus is:
|
||||
|
||||
- `11. AST Specification.md`
|
||||
- `12. Diagnostics Specification.md`
|
||||
- `13. Lowering IRBackend Specification.md`
|
||||
Reference in New Issue
Block a user