From 7b47912ea874141cbb2c5371815509f49df284a8 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 18:51:47 +0000 Subject: [PATCH 1/6] feat(extensions): accept omitted typed parameter defaults --- extensions/contracts.py | 16 ++++- extensions/interface.py | 7 ++- tests/unit/test_extension_contracts.py | 45 ++++++++++++++ tests/unit/test_extension_interface.py | 9 +-- .../unit/test_extension_optional_defaults.py | 61 +++++++++++++++++++ 5 files changed, 128 insertions(+), 10 deletions(-) create mode 100644 tests/unit/test_extension_optional_defaults.py diff --git a/extensions/contracts.py b/extensions/contracts.py index 5d29ff7..b50119e 100644 --- a/extensions/contracts.py +++ b/extensions/contracts.py @@ -229,14 +229,24 @@ def __post_init__(self) -> None: raise ValueError("semantic RECORD/LIST extension parameter cannot carry EvaluationMode") else: raise TypeError("public extension parameters support only NF_SET or semantic RECORD/LIST") - if self.default is inspect.Parameter.empty: + if self.kind is inspect.Parameter.VAR_KEYWORD: + raise ValueError("extension parameters cannot use **kwargs") + if self.kind is inspect.Parameter.VAR_POSITIONAL and self.default is not inspect.Parameter.empty: + raise ValueError("variadic extension parameter cannot declare a default") + if self.default is inspect.Parameter.empty or self.default is None: if self.default_type is not None: - raise ValueError("extension parameter without default cannot carry default_type") + raise ValueError("extension parameter without concrete default cannot carry default_type") + if self.default is None and self.type_spec.kind != "NF_SET": + raise ValueError("semantic RECORD/LIST extension parameters cannot declare defaults") else: if self.type_spec.kind != "NF_SET": raise ValueError("semantic RECORD/LIST extension parameters cannot declare defaults") + if self.evaluation_mode is EvaluationMode.RUNTIME_ONLY: + raise ValueError("RUNTIME_ONLY extension parameter cannot declare a concrete default") if not isinstance(self.default_type, NFType): - raise TypeError("extension parameter default requires canonical NFType") + raise TypeError("extension parameter concrete default requires canonical NFType") + if self.default_type not in self.type_spec.nf_types: + raise ValueError("extension parameter default NFType is not declared") @dataclass(frozen=True) diff --git a/extensions/interface.py b/extensions/interface.py index 25821d9..511ed20 100644 --- a/extensions/interface.py +++ b/extensions/interface.py @@ -400,9 +400,10 @@ def _normalize_declaration( raise CompileError(f"{callable_id.name}() variadic parameter cannot declare a default") if type_spec.kind != "NF_SET": raise CompileError(f"{callable_id.name}() semantic parameter {parameter.name!r} cannot declare a default") - if mode is EvaluationMode.RUNTIME_ONLY: - raise CompileError(f"{callable_id.name}() RUNTIME_ONLY parameter {parameter.name!r} cannot declare a default") - default, default_type = _normalize_default(default, type_spec, context=f"{callable_id.name}() parameter {parameter.name!r}") + if default is not None: + if mode is EvaluationMode.RUNTIME_ONLY: + raise CompileError(f"{callable_id.name}() RUNTIME_ONLY parameter {parameter.name!r} cannot declare a concrete default") + default, default_type = _normalize_default(default, type_spec, context=f"{callable_id.name}() parameter {parameter.name!r}") parameters.append(ExtensionParameterSpec(parameter.name, parameter.kind, type_spec, mode, default, default_type)) return_annotation = annotations.get("return", signature.return_annotation) if return_annotation is inspect.Signature.empty: diff --git a/tests/unit/test_extension_contracts.py b/tests/unit/test_extension_contracts.py index 7e518e0..9bbc710 100644 --- a/tests/unit/test_extension_contracts.py +++ b/tests/unit/test_extension_contracts.py @@ -110,3 +110,48 @@ def test_extension_argument_position_validator_is_the_shared_transport_authority validate_extension_argument_positions(((0, None), (0, 0))) with pytest.raises(ValueError, match="contiguous from zero"): validate_extension_argument_positions(((1, 0), (1, 2))) + + +@pytest.mark.parametrize("mode", list(EvaluationMode)) +def test_optional_none_contract_keeps_python_signature_and_mode(mode): + """An omitted direct argument has no NFType for every evaluation mode.""" + spec = ExtensionCallableSpec( + ExtensionCallableId(("system", "optional", "contract"), "call"), + ( + ExtensionParameterSpec("required", inspect.Parameter.POSITIONAL_OR_KEYWORD, + TypeSpec("NF_SET", frozenset({NFType.FLOAT})), mode), + ExtensionParameterSpec("optional", inspect.Parameter.KEYWORD_ONLY, + TypeSpec("NF_SET", frozenset({NFType.FLOAT, NFType.INT})), mode, None), + ), + TypeSpec("NF_SET", frozenset({NFType.FLOAT})), + ) + assert spec.parameters[1].default is None and spec.parameters[1].default_type is None + signature = spec.python_signature() + bound = signature.bind(1.5) + bound.apply_defaults() + assert bound.arguments == {"required": 1.5, "optional": None} + with pytest.raises(TypeError, match="required"): + signature.bind() + + +@pytest.mark.parametrize("default, default_type, mode, kind, message", [ + (inspect.Parameter.empty, NFType.FLOAT, EvaluationMode.COMPILE_TIME_ONLY, + inspect.Parameter.KEYWORD_ONLY, "without concrete"), + (None, NFType.FLOAT, EvaluationMode.RUNTIME_ONLY, + inspect.Parameter.KEYWORD_ONLY, "without concrete"), + (2.0, None, EvaluationMode.COMPILE_TIME_ONLY, + inspect.Parameter.KEYWORD_ONLY, "canonical NFType"), + (2.0, NFType.INT, EvaluationMode.COMPILE_TIME_ONLY, + inspect.Parameter.KEYWORD_ONLY, "not declared"), + (2.0, NFType.FLOAT, EvaluationMode.RUNTIME_ONLY, + inspect.Parameter.KEYWORD_ONLY, "RUNTIME_ONLY"), + (None, None, EvaluationMode.COMPILE_TIME_ONLY, + inspect.Parameter.VAR_POSITIONAL, "variadic"), + (None, None, EvaluationMode.COMPILE_TIME_ONLY, + inspect.Parameter.VAR_KEYWORD, r"\*\*kwargs"), +]) +def test_contract_rejects_invalid_default_states(default, default_type, mode, kind, message): + """Malformed signatures fail at contract creation before call analysis.""" + with pytest.raises((ValueError, TypeError), match=message): + ExtensionParameterSpec("value", kind, TypeSpec("NF_SET", frozenset({NFType.FLOAT})), + mode, default, default_type) diff --git a/tests/unit/test_extension_interface.py b/tests/unit/test_extension_interface.py index db5b758..4736205 100644 --- a/tests/unit/test_extension_interface.py +++ b/tests/unit/test_extension_interface.py @@ -240,8 +240,8 @@ def foo( assert params["s"].default == "x" and params["s"].default_type is NFType.STRING -def test_none_default_and_unresolved_result_tuple_are_rejected(tmp_path): - """Nullability and variadic result tuples are deferred rather than inferred implicitly.""" +def test_none_default_is_omittable_but_variadic_result_tuple_is_rejected(tmp_path): + """None marks omitted typed input, while executable result arity remains fixed.""" none_default = _session( tmp_path / "none", """ @@ -252,8 +252,9 @@ def test_none_default_and_unresolved_result_tuple_are_rejected(tmp_path): def foo(value: Annotated[Float, EvaluationMode.COMPILE_TIME_ONLY] = None) -> Float: ... """, ) - with pytest.raises(CompileError, match="Unsupported extension parameter default"): - none_default.normalize_interface() + specs, _ = none_default.normalize_interface() + parameter = next(iter(specs.values()))[0].parameters[0] + assert parameter.default is None and parameter.default_type is None tuple_var = _session( tmp_path / "tuplevar", diff --git a/tests/unit/test_extension_optional_defaults.py b/tests/unit/test_extension_optional_defaults.py new file mode 100644 index 0000000..65159fd --- /dev/null +++ b/tests/unit/test_extension_optional_defaults.py @@ -0,0 +1,61 @@ +"""Contract and analysis regressions for omitted Extension API v2 typed arguments.""" + +import inspect +from pathlib import Path + +import pytest + +from NodeForge.errors import CompileError +from NodeForge.extensions.registry import ExtensionOwnerSession, capture_owner_code_snapshot +from NodeForge.evaluation_modes import EvaluationMode + +pytestmark = pytest.mark.unit + + +def _owner(tmp_path: Path, interface: str, *, semantic: str | None = None): + """Capture a synthetic extension owner in the same source layout as packages.""" + tmp_path.mkdir(parents=True, exist_ok=True) + (tmp_path / "interface.py").write_text(interface, encoding="utf-8") + (tmp_path / "backend.py").write_text("def sample(*args, **kwargs): pass\n", encoding="utf-8") + if semantic is not None: + (tmp_path / "semantic.py").write_text(semantic, encoding="utf-8") + return ExtensionOwnerSession(capture_owner_code_snapshot(("system", "test.optional", tmp_path.name), tmp_path)) + + +@pytest.mark.parametrize("mode", list(EvaluationMode)) +def test_declaration_accepts_omitted_typed_union_without_type(tmp_path, mode): + """None is a declaration-level omission marker, including for runtime-only unions.""" + source = f'''from typing import Annotated +from NodeForge import Float, Int, EvaluationMode +EXTENSION_API = 2 +EXTENSIONS = {{"sample": ".backend:sample"}} +def sample(required: Annotated[Float, EvaluationMode.RUNTIME_ONLY], + *, optional: Annotated[Float | Int, EvaluationMode.{mode.name}] = None) -> Float: ... +''' + owner = _owner(tmp_path, source) + spec = next(iter(owner.normalize_interface()[0].values()))[0] + assert spec.parameters[0].default is inspect.Parameter.empty + assert spec.parameters[1].default is None and spec.parameters[1].default_type is None + bound = spec.python_signature().bind(object()) + bound.apply_defaults() + assert bound.arguments["optional"] is None + with pytest.raises(TypeError): + spec.python_signature().bind() + + +@pytest.mark.parametrize("annotation, default, error", [ + ("Annotated[Float, EvaluationMode.RUNTIME_ONLY]", "1.0", "RUNTIME_ONLY"), + ("Annotated[Float | None, EvaluationMode.COMPILE_TIME_ONLY]", "None", "union members"), + ("Annotated[Any, EvaluationMode.COMPILE_TIME_ONLY]", "None", "Any"), + ("Annotated[Float, EvaluationMode.COMPILE_TIME_ONLY]", "'wrong'", "default"), +]) +def test_invalid_optional_declarations_stay_rejected(tmp_path, annotation, default, error): + """Only an exact Python None default can bypass typed-value normalization.""" + source = f'''from typing import Annotated, Any +from NodeForge import Float, EvaluationMode +EXTENSION_API = 2 +EXTENSIONS = {{"sample": ".backend:sample"}} +def sample(value: {annotation} = {default}) -> Float: ... +''' + with pytest.raises(CompileError, match=error): + _owner(tmp_path, source).normalize_interface() From dc33453e3df8ca68fe72c671768ace0a3286d1a3 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 18:53:20 +0000 Subject: [PATCH 2/6] feat(semantic): bind omitted defaults in backend-only extension calls --- semantic/analysis.py | 12 +- tests/unit/test_extension_dynamic_results.py | 29 +++++ .../unit/test_extension_optional_defaults.py | 117 +++++++++++++++++- 3 files changed, 155 insertions(+), 3 deletions(-) diff --git a/semantic/analysis.py b/semantic/analysis.py index 8f23878..dbadc8c 100644 --- a/semantic/analysis.py +++ b/semantic/analysis.py @@ -546,6 +546,9 @@ def candidate_matches(item, *, exact: bool) -> bool: except CompileError: return False else: + if occurrence is None and parameter.default is None: + # Omitted typed inputs carry no type evidence for overload selection. + continue if parameter.default_type is None: raise CompileError("Internal error: extension bound default lost canonical type") actual_type = parameter.default_type @@ -581,9 +584,14 @@ def candidate_matches(item, *, exact: bool) -> bool: 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") transport_variadic = variadic_index if parameter.kind is inspect.Parameter.VAR_POSITIONAL else None + if occurrence is None: + if parameter.default is not None or parameter.kind is inspect.Parameter.VAR_POSITIONAL: + raise CompileError("Internal error: selected extension binding lost fixed parameter") + # A fixed positional slot is retained for physical signature reconstruction. + static_operands.append(AnalyzedStaticCallOperand(parameter_index, None, None)) + resolved_items.append(None) + continue if isinstance(occurrence, ast.AST): representation, payload, actual_type = acquired[id(occurrence)] if representation == "runtime": diff --git a/tests/unit/test_extension_dynamic_results.py b/tests/unit/test_extension_dynamic_results.py index 476f2db..4090fc5 100644 --- a/tests/unit/test_extension_dynamic_results.py +++ b/tests/unit/test_extension_dynamic_results.py @@ -355,3 +355,32 @@ def test_call_specific_tuple_index_rejects_out_of_range(tmp_path): bad = ast.parse("foo(geo, f)[5]", mode="eval").body with pytest.raises(CompileError): analyze_expression(bad, env) + + +def test_optional_backend_dynamic_resolver_sees_omission_separately_from_values(tmp_path): + """A resolver gets None only for an omitted parameter, not a synthetic typed view.""" + import ast + from NodeForge.semantic.analysis import analyze_expression + from NodeForge.extension_result_api import ResultRuntimeArg, ResultStaticArg + from NodeForge.nf_types import NFType + + source = _DYNAMIC_INTERFACE.replace( + 'domain: Annotated[String, EvaluationMode.COMPILE_TIME_ONLY] = "POINT"', + 'domain: Annotated[String, EvaluationMode.COMPILE_TIME_ONLY] = None', + ) + semantic = '''from NodeForge.nf_types import NFType +SEEN = [] +def _result_types_foo(arguments): + SEEN.append(dict(arguments)) + return (NFType.GEOMETRY,) +''' + owner = _owner(tmp_path, source, backend="def foo(*a, **kw): pass\n", semantic=semantic) + env, _ = _dynamic_semantic_environment(owner) + for expression in ("foo(geo)", "foo(geo, selection=b, domain='POINT')"): + node = ast.parse(expression, mode="eval").body + assert analyze_expression(node, env).facts[node].analyzed_call.result.types == (NFType.GEOMETRY,) + first, second = owner._phase_modules["SEMANTIC"]["semantic"].SEEN + assert first["domain"] is None + assert isinstance(first["selection"], ResultStaticArg) and first["selection"].value is True + assert isinstance(second["domain"], ResultStaticArg) and second["domain"].value == "POINT" + assert isinstance(second["selection"], ResultRuntimeArg) diff --git a/tests/unit/test_extension_optional_defaults.py b/tests/unit/test_extension_optional_defaults.py index 65159fd..33766c6 100644 --- a/tests/unit/test_extension_optional_defaults.py +++ b/tests/unit/test_extension_optional_defaults.py @@ -19,7 +19,7 @@ def _owner(tmp_path: Path, interface: str, *, semantic: str | None = None): (tmp_path / "backend.py").write_text("def sample(*args, **kwargs): pass\n", encoding="utf-8") if semantic is not None: (tmp_path / "semantic.py").write_text(semantic, encoding="utf-8") - return ExtensionOwnerSession(capture_owner_code_snapshot(("system", "test.optional", tmp_path.name), tmp_path)) + return ExtensionOwnerSession(capture_owner_code_snapshot(("system", "dynamic.test", tmp_path.name), tmp_path)) @pytest.mark.parametrize("mode", list(EvaluationMode)) @@ -59,3 +59,118 @@ def sample(value: {annotation} = {default}) -> Float: ... ''' with pytest.raises(CompileError, match=error): _owner(tmp_path, source).normalize_interface() + + +_BACKEND_INTERFACE = '''from typing import Annotated +from NodeForge import Float, Int, Geometry, EvaluationMode +EXTENSION_API = 2 +EXTENSIONS = {"sample": ".backend:sample"} +def sample(geometry: Annotated[Geometry, EvaluationMode.RUNTIME_ONLY], + *, optional: Annotated[Int, EvaluationMode.COMPILE_TIME_OR_RUNTIME] = None, + required_mode: Annotated[Float, EvaluationMode.COMPILE_TIME_ONLY] = 1.5, + runtime_optional: Annotated[Float, EvaluationMode.RUNTIME_ONLY] = None) -> Geometry: ... +''' + + +def _analyzed(owner, source): + """Type one synthetic package call with the actual compiler runtime bindings.""" + import ast + from NodeForge.tests.unit.test_extension_dynamic_results import _dynamic_semantic_environment + from NodeForge.semantic.analysis import analyze_expression + from NodeForge.semantic.lowering import lower_analyzed_expression + env, _ = _dynamic_semantic_environment(owner) + expression = ast.parse(source, mode="eval").body + analyzed = analyze_expression(expression, env) + return analyzed.facts[expression].analyzed_call, lower_analyzed_expression(expression, analyzed) + + +def test_backend_omission_keeps_indexed_ir_and_concrete_default(tmp_path): + """Only omission carries a None value; concrete defaults remain typed static IR.""" + from NodeForge.semantic.ir import IRCall + owner = _owner(tmp_path, _BACKEND_INTERFACE) + analyzed, program = _analyzed(owner, "sample(geo)") + assert [(a.parameter_index, a.value) for a in analyzed.static_operands] == [ + (1, None), (2, 1.5), (3, None)] + assert len(analyzed.runtime_operands) == 1 + call, = [op for op in program.operations if isinstance(op, IRCall)] + assert [(a.parameter_index, a.value) for a in call.static_arguments] == [ + (1, None), (2, 1.5), (3, None)] + assert [a.parameter_index for a in call.arguments] == [0] + + +def test_explicit_backend_values_obey_mode_and_keep_runtime_slots(tmp_path): + """Supplied constants and runtime arguments retain their normal typed carriers.""" + owner = _owner(tmp_path, _BACKEND_INTERFACE) + call, _ = _analyzed(owner, "sample(geo, runtime_optional=f, optional=i)") + assert [(a.parameter_index, a.value) for a in call.static_operands] == [(2, 1.5)] + assert sorted(a.parameter_index for a in call.runtime_operands) == [0, 1, 3] + call, _ = _analyzed(owner, "sample(geo, optional=10)") + assert [(a.parameter_index, a.value) for a in call.static_operands] == [ + (1, 10), (2, 1.5), (3, None)] + + +@pytest.mark.parametrize("source,match", [ + ("sample()", "signature"), + ("sample(geo, missing=10)", "signature"), + ("sample(geo, optional=1, optional=2)", "multiple values"), + ("sample(geo, optional=None)", "Only numeric, boolean and string constants"), + ("sample(geo, required_mode=f)", "compile time"), + ("sample(geo, runtime_optional=v)", "types do not match"), + ("sample(geo, **{})", "does not support caller-side"), + ("sample(geo, *[f])", "does not support caller-side"), +]) +def test_backend_omission_does_not_admit_invalid_calls(tmp_path, source, match): + """Omission must not bypass caller binding or supplied-argument validation.""" + owner = _owner(tmp_path, _BACKEND_INTERFACE) + with pytest.raises(CompileError, match=match): + _analyzed(owner, source) + + +def test_overload_omitted_input_gives_no_type_evidence(tmp_path): + """Equal omitted overloads remain ambiguous; explicit types select alternatives.""" + source = '''from typing import Annotated, overload +from NodeForge import Float, Int, Geometry, EvaluationMode +EXTENSION_API = 2 +EXTENSIONS = {"sample": ".backend:sample"} +@overload +def sample(geometry: Annotated[Geometry, EvaluationMode.RUNTIME_ONLY], + *, option: Annotated[Int, EvaluationMode.RUNTIME_ONLY] = None) -> Int: ... +@overload +def sample(geometry: Annotated[Geometry, EvaluationMode.RUNTIME_ONLY], + *, option: Annotated[Float, EvaluationMode.RUNTIME_ONLY] = None) -> Float: ... +def sample(*args, **kwargs): ... +''' + owner = _owner(tmp_path, source) + with pytest.raises(CompileError, match="ambiguous"): + _analyzed(owner, "sample(geo)") + for expression, index in [("sample(geo, option=i)", 0), ("sample(option=f, geometry=geo)", 1)]: + analyzed, _ = _analyzed(owner, expression) + assert analyzed.extension_overload_index == index + + +def test_backend_resolver_omission_is_plain_none(tmp_path): + """Resolver receives an untyped omitted slot and typed supplied/default arguments.""" + from NodeForge.nf_types import NFType + from NodeForge.extension_result_api import ResultRuntimeArg, ResultStaticArg + interface = _BACKEND_INTERFACE.replace("-> Geometry: ...", "-> DynamicResults: ...") + interface = interface.replace("from NodeForge import Float,", "from NodeForge import DynamicResults, Float,") + semantic = '''from NodeForge.nf_types import NFType +from NodeForge.extension_result_api import ResultRuntimeArg, ResultStaticArg +SEEN = [] +def _result_types_sample(arguments): + assert not hasattr(arguments, "__setitem__") + SEEN.append(dict(arguments)) + return (NFType.GEOMETRY, NFType.FLOAT) +''' + owner = _owner(tmp_path, interface, semantic=semantic) + call, _ = _analyzed(owner, "sample(geo)") + assert call.result.types == (NFType.GEOMETRY, NFType.FLOAT) + call, _ = _analyzed(owner, "sample(geo, optional=i, runtime_optional=f)") + assert call.result.types == (NFType.GEOMETRY, NFType.FLOAT) + seen = owner._phase_modules["SEMANTIC"]["semantic"].SEEN + assert len(seen) == 2 + assert seen[0]["optional"] is None and seen[0]["runtime_optional"] is None + assert isinstance(seen[0]["required_mode"], ResultStaticArg) + assert seen[0]["required_mode"].value == 1.5 + assert isinstance(seen[1]["optional"], ResultRuntimeArg) + assert isinstance(seen[1]["runtime_optional"], ResultRuntimeArg) From 1fa5044884691209387bec18cbeff88e4d307c46 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 18:54:35 +0000 Subject: [PATCH 3/6] feat(semantic): propagate omitted defaults through semantic extensions --- semantic/analysis.py | 12 +- tests/unit/test_extension_dynamic_results.py | 16 +++ .../unit/test_extension_optional_defaults.py | 118 ++++++++++++++++++ 3 files changed, 143 insertions(+), 3 deletions(-) diff --git a/semantic/analysis.py b/semantic/analysis.py index dbadc8c..cd971d9 100644 --- a/semantic/analysis.py +++ b/semantic/analysis.py @@ -817,8 +817,12 @@ def _analyze_extension_semantic_call( acquired_items: list[object] = [] type_spec = parameter.type_spec for occurrence in occurrences: - if occurrence is None and parameter.kind is not inspect.Parameter.VAR_POSITIONAL: - raise CompileError("Internal error: semantic extension binding lost fixed parameter") + if occurrence is None: + if type_spec.kind != "NF_SET" or parameter.default is not None: + raise CompileError("Internal error: semantic extension binding lost fixed parameter") + # An omitted typed parameter has no semantic dependency or type. + acquired_items.append(None) + continue if isinstance(occurrence, ExtensionSemanticPayload): payload = occurrence if type_spec.kind not in {"RECORD", "LIST"}: @@ -892,7 +896,9 @@ def _analyze_extension_semantic_call( 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": + if item is None and parameter.type_spec.kind == "NF_SET" and parameter.default is None: + argument_items.append(None) + elif 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)) diff --git a/tests/unit/test_extension_dynamic_results.py b/tests/unit/test_extension_dynamic_results.py index 4090fc5..7146b84 100644 --- a/tests/unit/test_extension_dynamic_results.py +++ b/tests/unit/test_extension_dynamic_results.py @@ -384,3 +384,19 @@ def _result_types_foo(arguments): assert isinstance(first["selection"], ResultStaticArg) and first["selection"].value is True assert isinstance(second["domain"], ResultStaticArg) and second["domain"].value == "POINT" assert isinstance(second["selection"], ResultRuntimeArg) + + + +def test_semantic_dynamic_resolver_reads_optional_none_once_per_call(tmp_path): + """A semantic-then-backend result resolver handles omitted direct NF inputs.""" + from NodeForge.tests.unit.test_extension_optional_defaults import ( + _SEMANTIC_BACKEND_INTERFACE, _SEMANTIC_BACKEND, _analyzed, _owner, + ) + from NodeForge.extension_result_api import ResultRuntimeArg + owner = _owner(tmp_path, _SEMANTIC_BACKEND_INTERFACE, semantic=_SEMANTIC_BACKEND) + for expression in ("sample(f)", "sample(f, optional=i)"): + _analyzed(owner, expression) + semantic = owner._phase_modules["SEMANTIC"]["semantic"] + assert len(semantic.RESOLVED) == len(semantic.SEEN) == 2 + assert semantic.RESOLVED[0]["optional"] is None + assert isinstance(semantic.RESOLVED[1]["optional"], ResultRuntimeArg) diff --git a/tests/unit/test_extension_optional_defaults.py b/tests/unit/test_extension_optional_defaults.py index 33766c6..f768031 100644 --- a/tests/unit/test_extension_optional_defaults.py +++ b/tests/unit/test_extension_optional_defaults.py @@ -174,3 +174,121 @@ def _result_types_sample(arguments): assert seen[0]["required_mode"].value == 1.5 assert isinstance(seen[1]["optional"], ResultRuntimeArg) assert isinstance(seen[1]["runtime_optional"], ResultRuntimeArg) + + +_SEMANTIC_ONLY_INTERFACE = '''from typing import Annotated +from dataclasses import dataclass +from NodeForge import Float, Int, EvaluationMode +EXTENSION_API = 2 +EXTENSIONS = {"sample": None} +@dataclass(frozen=True) +class Part: + base: Float + optional: Int | None +def sample(base: Annotated[Float, EvaluationMode.RUNTIME_ONLY], + *, optional: Annotated[Int, EvaluationMode.RUNTIME_ONLY] = None) -> Part: ... +''' + +_SEMANTIC_ONLY = '''from .interface import Part +SEEN = [] +def sample(base, *, optional=None) -> Part: + SEEN.append(optional) + return Part(base, optional) +''' + + +def test_semantic_only_omission_has_no_dependency_and_explicit_value_does(tmp_path): + """Semantic records retain the one required runtime value and any supplied optional.""" + from NodeForge.nf_types import NFType + from NodeForge.extensions.values import ExtensionDependencySlot + owner = _owner(tmp_path, _SEMANTIC_ONLY_INTERFACE, semantic=_SEMANTIC_ONLY) + from NodeForge.tests.unit.test_extension_dynamic_results import _dynamic_semantic_environment + from NodeForge.semantic.analysis import analyze_expression + import ast + env, _ = _dynamic_semantic_environment(owner) + omission = ast.parse("sample(f)", mode="eval").body + fact = analyze_expression(omission, env).facts[omission] + assert len(fact.semantic_payload.dependencies) == 1 + assert fact.semantic_payload.value.storage[1] is None + supplied = ast.parse("sample(f, optional=i)", mode="eval").body + fact = analyze_expression(supplied, env).facts[supplied] + assert len(fact.semantic_payload.dependencies) == 2 + assert isinstance(fact.semantic_payload.value.storage[1], ExtensionDependencySlot) + assert fact.semantic_payload.dependencies[1].typ is NFType.INT + seen = owner._phase_modules["SEMANTIC"]["semantic"].SEEN + assert seen[0] is None and seen[1] is not None + bad = ast.parse("sample(f, optional=None)", mode="eval").body + with pytest.raises(CompileError, match="Only numeric, boolean and string constants"): + analyze_expression(bad, env) + + +_SEMANTIC_BACKEND_INTERFACE = _SEMANTIC_ONLY_INTERFACE.replace( + 'EXTENSIONS = {"sample": None}', 'EXTENSIONS = {"sample": ".backend:sample"}' +).replace('class Part:', 'class _State:').replace(') -> Part: ...', ') -> DynamicResults: ...').replace( + 'from NodeForge import Float,', 'from NodeForge import DynamicResults, Float,' +) + +_SEMANTIC_BACKEND = '''from .interface import _State +from NodeForge.nf_types import NFType +from NodeForge.extension_result_api import ResultStaticArg, ResultRuntimeArg +SEEN = [] +RESOLVED = [] +def sample(base, *, optional=None) -> _State: + SEEN.append(optional) + return _State(base, optional) +def _result_types_sample(arguments): + assert not hasattr(arguments, "__setitem__") + RESOLVED.append(dict(arguments)) + return (NFType.FLOAT, NFType.INT) +''' + + +def test_semantic_then_backend_omission_is_compact_and_dynamic_resolver_is_typed(tmp_path): + """Resolver and semantic state independently retain omission and supplied dependencies.""" + from NodeForge.extension_result_api import ResultRuntimeArg + from NodeForge.nf_types import NFType + from NodeForge.semantic.ir import IRCall + owner = _owner(tmp_path, _SEMANTIC_BACKEND_INTERFACE, semantic=_SEMANTIC_BACKEND) + analyzed, program = _analyzed(owner, "sample(f)") + assert analyzed.result.types == (NFType.FLOAT, NFType.INT) + assert len(analyzed.runtime_operands) == 1 + call, = [op for op in program.operations if isinstance(op, IRCall)] + assert len(call.arguments) == 1 + assert call.extension_state_type is not None + analyzed, program = _analyzed(owner, "sample(f, optional=i)") + assert len(analyzed.runtime_operands) == 2 + call, = [op for op in program.operations if isinstance(op, IRCall)] + assert len(call.arguments) == 2 + semantic = owner._phase_modules["SEMANTIC"]["semantic"] + assert semantic.SEEN[0] is None and semantic.SEEN[1] is not None + assert len(semantic.RESOLVED) == 2 + assert semantic.RESOLVED[0]["optional"] is None + assert isinstance(semantic.RESOLVED[1]["optional"], ResultRuntimeArg) + assert semantic.RESOLVED[1]["optional"].typ is NFType.INT + + +def test_semantic_only_list_results_preserve_omission(tmp_path): + """Optional direct parameters are independent of semantic record/list return shape.""" + from NodeForge.tests.unit.test_extension_dynamic_results import _dynamic_semantic_environment + from NodeForge.semantic.analysis import analyze_expression + import ast + + interface = _SEMANTIC_ONLY_INTERFACE.replace( + ') -> Part: ...', ') -> list[Part]: ...', + ) + semantic = '''from .interface import Part +def sample(base, *, optional=None) -> list[Part]: + if optional is None: + return [Part(base, None)] + return [Part(base, optional), Part(base, None)] +''' + owner = _owner(tmp_path, interface, semantic=semantic) + env, _ = _dynamic_semantic_environment(owner) + first = ast.parse("sample(f)", mode="eval").body + first_fact = analyze_expression(first, env).facts[first] + assert len(first_fact.semantic_payload.value) == 1 + assert len(first_fact.semantic_payload.dependencies) == 1 + second = ast.parse("sample(f, optional=i)", mode="eval").body + second_fact = analyze_expression(second, env).facts[second] + assert len(second_fact.semantic_payload.value) == 2 + assert len(second_fact.semantic_payload.dependencies) == 2 From e20966c7cdde4109e86ba1e5f91406715d8a05c7 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 18:57:15 +0000 Subject: [PATCH 4/6] test(blender): cover optional extension sockets and downstream compatibility --- .../test_extension_optional_defaults.py | 250 ++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 tests/blender/test_extension_optional_defaults.py diff --git a/tests/blender/test_extension_optional_defaults.py b/tests/blender/test_extension_optional_defaults.py new file mode 100644 index 0000000..651223a --- /dev/null +++ b/tests/blender/test_extension_optional_defaults.py @@ -0,0 +1,250 @@ +"""Blender 5.2 socket/default and lifecycle checks for omitted Extension API v2 parameters.""" + +from __future__ import annotations + +import builtins +import json +from pathlib import Path + +import bpy +import pytest + +from helpers import compile_group +from NodeForge import compiler, packages +from NodeForge.blender.extension_group_materializer import ( + EXTENSION_AUTHORITY_PROP, EXTENSION_FINGERPRINT_PROP, +) +from NodeForge.errors import CompileError + +pytestmark = pytest.mark.blender + + +@pytest.fixture(autouse=True) +def track_optional_writes(): + """Record only socket writes by the test backend, not Blender initialization.""" + builtins._nf_optional_writes = [] + yield + del builtins._nf_optional_writes + + +def _install_optional_package(root: Path): + """Register one synthetic backend that only configures explicitly supplied sockets.""" + owner = root / 'systems' / 'resample' + owner.mkdir(parents=True) + (root / 'nodeforge_package.json').write_text(json.dumps({ + 'schema_version': 1, + 'id': 'vendor.optional.resample', + 'name': 'Optional Resample', + 'version': '1.0.0', + 'author': 'Tests', + 'description': 'Omission default preservation probe', + 'nodeforge_min_version': '0.97.4', + '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 Bool, EvaluationMode, Float, Geometry, Int, String +EXTENSION_API = 2 +EXTENSIONS = {'resample_curve': '.backend:resample_curve'} +def resample_curve( + curve: Annotated[Geometry, EvaluationMode.RUNTIME_ONLY], + *, + mode: Annotated[String, EvaluationMode.COMPILE_TIME_ONLY] = None, + count: Annotated[Int, EvaluationMode.COMPILE_TIME_OR_RUNTIME] = None, + length: Annotated[Float, EvaluationMode.COMPILE_TIME_OR_RUNTIME] = None, + selection: Annotated[Bool, EvaluationMode.RUNTIME_ONLY] = None, +) -> Geometry: ... +''', encoding='utf-8') + (owner / 'backend.py').write_text('''import builtins +from NodeForge.extension_api import ExtensionBackendValue, NFType + +def resample_curve(context, curve, *, mode=None, count=None, length=None, selection=None): + node = context.group.nodes.new('GeometryNodeResampleCurve') + node.location = context.location + context.group.links.new(curve.socket, node.inputs['Curve']) + if mode == 'BROKEN': + context.new_generated_mesh(role='optional-failure-probe', name_hint='OptionalFailureProbe') + raise ValueError('intentional optional extension failure') + if mode is not None: + if mode not in {'Count', 'Length', 'Evaluated'}: + raise ValueError('invalid Resample Curve mode') + node.inputs['Mode'].default_value = mode + builtins._nf_optional_writes.append('Mode') + effective_mode = node.inputs['Mode'].default_value + if count is not None and effective_mode != 'Count': + raise ValueError('Count is unavailable in selected mode') + if length is not None and effective_mode != 'Length': + raise ValueError('Length is unavailable in selected mode') + for key, argument in (('Count', count), ('Length', length), ('Selection', selection)): + if argument is None: + continue + if isinstance(argument, ExtensionBackendValue): + context.group.links.new(argument.socket, node.inputs[key]) + else: + node.inputs[key].default_value = argument + builtins._nf_optional_writes.append(key) + return context.value(node.outputs['Curve'], NFType.GEOMETRY) +''', encoding='utf-8') + packages.install_package_directory(root) + + +@pytest.fixture +def optional_package(tmp_path): + """Keep each test package version independent of user-installed inventory.""" + _install_optional_package(tmp_path / 'optional-source') + + +def _source(call, *, args='curve: Geometry', statements=None): + """Build a normal, compiled package call in a function body.""" + body = statements or f'return {call}' + return f'from packages import resample\n\ndef nf_fixture({args}) -> Geometry:\n {body}\n' + + +def _resample_nodes(group): + """Find native resample nodes in the provided tree without relying on node labels.""" + return [node for node in group.nodes if node.bl_idname == 'GeometryNodeResampleCurve'] + + +def _assert_native_defaults(group, *, mode='Count', count=10, length=0.1): + """Require Blender's actual input defaults and no optional socket links.""" + node, = _resample_nodes(group) + assert node.inputs['Mode'].default_value == mode + assert node.inputs['Count'].default_value == count + assert node.inputs['Length'].default_value == pytest.approx(length) + assert not any(link.to_socket in {node.inputs['Mode'], node.inputs['Count'], node.inputs['Length'], + node.inputs['Selection']} for link in group.links) + return node + + +@pytest.mark.parametrize('inline', [None, True, False]) +def test_omitted_sockets_stay_at_blender_defaults_in_both_modes(optional_package, inline): + """Only the Curve runtime operand is present; Count/Length retain native defaults.""" + modifier = '' if inline is None else f', __inline__={inline}' + group = compile_group(_source(f'resample_curve(curve{modifier})'), 'NFOptionalDefault_'+str(inline)) + if inline is False: + node, = [node for node in group.nodes if node.bl_idname == 'GeometryNodeGroup'] + child = node.node_tree + assert [sock.name for sock in node.inputs] == ['curve'] + assert child.get(EXTENSION_AUTHORITY_PROP) + else: + child = group + _assert_native_defaults(child) + assert builtins._nf_optional_writes == [] + + +@pytest.mark.parametrize('call,mode,count,length,writes', [ + ('resample_curve(curve, count=20)', 'Count', 20, 0.1, ['Count']), + ('resample_curve(curve, mode="Length")', 'Length', 10, 0.1, ['Mode']), + ('resample_curve(curve, mode="Length", length=0.5)', 'Length', 10, 0.5, ['Mode', 'Length']), +]) +def test_explicit_static_inputs_only_update_selected_sockets(optional_package, call, mode, count, length, writes): + """The test wrapper owns conditional socket assignment and does not duplicate defaults.""" + group = compile_group(_source(call), 'NFOptionalStatic_'+mode+str(count)) + _assert_native_defaults(group, mode=mode, count=count, length=length) + assert builtins._nf_optional_writes == writes + + +def test_runtime_count_and_runtime_only_selection_link_sockets(optional_package): + """Explicit runtime optional arguments become links; omitted ones do not.""" + group = compile_group(_source( + 'resample_curve(curve, count=count, selection=selection)', + args='curve: Geometry, count: Int, selection: Bool', + ), 'NFOptionalRuntime') + node, = _resample_nodes(group) + for name in ('Count', 'Selection'): + assert len([link for link in group.links if link.to_socket == node.inputs[name]]) == 1 + assert node.inputs['Mode'].default_value == 'Count' + assert node.inputs['Length'].default_value == pytest.approx(0.1) + assert builtins._nf_optional_writes == [] + + +def test_group_runtime_inputs_only_and_fingerprint_tracks_static_none(optional_package): + """Grouped children keep only runtime sockets and rebuild after static call changes.""" + initial = _source('resample_curve(curve, __inline__=False)') + group = compile_group(initial, 'NFOptionalGroupFingerprint') + node, = [node for node in group.nodes if node.bl_idname == 'GeometryNodeGroup'] + assert [sock.name for sock in node.inputs] == ['curve'] + old_authority = node.node_tree.get(EXTENSION_AUTHORITY_PROP) + old_fingerprint = node.node_tree.get(EXTENSION_FINGERPRINT_PROP) + old_pointer = node.node_tree.as_pointer() + compiler.update_expression_group(group, initial) + same, = [node for node in group.nodes if node.bl_idname == 'GeometryNodeGroup'] + assert same.node_tree.as_pointer() == old_pointer + assert same.node_tree.get(EXTENSION_FINGERPRINT_PROP) == old_fingerprint + modified = _source('resample_curve(curve, count=20, __inline__=False)') + compiler.update_expression_group(group, modified) + refreshed, = [node for node in group.nodes if node.bl_idname == 'GeometryNodeGroup'] + assert refreshed.node_tree.get(EXTENSION_AUTHORITY_PROP) == old_authority + assert refreshed.node_tree.get(EXTENSION_FINGERPRINT_PROP) != old_fingerprint + _assert_native_defaults(refreshed.node_tree, count=20) + + +@pytest.mark.parametrize('inline', [True, False]) +def test_inapplicable_explicit_socket_is_rejected_and_rolled_back(optional_package, inline): + """Package-specific Count/Length validation rolls back unsuccessful compilation.""" + before_groups = {g.as_pointer() for g in bpy.data.node_groups} + before_meshes = {mesh.as_pointer() for mesh in bpy.data.meshes} + with pytest.raises(CompileError, match='Count is unavailable'): + compile_group(_source(f'resample_curve(curve, mode="Length", count=20, __inline__={inline})'), + 'NFOptionalInvalid'+str(inline)) + assert {g.as_pointer() for g in bpy.data.node_groups} == before_groups + assert {mesh.as_pointer() for mesh in bpy.data.meshes} == before_meshes + + +def test_backend_resource_failure_rolls_back_groups_and_meshes(optional_package): + """An intentionally failed grouped call releases its generated resource transaction.""" + before_groups = {g.as_pointer() for g in bpy.data.node_groups} + before_meshes = {mesh.as_pointer() for mesh in bpy.data.meshes} + with pytest.raises(CompileError, match='intentional optional extension failure'): + compile_group(_source('resample_curve(curve, mode="BROKEN", __inline__=False)'), + 'NFOptionalResourceFailure') + assert {g.as_pointer() for g in bpy.data.node_groups} == before_groups + assert {mesh.as_pointer() for mesh in bpy.data.meshes} == before_meshes + + +def test_nested_and_root_materialization_preserves_omitted_defaults(optional_package): + """Nested calls and executable root composition share the same omission semantics.""" + group = compile_group( + _source('resample_curve(resample_curve(curve))'), 'NFOptionalNested' + ) + nested = _resample_nodes(group) + assert len(nested) == 2 + assert all(node.inputs['Mode'].default_value == 'Count' for node in nested) + assert all(node.inputs['Count'].default_value == 10 for node in nested) + + root = bpy.data.node_groups.new('NFOptionalRootComposition', 'GeometryNodeTree') + source = '''from packages import resample +curve = node("GeometryNodeCurvePrimitiveLine", output="Curve", typ=Geometry) +result = resample_curve(curve) +''' + outcome = compiler.compile_source_in_tree(source, root) + assert outcome.outcome == 'ROOT_REPLACEMENT' + _assert_native_defaults(root) + + +def test_grouped_runtime_optional_sockets_have_only_supplied_inputs(optional_package): + """The child interface includes runtime Count and Selection but not omitted Mode/Length.""" + group = compile_group(_source( + 'resample_curve(curve, count=count, selection=selection, __inline__=False)', + args='curve: Geometry, count: Int, selection: Bool', + ), 'NFOptionalGroupedRuntime') + group_node, = [node for node in group.nodes if node.bl_idname == 'GeometryNodeGroup'] + assert [socket.name for socket in group_node.inputs] == ['curve', 'count', 'selection'] + assert [socket.name for socket in group_node.outputs] == ['Result'] + child = group_node.node_tree + resample, = _resample_nodes(child) + assert resample.inputs['Mode'].default_value == 'Count' + assert resample.inputs['Length'].default_value == pytest.approx(0.1) + assert len([link for link in child.links if link.to_socket == resample.inputs['Count']]) == 1 + assert len([link for link in child.links if link.to_socket == resample.inputs['Selection']]) == 1 + assert builtins._nf_optional_writes == [] + + +def test_optional_compile_time_mode_rejects_runtime_source(optional_package): + """An omitted parameter does not bypass COMPILE_TIME_ONLY for a supplied value.""" + before = {group.as_pointer() for group in bpy.data.node_groups} + with pytest.raises(CompileError, match='compile time'): + compile_group(_source('resample_curve(curve, mode=mode)', args='curve: Geometry, mode: String'), + 'NFOptionalInvalidRuntimeMode') + assert {group.as_pointer() for group in bpy.data.node_groups} == before From bd5223128a52927182299388f1e088439ef449f8 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 20:15:55 +0000 Subject: [PATCH 5/6] chore(release): consolidate Issue 68 changelog and bump to 0.98.0 --- __init__.py | 2 +- blender_manifest.toml | 2 +- dev/CHANGELOG.md | 6 +++++ tests/unit/test_unified_editor_signatures.py | 27 ++++++++++++++++++++ 4 files changed, 35 insertions(+), 2 deletions(-) diff --git a/__init__.py b/__init__.py index 8020af2..8b4ceb3 100644 --- a/__init__.py +++ b/__init__.py @@ -1,6 +1,6 @@ """NodeForge Blender addon package.""" -NODEFORGE_VERSION = (0, 97, 4) +NODEFORGE_VERSION = (0, 98, 0) bl_info = { "name": "NodeForge", "author": "nachitima", diff --git a/blender_manifest.toml b/blender_manifest.toml index fa8b397..8c5dd58 100644 --- a/blender_manifest.toml +++ b/blender_manifest.toml @@ -1,6 +1,6 @@ schema_version = "1.0.0" id = "nodeforge" -version = "0.97.4" +version = "0.98.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 3a3e228..b3e6bfe 100644 --- a/dev/CHANGELOG.md +++ b/dev/CHANGELOG.md @@ -820,3 +820,9 @@ lifecycle. - Added Blender characterization sources, deterministic graph baselines and focused assertions for Python Extension API v2 inline/grouped placement, nested calls, DynamicResults, compacted semantic dependencies, and Capture Attribute Rotation. - Extended characterization snapshots to retain Capture Attribute item types, domain and unlinked Float item defaults without changing existing recorded cases. + +## 0.98.0 + +- Added optional direct typed Extension API v2 parameters declared with `= None`, including compile-time, runtime, and mixed evaluation modes. +- Preserve omitted parameters as indexed static `None` operands through overload selection, semantic processing, dynamic result resolution, and inline/grouped Blender materialization. +- Added declaration, semantic, dynamic-result, Blender socket-default, and downstream `nodeforge.nodes` regression coverage. diff --git a/tests/unit/test_unified_editor_signatures.py b/tests/unit/test_unified_editor_signatures.py index 6d2c5cc..b3d2fd8 100644 --- a/tests/unit/test_unified_editor_signatures.py +++ b/tests/unit/test_unified_editor_signatures.py @@ -70,3 +70,30 @@ def test_no_legacy_root_input_completion(index): names = index.symbols('') [''] assert 'input_float' not in names assert 'output' not in names + + + +def test_extension_signature_displays_none_as_optional_without_changing_required_defaults(): + """Editor signatures distinguish omission from required and concrete defaults.""" + import inspect + from NodeForge.editor.intelligence import _extension_signatures + from NodeForge.extensions.contracts import ExtensionCallableId, ExtensionCallableSpec, ExtensionParameterSpec, TypeSpec + from NodeForge.evaluation_modes import EvaluationMode + from NodeForge.nf_types import NFType + + typ = TypeSpec("NF_SET", frozenset({NFType.FLOAT})) + spec = ExtensionCallableSpec( + ExtensionCallableId(("system", "test", "editor"), "sample"), + ( + ExtensionParameterSpec("required", inspect.Parameter.POSITIONAL_OR_KEYWORD, + typ, EvaluationMode.RUNTIME_ONLY), + ExtensionParameterSpec("optional", inspect.Parameter.KEYWORD_ONLY, + typ, EvaluationMode.RUNTIME_ONLY, None), + ExtensionParameterSpec("amount", inspect.Parameter.KEYWORD_ONLY, + typ, EvaluationMode.COMPILE_TIME_OR_RUNTIME, 1.5, NFType.FLOAT), + ), + typ, + ) + editor_signature, = _extension_signatures("sample", (spec,)) + assert [parameter.default for parameter in editor_signature.parameters] == [None, "None", "1.5"] + assert [parameter.keyword for parameter in editor_signature.parameters] == ["required", "optional", "amount"] From a86a6494e911b61c35edecad030671c6475d3e16 Mon Sep 17 00:00:00 2001 From: denikryt Date: Mon, 23 Nov 2026 03:48:08 +0200 Subject: [PATCH 6/6] docs update --- docs/EXTENSION_API.md | 50 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/docs/EXTENSION_API.md b/docs/EXTENSION_API.md index febbe78..902f206 100644 --- a/docs/EXTENSION_API.md +++ b/docs/EXTENSION_API.md @@ -139,13 +139,13 @@ The marker classes are annotation tokens rather than runtime values to instantia ### Evaluation modes -| Mode | Accepted representation | +| Mode | Supplied argument representation | | --- | --- | | `EvaluationMode.COMPILE_TIME_ONLY` | Detached compile-time data only. | | `EvaluationMode.RUNTIME_ONLY` | Runtime NodeForge value only; the backend receives an `ExtensionBackendValue`. | | `EvaluationMode.COMPILE_TIME_OR_RUNTIME` | Detached data when known at compile time, otherwise the runtime representation. | -`RUNTIME_ONLY` parameters cannot have defaults. Compile-time and mixed parameters may default to detached `Bool`, signed-32 `Int`, `Float`, `String`, 3-component `Vector` or `Rotation`, or 4-component `Color` values. Vector, Rotation and Color defaults may be written as Python lists or tuples and are canonicalized by NodeForge. Color is linear RGBA `(R, G, B, A)` with finite nonnegative binary32 components, including alpha and valid HDR values. A Color-marked parameter receives an immutable RGBA tuple in its compile-time branch, or an `ExtensionBackendValue` in its runtime branch. Ordinary extension `list` and `tuple` semantic fields remain structural Python values. +`RUNTIME_ONLY` parameters accept only `None` as a default; see [Optional typed parameters](#optional-typed-parameters). Compile-time and mixed parameters may default to detached `Bool`, signed-32 `Int`, `Float`, `String`, 3-component `Vector` or `Rotation`, or 4-component `Color` values. Vector, Rotation and Color defaults may be written as Python lists or tuples and are canonicalized by NodeForge. Color is linear RGBA `(R, G, B, A)` with finite nonnegative binary32 components, including alpha and valid HDR values. A Color-marked parameter receives an immutable RGBA tuple in its compile-time branch, or an `ExtensionBackendValue` in its runtime branch. Ordinary extension `list` and `tuple` semantic fields remain structural Python values. A declared `Rotation` default is an XYZ Euler-angle triple in radians, normalized to an immutable three-float binary32 tuple. Python integer components may exceed signed Int32 when their numeric values are representable as finite binary32 floats. A uniquely declared `Rotation` parameter interprets an untyped numeric triple as Rotation; `Vector` declarations interpret it as Vector. A parameter typed `Rotation | Vector` cannot use an untyped numeric triple as a default or static argument because both alternatives match. A typed runtime reference uses its exact declared type. Backend overloads with equally matching Rotation and Vector candidates also reject an untyped triple as ambiguous. See [Writing Functions](WRITING_FUNCTIONS.md#parameters-and-sockets) for the `.nf` source-default limits and explicit runtime Euler conversion. @@ -159,6 +159,47 @@ def tint(value: Annotated[Color, EvaluationMode.COMPILE_TIME_OR_RUNTIME] = (0.2, Use compile-time data for configuration that changes graph shape or node properties. Use runtime values for data that should remain connected as Geometry Nodes sockets or fields. +### Optional typed parameters + +Use `= None` in `interface.py` to allow omission of a direct typed argument. All three evaluation modes support it. + +| Declaration | Omitted argument | +| --- | --- | +| No default | Required; omission is an error. | +| Concrete default | Receives the declared value. | +| `= None` | Receives Python `None` in the backend and semantic function. | + +For example, a Resample Curve wrapper can leave Count at Blender's default: + +```python +# interface.py +from typing import Annotated +from NodeForge import EvaluationMode, Geometry, Int + + +def resample_curve( + curve: Annotated[Geometry, EvaluationMode.RUNTIME_ONLY], + *, + count: Annotated[Int, EvaluationMode.COMPILE_TIME_OR_RUNTIME] = None, +) -> Geometry: + ... +``` + +In the backend, skip socket assignment and linking when the argument is `None`: + +```python +# backend.py: after creating node and connecting Curve +from NodeForge.extension_api import ExtensionBackendValue + +if count is not None: + if isinstance(count, ExtensionBackendValue): + context.group.links.new(count.socket, node.inputs['Count']) + else: + node.inputs['Count'].default_value = count +``` + +Omit the keyword in `.nf` calls to use this behavior. Explicit `.nf` arguments such as `count=None` and direct parameter annotations such as `Int | None` are unsupported. Supplied values retain their declared type and evaluation-mode checks. + ### Direct results A backend-only callable may return one exact direct type: @@ -240,6 +281,7 @@ The resolver's `arguments` is a read-only mapping from parameter names to the fo | --- | --- | | Direct runtime value | `ResultRuntimeArg`: `.typ` is the actual `NFType`. | | Direct compile-time value | `ResultStaticArg`: `.typ` and the canonical immutable `.value`. | +| Omitted parameter declared with `= None` | Python `None`. | | 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. | @@ -255,7 +297,7 @@ The backend must return a Python tuple of `ExtensionBackendValue` objects, inclu ### Overloads -Use `typing.overload` for a finite set of direct-value signatures. Alternatives are tried in source order. +Use `typing.overload` for a finite set of direct-value signatures. Exact type matches take precedence over compatible matches. Omitted `= None` parameters provide no type evidence; equally matching alternatives are ambiguous. ```python from typing import Annotated, overload @@ -456,7 +498,7 @@ Import the public backend types from: from NodeForge.extension_api import ExtensionBackendContext, ExtensionBackendValue, NFType ``` -Runtime direct arguments are `ExtensionBackendValue` instances. Compile-time arguments are detached Python data selected by the parameter's evaluation mode. The compiler consumes `__inline__`; semantic functions and backends receive only their declared arguments. +Supplied runtime direct arguments are `ExtensionBackendValue` instances. Compile-time arguments are detached Python data selected by the parameter's evaluation mode. The compiler consumes `__inline__`; semantic functions and backends receive only their declared arguments. ### `ExtensionBackendValue`