Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion __init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""NodeForge Blender addon package."""

NODEFORGE_VERSION = (0, 94, 2)
NODEFORGE_VERSION = (0, 95, 0)


bl_info = {
"name": "NodeForge",
Expand All @@ -15,6 +16,7 @@
from .mesh_compute import mesh_compute
from .evaluation_modes import EvaluationMode
from .extension_semantic_api import RuntimeRef
from .extension_result_api import DynamicResults
from .extension_annotations import (
Bool, Bundle, Color, Float, Geometry, Int, Material, Object, Rotation, String, Vector,
)
Expand Down
29 changes: 18 additions & 11 deletions blender/extension_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,18 +93,24 @@ def _validate_result_leaf(value, expected_type: NFType, context: ExtensionBacken


def _validate_result(value, result_spec: TypeSpec, context: ExtensionBackendContext):
"""Validate exact selected result shape and convert it to internal backend Values."""
"""Compare physical return shape against the exact typed Call IR result tuple."""
expected_types = context.result_types
if result_spec.kind == "NF_SET":
expected = next(iter(result_spec.nf_types))
return _validate_result_leaf(value, expected, context)
if not isinstance(value, tuple) or len(value) != len(result_spec.items):
raise CompileError(
f"Extension implementation must return a {len(result_spec.items)}-item tuple"
)
return tuple(
_validate_result_leaf(item, next(iter(item_spec.nf_types)), context)
for item, item_spec in zip(value, result_spec.items)
)
declared_types = (next(iter(result_spec.nf_types)),)
elif result_spec.kind == "TUPLE_FIXED":
declared_types = tuple(next(iter(item.nf_types)) for item in result_spec.items)
elif result_spec.kind == "DYNAMIC_RESULTS":
declared_types = expected_types
else:
raise CompileError("Internal error: non-executable result reached the physical backend")
if expected_types != declared_types:
raise CompileError("Extension Call IR results disagree with the selected callable contract")
if result_spec.kind == "NF_SET":
return _validate_result_leaf(value, expected_types[0], context)
if not isinstance(value, tuple) or len(value) != len(expected_types):
raise CompileError(f"Extension implementation must return a {len(expected_types)}-item tuple")
return tuple(_validate_result_leaf(item, expected_types[index], context)
for index, item in enumerate(value))


def lower_extension_call(context, operation, operands, x, y):
Expand All @@ -122,6 +128,7 @@ def lower_extension_call(context, operation, operands, x, y):
group=context.group,
location=(x, y),
generated_resource_transaction=transaction,
result_types=tuple(item.typ for item in operation.results),
)
try:
if operation.extension_state_type is None:
Expand Down
2 changes: 1 addition & 1 deletion blender_manifest.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
schema_version = "1.0.0"
id = "nodeforge"
version = "0.94.2"
version = "0.95.0"
name = "NodeForge"
tagline = "Compile a procedural DSL into Blender Geometry Nodes"
maintainer = "nachitima"
Expand Down
8 changes: 8 additions & 0 deletions dev/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -778,3 +778,11 @@ lifecycle.
- Simplified root-producing compilation so the root updater alone owns its group transaction, staged-node cleanup, rollback, and Undo uncertainty. The internal lowering helper now requires its caller-provided transaction and canonical Group Input endpoint.
- Removed unused source-module forwarding through root lowering and added Blender regression coverage for delegated error cleanup and one transaction owner.
- Updated the user documentation for unified Compile Script modes, manual placement and refresh of function groups, mode transitions, and base-tree Group Input reuse.

## 0.95.0

- Added per-invocation typed result tuples to Extension API v2 through the `DynamicResults` annotation and same-owner `semantic.py::_result_types_<function>` resolver convention.
- Resolve exact ordered runtime result types during semantic analysis and transport them through existing typed Call IR to the Python backend.
- Validate dynamic extension results against call-specific IR arity, NF types, socket direction, physical type and current-group ownership before publishing generated candidates.
- Preserved fixed result declarations, semantic extension modes, owner snapshots, and existing root-tree physical extension restrictions.
- Documented invocation-dependent extension result declarations, resolver arguments and validation, backend result types, and package requirements.
84 changes: 81 additions & 3 deletions docs/EXTENSION_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ systems/
└── backend.py # physical Blender realization
```

`interface.py` is the declaration module. `semantic.py` is optional. A backend module may use any owner-local filename referenced by the declaration; `backend.py` is only a convention.
`interface.py` is the declaration module. `semantic.py` provides frontend processing and is required for [invocation-dependent results](#invocation-dependent-results). A backend module may use any owner-local filename referenced by the declaration; `backend.py` is only a convention.

An owner is either source-backed or Python-backed. Do not place both `source.nf` and `interface.py` in the same owner directory.

Expand Down Expand Up @@ -177,6 +177,82 @@ def split(value: Annotated[Float, EvaluationMode.RUNTIME_ONLY]) -> tuple[Float,

Variadic tuples such as `tuple[Float, ...]` and union results such as `Float | Int` are not executable direct-result contracts.

### Invocation-dependent results

Use `DynamicResults` when a call's output count or types depend on its arguments:

1. Set the return annotation in `interface.py` to `DynamicResults`, imported from `NodeForge`.
2. Define `_result_types_<public_name>(arguments)` in the same owner's `semantic.py`. Use the callable's key in `EXTENSIONS` as `<public_name>`.
3. Return the output types from the resolver and matching runtime values from the backend.

This extension forwards one or more values as a typed tuple:

```python
# interface.py
from typing import Annotated
from NodeForge import DynamicResults, EvaluationMode, Float, Int, Vector

EXTENSION_API = 2
EXTENSIONS = {'forward_values': '.backend:forward_values'}


def forward_values(
*values: Annotated[Float | Int | Vector, EvaluationMode.RUNTIME_ONLY],
) -> DynamicResults:
...
```

```python
# semantic.py

def _result_types_forward_values(arguments):
"""Return each supplied value's actual type in argument order."""
values = arguments['values']
if not values:
raise ValueError('forward_values requires at least one value')
return tuple(value.typ for value in values)
```

```python
# backend.py

def forward_values(context, *values):
"""Forward the current invocation's typed runtime values."""
return tuple(values)
```

Call it inside a grouped `.nf` function, using the installed package's import name:

```python
from packages import tools

def example(value: Float):
single = tools.forward_values(value)
direction, number = tools.forward_values(position(), index())
return single[0], direction, number
```

A single result is still a tuple: use `[0]` or a one-element unpack target.

The resolver's `arguments` is a read-only mapping from parameter names to the following values. Defaults are included; variadic arguments retain their source order.

| Argument | Resolver value |
| --- | --- |
| Direct runtime value | `ResultRuntimeArg`: `.typ` is the actual `NFType`. |
| Direct compile-time value | `ResultStaticArg`: `.typ` and the canonical immutable `.value`. |
| Variadic parameter | A tuple of argument views, empty when no arguments were supplied. |
| Semantic record or list | A reconstructed semantic value with `RuntimeRef` runtime leaves. |

Import `ResultRuntimeArg` and `ResultStaticArg` from `NodeForge.extension_result_api`.

Resolver rules:

- Return a nonempty tuple or list of exact `NFType` members in output order, for example `(NFType.FLOAT, NFType.INT)`. Import `NFType` from `NodeForge.extension_api`.
- Use argument types and compile-time data to select outputs. Create Blender nodes and resources in the backend. Importing registered physical implementation modules from the resolver is rejected.
- For overloads, annotate every alternative with `DynamicResults` and provide one resolver for the public name.

The backend must return a Python tuple of `ExtensionBackendValue` objects, including for a single result. See [`context.result_types`](#extensionbackendcontext) for output validation and [Loading and reload behavior](#loading-and-reload-behavior) for resolver loading.

### Overloads

Use `typing.overload` for a finite set of direct-value signatures. Alternatives are tried in source order.
Expand Down Expand Up @@ -397,6 +473,8 @@ Do not construct compiler values or depend on compiler internals. Use the suppli

`context.location` is the `(x, y)` placement anchor for the extension call.

`context.result_types` is the read-only tuple of exact `NFType` members for this call's outputs. It is available for fixed and [invocation-dependent results](#invocation-dependent-results). Return values must match its count, order, and types. Each runtime leaf must use an output socket of the matching physical type in `context.group`; input sockets and sockets from other groups are rejected. Invalid backend results reject compilation before the candidate group is published.

`context.value(socket, typ)` validates and wraps an output socket from the current group as the declared NodeForge type:

```python
Expand Down Expand Up @@ -427,7 +505,7 @@ Resources created through these helpers participate in the active NodeForge tran

NodeForge snapshots `interface.py`, `semantic.py`, backend modules, and owner-local helpers as one extension owner. Source bytes determine freshness; filesystem timestamp changes alone do not.

Semantic and backend modules are loaded lazily for the phase that uses them. Do not rely on mutable module state being shared between frontend semantic execution and Blender-side realization.
For invocation-dependent results, contract loading imports `semantic.py` and checks the required resolver exports without running their bodies. Other semantic modules and physical implementation modules load when their phase is used. Do not rely on mutable module state being shared between frontend semantic execution and Blender-side realization.

A new root compilation resolves a new package environment snapshot and uses it consistently for nested calls.

Expand All @@ -440,6 +518,6 @@ Package installation validates Extension API declarations before the candidate p
- `EXTENSION_API` must equal `2` and `EXTENSIONS` must be non-empty;
- `__unique__` is compiler-reserved and cannot be an extension parameter;
- public extension signatures do not support `**kwargs`;
- direct executable results must be one exact NodeForge type or a fixed tuple of exact types.
- executable results use one exact NodeForge type, a fixed tuple of exact types, or [`DynamicResults`](#invocation-dependent-results).

Treat validation failures as declaration errors rather than compensating for malformed contracts inside backend code.
4 changes: 4 additions & 0 deletions docs/PACKAGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,10 @@ privileges. Install packages only from sources you trust. The
[Extension API Reference](EXTENSION_API.md) defines owner layouts, declarations,
evaluation modes, backend contexts, semantic values, and resource ownership.

Owners declaring [`DynamicResults`](EXTENSION_API.md#invocation-dependent-results)
require a same-owner `semantic.py` in the package ZIP. Set `nodeforge_min_version`
to `0.94.0` or newer when using this API.

## Public path constraints

Public directory and module names must be ASCII identifiers and cannot be
Expand Down
6 changes: 5 additions & 1 deletion editor/intelligence.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,8 @@ def _def_signatures(source: str) -> dict[str, tuple[Signature, ...]]:

def _typespec_label(spec) -> str:
"""Convert an extension's frozen TypeSpec to a concise display label."""
if spec.kind == "DYNAMIC_RESULTS":
return "tuple[dynamic]"
if spec.kind == "NF_SET":
return " | ".join(sorted(t.value.title() for t in spec.nf_types))
if spec.kind == "TUPLE_FIXED":
Expand All @@ -193,7 +195,9 @@ def _extension_signatures(name: str, specs) -> tuple[Signature, ...]:
default = None if param.default is inspect.Parameter.empty else repr(param.default)
kw = None if param.kind is inspect.Parameter.POSITIONAL_ONLY else param.name
parameters.append(Parameter(param.name, _typespec_label(param.type_spec), default, kw))
if spec.result.kind == "TUPLE_FIXED":
if spec.result.kind == "DYNAMIC_RESULTS":
outputs = (Output("Results", "tuple[dynamic]"),)
elif spec.result.kind == "TUPLE_FIXED":
outputs = tuple(Output(f"Value {i + 1}", _typespec_label(item))
for i, item in enumerate(spec.result.items))
else:
Expand Down
12 changes: 10 additions & 2 deletions extension_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ def __post_init__(self) -> None:
class ExtensionBackendContext:
"""Expose the minimal physical realization surface to one extension invocation."""

def __init__(self, *, group, location, generated_resource_transaction):
"""Bind one invocation to its target group, layout anchor, and outer transaction."""
def __init__(self, *, group, location, generated_resource_transaction, result_types=()):
"""Bind one invocation to the candidate group and immutable typed output contract."""
if group is None:
raise ValueError("ExtensionBackendContext requires a target node group")
if (
Expand All @@ -48,6 +48,14 @@ def __init__(self, *, group, location, generated_resource_transaction):
self._group = group
self._location = (float(location[0]), float(location[1]))
self._generated_resource_transaction = generated_resource_transaction
if not isinstance(result_types, tuple) or any(type(typ) is not NFType for typ in result_types):
raise TypeError("ExtensionBackendContext.result_types must be a tuple of exact NFType members")
self._result_types = result_types

@property
def result_types(self) -> tuple[NFType, ...]:
"""Return the selected call's ordered immutable executable result signature."""
return self._result_types

@property
def group(self) -> "bpy.types.GeometryNodeTree":
Expand Down
45 changes: 45 additions & 0 deletions extension_result_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""Blender-independent declarations and invocation types for dynamic extension results."""


class DynamicResults:
"""Annotation-only opt-in to invocation-dependent executable result tuples."""

def __new__(cls, *args, **kwargs):
"""Reject runtime construction of the declaration-only result marker."""
raise TypeError("DynamicResults is an annotation-only marker")


from dataclasses import dataclass
from .nf_types import NFType


@dataclass(frozen=True)
class ResultRuntimeArg:
"""Expose the actual NF type of one already-acquired runtime argument."""

typ: NFType

def __post_init__(self) -> None:
"""Require an exact runtime type token, rather than a declaration marker."""
if type(self.typ) is not NFType:
raise TypeError("ResultRuntimeArg.typ must be an exact NFType")


@dataclass(frozen=True)
class ResultStaticArg:
"""Expose one detached canonical compile-time value and its selected NF type."""

typ: NFType
value: object

def __post_init__(self) -> None:
"""Reject mutable or noncanonical value carriers crossing the resolver boundary."""
if type(self.typ) is not NFType:
raise TypeError("ResultStaticArg.typ must be an exact NFType")
def detached(item):
"""Admit only recursively immutable canonical literal storage."""
return type(item) in (str, bool, int, float) or (
type(item) is tuple and all(detached(part) for part in item)
)
if not detached(self.value):
raise TypeError("ResultStaticArg.value must be detached immutable literal storage")
10 changes: 8 additions & 2 deletions extensions/contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ class PythonScalarKind(str, Enum):

TypeSpecKind = Literal[
"NF_SET",
"DYNAMIC_RESULTS",
"PY_SCALAR",
"RECORD",
"LIST",
Expand All @@ -98,7 +99,7 @@ def __post_init__(self) -> None:
object.__setattr__(self, "nf_types", frozenset(self.nf_types))
object.__setattr__(self, "items", tuple(self.items))
allowed = {
"NF_SET", "PY_SCALAR", "RECORD", "LIST",
"NF_SET", "DYNAMIC_RESULTS", "PY_SCALAR", "RECORD", "LIST",
"TUPLE_FIXED", "TUPLE_VAR", "DICT_STR", "OPTIONAL",
}
if self.kind not in allowed:
Expand All @@ -121,7 +122,10 @@ def __post_init__(self) -> None:
"record": self.record_type is not None,
"item": self.item is not None,
}
if self.kind == "NF_SET":
if self.kind == "DYNAMIC_RESULTS":
if any(populated.values()):
raise ValueError("DYNAMIC_RESULTS must carry no payload")
elif self.kind == "NF_SET":
if not populated["nf"] or any(populated[key] for key in ("items", "scalar", "record", "item")):
raise ValueError("NF_SET requires one or more NFTypes and no other payload")
elif self.kind == "PY_SCALAR":
Expand Down Expand Up @@ -182,6 +186,8 @@ def is_frontend_semantic_type_spec(spec: TypeSpec) -> bool:

def is_executable_result_type_spec(spec: TypeSpec) -> bool:
"""Return whether *spec* is an executable public result shape from the backend-only declarative extension contract."""
if spec.kind == "DYNAMIC_RESULTS":
return True
if spec.kind == "NF_SET":
return len(spec.nf_types) == 1
if spec.kind == "TUPLE_FIXED":
Expand Down
5 changes: 5 additions & 0 deletions extensions/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
is_frontend_semantic_type_spec,
)
from ..nf_types import NFType
from ..extension_result_api import DynamicResults


EXTENSION_API_VERSION = 2
Expand Down Expand Up @@ -318,6 +319,8 @@ def _normalize_result_annotation(
class_type_ids: Mapping[type, ExtensionTypeId],
) -> TypeSpec:
"""Normalize one executable or frontend-semantic public result."""
if annotation is DynamicResults:
return TypeSpec("DYNAMIC_RESULTS")
try:
semantic = normalize_semantic_type_annotation(annotation, class_type_ids=class_type_ids, context=context)
except CompileError:
Expand Down Expand Up @@ -491,6 +494,8 @@ def normalize_interface_module(
record_type_specs,
context=f"{name}() result",
)
if len({spec.result.kind == "DYNAMIC_RESULTS" for spec in specs}) > 1:
raise CompileError(f"{name}() overload family mixes dynamic and fixed results")
if overloads:
for spec in specs:
if any(parameter.type_spec.kind != "NF_SET" for parameter in spec.parameters):
Expand Down
Loading
Loading