Python compiler.parse() Examples

The following are 30 code examples of compiler.parse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module compiler , or try the search function .
Example #1
Source File: _assertionold.py    From scylla with Apache License 2.0 6 votes vote down vote up
def check(s, frame=None):
    if frame is None:
        frame = sys._getframe(1)
        frame = py.code.Frame(frame)
    expr = parse(s, 'eval')
    assert isinstance(expr, ast.Expression)
    node = Interpretable(expr.node)
    try:
        node.eval(frame)
    except passthroughex:
        raise
    except Failure:
        e = sys.exc_info()[1]
        report_failure(e)
    else:
        if not frame.is_true(node.result):
            sys.stderr.write("assertion failed: %s\n" % node.nice_explanation())


###########################################################
# API / Entry points
# ######################################################### 
Example #2
Source File: input.py    From android-xmrig-miner with GNU General Public License v3.0 6 votes vote down vote up
def CheckedEval(file_contents):
  """Return the eval of a gyp file.

  The gyp file is restricted to dictionaries and lists only, and
  repeated keys are not allowed.

  Note that this is slower than eval() is.
  """

  ast = compiler.parse(file_contents)
  assert isinstance(ast, Module)
  c1 = ast.getChildren()
  assert c1[0] is None
  assert isinstance(c1[1], Stmt)
  c2 = c1[1].getChildren()
  assert isinstance(c2[0], Discard)
  c3 = c2[0].getChildren()
  assert len(c3) == 1
  return CheckNode(c3[0], []) 
Example #3
Source File: input.py    From android-xmrig-miner with GNU General Public License v3.0 6 votes vote down vote up
def CheckedEval(file_contents):
  """Return the eval of a gyp file.

  The gyp file is restricted to dictionaries and lists only, and
  repeated keys are not allowed.

  Note that this is slower than eval() is.
  """

  ast = compiler.parse(file_contents)
  assert isinstance(ast, Module)
  c1 = ast.getChildren()
  assert c1[0] is None
  assert isinstance(c1[1], Stmt)
  c2 = c1[1].getChildren()
  assert isinstance(c2[0], Discard)
  c3 = c2[0].getChildren()
  assert len(c3) == 1
  return CheckNode(c3[0], []) 
Example #4
Source File: comment_eater.py    From megaman with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_class_traits(klass):
    """ Yield all of the documentation for trait definitions on a class object.
    """
    # FIXME: gracefully handle errors here or in the caller?
    source = inspect.getsource(klass)
    cb = CommentBlocker()
    cb.process_file(StringIO(source))
    mod_ast = compiler.parse(source)
    class_ast = mod_ast.node.nodes[0]
    for node in class_ast.code.nodes:
        # FIXME: handle other kinds of assignments?
        if isinstance(node, compiler.ast.Assign):
            name = node.nodes[0].name
            rhs = unparse(node.expr).strip()
            doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
            yield name, rhs, doc 
Example #5
Source File: input.py    From kawalpemilu2014 with GNU Affero General Public License v3.0 6 votes vote down vote up
def CheckedEval(file_contents):
  """Return the eval of a gyp file.

  The gyp file is restricted to dictionaries and lists only, and
  repeated keys are not allowed.

  Note that this is slower than eval() is.
  """

  ast = compiler.parse(file_contents)
  assert isinstance(ast, Module)
  c1 = ast.getChildren()
  assert c1[0] is None
  assert isinstance(c1[1], Stmt)
  c2 = c1[1].getChildren()
  assert isinstance(c2[0], Discard)
  c3 = c2[0].getChildren()
  assert len(c3) == 1
  return CheckNode(c3[0], []) 
Example #6
Source File: comment_eater.py    From DMDpack with GNU General Public License v3.0 6 votes vote down vote up
def get_class_traits(klass):
    """ Yield all of the documentation for trait definitions on a class object.
    """
    # FIXME: gracefully handle errors here or in the caller?
    source = inspect.getsource(klass)
    cb = CommentBlocker()
    cb.process_file(StringIO(source))
    mod_ast = compiler.parse(source)
    class_ast = mod_ast.node.nodes[0]
    for node in class_ast.code.nodes:
        # FIXME: handle other kinds of assignments?
        if isinstance(node, compiler.ast.Assign):
            name = node.nodes[0].name
            rhs = unparse(node.expr).strip()
            doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
            yield name, rhs, doc 
Example #7
Source File: comment_eater.py    From artview with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_class_traits(klass):
    """ Yield all of the documentation for trait definitions on a class object.
    """
    # FIXME: gracefully handle errors here or in the caller?
    source = inspect.getsource(klass)
    cb = CommentBlocker()
    cb.process_file(StringIO(source))
    mod_ast = compiler.parse(source)
    class_ast = mod_ast.node.nodes[0]
    for node in class_ast.code.nodes:
        # FIXME: handle other kinds of assignments?
        if isinstance(node, compiler.ast.Assign):
            name = node.nodes[0].name
            rhs = unparse(node.expr).strip()
            doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
            yield name, rhs, doc 
Example #8
Source File: input.py    From StarsAndClown with GNU General Public License v3.0 6 votes vote down vote up
def CheckedEval(file_contents):
  """Return the eval of a gyp file.

  The gyp file is restricted to dictionaries and lists only, and
  repeated keys are not allowed.

  Note that this is slower than eval() is.
  """

  ast = compiler.parse(file_contents)
  assert isinstance(ast, Module)
  c1 = ast.getChildren()
  assert c1[0] is None
  assert isinstance(c1[1], Stmt)
  c2 = c1[1].getChildren()
  assert isinstance(c2[0], Discard)
  c3 = c2[0].getChildren()
  assert len(c3) == 1
  return CheckNode(c3[0], []) 
Example #9
Source File: comment_eater.py    From gatspy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_class_traits(klass):
    """ Yield all of the documentation for trait definitions on a class object.
    """
    # FIXME: gracefully handle errors here or in the caller?
    source = inspect.getsource(klass)
    cb = CommentBlocker()
    cb.process_file(StringIO(source))
    mod_ast = compiler.parse(source)
    class_ast = mod_ast.node.nodes[0]
    for node in class_ast.code.nodes:
        # FIXME: handle other kinds of assignments?
        if isinstance(node, compiler.ast.Assign):
            name = node.nodes[0].name
            rhs = unparse(node.expr).strip()
            doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
            yield name, rhs, doc 
Example #10
Source File: _assertionold.py    From scylla with Apache License 2.0 6 votes vote down vote up
def interpret(source, frame, should_fail=False):
    module = Interpretable(parse(source, 'exec').node)
    #print "got module", module
    if isinstance(frame, py.std.types.FrameType):
        frame = py.code.Frame(frame)
    try:
        module.run(frame)
    except Failure:
        e = sys.exc_info()[1]
        return getfailure(e)
    except passthroughex:
        raise
    except:
        import traceback
        traceback.print_exc()
    if should_fail:
        return ("(assertion failed, but when it was re-run for "
                "printing intermediate values, it did not fail.  Suggestions: "
                "compute assert expression before the assert or use --nomagic)")
    else:
        return None 
Example #11
Source File: __init__.py    From signac with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getObj(s):
    global compiler
    if compiler is None:
        import compiler
    s = "a=" + s
    p = compiler.parse(s)
    return p.getChildren()[1].getChildren()[0].getChildren()[1] 
Example #12
Source File: comment_eater.py    From supersmoother with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_class_traits(klass):
    """ Yield all of the documentation for trait definitions on a class object.
    """
    # FIXME: gracefully handle errors here or in the caller?
    source = inspect.getsource(klass)
    cb = CommentBlocker()
    cb.process_file(StringIO(source))
    mod_ast = compiler.parse(source)
    class_ast = mod_ast.node.nodes[0]
    for node in class_ast.code.nodes:
        # FIXME: handle other kinds of assignments?
        if isinstance(node, compiler.ast.Assign):
            name = node.nodes[0].name
            rhs = unparse(node.expr).strip()
            doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
            yield name, rhs, doc 
Example #13
Source File: _assertionold.py    From python-netsurv with MIT License 6 votes vote down vote up
def check(s, frame=None):
    if frame is None:
        frame = sys._getframe(1)
        frame = py.code.Frame(frame)
    expr = parse(s, 'eval')
    assert isinstance(expr, ast.Expression)
    node = Interpretable(expr.node)
    try:
        node.eval(frame)
    except passthroughex:
        raise
    except Failure:
        e = sys.exc_info()[1]
        report_failure(e)
    else:
        if not frame.is_true(node.result):
            sys.stderr.write("assertion failed: %s\n" % node.nice_explanation())


###########################################################
# API / Entry points
# ######################################################### 
Example #14
Source File: _assertionold.py    From py with MIT License 6 votes vote down vote up
def interpret(source, frame, should_fail=False):
    module = Interpretable(parse(source, 'exec').node)
    #print "got module", module
    if isinstance(frame, types.FrameType):
        frame = py.code.Frame(frame)
    try:
        module.run(frame)
    except Failure:
        e = sys.exc_info()[1]
        return getfailure(e)
    except passthroughex:
        raise
    except:
        import traceback
        traceback.print_exc()
    if should_fail:
        return ("(assertion failed, but when it was re-run for "
                "printing intermediate values, it did not fail.  Suggestions: "
                "compute assert expression before the assert or use --nomagic)")
    else:
        return None 
Example #15
Source File: _assertionold.py    From py with MIT License 6 votes vote down vote up
def check(s, frame=None):
    if frame is None:
        frame = sys._getframe(1)
        frame = py.code.Frame(frame)
    expr = parse(s, 'eval')
    assert isinstance(expr, ast.Expression)
    node = Interpretable(expr.node)
    try:
        node.eval(frame)
    except passthroughex:
        raise
    except Failure:
        e = sys.exc_info()[1]
        report_failure(e)
    else:
        if not frame.is_true(node.result):
            sys.stderr.write("assertion failed: %s\n" % node.nice_explanation())


###########################################################
# API / Entry points
# ######################################################### 
Example #16
Source File: _assertionold.py    From python-netsurv with MIT License 6 votes vote down vote up
def check(s, frame=None):
    if frame is None:
        frame = sys._getframe(1)
        frame = py.code.Frame(frame)
    expr = parse(s, 'eval')
    assert isinstance(expr, ast.Expression)
    node = Interpretable(expr.node)
    try:
        node.eval(frame)
    except passthroughex:
        raise
    except Failure:
        e = sys.exc_info()[1]
        report_failure(e)
    else:
        if not frame.is_true(node.result):
            sys.stderr.write("assertion failed: %s\n" % node.nice_explanation())


###########################################################
# API / Entry points
# ######################################################### 
Example #17
Source File: _assertionold.py    From python-netsurv with MIT License 6 votes vote down vote up
def interpret(source, frame, should_fail=False):
    module = Interpretable(parse(source, 'exec').node)
    #print "got module", module
    if isinstance(frame, types.FrameType):
        frame = py.code.Frame(frame)
    try:
        module.run(frame)
    except Failure:
        e = sys.exc_info()[1]
        return getfailure(e)
    except passthroughex:
        raise
    except:
        import traceback
        traceback.print_exc()
    if should_fail:
        return ("(assertion failed, but when it was re-run for "
                "printing intermediate values, it did not fail.  Suggestions: "
                "compute assert expression before the assert or use --nomagic)")
    else:
        return None 
Example #18
Source File: input.py    From archived-pangyp with MIT License 6 votes vote down vote up
def CheckedEval(file_contents):
  """Return the eval of a gyp file.

  The gyp file is restricted to dictionaries and lists only, and
  repeated keys are not allowed.

  Note that this is slower than eval() is.
  """

  ast = compiler.parse(file_contents)
  assert isinstance(ast, Module)
  c1 = ast.getChildren()
  assert c1[0] is None
  assert isinstance(c1[1], Stmt)
  c2 = c1[1].getChildren()
  assert isinstance(c2[0], Discard)
  c3 = c2[0].getChildren()
  assert len(c3) == 1
  return CheckNode(c3[0], []) 
Example #19
Source File: _assertionold.py    From python-netsurv with MIT License 6 votes vote down vote up
def interpret(source, frame, should_fail=False):
    module = Interpretable(parse(source, 'exec').node)
    #print "got module", module
    if isinstance(frame, types.FrameType):
        frame = py.code.Frame(frame)
    try:
        module.run(frame)
    except Failure:
        e = sys.exc_info()[1]
        return getfailure(e)
    except passthroughex:
        raise
    except:
        import traceback
        traceback.print_exc()
    if should_fail:
        return ("(assertion failed, but when it was re-run for "
                "printing intermediate values, it did not fail.  Suggestions: "
                "compute assert expression before the assert or use --nomagic)")
    else:
        return None 
Example #20
Source File: comment_eater.py    From queueing-tool with MIT License 6 votes vote down vote up
def get_class_traits(klass):
    """ Yield all of the documentation for trait definitions on a class object.
    """
    # FIXME: gracefully handle errors here or in the caller?
    source = inspect.getsource(klass)
    cb = CommentBlocker()
    cb.process_file(StringIO(source))
    mod_ast = compiler.parse(source)
    class_ast = mod_ast.node.nodes[0]
    for node in class_ast.code.nodes:
        # FIXME: handle other kinds of assignments?
        if isinstance(node, compiler.ast.Assign):
            name = node.nodes[0].name
            rhs = unparse(node.expr).strip()
            doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
            yield name, rhs, doc 
Example #21
Source File: reprconf.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def astnode(self, s):
        """Return a Python2 ast Node compiled from a string."""
        try:
            import compiler
        except ImportError:
            # Fallback to eval when compiler package is not available,
            # e.g. IronPython 1.0.
            return eval(s)

        p = compiler.parse('__tempvalue__ = ' + s)
        return p.getChildren()[1].getChildren()[0].getChildren()[1] 
Example #22
Source File: __init__.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def getObj(s):
    global compiler
    if compiler is None:
        import compiler
    s = "a=" + s
    p = compiler.parse(s)
    return p.getChildren()[1].getChildren()[0].getChildren()[1] 
Example #23
Source File: pycodegen.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def _get_tree(self):
        tree = parse(self.source, self.mode)
        misc.set_filename(self.filename, tree)
        syntax.check(tree)
        return tree 
Example #24
Source File: reprconf.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def astnode(self, s):
        """Return a Python3 ast Node compiled from a string."""
        try:
            import ast
        except ImportError:
            # Fallback to eval when ast package is not available,
            # e.g. IronPython 1.0.
            return eval(s)

        p = ast.parse('__tempvalue__ = ' + s)
        return p.body[0].value 
Example #25
Source File: reprconf.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def astnode(self, s):
        """Return a Python3 ast Node compiled from a string."""
        try:
            import ast
        except ImportError:
            # Fallback to eval when ast package is not available,
            # e.g. IronPython 1.0.
            return eval(s)

        p = ast.parse("__tempvalue__ = " + s)
        return p.body[0].value 
Example #26
Source File: reprconf.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def astnode(self, s):
        """Return a Python2 ast Node compiled from a string."""
        try:
            import compiler
        except ImportError:
            # Fallback to eval when compiler package is not available,
            # e.g. IronPython 1.0.
            return eval(s)

        p = compiler.parse('__tempvalue__ = ' + s)
        return p.getChildren()[1].getChildren()[0].getChildren()[1] 
Example #27
Source File: template.py    From cosa-nostra with GNU General Public License v3.0 5 votes vote down vote up
def generate_code(text, filename, parser=None):
        # parse the text
        parser = parser or Parser()
        rootnode = parser.parse(text, filename)
                
        # generate python code from the parse tree
        code = rootnode.emit(indent="").strip()
        return safestr(code) 
Example #28
Source File: pycodegen.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def _get_tree(self):
        tree = parse(self.source, self.mode)
        misc.set_filename(self.filename, tree)
        syntax.check(tree)
        return tree 
Example #29
Source File: template.py    From cosa-nostra with GNU General Public License v3.0 5 votes vote down vote up
def parse(self, text, name="<template>"):
        self.text = text
        self.name = name
        
        defwith, text = self.read_defwith(text)
        suite = self.read_suite(text)
        return DefwithNode(defwith, suite) 
Example #30
Source File: reprconf.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def astnode(self, s):
        """Return a Python3 ast Node compiled from a string."""
        try:
            import ast
        except ImportError:
            # Fallback to eval when ast package is not available,
            # e.g. IronPython 1.0.
            return eval(s)

        p = ast.parse('__tempvalue__ = ' + s)
        return p.body[0].value