Пример #1
0
def 调用(源码, 文件名):
    分析器 = Parser()
    节点 = 分析器.parse(源码, 文件名)

    code = compile(节点, 文件名, 'exec')

    globals = create_globals(argv=[], fname=文件名)

    # 传出变量, 参考:
    # https://stackoverflow.com/questions/45535284/exec-and-variable-scope
    # https://stackoverflow.com/questions/1463306/how-does-exec-work-with-locals
    # https://docs.python.org/3/library/functions.html#exec
    本地量 = {}
    exec(code, globals, 本地量)
Пример #2
0
def repl(ps1='> ', ps2='>> ', globals=None):
    """
    A simple read-eval-print-loop for the µLang program
    """
    info = [
     '\tglobals: to list all builtins',
     '\tquit: to quit the REPL',
     '\thelp: to show this message']
    if not globals:
        globals = create_globals(fname='<STDIN>')
    globals['globals'] = lambda : print('\n'.join([' %s (%s)' % (k, v.__class__.__name__) for k, v in globals.items() if k != '__builtins__' if k != '___']))
    globals['help'] = lambda *args: if not args: print('\n'.join(info)) # Avoid dead code: help(*args)
    Repl(ps1, ps2, globals).cmdloop("Welcome to ulang's REPL..\nType 'help' for more informations.")
    sys.exit(0)
Пример #3
0
def repl(ps1='> ', ps2='>> ', globals=None):
    """
    A simple read-eval-print-loop for the µLang program
    """
    info = ['\t详情: 列出内置功能', '\t再会: 结束对话', '\t你好: 显示这段']
    if not globals:
        globals = create_globals(fname='<STDIN>')
    globals['详情'] = lambda: print('\n'.join([
        ' %s (%s)' % (k, v.__class__.__name__) for k, v in globals.items()
        if k != '__builtins__' if k != '___'
    ]))
    globals['你好'] = lambda *args: print('\n'.join(info)
                                        ) if not args else print()
    Repl(ps1, ps2, globals).cmdloop("木兰向您问好\n更多信息请说'你好'")
    sys.exit(0)
Пример #4
0
def repl(ps1="> ", ps2=">> ", globals=None):
    """
    A simple read-eval-print-loop for the µLang program
    """
    info = [
        "\tglobals: to list all builtins",
        "\tquit: to quit the REPL",
        "\thelp: to show this message",
    ]
    if not globals:
        globals = create_globals(fname="<STDIN>")
    globals["globals"] = lambda: print("\n".join([
        " %s (%s)" % (k, v.__class__.__name__) for k, v in globals.items()
        if k != "__builtins__" if k != "___"
    ]))
    globals["help"] = lambda *args: print("\n".join(info)
                                          ) if not args else print()
    Repl(ps1, ps2, globals).cmdloop(
        "Welcome to ulang's REPL..\nType 'help' for more informations.")
    sys.exit(0)
Пример #5
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    try:
        opts, args = getopt.getopt(argv[1:], 'hdapbctisDTe:v', [
            'dump-ast',
            'dump-python',
            'dump-blockly',
            'dump-bytecode',
            'dump-tokens',
            'python-to-ulang',
            'exec-code=',
            'debug',
            'disassemble',
            'show-backtrace',
            'help',
            'version',
            'interact'])
            
    except getopt.GetoptError as e:
        try:
            sys.stderr.write(str(e) + '\n')
            usage(argv[0])
        finally:
            e = None
            del e
    
    input_file = None
    dump_ast = False
    dump_python = False
    dump_blockly = False
    dump_bytecode = False
    dump_tokens = False
    disassemble = False
    trace_exception = False
    interactive = False
    python2ulang = False
    exec_code = None
    debug = False
    for opt, value in opts:
        if opt in ('-i', '--interact'):
            interactive = True
        elif opt in ('-p', '--dump-python'):
            dump_python = True
        elif opt in ('-a', '--dump-ast'):
            dump_ast = True
        elif opt in ('-b', '--dump-blockly'):
            dump_blockly = True
        elif opt in ('-c', '--dump-bytecode'):
            dump_bytecode = True
        elif opt in ('-d', '--disassemble'):
            disassemble = True
        elif opt in ('-s', '--python-to-ulang'):
            python2ulang = True
        elif opt in ('-D', '--debug'):
            debug = True
        elif opt in ('-t', '--show-backtrace'):
            trace_exception = True
        elif opt in ('-T', '--dump-tokens'):
            dump_tokens = True
        elif opt in ('-e', '--exec-code'):
            exec_code = value
        elif opt in ('-v', '--version'):
            from ulang import __version__
            sys.stderr.write('%s\n' % __version__)
            sys.exit()

    if len(argv) == 1:
        sys.exit(repl())

    if len(args) > 0:
        input_file = args[0]

    if input_file is None:
        if len(argv) == 1:
            sys.exit(repl())
        if not exec_code:
            usage(argv[0])
    try:
        source = None
        if exec_code:
            source = exec_code
            input_file = '<CLI>'
        elif input_file == '-':
            source = sys.stdin.read()
            input_file = '<STDIN>'
        else:
            with open(input_file, 'r') as f:
                source = f.read()
        if not source:
            sys.stderr.write('cannot open file "%s"!\n' % input_file)
            sys.exit(-1)
        
        if python2ulang:
            nodes = ast.parse(source, input_file)
            print(ulgen.dump(nodes))
            return

        if dump_tokens:
            tokens = lexer.lex(source)
            for token in tokens:
                print((token.gettokentype()), end=' ')

            return
        parser = Parser()
        nodes = parser.parse(source, input_file)
        if dump_ast:
            print(ast.dump(nodes, True, True))
            return
        if dump_python:
            print(python.dump(nodes))
            return
        if dump_blockly:
            print(blockly.dump(nodes))
            return
        if dump_bytecode:
            from pygen.compiler import Compiler
            print(Compiler().compile(nodes, input_file).dump())
            return
        code = compile(nodes, input_file, 'exec')
        if disassemble:
            dis.dis(code)
            return
        
        globals = create_globals(argv=(args[1:]),
            fname=input_file)
        if debug:
            import pdb
            while True:
                try:
                    pdb.run(code, globals, None)
                except pdb.Restart:
                    pass
                else:
                    break
        else:
            exec(code, globals)
        if interactive:
            repl(globals=globals)
    except Exception as e:
        try:
            sys.stderr.write('%s: %s\n' % (e.__class__.__name__, str(e)))
            if trace_exception:
                import pdb
                extype, value, tb = sys.exc_info()
                pdb.post_mortem(tb)
                raise e
        finally:
            e = None
            del e
Пример #6
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    else:
        try:
            opts, args = getopt.getopt(
                argv[1:],
                "hdapbctisDTe:v",
                [
                    "dump-ast",
                    "dump-python",
                    "dump-blockly",
                    "dump-bytecode",
                    "dump-tokens",
                    "python-to-ulang",
                    "exec-code=",
                    "debug",
                    "disassemble",
                    "show-backtrace",
                    "help",
                    "version",
                    "interact",
                ],
            )
        except getopt.GetoptError as e:
            try:
                sys.stderr.write(str(e) + "\n")
                usage(argv[0])
            finally:
                e = None
                del e

        input_file = None
        dump_ast = False
        dump_python = False
        dump_blockly = False
        dump_bytecode = False
        dump_tokens = False
        disassemble = False
        trace_exception = False
        interactive = False
        python2ulang = False
        exec_code = None
        debug = False
        for opt, value in opts:
            if opt in ("-i", "--interact"):
                interactive = True
            elif opt in ("-p", "--dump-python"):
                dump_python = True
            elif opt in ("-a", "--dump-ast"):
                dump_ast = True
            elif opt in ("-b", "--dump-blockly"):
                dump_blockly = True
            elif opt in ("-c", "--dump-bytecode"):
                dump_bytecode = True
            elif opt in ("-d", "--disassemble"):
                disassemble = True
            elif opt in ("-s", "--python-to-ulang"):
                python2ulang = True
            elif opt in ("-D", "--debug"):
                debug = True
            elif opt in ("-t", "--show-backtrace"):
                trace_exception = True
            elif opt in ("-T", "--dump-tokens"):
                dump_tokens = True
            elif opt in ("-e", "--exec-code"):
                exec_code = value
            else:
                if opt in ("-v", "--version"):
                    from ulang import __version__

                    sys.stderr.write("%s\n" % __version__)
                    sys.exit()

        if input_file is None:
            if len(args) > 0:
                input_file = args[0]
        if input_file is None:
            if len(argv) == 1:
                sys.exit(repl())
            else:
                if not exec_code:
                    usage(argv[0])
        try:
            source = None
            if exec_code:
                source = exec_code
                input_file = "<CLI>"
            else:
                if input_file == "-":
                    source = sys.stdin.read()
                    input_file = "<STDIN>"
                else:
                    with open(input_file, "r") as (f):
                        source = f.read()
            if not source:
                sys.stderr.write('cannot open file "%s"!\n' % input_file)
                sys.exit(-1)
            if python2ulang:
                nodes = ast.parse(source, input_file)
                print(ulgen.dump(nodes))
                return
                if dump_tokens:
                    tokens = lexer.lex(source)
                    for token in tokens:
                        print((token.gettokentype()), end=" ")

                    return
                parser = Parser()
                nodes = parser.parse(source, input_file)
                if dump_ast:
                    print(ast.dump(nodes, True, True))
                    return
                if dump_python:
                    print(python.dump(nodes))
                    return
                if dump_blockly:
                    print(blockly.dump(nodes))
                    return
                if dump_bytecode:
                    from pygen.compiler import Compiler

                    print(Compiler().compile(nodes, input_file).dump())
                    return
                code = compile(nodes, input_file, "exec")
                if disassemble:
                    dis.dis(code)
                    return
                globals = create_globals(argv=(args[1:]), fname=input_file)
                if debug:
                    import pdb

                    while True:
                        try:
                            pdb.run(code, globals, None)
                        except pdb.Restart:
                            pass
                        else:
                            break

            else:
                exec(code, globals)
            if interactive:
                repl(globals=globals)
        except Exception as e:
            try:
                sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e)))
                if trace_exception:
                    raise e
            finally:
                e = None
                del e