Skip to content

AST-Based Variable Name Detection Implementation

Overview

We've successfully implemented an import hook solution for extracting variable names for Resource classes and their subclasses. This replaces the slower stack introspection approach with a more performant AST transformation.

Key Components

1. AST Transformer (ast_transformer.py)

  • ResourceInstantiationTransformer: AST visitor that wraps Resource instantiation calls
  • NFSourceLoader: Custom source loader that applies AST transformations
  • NFMetaFinder: Meta path finder that installs our custom loader
  • _nf_check_resource_instantiation: Helper function injected into transformed code

2. Import Hook Management (import_hook.py)

  • Functions to enable/disable AST transformation
  • Context manager for scoped transformation
  • Auto-installation logic with pytest detection

3. Core Integration

  • Modified Construct.__init__ to support both AST and stack introspection
  • Fallback mechanism ensures backward compatibility
  • Programmatic controls: enable_ast_transform() and disable_ast_transform()

How It Works

  1. Assignment Detection: The AST transformer identifies patterns like:
  2. my_bucket = Resource(...) → ID becomes "my_bucket"
  3. self.vpc = Resource(...) → ID becomes "vpc"

  4. Call Wrapping: Transforms the AST to wrap instantiation calls:

    # Original
    my_bucket = Resource(stack, type="aws_s3_bucket")
    
    # Transformed (internally)
    my_bucket = _nf_check_resource_instantiation(Resource, "my_bucket", stack, type="aws_s3_bucket")
    

  5. Smart Injection: Only injects nf_id for direct nf.core classes, not user subclasses

Benefits

  • Performance: Eliminates runtime stack inspection overhead
  • Reliability: No frame walking or source line parsing
  • Compatibility: Works with autoscope decorator and all existing patterns
  • Pytest Support: Automatically disabled in pytest by default, can be enabled with import_hook()

Usage

Basic Usage

from nf.core import enable_ast_transform, import_hook

# Enable globally
enable_ast_transform()

# Or use context manager
with import_hook():
    import my_infrastructure_module

Testing

# In tests, enable explicitly
with import_hook():
    # Test code here
    pass

Limitations

  1. Only works at import time - dynamic code (eval/exec) isn't transformed
  2. Binary modules (.so, .pyd) are skipped
  3. Standard library and most third-party packages are excluded

Fallback Behavior

If AST transformation fails or is disabled: 1. System falls back to stack introspection 2. No code changes required 3. Performance degrades but functionality remains

Configuration

Environment Variables

netherframe reads no environment variables, and the variables this design once used are gone. Automatic naming is now the nf_autoid source codec (# coding: nf_autoid; see the Preprocessor Quick Reference); nf synth --no-auto-naming turns it off for one run.

File Filtering

The transformer skips: - Non-Python files - Standard library modules - Third-party packages (except nf) - Binary extensions - Test files (unless explicitly enabled)

Testing

Created comprehensive tests in test_ast_transform.py that verify: - Simple variable assignment - Self attribute assignment - Explicit ID override - Performance comparison - Toggle functionality

Future Improvements

  1. Cache transformed modules for faster subsequent imports
  2. Support for more assignment patterns (list comprehensions, etc.)
  3. Better integration with IDEs and debuggers
  4. Performance profiling and optimization