diff --git a/__init__.py b/__init__.py index 8020af2..2b0588d 100644 --- a/__init__.py +++ b/__init__.py @@ -1,6 +1,6 @@ """NodeForge Blender addon package.""" -NODEFORGE_VERSION = (0, 97, 4) +NODEFORGE_VERSION = (0, 97, 5) bl_info = { "name": "NodeForge", "author": "nachitima", diff --git a/blender_manifest.toml b/blender_manifest.toml index fa8b397..d4b34b4 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.97.5" 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..d7786ee 100644 --- a/dev/CHANGELOG.md +++ b/dev/CHANGELOG.md @@ -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. diff --git a/docs/GET_STARTED.md b/docs/GET_STARTED.md index 5996748..06f0a84 100644 --- a/docs/GET_STARTED.md +++ b/docs/GET_STARTED.md @@ -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 diff --git a/editor/blender_ui.py b/editor/blender_ui.py index df828af..5d65852 100644 --- a/editor/blender_ui.py +++ b/editor/blender_ui.py @@ -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.""" @@ -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) @@ -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'} @@ -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): diff --git a/editor/intelligence.py b/editor/intelligence.py index e8cb06c..9cf330f 100644 --- a/editor/intelligence.py +++ b/editor/intelligence.py @@ -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) @@ -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 @@ -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 = [] @@ -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) @@ -157,8 +291,15 @@ 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 @@ -166,7 +307,7 @@ def _def_signatures(source: str) -> dict[str, tuple[Signature, ...]]: 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} diff --git a/tests/blender/test_editor_popup.py b/tests/blender/test_editor_popup.py index 2b64079..0726f20 100644 --- a/tests/blender/test_editor_popup.py +++ b/tests/blender/test_editor_popup.py @@ -1,5 +1,8 @@ """Blender-bound popup layout checks: no repeated parameters or clipped signature line.""" +import pytest +from types import SimpleNamespace + from NodeForge.editor.blender_ui import _popup_rows from NodeForge.editor.intelligence import Assistance, Output, Parameter, Signature, Suggestion @@ -43,3 +46,454 @@ def test_multiple_outputs_remain_separate_rows(): assert [row[0] for row in rows][-4:] == [ '→ 3 outputs:', ' Mesh: Geometry', ' Distance: Float', ' Valid: Bool', ] + + +class _FakeText: + """Minimal Text snapshot for testing modal state transitions without a UI window.""" + + def __init__(self, source='nodes.', pointer=101): + self.source = source + self.pointer = pointer + self.current_line_index = 0 + self.current_character = len(source) + self.edits = [] + + def delete(self, *, type): + assert type == 'PREVIOUS_CHARACTER' + self.edits.append(('delete', type)) + index = self.current_character + self.source = self.source[:index - 1] + self.source[index:] + self.current_character -= 1 + + def insert(self, *, text): + self.edits.append(('insert', text)) + index = self.current_character + self.source = self.source[:index] + text + self.source[index:] + self.current_character += len(text) + + def as_pointer(self): + return self.pointer + + def as_string(self): + return self.source + + +@pytest.fixture +def popup_session(monkeypatch): + """Run the real modal handler against an area-scoped, opt-in fake Text Editor.""" + from types import SimpleNamespace + from NodeForge.editor import blender_ui as ui + + text = _FakeText() + area = SimpleNamespace( + as_pointer=lambda: 17, + spaces=SimpleNamespace(active=SimpleNamespace(type='TEXT_EDITOR', text=text)), + regions=[SimpleNamespace(type='WINDOW', tag_redraw=lambda: None)], + tag_redraw=lambda: None, + ) + window_manager = SimpleNamespace(nodeforge_assist_enabled=True) + monkeypatch.setattr(ui, 'bpy', SimpleNamespace( + context=SimpleNamespace(window_manager=window_manager), + ops=SimpleNamespace(text=SimpleNamespace(delete=text.delete, insert=text.insert)))) + monkeypatch.setattr(ui, '_ENABLED', True) + monkeypatch.setattr(ui, '_SYMBOLS', object()) + monkeypatch.setattr(ui, '_STATES', {}) + monkeypatch.setattr(ui, '_RUNNING_AREAS', {17}) + candidate = Suggestion('mesh', 'mesh', 'function') + calls = [] + + def assistance(source, line, character, index): + calls.append((source, line, character)) + return Assistance(candidates=(candidate,), line=line, replace_start=0, replace_end=character) + + monkeypatch.setattr(ui, 'cursor_assistance', assistance) + context = SimpleNamespace(area=area, region=area.regions[0]) + operator = SimpleNamespace(area_pointer=17) + operator.modal = lambda ctx, event: ui.NODEFORGE_OT_editor_session.modal(operator, ctx, event) + ui._refresh_state(area) + + def event(kind, *, unicode='', value='PRESS', ctrl=False, alt=False, oskey=False): + return SimpleNamespace(type=kind, value=value, unicode=unicode, ctrl=ctrl, + alt=alt, oskey=oskey, shift=False) + + return ui, operator, context, text, calls, event + + +def test_dismissed_popup_stays_hidden_without_editor_input(popup_session): + """Escape consumes only the active popup; repeated Escape/idle do not unlock it.""" + ui, operator, context, text, calls, event = popup_session + state = ui._STATES[17] + assert operator.modal(context, event('ESC')) == {'RUNNING_MODAL'} + assert state.suppressed == state.key + for tick in range(3): + ui._refresh_state(context.area) + assert state.suppressed == state.key + assert operator.modal(context, event('MOUSEMOVE')) == {'PASS_THROUGH'} + assert operator.modal(context, event('ESC')) == {'PASS_THROUGH'} + assert operator.modal(context, event('A', unicode='a', value='RELEASE')) == {'PASS_THROUGH'} + assert operator.modal(context, event('LEFT_SHIFT')) == {'PASS_THROUGH'} + assert len(calls) == 1 + assert operator.modal(SimpleNamespace(area=SimpleNamespace(as_pointer=lambda: 18)), + event('BACK_SPACE')) == {'PASS_THROUGH'} + assert state.suppressed == state.key + + +def test_edit_after_escape_recomputes_even_when_snapshot_returns_identical(popup_session): + """Backspace/retype events unlock the popup before the next 250 ms poll.""" + ui, operator, context, text, calls, event = popup_session + state = ui._STATES[17] + old_key = state.key + assert operator.modal(context, event('ESC')) == {'RUNNING_MODAL'} + assert operator.modal(context, event('BACK_SPACE')) == {'PASS_THROUGH'} + assert state.key is None and state.suppressed is None and not state.help.candidates + # Blender handles two edits between ticks, returning to the identical source/caret. + text.source = 'nodes' + text.current_character = 5 + text.source = 'nodes.' + text.current_character = 6 + ui._refresh_state(context.area) + assert state.key == old_key and state.help.candidates + assert len(calls) == 2 + assert operator.modal(context, event('ESC')) == {'RUNNING_MODAL'} + assert operator.modal(context, event('PERIOD', unicode='.')) == {'PASS_THROUGH'} + assert state.key is None + + +def test_caret_navigation_and_shortcuts_restart_but_noop_events_do_not(popup_session): + """Mouse placement/navigation and editing shortcuts restart without consuming input.""" + ui, operator, context, text, calls, event = popup_session + state = ui._STATES[17] + for trigger in (event('LEFTMOUSE'), event('RIGHT_ARROW'), event('HOME'), + event('Z', ctrl=True), event('V', oskey=True), event('RET')): + ui._refresh_state(context.area) + operator.modal(context, event('ESC')) + assert operator.modal(context, trigger) == {'PASS_THROUGH'} + assert state.key is None and state.suppressed is None + ui._refresh_state(context.area) + operator.modal(context, event('ESC')) + assert operator.modal(context, event('F5')) == {'PASS_THROUGH'} + assert state.suppressed == state.key + + +def test_escape_suppresses_live_snapshot_if_timer_has_not_refreshed(popup_session): + """A pre-Escape edit cannot reopen hints on a subsequent idle timer tick.""" + ui, operator, context, text, calls, event = popup_session + state = ui._STATES[17] + assert state.help.candidates + text.source = 'nodes.c' + text.current_character = len(text.source) + assert state.key[1] == 'nodes.' + assert operator.modal(context, event('ESC')) == {'RUNNING_MODAL'} + assert state.suppressed == state.key == (101, 'nodes.c', 0, 7) + assert not state.help.candidates + ui._refresh_state(context.area) + assert state.suppressed == state.key + assert not state.help.candidates + # The next editor action, rather than the idle tick, restores completion. + assert operator.modal(context, event('BACK_SPACE')) == {'PASS_THROUGH'} + assert state.suppressed is None and state.key is None + ui._refresh_state(context.area) + assert state.help.candidates + + +def test_non_text_clicks_do_not_reopen_dismissed_popup(popup_session): + """Only the Text Editor WINDOW region may restart on a left click.""" + ui, operator, context, text, calls, event = popup_session + state = ui._STATES[17] + assert operator.modal(context, event('ESC')) == {'RUNNING_MODAL'} + for region_type in ('HEADER', 'UI'): + context.region = SimpleNamespace(type=region_type) + assert operator.modal(context, event('LEFTMOUSE')) == {'PASS_THROUGH'} + ui._refresh_state(context.area) + assert state.suppressed == state.key + assert not state.help.candidates + context.region = None + assert operator.modal(context, event('LEFTMOUSE')) == {'PASS_THROUGH'} + assert state.suppressed == state.key + context.region = SimpleNamespace(type='WINDOW') + assert operator.modal(context, event('LEFTMOUSE')) == {'PASS_THROUGH'} + assert state.suppressed is None and state.key is None + ui._refresh_state(context.area) + assert state.help.candidates + + +@pytest.mark.parametrize('region_type', ['HEADER', 'UI', None]) +def test_non_text_region_keys_do_not_change_popup_state(popup_session, region_type): + """Only the Text Editor WINDOW region owns modal completion key handling.""" + ui, operator, context, text, calls, event = popup_session + state = ui._STATES[17] + context.region = SimpleNamespace(type=region_type) if region_type else None + current_key = state.key + original_help = state.help + + # A visible candidate must not accept, navigate, or dismiss through another region. + for key in ('RET', 'NUMPAD_ENTER', 'TAB', 'UP_ARROW', 'DOWN_ARROW', 'ESC'): + assert operator.modal(context, event(key)) == {'PASS_THROUGH'} + assert (state.key, state.help, state.selection, state.suppressed) == ( + current_key, original_help, 0, None) + assert text.source == 'nodes.' and not text.edits + + # Dismiss from the text region, then try typing/restarting from another region. + context.region = SimpleNamespace(type='WINDOW') + assert operator.modal(context, event('ESC')) == {'RUNNING_MODAL'} + dismissed_help = state.help + context.region = SimpleNamespace(type=region_type) if region_type else None + for key, uni in (('A', 'a'), ('BACK_SPACE', ''), ('LEFT_ARROW', ''), + ('RET', ''), ('TAB', ''), ('ESC', '')): + assert operator.modal(context, event(key, unicode=uni)) == {'PASS_THROUGH'} + ui._refresh_state(context.area) + assert (state.key, state.help, state.selection, state.suppressed) == ( + current_key, dismissed_help, 0, current_key) + assert text.source == 'nodes.' and not text.edits + context.region = SimpleNamespace(type='WINDOW') + assert operator.modal(context, event('BACK_SPACE')) == {'PASS_THROUGH'} + ui._refresh_state(context.area) + assert state.help.candidates and state.suppressed is None + + +@pytest.mark.parametrize('key', ['RET', 'NUMPAD_ENTER', 'TAB']) +def test_completion_accepts_selected_candidate_once(popup_session, key): + """All acceptance keys insert exactly the highlighted value without a newline.""" + ui, operator, context, text, calls, event = popup_session + state = ui._STATES[17] + state.help = Assistance(candidates=(Suggestion('mesh', 'mesh', 'function'), + Suggestion('cube', 'cube', 'function')), + line=0, replace_start=0, replace_end=6) + assert operator.modal(context, event('DOWN_ARROW')) == {'RUNNING_MODAL'} + assert state.selection == 1 + assert operator.modal(context, event(key)) == {'RUNNING_MODAL'} + assert text.source == 'cube' and '\n' not in text.source + assert text.edits == [('delete', 'PREVIOUS_CHARACTER')] * 6 + [('insert', 'cube')] + assert operator.modal(context, event(key)) == {'PASS_THROUGH'} + assert len(text.edits) == 7 + + +@pytest.mark.parametrize('key,kw', [ + ('RET', {}), ('NUMPAD_ENTER', {}), ('TAB', {}), ('RET', {'shift': True}), + ('RET', {'ctrl': True}), ('NUMPAD_ENTER', {'alt': True}), + ('RET', {'oskey': True}), +]) +def test_native_keys_with_no_popup_or_modified_enter(popup_session, key, kw): + """No popup or modified Enter leaves Blender free to handle the keystroke.""" + ui, operator, context, text, calls, event = popup_session + state = ui._STATES[17] + if kw: + key_event = event(key) + for name, value in kw.items(): + setattr(key_event, name, value) + assert operator.modal(context, key_event) == {'PASS_THROUGH'} + else: + state.help = Assistance() + assert operator.modal(context, event(key)) == {'PASS_THROUGH'} + assert not text.edits + assert text.source == 'nodes.' + + +@pytest.mark.parametrize('mutation', ['source', 'caret', 'line', 'text', 'range', 'selection']) +def test_stale_completion_is_never_inserted(popup_session, mutation): + """Snapshot and span checks happen before any destructive editor operation.""" + ui, operator, context, text, calls, event = popup_session + state = ui._STATES[17] + if mutation == 'source': + text.source = 'nodesx' + elif mutation == 'caret': + text.current_character = 4 + elif mutation == 'line': + text.source = 'nodes.\n' + text.current_line_index = 1 + text.current_character = 0 + elif mutation == 'text': + other = _FakeText(source='nodes.', pointer=202) + context.area.spaces.active.text = other + elif mutation == 'range': + state.help = Assistance(candidates=state.help.candidates, line=0, + replace_start=-1, replace_end=6) + elif mutation == 'selection': + state.selection = 99 + assert operator.modal(context, event('RET')) == {'PASS_THROUGH'} + assert not text.edits + if mutation == 'text': + assert not context.area.spaces.active.text.edits + # The next timer tick is responsible for refreshing changed snapshots. + if mutation in {'source', 'caret', 'line', 'text'}: + ui._refresh_state(context.area) + assert state.key != (101, 'nodes.', 0, 6) + + +def test_source_outputs_share_popup_rows_and_preview_with_overflow(): + """AST-derived outputs feed the existing row renderer without a parallel formatter.""" + from NodeForge.editor.intelligence import _def_signatures, _return_preview + source = """def many(): + result = node('X', outputs={'a': (ID('Mesh'), Geometry), 'b': (ID('Top'), Bool), 'c': (ID('Bottom'), Bool), 'd': (ID('Side'), Bool), 'e': (ID('UV Map'), Vector)}) + return result.a, result.b, result.c, result.d, result.e +""" + signature = _def_signatures(source)['many'][0] + rows = _popup_rows(Assistance(signatures=(signature,)), 0, 500) + assert [row[0] for row in rows][-6:] == [ + '→ 5 outputs:', ' Mesh: Geometry', ' Top: Bool', ' Bottom: Bool', + ' Side: Bool', ' … +1 outputs'] + assert _return_preview(signature) == '→ (Geometry, Bool, Bool, Bool, Vector)' + + +def test_real_blender_text_editor_escape_and_enter_leave_node_graph_untouched(): + """Exercise modal acceptance using actual Text datablocks and bpy text operators.""" + import bpy + from NodeForge.editor import blender_ui as ui + + area = bpy.context.screen.areas[0] + old_type = area.type + initially_enabled = ui._ENABLED + before_groups = set(bpy.data.node_groups.keys()) + text = bpy.data.texts.new('NFTest_PopupRealEditor') + other = bpy.data.texts.new('NFTest_PopupOtherText') + pointer = area.as_pointer() + try: + if not initially_enabled: + ui.register() + bpy.context.window_manager.nodeforge_assist_enabled = True + area.type = 'TEXT_EDITOR' + area.spaces.active.text = text + region = next(item for item in area.regions if item.type == 'WINDOW') + operator = SimpleNamespace(area_pointer=pointer) + ui._RUNNING_AREAS.add(pointer) + + def event(key, unicode='', **modifiers): + data = dict(type=key, value='PRESS', unicode=unicode, ctrl=False, + alt=False, oskey=False, shift=False) + data.update(modifiers) + return SimpleNamespace(**data) + + with bpy.context.temp_override(area=area, region=region): + bpy.ops.text.insert(text='cu') + ui._refresh_state(area) + state = ui._STATES[pointer] + assert any(item.insert == 'cube' for item in state.help.candidates) + assert ui.NODEFORGE_OT_editor_session.modal(operator, bpy.context, event('ESC')) == {'RUNNING_MODAL'} + assert state.suppressed == state.key + assert ui.NODEFORGE_OT_editor_session.modal(operator, bpy.context, event('BACK_SPACE')) == {'PASS_THROUGH'} + bpy.ops.text.delete(type='PREVIOUS_CHARACTER') + bpy.ops.text.insert(text='u') + ui._refresh_state(area) + assert state.help.candidates and state.suppressed is None + assert ui.NODEFORGE_OT_editor_session.modal(operator, bpy.context, event('RET')) == {'RUNNING_MODAL'} + assert text.as_string() == 'cube' + + # A native Text datablock switch before the next poll invalidates the hint. + area.spaces.active.text = other + bpy.ops.text.insert(text='cu') + assert ui.NODEFORGE_OT_editor_session.modal(operator, bpy.context, event('RET')) == {'PASS_THROUGH'} + assert other.as_string() == 'cu' + ui._refresh_state(area) + assert ui.NODEFORGE_OT_editor_session.modal(operator, bpy.context, event('NUMPAD_ENTER')) == {'RUNNING_MODAL'} + assert other.as_string() == 'cube' + finally: + ui._STATES.pop(pointer, None) + ui._RUNNING_AREAS.discard(pointer) + bpy.context.window_manager.nodeforge_assist_enabled = False + area.type = old_type + bpy.data.texts.remove(text) + bpy.data.texts.remove(other) + if not initially_enabled: + ui.unregister() + assert set(bpy.data.node_groups.keys()) == before_groups + + +def test_real_blender_escape_with_stale_snapshot_and_header_click(): + """Dismiss the current Text state, not a cached one; ignore header clicks.""" + import bpy + from NodeForge.editor import blender_ui as ui + + area = bpy.context.screen.areas[0] + old_type = area.type + initially_enabled = ui._ENABLED + manager = bpy.context.window_manager + old_assist = getattr(manager, 'nodeforge_assist_enabled', False) + pointer = area.as_pointer() + text = bpy.data.texts.new('NFTest_PopupStaleEscape') + operator = SimpleNamespace(area_pointer=pointer) + + def event(name): + return SimpleNamespace(type=name, value='PRESS', unicode='', ctrl=False, + alt=False, oskey=False, shift=False) + + try: + if not initially_enabled: + ui.register() + manager.nodeforge_assist_enabled = True + area.type = 'TEXT_EDITOR' + area.spaces.active.text = text + window_region = next(region for region in area.regions if region.type == 'WINDOW') + header_region = next(region for region in area.regions if region.type == 'HEADER') + ui._RUNNING_AREAS.add(pointer) + + with bpy.context.temp_override(area=area, region=window_region): + bpy.ops.text.insert(text='cu') + ui._refresh_state(area) + state = ui._STATES[pointer] + assert state.help.candidates + assert state.key[1] == 'cu' + bpy.ops.text.insert(text='b') + assert state.key[1] == 'cu' and text.as_string() == 'cub' + assert ui.NODEFORGE_OT_editor_session.modal(operator, bpy.context, + event('ESC')) == {'RUNNING_MODAL'} + assert state.key[1] == 'cub' and state.suppressed == state.key + ui._refresh_state(area) + assert state.suppressed == state.key + assert not state.help.candidates + + with bpy.context.temp_override(area=area, region=header_region): + for key, uni in (('LEFTMOUSE', ''), ('A', 'a'), ('RET', ''), ('BACK_SPACE', '')): + header_event = event(key) + header_event.unicode = uni + assert ui.NODEFORGE_OT_editor_session.modal( + operator, bpy.context, header_event) == {'PASS_THROUGH'} + assert state.suppressed == state.key + with bpy.context.temp_override(area=area, region=window_region): + ui._refresh_state(area) + assert state.suppressed == state.key + assert not state.help.candidates + assert ui.NODEFORGE_OT_editor_session.modal(operator, bpy.context, + event('LEFTMOUSE')) == {'PASS_THROUGH'} + ui._refresh_state(area) + assert state.suppressed is None + assert state.help.candidates + current = (state.key, state.help, state.selection) + with bpy.context.temp_override(area=area, region=header_region): + for key in ('RET', 'NUMPAD_ENTER', 'TAB', 'UP_ARROW', 'ESC'): + assert ui.NODEFORGE_OT_editor_session.modal( + operator, bpy.context, event(key)) == {'PASS_THROUGH'} + assert (state.key, state.help, state.selection) == current + assert text.as_string() == 'cub' + with bpy.context.temp_override(area=area, region=window_region): + assert ui.NODEFORGE_OT_editor_session.modal( + operator, bpy.context, event('RET')) == {'RUNNING_MODAL'} + assert text.as_string() != 'cub' + finally: + ui._STATES.pop(pointer, None) + ui._RUNNING_AREAS.discard(pointer) + manager.nodeforge_assist_enabled = old_assist + area.type = old_type + bpy.data.texts.remove(text) + if not initially_enabled: + ui.unregister() + + +def test_raw_node_declared_selectors_match_blender_mesh_cube_sockets(): + """The supplied Blender 5.2 Mesh Cube exposes the declared Mesh/UV Map sockets.""" + import bpy + from NodeForge.editor.intelligence import _def_signatures + signatures = _def_signatures("""def mesh_cube(): + result = node('GeometryNodeMeshCube', outputs={'mesh': (ID('Mesh'), Geometry), 'uv': (ID('UV Map'), Vector)}) + return result.mesh, result.uv +""") + tree = bpy.data.node_groups.new('NFTest_CompletionSocketNames', 'GeometryNodeTree') + try: + native = tree.nodes.new('GeometryNodeMeshCube') + expected = [(socket.name, {'NodeSocketGeometry': 'Geometry', + 'NodeSocketVector': 'Vector'}[socket.bl_idname]) + for socket in native.outputs if socket.name in {'Mesh', 'UV Map'}] + assert [(o.name, o.typ) for o in signatures['mesh_cube'][0].outputs] == expected + assert [socket.identifier for socket in native.outputs if socket.name in {'Mesh', 'UV Map'}] == [ + 'Mesh', 'UV Map'] + finally: + bpy.data.node_groups.remove(tree) diff --git a/tests/unit/test_editor_intelligence.py b/tests/unit/test_editor_intelligence.py index cb11a47..58f444e 100644 --- a/tests/unit/test_editor_intelligence.py +++ b/tests/unit/test_editor_intelligence.py @@ -138,7 +138,7 @@ def test_typed_single_and_multiple_local_outputs(editor_index): index = SymbolIndex(resolve_environment()) hint = help_at_caret('from local.two_outputs import both\nx = both(|', index) assert [(item.name, item.typ) for item in hint.signatures[0].outputs] == [ - ('Geo', '?'), ('Weight', '?') + ('Geo', 'Geometry'), ('Weight', 'Float') ] # Cached snapshots key on the source path and selected definition. assert len(index._source_cache) == 1 @@ -156,10 +156,51 @@ def test_source_fallback_keeps_named_outputs_if_analysis_fails(editor_index): index = SymbolIndex(resolve_environment()) hint = help_at_caret('from local.broken import broken\nx = broken(|', index) assert [(item.name, item.typ) for item in hint.signatures[0].outputs] == [ - ('Value 1', '?'), ('X', '?') + ('Value 1', '?'), ('X', 'Float') ] +@pytest.mark.parametrize('statement, expected', [ + ('dummy = (result := unrelated())', [('Value 1', '?'), ('Value 2', '?')]), + ("dummy = {'socket': (result := unrelated())}", [('Value 1', '?'), ('Value 2', '?')]), + ('(result := unrelated())', [('Value 1', '?'), ('Value 2', '?')]), + ('dummy = (other := unrelated())', [('Mesh', 'Geometry'), ('Mesh 2', 'Geometry')]), +]) +def test_return_projection_discards_only_rebound_named_expr_targets(statement, expected): + """Unsupported walrus expressions cannot retain obsolete socket metadata.""" + from NodeForge.editor.intelligence import _def_signatures + source = ("def sample():\n" + " result = node('X', outputs={'out': (ID('Mesh'), Geometry)})\n" + f" {statement}\n" + " return result.out, result.out\n") + signature = _def_signatures(source)['sample'][0] + assert [(out.name, out.typ) for out in signature.outputs] == expected + + +def test_return_projection_drops_rebound_name_within_return_tuple(): + """A walrus rebinding in return invalidates a later socket access.""" + from NodeForge.editor.intelligence import _def_signatures, _return_preview + source = ("def sample():\n" + " result = node('X', outputs={'out': (ID('Mesh'), Geometry)})\n" + " return (result := unrelated()), result.out\n") + signature = _def_signatures(source)['sample'][0] + assert [(out.name, out.typ) for out in signature.outputs] == [ + ('Value 1', '?'), ('Value 2', '?')] + assert _return_preview(signature) == '' + + +def test_later_known_assignment_recovers_socket_metadata_after_walrus(): + """A later explicit declaration can safely establish a new raw-node binding.""" + from NodeForge.editor.intelligence import _def_signatures + source = ("def sample():\n" + " result = node('X', outputs={'out': (ID('Old'), Vector)})\n" + " dummy = (result := unrelated())\n" + " result = node('X', outputs={'out': (ID('Mesh'), Geometry)})\n" + " return result.out\n") + signature = _def_signatures(source)['sample'][0] + assert [(out.name, out.typ) for out in signature.outputs] == [('Mesh', 'Geometry')] + + def test_tuple_extension_result_is_split_into_ordered_outputs(): """Extension tuple results must show individual types, not one long type string.""" from types import SimpleNamespace @@ -202,6 +243,11 @@ def _install_nested_editor_package(tmp_path): 'def cube(size: Float, bevel: Float = 0.0) -> Float:\n' ' return size + bevel\n' ), + 'mesh/sockets.nf': ( + "def dual(geo: Geometry):\n" + " out = node('X', outputs={'mesh': (ID('Mesh'), Geometry), 'uv': (ID('UV Map'), Vector)})\n" + " return out.mesh, out.uv\n" + ), 'curve/primitives.nf': ( 'def cube(radius: Float = 1.0) -> Float:\n' ' return radius\n' @@ -219,6 +265,11 @@ def _install_nested_editor_package(tmp_path): ' return value\n' ), } + (root / 'examples').mkdir(parents=True, exist_ok=True) + (root / 'examples' / 'preview.nf').write_text( + "def example():\n" + " out = node('X', outputs={'mesh': (ID('Mesh'), Geometry), 'uv': (ID('UV Map'), Vector)})\n" + " return out.uv, out.mesh\n", encoding='utf-8') for relative, content in files.items(): path = root / 'functions' / relative path.parent.mkdir(parents=True, exist_ok=True) @@ -228,7 +279,7 @@ def _install_nested_editor_package(tmp_path): 'name': 'Nested Editor', 'version': '1.0.0', 'author': 'Test', 'description': 'Nested completion fixture', 'nodeforge_min_version': '0.65.0', - 'contents': {'functions': 'functions'}, + 'contents': {'functions': 'functions', 'examples': 'examples'}, }), encoding='utf-8') packages.install_package_directory(root) return root @@ -277,3 +328,157 @@ def test_nested_package_signatures_are_owner_exact_and_frozen(editor_index): again = help_at_caret(prefix + 'n.mesh.primitives.cube(be|', index) assert [p.name for p in again.signatures[0].parameters] == ['size', 'bevel'] assert 'bevel=' in [item.insert for item in again.candidates] + + +@pytest.mark.parametrize('source, expected', [ + ("""def dual(): + result = node('GeometryNodeMeshCube', outputs={'r1': (ID('UV Map'), Vector), 'r0': (ID('Mesh'), Geometry)}) + return (result.r0, result.r1) +""", [('Mesh', 'Geometry'), ('UV Map', 'Vector')]), + ("""def dual(): + result = node('GeometryNodeMeshCube', outputs={'r1': (ID('UV Map'), Vector), 'r0': (ID('Mesh'), Geometry)}) + return result.r0, result.r1 +""", [('Mesh', 'Geometry'), ('UV Map', 'Vector')]), + ("""def dual(): + result = node('X', outputs={'mesh': Geometry, 'uv_map': (3, Vector), 'direct': ('Normal', Vector)}) + return result.uv_map, result.mesh, result.direct +""", [('Uv Map', 'Vector'), ('Mesh', 'Geometry'), ('Normal', 'Vector')]), + ("""def dual(): + output = node('X', outputs={'mesh': (ID('Mesh'), Geometry), 'bad': (ID(variable), Float)}) + return output.mesh, output.bad +""", [('Mesh', 'Geometry'), ('Value 2', '?')]), + ("""def dual(): + data = node('X', outputs={'a': (ID('Mesh'), Geometry), 'b': (ID('Mesh'), Geometry)}) + return data.a, data.b +""", [('Mesh', 'Geometry'), ('Mesh 2', 'Geometry')]), + ("""def dual(geo: Geometry, weight: Float): + alias = geo + return alias, weight +""", [('Alias', 'Geometry'), ('Weight', 'Float')]), + ("""def dual(): + original = node('X', outputs={'mesh': (ID('Mesh'), Geometry)}) + alias = original + copy = alias.mesh + return copy, alias.mesh +""", [('Mesh', 'Geometry'), ('Mesh 2', 'Geometry')]), + ("""def dual(geo: Geometry): + return unknown(geo), geo +""", [('Value 1', '?'), ('Geo', 'Geometry')]), + ("""def dual(): + result = node('X', outputs={'mesh': (ID('Mesh'), Geometry)}) + result = unknown() + return result.mesh, result.missing +""", [('Value 1', '?'), ('Value 2', '?')]), + ("""def dual(): + result = node('X', outputs={'mesh': (ID('Mesh'), Geometry)}) + if flag: + result = unknown() + return result.mesh, result.mesh +""", [('Value 1', '?'), ('Value 2', '?')]), + ("""def dual(geo: Geometry): + geo = random() + return geo, geo +""", [('Geo', '?'), ('Geo 2', '?')]), +]) +def test_source_return_projection_and_conservative_fallback(source, expected): + """Literal raw selectors and simple assignments preserve only defensible metadata.""" + from NodeForge.editor.intelligence import _def_signatures + signature = _def_signatures(source)['dual'][0] + assert [(o.name, o.typ) for o in signature.outputs] == expected + + +def test_direct_single_source_output_and_annotation_labels(): + """Direct raw-node sockets use their declared name; explicit Type labels win.""" + from NodeForge.editor.intelligence import _def_signatures, _return_preview + source = """def circle() -> Geometry: + return node('GeometryNodeMeshCircle', output=ID('Mesh'), typ=Geometry) +def labeled() -> Geometry['Result']: + return node('GeometryNodeMeshCircle', output=ID('Mesh'), typ=Geometry) +def unnamed(geo: Geometry) -> Geometry: + return transform(geo) +def unknown(): + return other_function() +""" + signatures = _def_signatures(source) + assert [(o.name, o.typ) for o in signatures['circle'][0].outputs] == [('Mesh', 'Geometry')] + assert [(o.name, o.typ) for o in signatures['labeled'][0].outputs] == [('Result', 'Geometry')] + assert [(o.name, o.typ) for o in signatures['unnamed'][0].outputs] == [('Value', 'Geometry')] + assert signatures['unknown'][0].outputs[0].typ == '?' + assert _return_preview(signatures['circle'][0]) == '→ Geometry' + assert _return_preview(signatures['unknown'][0]) == '' + + +def test_unsaved_function_source_survives_incomplete_call(editor_index): + """An unfinished expression below a full declaration retains its output metadata.""" + index, _ = editor_index + source = """def local_mesh(): + value = node('X', outputs={'mesh': (ID('Mesh'), Geometry), 'uv': (ID('UV Map'), Vector)}) + return value.mesh, value.uv +x = local_mesh(|""" + hint = help_at_caret(source, index) + assert [(o.name, o.typ) for o in hint.signatures[0].outputs] == [ + ('Mesh', 'Geometry'), ('UV Map', 'Vector') + ] + + +def test_real_nodes_package_outputs(editor_index): + """The supplied nodeforge.nodes package exposes actual raw-node selector labels.""" + import os + from NodeForge.editor.intelligence import _return_preview + source_root = os.environ.get('NODEFORGE_NODES_TEST_DIR') + if source_root is None: + pytest.skip('nodeforge.nodes fixture directory not supplied') + index, _ = editor_index + packages.install_package_directory(Path(source_root)) + index = SymbolIndex(resolve_environment()) + prefix = 'from packages import nodes as n\nx = n.mesh.primitives.' + expected = { + 'mesh_cube': [('Mesh', 'Geometry'), ('UV Map', 'Vector')], + 'mesh_cone': [('Mesh', 'Geometry'), ('Top', 'Bool'), ('Bottom', 'Bool'), + ('Side', 'Bool'), ('UV Map', 'Vector')], + 'mesh_circle': [('Mesh', 'Geometry')], + } + for function, outputs in expected.items(): + hint = help_at_caret(prefix + function + '(|', index) + assert [(o.name, o.typ) for o in hint.signatures[0].outputs] == outputs + members = help_at_caret(prefix + 'mesh_cu|', index) + assert [(s.label, s.detail) for s in members.candidates if s.label == 'mesh_cube'] == [ + ('mesh_cube', '→ (Geometry, Vector)')] + + + +def test_package_source_output_metadata_is_frozen_and_example_visible(editor_index): + """Package, aliases, and Examples show the same source-backed types and order.""" + _, tmp_path = editor_index + root = _install_nested_editor_package(tmp_path) + index = SymbolIndex(resolve_environment()) + qualified = help_at_caret('from packages import nodes as n\nx = n.mesh.sockets.dual(|', index) + assert [(o.name, o.typ) for o in qualified.signatures[0].outputs] == [ + ('Mesh', 'Geometry'), ('UV Map', 'Vector')] + short = help_at_caret('from packages import nodes as n\nx = n.dual(|', index) + assert short.signatures[0].outputs == qualified.signatures[0].outputs + example = help_at_caret('from examples import preview as ex\nx = ex.example(|', index) + assert [(o.name, o.typ) for o in example.signatures[0].outputs] == [ + ('UV Map', 'Vector'), ('Mesh', 'Geometry')] + (root / 'functions/mesh/sockets.nf').write_text('def dual(changed: Float):\n return changed\n') + frozen = help_at_caret('from packages import nodes as n\nx = n.mesh.sockets.dual(|', index) + assert frozen.signatures[0].outputs == qualified.signatures[0].outputs + + +def test_plain_expr_and_docstring_do_not_erase_known_parameter_types(): + """Non-binding expressions preserve types, while assignment expressions do not.""" + from NodeForge.editor.intelligence import _def_signatures + source = """def stable(geo: Geometry, weight: Float): + '''A source-docstring does not rebind parameters.''' + inspect(geo) + return geo, weight + +def mutated(geo: Geometry): + inspect((geo := other())) + return geo, geo +""" + signatures = _def_signatures(source) + assert [(o.name, o.typ) for o in signatures['stable'][0].outputs] == [ + ('Geo', 'Geometry'), ('Weight', 'Float')] + assert [(o.name, o.typ) for o in signatures['mutated'][0].outputs] == [ + ('Geo', '?'), ('Geo 2', '?')] diff --git a/tests/unit/test_unified_editor_signatures.py b/tests/unit/test_unified_editor_signatures.py index 6d2c5cc..ede575b 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_local_source_return_types_follow_mtime_and_import_alias(index, tmp_path): + """Local source refresh changes the cached projection without rebuilding the index.""" + path = tmp_path / 'local' / 'terrain' / 'geometry.nf' + initial = _at('from local.terrain.geometry import move as go\nx = go(|', index) + assert initial.signatures[0].outputs[0].typ == 'Geometry' + import os + prior_stamp = path.stat().st_mtime_ns + path.write_text('''def move(geo: Geometry): + out = node('X', outputs={'mesh': (ID('Mesh'), Geometry), 'uv': (ID('UV Map'), Vector)}) + return out.mesh, out.uv +''', encoding='utf-8') + os.utime(path, ns=(prior_stamp + 10_000_000, prior_stamp + 10_000_000)) + updated = _at('from local.terrain.geometry import move as go\nx = go(|', index) + assert updated.signatures[0].name == 'go' + assert [(o.name, o.typ) for o in updated.signatures[0].outputs] == [ + ('Mesh', 'Geometry'), ('UV Map', 'Vector')] + + +def test_unresolved_source_does_not_change_core_or_parameter_contract(index): + """Source inference cannot alter core signature keywords or unknown-call honesty.""" + core = _at('x = set_position(|', index) + assert core.signatures and core.signatures[0].outputs[0].typ == 'Geometry' + local = _at('from local.terrain.geometry import move as go\nx = go(of|', index) + assert [item.insert for item in local.candidates] == ['offset='] + assert local.signatures[0].parameters[1].keyword == 'offset'