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

Filter by extension

Filter by extension

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

NODEFORGE_VERSION = (0, 97, 4)
NODEFORGE_VERSION = (0, 97, 5)
bl_info = {
"name": "NodeForge",
"author": "nachitima",
Expand Down
2 changes: 1 addition & 1 deletion blender_manifest.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
schema_version = "1.0.0"
id = "nodeforge"
version = "0.97.4"
version = "0.97.5"
name = "NodeForge"
tagline = "Compile a procedural DSL into Blender Geometry Nodes"
maintainer = "nachitima"
Expand Down
8 changes: 8 additions & 0 deletions dev/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -820,3 +820,11 @@ 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.97.5

- Made Blender Text Editor completion accept Enter/Numpad Enter as well as Tab, reopen after Escape on the next editor action, and reject stale selections.
- Displayed static raw-node output selector names and types, including multi-return functions, in completion signatures and member previews.
- Kept Text Editor suggestions dismissed after Escape when edits precede the next refresh; ignored unrelated header/sidebar mouse clicks.
- Invalidated stale socket names and types after nested assignment expressions in source-signature previews.
- Limited Text Editor completion keyboard handling to the text WINDOW region, preserving Escape dismissal and native header/sidebar key behavior.
2 changes: 1 addition & 1 deletion docs/GET_STARTED.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ To call functions saved in Local from another script, see [Import functions](MOD

## Text Editor completion (prototype)

NodeForge has built-in text completion for scripts in Blender's Text Editor. This prototype suggests Core DSL functions, Local and package imports, imported members, and functions declared in the current script. It also shows function parameters and return types when available. Enable it with **NodeForge** in the Text Editor header.
Text Editor completion suggests Core DSL functions, Local and package imports, imported members, and functions declared in the current Text. Call hints show parameter names, types, and defaults, plus available output names and types in return order.

## What to read next

Expand Down
58 changes: 54 additions & 4 deletions editor/blender_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,23 @@ def _draw_overlay():
gpu.state.blend_set('NONE')


def _restarts_dismissed_completion(event, region) -> bool:
"""Recognize editor input after Escape without intercepting Blender's keymap."""
if event.value != 'PRESS' or event.type == 'ESC':
return False
if event.type == 'LEFTMOUSE':
# Header/sidebar clicks are not Text Editor caret-placement actions.
return region is not None and region.type == 'WINDOW'
if (event.type in {'BACK_SPACE', 'DEL', 'RET', 'NUMPAD_ENTER', 'TAB',
'LEFT_ARROW', 'RIGHT_ARROW', 'UP_ARROW', 'DOWN_ARROW',
'HOME', 'END', 'PAGE_UP', 'PAGE_DOWN', 'HOME_KEY', 'END_KEY'}):
return True
if (event.ctrl or event.oskey) and not event.alt and event.type in {'Z', 'Y', 'V', 'X'}:
return True
return bool(event.unicode and event.unicode.isprintable() and
not (event.ctrl or event.alt or event.oskey))


class NODEFORGE_OT_editor_session(bpy.types.Operator):
"""Receive popup navigation while allowing normal Text Editor keys through."""

Expand All @@ -265,7 +282,7 @@ def invoke(self, context, event):
return {'RUNNING_MODAL'}

def modal(self, context, event):
"""Accept Tab, navigate Up/Down, dismiss Escape; pass every other event."""
"""Accept fresh completions, navigate suggestions, and dismiss on Escape."""
pointer = self.area_pointer
if not _ENABLED or pointer not in _RUNNING_AREAS:
_RUNNING_AREAS.discard(pointer)
Expand All @@ -278,7 +295,23 @@ def modal(self, context, event):
_STATES.pop(pointer, None)
return {'CANCELLED'}
state = _STATES.get(pointer)
if state is None or not state.help.candidates or state.suppressed == state.key:
if state is None:
return {'PASS_THROUGH'}
# One modal listener covers the whole area. Only its text WINDOW region
# may navigate, accept, dismiss, or restart completion suggestions.
region = getattr(context, 'region', None)
if region is None or region.type != 'WINDOW':
return {'PASS_THROUGH'}
if state.suppressed is not None and state.suppressed == state.key:
if _restarts_dismissed_completion(event, getattr(context, 'region', None)):
# Invalidate even when several edits restore the same key before a timer tick.
state.suppressed = None
state.key = None
state.help = Assistance()
state.selection = 0
context.area.tag_redraw()
return {'PASS_THROUGH'}
if not state.help.candidates:
return {'PASS_THROUGH'}
if event.value != 'PRESS':
return {'PASS_THROUGH'}
Expand All @@ -288,13 +321,30 @@ def modal(self, context, event):
context.area.tag_redraw()
return {'RUNNING_MODAL'}
if event.type == 'ESC':
# The user may have edited the Text since the last 250 ms poll.
# Suppress the live snapshot, not the stale candidate snapshot.
text = space.text
state.key = (text.as_pointer(), text.as_string(), text.current_line_index,
text.current_character)
state.suppressed = state.key
state.help = Assistance()
state.selection = 0
context.area.tag_redraw()
return {'RUNNING_MODAL'}
if event.type == 'TAB' and not (event.ctrl or event.alt or event.oskey):
if event.type in {'TAB', 'RET', 'NUMPAD_ENTER'}:
if event.ctrl or event.alt or event.oskey or (event.type != 'TAB' and event.shift):
return {'PASS_THROUGH'}
hint = state.help
text = space.text
if text.current_line_index != hint.line or text.current_character != hint.replace_end:
source = text.as_string()
current_key = (text.as_pointer(), source, text.current_line_index, text.current_character)
lines = source.split('\n')
if (current_key != state.key or
not 0 <= state.selection < len(hint.candidates) or
not 0 <= hint.line < len(lines) or
text.current_line_index != hint.line or
text.current_character != hint.replace_end or
not 0 <= hint.replace_start <= hint.replace_end <= len(lines[hint.line])):
return {'PASS_THROUGH'}
suggestion = hint.candidates[state.selection]
for _ in range(hint.replace_end - hint.replace_start):
Expand Down
189 changes: 165 additions & 24 deletions editor/intelligence.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from pathlib import Path

from ..semantic.builtin_registry import BUILTIN_NAMES
from ..semantic.constants import TYPE_TOKEN_NAMES


@dataclass(frozen=True)
Expand All @@ -37,7 +38,7 @@ def label(self) -> str:

@dataclass(frozen=True)
class Output:
"""One named return value with a compiler-confirmed or unknown type."""
"""One named return value with a projected or unknown type."""

name: str
typ: str
Expand Down Expand Up @@ -112,8 +113,140 @@ def _core_signature(name: str) -> Signature:
return Signature(name, tuple(params), outputs)


def _socket_selector_name(expr: ast.expr) -> str | None:
"""Return a literal raw-node socket selector label, never evaluating DSL code."""
if isinstance(expr, ast.Constant) and isinstance(expr.value, str) and expr.value:
return expr.value
if (isinstance(expr, ast.Call) and isinstance(expr.func, ast.Name) and
expr.func.id == 'ID' and len(expr.args) == 1 and not expr.keywords):
return _socket_selector_name(expr.args[0])
return None


def _node_output_declarations(call: ast.expr) -> dict[str, Output] | None:
"""Project literal ``node(outputs={...})`` aliases and their types."""
if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Name)
and call.func.id == 'node'):
return None
mapping = next((kw.value for kw in call.keywords if kw.arg == 'outputs'), None)
if not isinstance(mapping, ast.Dict):
return None
outputs = {}
for key, value in zip(mapping.keys, mapping.values):
if not (isinstance(key, ast.Constant) and isinstance(key.value, str) and key.value):
continue
alias = key.value
label = alias.replace('_', ' ').title()
typ = value
if isinstance(value, ast.Tuple) and len(value.elts) == 2:
selector, typ = value.elts
literal = _socket_selector_name(selector)
if literal is not None:
label = literal
elif not (isinstance(selector, ast.Constant) and type(selector.value) is int
and selector.value >= 0):
continue
if isinstance(typ, ast.Name) and typ.id in TYPE_TOKEN_NAMES:
outputs[alias] = Output(label, typ.id)
return outputs


def _direct_node_output(call: ast.expr) -> Output | None:
"""Read a single raw-node output selector and type from literal keywords."""
if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Name)
and call.func.id == 'node'):
return None
keywords = {kw.arg: kw.value for kw in call.keywords if kw.arg is not None}
typ = keywords.get('typ')
selector = keywords.get('output')
if not (isinstance(typ, ast.Name) and typ.id in TYPE_TOKEN_NAMES and selector is not None):
return None
return Output(_socket_selector_name(selector) or 'Value', typ.id)


def _source_return_values(fn: ast.FunctionDef, parameters: list[Parameter],
returned: ast.expr) -> tuple[Output, ...]:
"""Project the final straight-line return from known arguments and node sockets.

Bindings are invalidated on assignment and ambiguous control flow. They are
display metadata, not compiler type inference, and cannot execute source.
"""
# A binding also tracks whether its label came from a raw socket selector.
values: dict[str, tuple[Output, bool]] = {
param.name: (Output(param.name.replace('_', ' ').title(), param.typ), False)
for param in parameters if param.typ in TYPE_TOKEN_NAMES
}
raw_results: dict[str, dict[str, Output]] = {}

def resolve(expr: ast.expr) -> tuple[Output, bool] | None:
"""Resolve a known value or selected raw socket in the current block."""
if isinstance(expr, ast.Name):
return values.get(expr.id)
if isinstance(expr, ast.Attribute) and isinstance(expr.value, ast.Name):
output = raw_results.get(expr.value.id, {}).get(expr.attr)
return (output, True) if output is not None else None
output = _direct_node_output(expr)
return (output, True) if output is not None else None

def invalidate_named_targets(tree: ast.AST) -> None:
"""Discard old metadata for names rebound by unsupported ``:=`` expressions."""
for item in ast.walk(tree):
if isinstance(item, ast.NamedExpr) and isinstance(item.target, ast.Name):
raw_results.pop(item.target.id, None)
values.pop(item.target.id, None)

for statement in fn.body[:-1]:
# Assignment expressions can rebind a name within another statement's RHS.
invalidate_named_targets(statement)
if isinstance(statement, ast.Assign) and len(statement.targets) == 1 and isinstance(statement.targets[0], ast.Name):
target = statement.targets[0].id
declaration = _node_output_declarations(statement.value)
source_results = (raw_results.get(statement.value.id) if isinstance(statement.value, ast.Name)
else None)
bound = resolve(statement.value)
raw_results.pop(target, None)
values.pop(target, None)
if declaration is not None:
raw_results[target] = declaration
elif source_results is not None:
raw_results[target] = source_results.copy()
elif bound is not None:
output, from_socket = bound
name = output.name if from_socket else target.replace('_', ' ').title()
values[target] = (Output(name, output.typ), from_socket)
elif isinstance(statement, (ast.Assign, ast.AnnAssign, ast.AugAssign, ast.Delete)):
targets = (statement.targets if isinstance(statement, (ast.Assign, ast.Delete))
else (statement.target,))
for target in targets:
for item in ast.walk(target):
if isinstance(item, ast.Name):
raw_results.pop(item.id, None)
values.pop(item.id, None)
elif not isinstance(statement, (ast.Expr, ast.Pass)):
# A branch, loop, or other unsupported statement can rebind any local.
raw_results.clear()
values.clear()

# A return tuple can rebind an earlier result before a later element reads it.
invalidate_named_targets(returned)
elements = returned.elts if isinstance(returned, ast.Tuple) else [returned]
outputs = []
duplicates: dict[str, int] = {}
for index, expr in enumerate(elements):
bound = resolve(expr)
name = (bound[0].name if bound is not None else
expr.id.replace('_', ' ').title() if isinstance(expr, ast.Name) else
f'Value {index + 1}' if isinstance(returned, ast.Tuple) else 'Value')
typ = bound[0].typ if bound is not None else '?'
if typ == '?' and isinstance(expr, ast.Call) and isinstance(expr.func, ast.Name):
typ = _CORE_OUTPUT_TYPES.get(expr.func.id, '?')
duplicates[name] = duplicates.get(name, 0) + 1
outputs.append(Output(name if duplicates[name] == 1 else f'{name} {duplicates[name]}', typ))
return tuple(outputs)


def _definition_signature(fn: ast.FunctionDef, display_name: str) -> Signature:
"""Project one source function's exact keyword contract from its AST."""
"""Project one source function's exact keyword and statically known result contract."""
arguments = fn.args.args
offset = len(arguments) - len(fn.args.defaults)
parameters = []
Expand All @@ -129,26 +262,27 @@ def _definition_signature(fn: ast.FunctionDef, display_name: str) -> Signature:
default = ast.unparse(fn.args.defaults[index - offset]) if index >= offset else None
parameters.append(Parameter(arg.arg, typ, default, arg.arg, label))
outputs = ()
if fn.body and isinstance(fn.body[-1], ast.Return):
if fn.body and isinstance(fn.body[-1], ast.Return) and fn.body[-1].value is not None:
returned = fn.body[-1].value
if isinstance(returned, ast.Tuple):
names = []
for index, element in enumerate(returned.elts):
title = element.id.replace('_', ' ').title() if isinstance(element, ast.Name) else f'Value {index + 1}'
names.append(title)
counts = {}
unique = []
for title in names:
counts[title] = counts.get(title, 0) + 1
unique.append(title if counts[title] == 1 else f'{title} {counts[title]}')
outputs = tuple(Output(title, '?') for title in unique)
elif returned is not None:
annotation = ast.unparse(fn.returns) if fn.returns is not None else '?'
if fn.returns is None and isinstance(returned, ast.Name):
annotation = next((p.typ for p in parameters if p.name == returned.id and p.typ), '?')
if fn.returns is None and isinstance(returned, ast.Call) and isinstance(returned.func, ast.Name):
annotation = _CORE_OUTPUT_TYPES.get(returned.func.id, '?')
outputs = (Output('Value', annotation),)
outputs = _source_return_values(fn, parameters, returned)
if not isinstance(returned, ast.Tuple):
label = None
if (isinstance(fn.returns, ast.Subscript) and
isinstance(fn.returns.value, ast.Name) and
isinstance(fn.returns.slice, ast.Constant) and
isinstance(fn.returns.slice.value, str) and
fn.returns.value.id in TYPE_TOKEN_NAMES):
label = fn.returns.slice.value
annotation = fn.returns.value.id
else:
annotation = ast.unparse(fn.returns) if fn.returns is not None else None
inferred = outputs[0]
# Ordinary single-return labels remain "Value" unless a raw socket
# or an explicit Type['Label'] gives a more meaningful source label.
raw_socket = (isinstance(returned, ast.Call) and _direct_node_output(returned) is not None) or (
isinstance(returned, ast.Attribute) and inferred.typ != '?')
outputs = (Output(label or (inferred.name if raw_socket else 'Value'),
annotation or inferred.typ),)
return Signature(display_name, tuple(parameters), outputs)


Expand All @@ -157,16 +291,23 @@ def _def_signatures(source: str) -> dict[str, tuple[Signature, ...]]:
try:
definitions = [statement for statement in ast.parse(source).body
if isinstance(statement, ast.FunctionDef)]
except SyntaxError:
definitions = []
except SyntaxError as exc:
# Incomplete typing at the caret must not erase fully parsed definitions
# above the error. Retain the old header fallback for incomplete bodies.
try:
prefix = '\n'.join(source.split('\n')[:max(0, (exc.lineno or 1) - 1)])
definitions = [statement for statement in ast.parse(prefix).body
if isinstance(statement, ast.FunctionDef)]
except SyntaxError:
definitions = []
for line in source.splitlines():
if not line.startswith('def ') or not line.rstrip().endswith(':'):
continue
try:
definition = ast.parse(line + '\n pass').body[0]
except SyntaxError:
continue
if isinstance(definition, ast.FunctionDef):
if isinstance(definition, ast.FunctionDef) and not any(fn.name == definition.name for fn in definitions):
definitions.append(definition)
return {fn.name: (_definition_signature(fn, fn.name),) for fn in definitions}

Expand Down
Loading
Loading