astoptimizer / demo.py

#!/usr/bin/env python
import ast
import dis
import sys
import types
from astoptimizer import Config, parse_ast, optimize_ast, compile_ast

def dump_bytecode(code):
    dis.dis(code)
    for const in code.co_consts:
        if not isinstance(const, types.CodeType):
            continue
        print("")
        print("%s:" % const)
        dump_bytecode(const)

def main():
    if len(sys.argv) < 2:
        print("usage: %s code ..." % sys.argv[0])
        print("   or: %s -   # read input from stdin" % sys.argv[0])
        print("example: %s '1+1'" % sys.argv[0])
        sys.exit(1)
    if len(sys.argv) == 2 and sys.argv[1] == '-':
        code_str = sys.stdin.read()
    else:
        code_str = '\n'.join(sys.argv[1:])

    config = Config('builtin_funcs', 'pythonenv')
    config.use_experimental_vars = True
    print("Config features: %s" % ', '.join(sorted(config.features)))
    print("")

    tree = parse_ast(code_str)
    print("Original AST:")
    print(ast.dump(tree))
    print("")

    print("Original bytecode:")
    try:
        code = compile(code_str, "<string>", "exec")
    except SyntaxError:
        print("*** SYNTAX ERROR ***")
    else:
        dump_bytecode(code)
    print("")

    tree = optimize_ast(tree, config)
    print("Optimised AST:")
    print(ast.dump(tree))
    print("")

    print("Optimized bytecode:")
    try:
        code = compile_ast(tree)
    except SyntaxError:
        print("*** SYNTAX ERROR ***")
    else:
        dump_bytecode(code)
        print("")

        print("Execute code:")
        exec(code)

if __name__ == "__main__":
    main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.