Copy docker run --rm zchencow/innozverse-python:latest python3 -c "
import ast, dis, tokenize, io, textwrap
# Step 3: AST Transformer — auto-inject logging
class LogInserter(ast.NodeTransformer):
'''Inserts a print() call at the start of every function.'''
def visit_FunctionDef(self, node):
log_stmt = ast.parse(
f'print(f\"CALL: {node.name}({', '.join(a.arg + '={' + a.arg + '!r}' for a in node.args.args)})\")'
).body[0]
# Preserve line info
ast.copy_location(log_stmt, node)
node.body.insert(0, log_stmt)
return self.generic_visit(node)
src = textwrap.dedent('''
def add(a, b):
return a + b
def multiply(x, y):
return x * y
''')
tree = ast.parse(src)
new_tree = LogInserter().visit(tree)
ast.fix_missing_locations(new_tree)
code = compile(new_tree, '<transformed>', 'exec')
ns = {}
exec(code, ns)
print('=== Auto-logged function calls ===')
print(ns['add'](3, 4))
print(ns['multiply'](6, 7))
# Step 4: AST-based type checker
class TypeCheckInserter(ast.NodeTransformer):
def visit_FunctionDef(self, node):
checks = []
for arg in node.args.args:
if arg.annotation and isinstance(arg.annotation, ast.Name):
check = ast.parse(
f'assert isinstance({arg.arg}, {arg.annotation.id}), '
f'f\"{arg.arg} must be {arg.annotation.id.__class__.__name__}, got {{type({arg.arg}).__name__}}\"'
).body[0]
checks.append(check)
node.body = checks + node.body
return self.generic_visit(node)
src2 = textwrap.dedent('''
def safe_divide(a: int, b: int) -> float:
if b == 0: raise ZeroDivisionError(\"b cannot be zero\")
return a / b
''')
tree2 = TypeCheckInserter().visit(ast.parse(src2))
ast.fix_missing_locations(tree2)
ns2 = {}
exec(compile(tree2, '<typed>', 'exec'), ns2)
print()
print('=== AST-injected type checks ===')
print(f'safe_divide(10, 3) = {ns2[\"safe_divide\"](10, 3):.4f}')
try: ns2['safe_divide'](10, 'three')
except AssertionError as e: print(f'Type error: {e}')
# Step 5: Bytecode inspection with dis
print()
print('=== Bytecode: fibonacci ===')
def fib(n):
if n <= 1: return n
return fib(n-1) + fib(n-2)
dis.dis(fib)
co = fib.__code__
print(f'co_varnames: {co.co_varnames}')
print(f'co_consts: {co.co_consts}')
print(f'co_freevars: {co.co_freevars}')
print(f'stacksize: {co.co_stacksize}')
print(f'code bytes: {len(co.co_code)} bytes')
# Step 6: Tokenizer
print()
print('=== Token stream ===')
src3 = 'result = price * (1 - discount)'
tokens = list(tokenize.generate_tokens(io.StringIO(src3).readline))
for tok in tokens[:12]:
if tok.type not in (tokenize.NL, tokenize.NEWLINE, tokenize.ENDMARKER):
print(f' {tokenize.tok_name[tok.type]:10s} {tok.string!r}')
# Step 7: eval() / compile() for dynamic expressions
print()
print('=== Dynamic expression evaluation ===')
exprs = [
'price * (1 - discount)',
'stock > 0 and price < 1000',
'[p[\"name\"] for p in products if p[\"stock\"] > 0]',
]
ctx = {
'price': 864.0, 'discount': 0.1, 'stock': 15,
'products': [
{'name': 'Surface Pro', 'stock': 15},
{'name': 'USB-C Hub', 'stock': 0},
{'name': 'Surface Pen', 'stock': 80},
]
}
for expr in exprs:
result = eval(compile(expr, '<expr>', 'eval'), {'__builtins__': {}}, ctx)
print(f' {expr[:40]:40s} → {result}')
# Step 8: Capstone — expression DSL compiler
print()
print('=== Capstone: Filter DSL compiler ===')
class FilterCompiler(ast.NodeVisitor):
'''Compiles a simple filter expression to a Python lambda.'''
SAFE_OPS = {ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE,
ast.And, ast.Or, ast.Not}
def compile(self, expr: str):
tree = ast.parse(expr, mode='eval')
self._validate(tree)
code = compile(tree, '<filter>', 'eval')
return lambda ctx: eval(code, {'__builtins__': {}}, ctx)
def _validate(self, tree):
for node in ast.walk(tree):
if isinstance(node, ast.Call):
raise ValueError('Function calls not allowed in filter expressions')
if isinstance(node, (ast.Import, ast.ImportFrom)):
raise ValueError('Imports not allowed')
filters = [
('price < 100', 'Affordable'),
('stock > 0', 'In stock'),
('price < 100 and stock > 0', 'Budget in-stock'),
('category == \"Laptop\"', 'Laptops'),
]
products = [
{'name': 'Surface Pro', 'price': 864.0, 'stock': 15, 'category': 'Laptop'},
{'name': 'Surface Pen', 'price': 49.99, 'stock': 80, 'category': 'Accessory'},
{'name': 'USB-C Hub', 'price': 29.99, 'stock': 0, 'category': 'Hardware'},
{'name': 'Office 365', 'price': 99.99, 'stock': 999,'category': 'Software'},
]
compiler = FilterCompiler()
for expr, label in filters:
fn = compiler.compile(expr)
matches = [p['name'] for p in products if fn(p)]
print(f' [{label}] {expr!r} → {matches}')
# Security check
try:
compiler.compile('__import__(\"os\").system(\"rm -rf /\")')
except ValueError as e:
print(f' [Security] Blocked: {e}')
"