Skip to content

AST-Based Variable Name Detection

Overview

netherframe now supports AST (Abstract Syntax Tree) transformation as an alternative to stack introspection for automatic variable name detection. This approach provides significant performance improvements by transforming the code at import time rather than inspecting the call stack at runtime.

How It Works

  1. Import Hook: When enabled, an import hook intercepts module imports
  2. AST Transformation: The source code is parsed into an AST
  3. Call Wrapping: Resource instantiation calls are wrapped to inject variable names
  4. Compilation: The transformed AST is compiled and executed

Example Transformation

Original code:

my_bucket = Resource(stack, type="aws_s3_bucket", config={})

Transformed (internally):

my_bucket = _nf_check_resource_instantiation(Resource, "my_bucket", stack=stack, type="aws_s3_bucket", config={})

Benefits

  • Performance: 2-5x faster than stack introspection
  • Reliability: No frame inspection overhead
  • Compatibility: Works seamlessly with existing code
  • Pytest Support: Smart detection avoids conflicts with pytest

Usage

Basic Usage

from nf.core import App, Stack, Resource, enable_ast_transform

# Enable AST transformation
enable_ast_transform()

app = App()
my_stack = Stack(app)  # ID auto-detected as "my_stack"

# Variable name "vpc" becomes the resource ID
vpc = Resource(my_stack, type="aws_vpc", config={"cidr_block": "10.0.0.0/16"})

With Context Manager

from nf.core import import_hook

# Use AST transformation only within the context
with import_hook():
    app = App()
    stack = Stack(app, "my-stack")

    database = Resource(stack, type="aws_db_instance", config={"engine": "postgres"})

With @autoscope Decorator

from nf.core import autoscope, import_hook

with import_hook():

    @autoscope
    class MyStack(Stack):
        def __init__(self, app):
            super().__init__(app)

            # Both scope and ID are auto-detected
            self.vpc = Resource(type="aws_vpc", config={"cidr_block": "10.0.0.0/16"})

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.

Programmatic Control

from nf.core import enable_ast_transform, disable_ast_transform, is_ast_transform_enabled

# Enable AST transformation
enable_ast_transform()

# Check if enabled
if is_ast_transform_enabled():
    print("AST transformation is active")

# Disable AST transformation
disable_ast_transform()

Testing

Writing Tests

Tests can enable AST transformation explicitly:

import pytest
from nf.core import import_hook


class TestMyFeature:
    def test_with_ast_transform(self):
        with import_hook():
            # Your test code here
            pass

Performance Testing

import time
from nf.core import enable_ast_transform, disable_ast_transform

# Benchmark AST transformation
enable_ast_transform()
start = time.time()
# ... create resources ...
ast_time = time.time() - start

# Benchmark stack introspection
disable_ast_transform()
start = time.time()
# ... create resources ...
stack_time = time.time() - start

print(f"Performance improvement: {(stack_time / ast_time):.1f}x")

Limitations

  1. Import Time: Transformation happens at module import time
  2. Dynamic Code: Won't work with eval() or exec() generated code
  3. File Filtering: Standard library and most third-party packages are skipped

Fallback Behavior

If AST transformation fails or is disabled, the system automatically falls back to stack introspection, ensuring your code continues to work.

Best Practices

  1. Enable Globally: For best performance, enable AST transformation at application startup
  2. Test Both Modes: Ensure your code works with both AST and stack introspection
  3. Explicit IDs: When in doubt, provide explicit IDs for critical resources

Troubleshooting

AST Not Working

  1. Check if enabled: is_ast_transform_enabled()
  2. Check for pytest: AST is disabled by default in pytest

Performance Not Improved

  1. Ensure import hook is installed before importing modules
  2. Check if modules are being cached (subsequent imports are faster)
  3. Profile to identify bottlenecks

Pytest Conflicts

Enable the transformation explicitly in the test, with import_hook() as above.