diff --git a/__init__.py b/__init__.py index 8d958c1..f4e6f9a 100644 --- a/__init__.py +++ b/__init__.py @@ -1,6 +1,7 @@ """NodeForge Blender addon package.""" -NODEFORGE_VERSION = (0, 94, 2) +NODEFORGE_VERSION = (0, 95, 0) + bl_info = { "name": "NodeForge", @@ -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, ) diff --git a/blender/extension_backend.py b/blender/extension_backend.py index f4d7789..002dbb3 100644 --- a/blender/extension_backend.py +++ b/blender/extension_backend.py @@ -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): @@ -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: diff --git a/blender_manifest.toml b/blender_manifest.toml index 5a2a355..4c4cb38 100644 --- a/blender_manifest.toml +++ b/blender_manifest.toml @@ -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" diff --git a/dev/CHANGELOG.md b/dev/CHANGELOG.md index 8edef2a..ca8d40a 100644 --- a/dev/CHANGELOG.md +++ b/dev/CHANGELOG.md @@ -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_` 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. \ No newline at end of file diff --git a/docs/EXTENSION_API.md b/docs/EXTENSION_API.md index 5fa3429..96877fd 100644 --- a/docs/EXTENSION_API.md +++ b/docs/EXTENSION_API.md @@ -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. @@ -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_(arguments)` in the same owner's `semantic.py`. Use the callable's key in `EXTENSIONS` as ``. +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. @@ -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 @@ -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. @@ -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. diff --git a/docs/PACKAGES.md b/docs/PACKAGES.md index b6549d9..fe2d8ad 100644 --- a/docs/PACKAGES.md +++ b/docs/PACKAGES.md @@ -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 diff --git a/editor/intelligence.py b/editor/intelligence.py index c08e62e..e8cb06c 100644 --- a/editor/intelligence.py +++ b/editor/intelligence.py @@ -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": @@ -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: diff --git a/extension_api.py b/extension_api.py index 502b24a..15ec5f6 100644 --- a/extension_api.py +++ b/extension_api.py @@ -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 ( @@ -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": diff --git a/extension_result_api.py b/extension_result_api.py new file mode 100644 index 0000000..aae4ec3 --- /dev/null +++ b/extension_result_api.py @@ -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") diff --git a/extensions/contracts.py b/extensions/contracts.py index 26ad757..5d29ff7 100644 --- a/extensions/contracts.py +++ b/extensions/contracts.py @@ -72,6 +72,7 @@ class PythonScalarKind(str, Enum): TypeSpecKind = Literal[ "NF_SET", + "DYNAMIC_RESULTS", "PY_SCALAR", "RECORD", "LIST", @@ -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: @@ -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": @@ -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": diff --git a/extensions/interface.py b/extensions/interface.py index d73a5bb..d1cc47d 100644 --- a/extensions/interface.py +++ b/extensions/interface.py @@ -26,6 +26,7 @@ is_frontend_semantic_type_spec, ) from ..nf_types import NFType +from ..extension_result_api import DynamicResults EXTENSION_API_VERSION = 2 @@ -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: @@ -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): diff --git a/extensions/registry.py b/extensions/registry.py index 1824cf4..c39bc62 100644 --- a/extensions/registry.py +++ b/extensions/registry.py @@ -485,6 +485,13 @@ def normalize_interface(self) -> tuple[ implementation_modules = frozenset( ref.module[1:] for ref in refs.values() if ref is not None ) + # Stage the physical targets so preflight cannot import a backend in SEMANTIC. + self._implementation_modules = implementation_modules + try: + self._preflight_result_resolvers(families) + except Exception: + self._implementation_modules = frozenset() + raise self._families = MappingProxyType(dict(families)) self._refs = MappingProxyType(dict(refs)) self._type_specs = MappingProxyType(dict(type_specs)) @@ -493,6 +500,51 @@ def normalize_interface(self) -> tuple[ self._implementation_modules = implementation_modules return self._families, self._refs + def _preflight_result_resolvers(self, families) -> None: + """Validate each dynamic resolver export during contract load in SEMANTIC.""" + dynamic_ids = [callable_id for callable_id, specs in families.items() + if specs[0].result.kind == "DYNAMIC_RESULTS"] + if not dynamic_ids: + return + if "semantic" not in self.snapshot.modules: + raise CompileError("Dynamic extension result requires same-owner semantic.py") + with self._mounted("SEMANTIC"): + try: + module = importlib.import_module(self._full_name("semantic")) + for callable_id in dynamic_ids: + name = f"_result_types_{callable_id.name}" + if not callable(getattr(module, name, None)): + raise CompileError( + f"Dynamic result resolver semantic.py::{name} must exist and be callable" + ) + except CompileError: + raise + except Exception as exc: + raise CompileError(f"Dynamic result resolver preflight failed for {self.snapshot.owner_key}: {exc}") from exc + + def invoke_result_resolver(self, callable_id: ExtensionCallableId, arguments, *, overload_index=None) -> tuple: + """Resolve one exact ordered executable tuple within the owner's SEMANTIC generation.""" + families, _ = self.normalize_interface() + family = families.get(callable_id) + if not family or family[0].result.kind != "DYNAMIC_RESULTS": + raise CompileError(f"{callable_id.name!r} has no dynamic result contract") + if overload_index is not None and (type(overload_index) is not int or not 0 <= overload_index < len(family)): + raise CompileError("Dynamic extension result has invalid selected overload index") + label = f"{callable_id.owner}.{callable_id.name} overload {overload_index}" + with self._mounted("SEMANTIC"): + try: + module = importlib.import_module(self._full_name("semantic")) + function = getattr(module, f"_result_types_{callable_id.name}") + result = function(arguments) + except Exception as exc: + raise CompileError(f"Dynamic result resolver {label} failed: {exc}") from exc + from ..nf_types import NFType + if type(result) not in (tuple, list) or not result or any(type(typ) is not NFType for typ in result): + raise CompileError( + f"Dynamic result resolver {label} must return a nonempty tuple/list of exact NFType members" + ) + return tuple(result) + def type_specs(self) -> Mapping[ExtensionTypeId, ExtensionTypeSpec]: """Return the immutable normalized semantic record schemas for this owner.""" self.normalize_interface() @@ -743,6 +795,12 @@ def owner_fingerprint(self, owner_key: tuple[str, ...]) -> str: """Return the conservative owner-code fingerprint for one admitted owner.""" return self._session_for_owner(owner_key).snapshot.fingerprint + def invoke_result_resolver(self, callable_id: ExtensionCallableId, arguments, *, overload_index=None) -> tuple: + """Delegate one call-local signature request to the selected owner session.""" + return self._session_for_owner(callable_id.owner).invoke_result_resolver( + callable_id, arguments, overload_index=overload_index, + ) + def invoke_implementation(self, callable_id: ExtensionCallableId, *args, **kwargs): """Invoke physical owner code while its IMPLEMENTATION generation remains mounted.""" return self._session_for_owner(callable_id.owner).invoke_implementation(callable_id, *args, **kwargs) diff --git a/extensions/semantics.py b/extensions/semantics.py index f7e8272..5652b44 100644 --- a/extensions/semantics.py +++ b/extensions/semantics.py @@ -234,6 +234,19 @@ def resolve_runtime_leaf(stored: object): runtime_leaf_resolver=resolve_runtime_leaf, ) + def clone_semantic_argument(self, type_spec: TypeSpec, value: object) -> object: + """Reconstruct a separate record/list view without copying active RuntimeRef tokens.""" + storage = pack_value(type_spec, value, registry=self.registry, active_runtime_refs=self._active) + + def resolve_runtime_leaf(stored: object): + """Resolve detached dependency slots using this invocation's canonical tokens.""" + if not isinstance(stored, ExtensionDependencySlot): + return None + return stored.typ, self.runtime_ref(stored.dependency_index, stored.typ) + + return unpack_value(type_spec, storage, registry=self.registry, + runtime_leaf_resolver=resolve_runtime_leaf) + def pack_result(self, return_type: TypeSpec, value: object) -> object: """Validate and detach one semantic function result against its declared TypeSpec.""" return pack_value( diff --git a/semantic/analysis.py b/semantic/analysis.py index 974a255..d5d1c3f 100644 --- a/semantic/analysis.py +++ b/semantic/analysis.py @@ -65,6 +65,8 @@ from .compile_time import CompileTimeSnapshot, detached_compile_time_mapping, _is_const_vector from ..errors import CompileError from ..nf_types import NFType, NUMERIC_NF_TYPES +from ..extension_result_api import ResultRuntimeArg, ResultStaticArg +from ..extension_semantic_api import RuntimeRef from .numeric_semantics import ( INT_MIN, normalize_float_constant, @@ -396,8 +398,12 @@ def _call_result_types(result): -def _extension_result_spec(spec: ExtensionCallableSpec): +def _extension_result_spec(spec: ExtensionCallableSpec, resolved_types=None): """Convert one exact extension result TypeSpec to the existing analyzed call shape.""" + if spec.result.kind == "DYNAMIC_RESULTS": + if resolved_types is None: + raise CompileError("Internal error: dynamic extension result has not been resolved") + return TupleCallResult(tuple(resolved_types)) if spec.result.kind == "NF_SET": return RuntimeCallResult(next(iter(spec.result.nf_types))) return TupleCallResult(tuple(next(iter(item.nf_types)) for item in spec.result.items)) @@ -548,9 +554,11 @@ def candidate_matches(item, *, exact: bool) -> bool: runtime_nodes: list[ast.expr] = [] runtime_operands: list[AnalyzedCallOperand] = [] static_operands: list[AnalyzedStaticCallOperand] = [] + resolver_arguments: dict[str, object] = {} for parameter_index, parameter in enumerate(selected_spec.parameters): value = selected_bound.arguments.get(parameter.name, ()) if parameter.kind is inspect.Parameter.VAR_POSITIONAL else selected_bound.arguments.get(parameter.name) occurrences = tuple(value) if parameter.kind is inspect.Parameter.VAR_POSITIONAL else (value,) + resolved_items = [] for variadic_index, occurrence in enumerate(occurrences): if occurrence is None and parameter.kind is not inspect.Parameter.VAR_POSITIONAL: raise CompileError("Internal error: selected extension binding lost fixed parameter") @@ -558,6 +566,7 @@ def candidate_matches(item, *, exact: bool) -> bool: if isinstance(occurrence, ast.AST): representation, payload, actual_type = acquired[id(occurrence)] if representation == "runtime": + resolved_items.append(ResultRuntimeArg(actual_type)) runtime_nodes.append(occurrence) runtime_operands.append( AnalyzedCallOperand(parameter.name, actual_type, parameter_index, transport_variadic) @@ -566,6 +575,7 @@ def candidate_matches(item, *, exact: bool) -> bool: actual_type = static_nf_type(payload, declared=parameter.type_spec) expected_type = select_declared_nf_type(parameter.type_spec, actual_type) canonical = canonicalize_group_input_default(expected_type, payload) + resolved_items.append(ResultStaticArg(expected_type, canonical)) static_operands.append( AnalyzedStaticCallOperand(parameter_index, canonical, transport_variadic) ) @@ -575,9 +585,18 @@ def candidate_matches(item, *, exact: bool) -> bool: static_operands.append( AnalyzedStaticCallOperand(parameter_index, occurrence, transport_variadic) ) + resolved_items.append(ResultStaticArg(parameter.default_type, occurrence)) + resolver_arguments[parameter.name] = ( + tuple(resolved_items) if parameter.kind is inspect.Parameter.VAR_POSITIONAL else resolved_items[0] + ) overload_index = selected_index if len(family) > 1 else None - result_spec = _extension_result_spec(selected_spec) + result_types = None + if selected_spec.result.kind == "DYNAMIC_RESULTS": + result_types = registry.invoke_result_resolver( + selected_spec.id, MappingProxyType(resolver_arguments), overload_index=overload_index, + ) + result_spec = _extension_result_spec(selected_spec, result_types) analyzed_call = AnalyzedCall( target=resolved, runtime_operands=tuple(runtime_operands), @@ -833,6 +852,26 @@ def _analyze_extension_semantic_call( else: bound.arguments[parameter.name] = acquired_items[0] + result_types = None + if spec.result.kind == "DYNAMIC_RESULTS": + resolver_arguments = {} + for parameter in spec.parameters: + value = bound.arguments[parameter.name] + occurrences = tuple(value) if parameter.kind is inspect.Parameter.VAR_POSITIONAL else (value,) + argument_items = [] + for item in occurrences: + if parameter.type_spec.kind != "NF_SET": + argument_items.append(invocation.clone_semantic_argument(parameter.type_spec, item)) + elif isinstance(item, RuntimeRef): + argument_items.append(ResultRuntimeArg(item.typ)) + else: + actual = static_nf_type(item, declared=parameter.type_spec) + argument_items.append(ResultStaticArg(select_declared_nf_type(parameter.type_spec, actual), item)) + resolver_arguments[parameter.name] = ( + tuple(argument_items) if parameter.kind is inspect.Parameter.VAR_POSITIONAL else argument_items[0] + ) + result_types = registry.invoke_result_resolver(spec.id, MappingProxyType(resolver_arguments)) + semantic_value = registry.invoke_semantic(spec.id, *bound.args, **bound.kwargs) packed = invocation.pack_result(semantic_return, semantic_value) semantic_payload = compact_extension_semantic_payload(semantic_return, packed, invocation.dependencies) @@ -847,7 +886,7 @@ def _analyze_extension_semantic_call( if execution_form is not ExtensionExecutionForm.SEMANTIC_THEN_BACKEND: raise CompileError("Internal error: semantic extension call has unexpected execution form") - result_spec = _extension_result_spec(spec) + result_spec = _extension_result_spec(spec, result_types) runtime_operands = tuple(AnalyzedCallOperand(None, source.typ) for source in dependencies) analyzed_call = AnalyzedCall( target=resolved, diff --git a/tests/blender/test_extension_dynamic_results.py b/tests/blender/test_extension_dynamic_results.py new file mode 100644 index 0000000..20ae8a1 --- /dev/null +++ b/tests/blender/test_extension_dynamic_results.py @@ -0,0 +1,137 @@ +"""Blender 5.2 physical validation for invocation-dependent extension results.""" + +from __future__ import annotations + +import json +import tempfile +from pathlib import Path + +import bpy +import pytest + +from helpers import compile_group +from NodeForge import packages +from NodeForge.errors import CompileError +from NodeForge.extension_api import ExtensionBackendContext +from NodeForge.nf_types import NFType + +pytestmark = pytest.mark.blender + + +def _write_package(root: Path, *, bad: str = "") -> None: + """Create one dynamically typed physical owner with selectable result violations.""" + owner = root / "systems" / "dynamic" + owner.mkdir(parents=True) + (root / "nodeforge_package.json").write_text(json.dumps({ + "schema_version": 1, "id": "vendor.extension.dynamic", + "name": "Dynamic Result Fixture", "version": "1.0.0", "author": "Tests", + "description": "Dynamic tuple physical verification", "nodeforge_min_version": "0.93.3", + "nodeforge_max_version": None, "contents": {"systems": "systems"}, + "permissions": {"python": True}, + }), encoding="utf-8") + (owner / "interface.py").write_text(''' +from typing import Annotated +from NodeForge import DynamicResults, EvaluationMode, Float +EXTENSION_API = 2 +EXTENSIONS = {"foo": ".backend:foo"} +def foo(value: Annotated[Float, EvaluationMode.RUNTIME_ONLY]) -> DynamicResults: ... +''', encoding="utf-8") + (owner / "semantic.py").write_text(''' +from NodeForge.nf_types import NFType +def _result_types_foo(arguments): + return (NFType.FLOAT, NFType.FLOAT) +''', encoding="utf-8") + variant = { + "": "return (context.value(node.outputs[0], NFType.FLOAT), value)", + "short": "return (context.value(node.outputs[0], NFType.FLOAT),)", + "long": "return (context.value(node.outputs[0], NFType.FLOAT), value, value)", + "scalar": "return context.value(node.outputs[0], NFType.FLOAT)", + "wrong_type": "return (ExtensionBackendValue(node.outputs[0], NFType.BOOL), value)", + "input_socket": "return (ExtensionBackendValue(node.inputs[0], NFType.FLOAT), value)", + "wrong_socket_type": "other = context.group.nodes.new('GeometryNodeInputPosition'); return (ExtensionBackendValue(other.outputs[0], NFType.FLOAT), value)", + "foreign_socket": "return (ExtensionBackendValue(bpy.data.node_groups['NFTest_other_dynamic'].nodes[0].outputs[0], NFType.FLOAT), value)", + }[bad] + (owner / "backend.py").write_text(f''' +import bpy +from NodeForge.extension_api import ExtensionBackendValue +from NodeForge.nf_types import NFType + +def foo(context, value): + assert context.result_types == (NFType.FLOAT, NFType.FLOAT) + context.new_generated_mesh(role="dynamic-rollback", name_hint="Probe") + node = context.group.nodes.new("ShaderNodeMath") + node.operation = "MULTIPLY" + context.group.links.new(value.socket, node.inputs[0]) + node.inputs[1].default_value = 2.0 + {variant} +''', encoding="utf-8") + + +_SOURCE = '''from packages import dynamic + +def nf_fixture(value: Float['Value']=3.0): + a, b = foo(value) + return a, b +''' + + +def test_dynamic_tuple_creates_valid_typed_nodes_and_immutable_context(): + """The selected IR result types reach one backend and validate exact sockets.""" + with tempfile.TemporaryDirectory() as tmp: + source = Path(tmp) / "package" + _write_package(source) + packages.install_package_directory(source) + group = compile_group(_SOURCE, "NFTest_dynamic_result_ok") + assert len([node for node in group.nodes if node.bl_idname == "ShaderNodeMath"]) == 1 + assert len([socket for socket in group.interface.items_tree if socket.item_type == "SOCKET" and socket.in_out == "OUTPUT"]) == 2 + test_context = ExtensionBackendContext(group=group, location=(0, 0), + generated_resource_transaction=object(), + result_types=(NFType.FLOAT,)) + with pytest.raises(AttributeError): + test_context.result_types = (NFType.INT,) + bpy.data.node_groups.remove(group) + + +@pytest.mark.parametrize("bad,pattern", [ + ("short", "2-item tuple"), ("long", "2-item tuple"), + ("scalar", "2-item tuple"), ("wrong_type", "expected FLOAT"), + ("input_socket", "output sockets"), ("wrong_socket_type", "physical socket type"), + ("foreign_socket", "current Geometry Nodes group"), +]) +def test_dynamic_backend_rejects_malformed_result_and_rolls_back(bad, pattern): + """No returned malformed leaf or generated resource can publish a candidate.""" + foreign = None + try: + if bad == "foreign_socket": + foreign = bpy.data.node_groups.new("NFTest_other_dynamic", "GeometryNodeTree") + foreign.nodes.new("ShaderNodeMath") + with tempfile.TemporaryDirectory() as tmp: + source = Path(tmp) / "package" + _write_package(source, bad=bad) + packages.install_package_directory(source) + groups = {item.as_pointer() for item in bpy.data.node_groups} + meshes = {item.as_pointer() for item in bpy.data.meshes} + with pytest.raises(CompileError, match=pattern): + compile_group(_SOURCE, f"NFTest_dynamic_bad_{bad}") + assert {item.as_pointer() for item in bpy.data.node_groups} == groups + assert {item.as_pointer() for item in bpy.data.meshes} == meshes + finally: + if foreign is not None and foreign.name in bpy.data.node_groups: + bpy.data.node_groups.remove(foreign) + + +def test_dynamic_extension_keeps_existing_root_tree_physical_restriction(): + """Issue 62 does not bypass the root-owned tree restriction from Issue 61.""" + from NodeForge import compiler + with tempfile.TemporaryDirectory() as tmp: + source = Path(tmp) / "package" + _write_package(source) + packages.install_package_directory(source) + root = bpy.data.node_groups.new("NFTest_dynamic_direct_root", "GeometryNodeTree") + try: + with pytest.raises(CompileError, match="existing base GeometryNodeTree"): + compiler.compose_source_initial('''from packages import dynamic +value_a, value_b = foo(1.0) +''', root) + finally: + bpy.data.node_groups.remove(root) diff --git a/tests/unit/test_extension_dynamic_results.py b/tests/unit/test_extension_dynamic_results.py new file mode 100644 index 0000000..476f2db --- /dev/null +++ b/tests/unit/test_extension_dynamic_results.py @@ -0,0 +1,357 @@ +"""Dynamic extension declarations and owner-load preflight regressions.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from NodeForge import DynamicResults +from NodeForge.errors import CompileError +from NodeForge.extensions.registry import ExtensionOwnerSession, ExtensionRegistry, capture_owner_code_snapshot +from NodeForge.extensions.semantics import ExtensionExecutionForm, classify_extension_execution + +pytestmark = pytest.mark.unit + + +def _owner(root: Path, interface: str, **files: str): + """Construct an isolated owner from its exact captured source files.""" + root.mkdir(parents=True, exist_ok=True) + (root / "interface.py").write_text(interface, encoding="utf-8") + for module, source in files.items(): + (root / f"{module}.py").write_text(source, encoding="utf-8") + return ExtensionOwnerSession(capture_owner_code_snapshot(("system", "dynamic.test", root.name), root)) + + +_INTERFACE = ''' +from typing import Annotated +from NodeForge import Float, DynamicResults, EvaluationMode +EXTENSION_API = 2 +EXTENSIONS = {"foo": ".backend:foo"} +def foo(value: Annotated[Float, EvaluationMode.RUNTIME_ONLY]) -> DynamicResults: ... +''' + + +def test_dynamic_declaration_preflight_is_resolver_body_lazy_and_backend_only(tmp_path): + """Private semantic resolver is validated, but not executed at contract load.""" + owner = _owner(tmp_path, _INTERFACE, + semantic=''' +CALLED = 0 +def _result_types_foo(arguments): + global CALLED + CALLED += 1 + return () +''', backend="def foo(context, value): return value\n") + families, _ = owner.normalize_interface() + spec = next(iter(families.values()))[0] + assert spec.result.kind == "DYNAMIC_RESULTS" + assert owner._phase_modules["SEMANTIC"]["semantic"].CALLED == 0 + assert classify_extension_execution(spec, None, has_implementation=True) is ExtensionExecutionForm.BACKEND_ONLY + assert not hasattr(spec, "resolver_ref") + assert not hasattr(DynamicResults, "__nodeforge_nf_type__") + with pytest.raises(TypeError, match="annotation-only"): + DynamicResults() + + +@pytest.mark.parametrize("semantic,match", [ + (None, "same-owner semantic.py"), + ("OTHER = 123\n", "_result_types_foo"), + ("_result_types_foo = 14\n", "callable"), + ("from .backend import foo\ndef _result_types_foo(args): return ()\n", "SEMANTIC"), +]) +def test_dynamic_owner_rejects_broken_resolver_on_load(tmp_path, semantic, match): + """Malformed resolver contracts are rejected before callable publication.""" + kwargs = {"backend": "def foo(context, value): return value\n"} + if semantic is not None: + kwargs["semantic"] = semantic + owner = _owner(tmp_path, _INTERFACE, **kwargs) + with pytest.raises(CompileError, match=match): + owner.normalize_interface() + assert owner._families is None + assert owner._implementation_modules == frozenset() + + +def test_dynamic_family_rejects_mixed_return_types(tmp_path): + """The overload family cannot contain both dynamic and fixed results.""" + interface = ''' +from typing import Annotated, overload +from NodeForge import Float, Int, DynamicResults, EvaluationMode +EXTENSION_API = 2 +EXTENSIONS = {"foo": ".backend:foo"} +@overload +def foo(value: Annotated[Float, EvaluationMode.RUNTIME_ONLY]) -> DynamicResults: ... +@overload +def foo(value: Annotated[Int, EvaluationMode.RUNTIME_ONLY]) -> Int: ... +def foo(value): ... +''' + owner = _owner(tmp_path, interface, backend="def foo(context, value): return value\n", + semantic="def _result_types_foo(args): return ()\n") + with pytest.raises(CompileError, match="mixes dynamic and fixed"): + owner.normalize_interface() + + +def test_two_dynamic_exports_can_share_same_semantic_module(tmp_path): + """Derived exports use each public name and one preflighted semantic generation.""" + interface = _INTERFACE.replace('"foo": ".backend:foo"', '"foo": ".backend:foo", "bar": ".backend:bar"') + interface += 'def bar(value: Annotated[Float, EvaluationMode.RUNTIME_ONLY]) -> DynamicResults: ...\n' + owner = _owner(tmp_path, interface, + backend="def foo(context, value): return value\ndef bar(context, value): return value\n", + semantic="def _result_types_foo(args): return ()\ndef _result_types_bar(args): return ()\n") + registry = ExtensionRegistry((owner,)) + assert {cid.name for cid in registry._families} == {"foo", "bar"} + assert set(owner._phase_modules["SEMANTIC"]) == {"semantic"} + + +def test_non_exact_dynamic_marker_does_not_opt_in(tmp_path): + """Subclassed result markers have no special authority at contract load.""" + interface = _INTERFACE.replace('EXTENSION_API = 2', 'class Other(DynamicResults): pass\nEXTENSION_API = 2') + interface = interface.replace('-> DynamicResults:', '-> Other:') + owner = _owner(tmp_path, interface, backend="def foo(context, value): return value\n", + semantic="def _result_types_foo(args): return ()\n") + with pytest.raises(CompileError, match="Unsupported"): + owner.normalize_interface() + + +def _dynamic_semantic_environment(owner: ExtensionOwnerSession): + """Expose a synthetic dynamic owner with already-typed frontend runtime bindings.""" + import ast + from types import MappingProxyType + from NodeForge.compiler_identities import BindingId + from NodeForge.nf_types import NFType + from NodeForge.resolved_environment import PackageCallableExport, ResolvedPackageNamespace + from NodeForge.semantic.call_resolution import CallableEnvironment + from NodeForge.semantic.source_bindings import PackageNamespaceBinding + from NodeForge.semantic.analysis import SemanticEnvironment + from NodeForge.semantic.runtime_bindings import RuntimeBindingSymbol + + registry = ExtensionRegistry((owner,)) + cid = next(iter(owner.normalize_interface()[0])) + namespace = ResolvedPackageNamespace("dynamic.test", "dyn", "Dynamic", "1", { + cid.name: PackageCallableExport("dynamic.test", cid.name, extension_callable_id=cid), + }) + types = { + "geo": NFType.GEOMETRY, "f": NFType.FLOAT, "v": NFType.VECTOR, + "i": NFType.INT, "b": NFType.BOOL, "s": NFType.STRING, + } + variables = {name: RuntimeBindingSymbol(BindingId("scope", index), typ) + for index, (name, typ) in enumerate(types.items())} + calls = CallableEnvironment(frozenset(), {}, {}, + package_namespaces={"dyn": PackageNamespaceBinding("dyn", namespace)}) + env = SemanticEnvironment(MappingProxyType(variables), MappingProxyType({}), + MappingProxyType({}), MappingProxyType({}), calls, + extension_registry=registry) + return env, cid + + +_DYNAMIC_INTERFACE = ''' +from typing import Annotated +from NodeForge import Bool, DynamicResults, EvaluationMode, Float, Geometry, Int, String, Vector +EXTENSION_API = 2 +EXTENSIONS = {"foo": ".backend:foo"} +def foo(geometry: Annotated[Geometry, EvaluationMode.RUNTIME_ONLY], + *values: Annotated[Float | Int | Vector, EvaluationMode.RUNTIME_ONLY], + selection: Annotated[Bool, EvaluationMode.COMPILE_TIME_OR_RUNTIME] = True, + domain: Annotated[String, EvaluationMode.COMPILE_TIME_ONLY] = "POINT") -> DynamicResults: ... +''' +_DYNAMIC_SEMANTIC = ''' +from NodeForge.nf_types import NFType +from NodeForge.extension_result_api import ResultRuntimeArg, ResultStaticArg +CALLED = 0 +LAST_ARGUMENTS = None +def _result_types_foo(arguments): + global CALLED, LAST_ARGUMENTS + CALLED += 1 + LAST_ARGUMENTS = arguments + assert isinstance(arguments['geometry'], ResultRuntimeArg) + assert isinstance(arguments['selection'], (ResultRuntimeArg, ResultStaticArg)) + assert isinstance(arguments['domain'], ResultStaticArg) + return (NFType.GEOMETRY, NFType.BOOL, *(arg.typ for arg in arguments['values'])) +''' + + +def test_resolver_uses_call_local_actual_types_and_exact_ir(tmp_path): + """Two invocations share a declaration but own different concrete typed IR tuples.""" + import ast + from NodeForge.nf_types import NFType + from NodeForge.semantic.analysis import analyze_expression + from NodeForge.semantic.ir import IRCall + from NodeForge.semantic.lowering import lower_analyzed_expression + owner = _owner(tmp_path, _DYNAMIC_INTERFACE, backend="def foo(*args, **kw): pass\n", + semantic=_DYNAMIC_SEMANTIC) + env, _cid = _dynamic_semantic_environment(owner) + module = owner._phase_modules["SEMANTIC"]["semantic"] + assert module.CALLED == 0 + for text, expected in [ + ("foo(geo, f)", (NFType.GEOMETRY, NFType.BOOL, NFType.FLOAT)), + ("foo(geo, v, i, domain='point')", (NFType.GEOMETRY, NFType.BOOL, NFType.VECTOR, NFType.INT)), + ]: + root = ast.parse(text, mode="eval").body + analysis = analyze_expression(root, env) + analyzed = analysis.facts[root].analyzed_call + assert analyzed.result.types == expected + program = lower_analyzed_expression(root, analysis) + call = next(item for item in program.operations if isinstance(item, IRCall)) + assert tuple(result.typ for result in call.results) == expected + assert len(call.arguments) == (2 if "v, i" in text else 2) + (0 if "v, i" not in text else 1) + assert module.CALLED == 2 + assert module.LAST_ARGUMENTS["domain"].value == "point" + assert module.LAST_ARGUMENTS["selection"].value is True + assert type(module.LAST_ARGUMENTS["values"]) is tuple + assert not hasattr(module.LAST_ARGUMENTS, "__setitem__") + with pytest.raises(TypeError): + module.LAST_ARGUMENTS["domain"] = None + + +def test_empty_dynamic_values_still_resolve_a_structural_tuple(tmp_path): + """A one-element resolver result does not silently become a scalar expression.""" + import ast + from NodeForge.nf_types import NFType + from NodeForge.semantic.analysis import analyze_expression + owner = _owner(tmp_path, _DYNAMIC_INTERFACE, backend="def foo(*args, **kw): pass\n", + semantic="from NodeForge.nf_types import NFType\ndef _result_types_foo(args): return [NFType.FLOAT]\n") + env, _ = _dynamic_semantic_environment(owner) + root = ast.parse("foo(geo)", mode="eval").body + result = analyze_expression(root, env).facts[root].analyzed_call.result + assert result.types == (NFType.FLOAT,) + + +@pytest.mark.parametrize("expression", ["[]", "()", "None", "{NFType.FLOAT}", + "(NFType.FLOAT, 42)", "'FLOAT'"]) +def test_dynamic_result_resolver_rejects_invalid_shapes_during_analysis(tmp_path, expression): + """All malformed resolver outputs fail before typed Call IR or Blender creation.""" + import ast + from NodeForge.semantic.analysis import analyze_expression + owner = _owner(tmp_path, _DYNAMIC_INTERFACE, backend="def foo(*args, **kw): pass\n", + semantic=f"from NodeForge.nf_types import NFType\ndef _result_types_foo(args): return {expression}\n") + env, _ = _dynamic_semantic_environment(owner) + root = ast.parse("foo(geo, f)", mode="eval").body + with pytest.raises(CompileError, match="dynamic|Dynamic|resolver"): + analyze_expression(root, env) + + +def test_snapshot_owned_resolver_remains_unchanged_when_source_changes(tmp_path): + """Each captured generation uses its own semantic.py body and fingerprint.""" + import ast + from NodeForge.nf_types import NFType + from NodeForge.semantic.analysis import analyze_expression + semantic = "from NodeForge.nf_types import NFType\ndef _result_types_foo(args): return (NFType.FLOAT,)\n" + old = _owner(tmp_path, _DYNAMIC_INTERFACE, backend="def foo(*args, **kw): pass\n", semantic=semantic) + old_env, _ = _dynamic_semantic_environment(old) + expression = ast.parse("foo(geo, f)", mode="eval").body + assert analyze_expression(expression, old_env).facts[expression].analyzed_call.result.types == (NFType.FLOAT,) + (tmp_path / "semantic.py").write_text(semantic.replace("NFType.FLOAT,", "NFType.INT,"), encoding="utf-8") + new = ExtensionOwnerSession(capture_owner_code_snapshot(old.snapshot.owner_key, tmp_path)) + new_env, _ = _dynamic_semantic_environment(new) + assert old.snapshot.fingerprint != new.snapshot.fingerprint + assert analyze_expression(expression, old_env).facts[expression].analyzed_call.result.types == (NFType.FLOAT,) + assert analyze_expression(expression, new_env).facts[expression].analyzed_call.result.types == (NFType.INT,) + + +def test_overloads_share_one_resolver_with_selected_actual_type(tmp_path): + """One derived resolver sees the selected typed alternative, not its union.""" + import ast + from NodeForge.nf_types import NFType + from NodeForge.semantic.analysis import analyze_expression + interface = ''' +from typing import Annotated, overload +from NodeForge import Float, Vector, DynamicResults, EvaluationMode +EXTENSION_API = 2 +EXTENSIONS = {"foo": ".backend:foo"} +@overload +def foo(value: Annotated[Float, EvaluationMode.RUNTIME_ONLY]) -> DynamicResults: ... +@overload +def foo(value: Annotated[Vector, EvaluationMode.RUNTIME_ONLY]) -> DynamicResults: ... +def foo(value): ... +''' + owner = _owner(tmp_path, interface, backend="def foo(*args): pass\n", + semantic="def _result_types_foo(args): return (args['value'].typ,)\n") + env, _ = _dynamic_semantic_environment(owner) + for source, index, typ in [("foo(f)", 0, NFType.FLOAT), ("foo(v)", 1, NFType.VECTOR)]: + root = ast.parse(source, mode="eval").body + call = analyze_expression(root, env).facts[root].analyzed_call + assert call.extension_overload_index == index + assert call.result.types == (typ,) + + +def test_public_semantic_state_and_private_result_resolver_coexist(tmp_path): + """A result-only helper neither replaces nor double-executes semantic state.""" + import ast + from NodeForge.nf_types import NFType + from NodeForge.semantic.analysis import analyze_expression + from NodeForge.extensions.semantics import ExtensionExecutionForm + interface = ''' +from dataclasses import dataclass +from typing import Annotated +from NodeForge import DynamicResults, Float, EvaluationMode +EXTENSION_API = 2 +EXTENSIONS = {"foo": ".backend:foo"} +@dataclass(frozen=True) +class _State: + value: Float +def foo(value: Annotated[Float, EvaluationMode.RUNTIME_ONLY]) -> DynamicResults: ... +''' + semantic = ''' +from .interface import _State +from NodeForge.nf_types import NFType +CALLS = 0 +RESOLVES = 0 +def foo(value) -> _State: + global CALLS + CALLS += 1 + return _State(value) +def _result_types_foo(args): + global RESOLVES + RESOLVES += 1 + return (args['value'].typ,) +''' + owner = _owner(tmp_path, interface, semantic=semantic, + backend="def foo(context, state): return None\n") + env, cid = _dynamic_semantic_environment(owner) + spec = owner.normalize_interface()[0][cid][0] + state = owner.semantic_return_type(cid) + assert classify_extension_execution(spec, state, has_implementation=True) is ExtensionExecutionForm.SEMANTIC_THEN_BACKEND + root = ast.parse("foo(f)", mode="eval").body + result = analyze_expression(root, env).facts[root].analyzed_call + assert result.result.types == (NFType.FLOAT,) + sem = owner._phase_modules["SEMANTIC"]["semantic"] + assert sem.CALLS == sem.RESOLVES == 1 + assert result.extension_state_type == state + + +def test_dynamic_editor_signature_reports_unbound_tuple_without_fabricated_fields(tmp_path): + """Editor completion shows the marker while leaving per-call arity unspecified.""" + from NodeForge.editor.intelligence import _extension_signatures, _return_preview + owner = _owner(tmp_path, _DYNAMIC_INTERFACE, semantic=_DYNAMIC_SEMANTIC, + backend="def foo(*args, **kw): pass\n") + specs = next(iter(owner.normalize_interface()[0].values())) + signature, = _extension_signatures("foo", specs) + assert signature.outputs[0].typ == "tuple[dynamic]" + assert len(signature.outputs) == 1 + assert "tuple[dynamic]" in _return_preview(signature) + assert len(signature.parameters) == 4 + + +def test_dynamic_resolver_rejects_runtime_domain_from_same_binding_path(tmp_path): + """Existing argument-mode checks reject a runtime-only static parameter early.""" + import ast + from NodeForge.semantic.analysis import analyze_expression + owner = _owner(tmp_path, _DYNAMIC_INTERFACE, backend="def foo(*args): pass\n", + semantic=_DYNAMIC_SEMANTIC) + env, _ = _dynamic_semantic_environment(owner) + root = ast.parse("foo(geo, f, domain=s)", mode="eval").body + with pytest.raises(CompileError, match="compile time"): + analyze_expression(root, env) + + +def test_call_specific_tuple_index_rejects_out_of_range(tmp_path): + """Resolved arity participates in ordinary tuple indexing semantics.""" + import ast + from NodeForge.semantic.analysis import analyze_expression + owner = _owner(tmp_path, _DYNAMIC_INTERFACE, backend="def foo(*args): pass\n", + semantic=_DYNAMIC_SEMANTIC) + env, _ = _dynamic_semantic_environment(owner) + good = ast.parse("foo(geo, f)[2]", mode="eval").body + assert analyze_expression(good, env).facts[good].result_shape is not None + bad = ast.parse("foo(geo, f)[5]", mode="eval").body + with pytest.raises(CompileError): + analyze_expression(bad, env)