Python parser.expr() Examples

The following are 30 code examples of parser.expr(). 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 parser , or try the search function .
Example #1
Source File: transformer.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def decorator(self, nodelist):
        # '@' dotted_name [ '(' [arglist] ')' ]
        assert len(nodelist) in (3, 5, 6)
        assert nodelist[0][0] == token.AT
        assert nodelist[-1][0] == token.NEWLINE

        assert nodelist[1][0] == symbol.dotted_name
        funcname = self.decorator_name(nodelist[1][1:])

        if len(nodelist) > 3:
            assert nodelist[2][0] == token.LPAR
            expr = self.com_call_function(funcname, nodelist[3])
        else:
            expr = funcname

        return expr 
Example #2
Source File: transformer.py    From BinderFilter with MIT License 6 votes vote down vote up
def decorator(self, nodelist):
        # '@' dotted_name [ '(' [arglist] ')' ]
        assert len(nodelist) in (3, 5, 6)
        assert nodelist[0][0] == token.AT
        assert nodelist[-1][0] == token.NEWLINE

        assert nodelist[1][0] == symbol.dotted_name
        funcname = self.decorator_name(nodelist[1][1:])

        if len(nodelist) > 3:
            assert nodelist[2][0] == token.LPAR
            expr = self.com_call_function(funcname, nodelist[3])
        else:
            expr = funcname

        return expr 
Example #3
Source File: variables.py    From AlphaPy with Apache License 2.0 6 votes vote down vote up
def __new__(cls,
                name,
                expr,
                replace = False):
        # code
        efound = expr in [Variable.variables[key].expr for key in Variable.variables]
        if efound:
            key = [key for key in Variable.variables if expr in Variable.variables[key].expr]
            logger.info("Expression '%s' already exists for key %s", expr, key)
            return
        else:
            if replace or not name in Variable.variables:
                if not valid_name(name):
                    logger.info("Invalid variable key: %s", name)
                    return
                try:
                    result = parser.expr(expr)
                except:
                    logger.info("Invalid expression: %s", expr)
                    return
                return super(Variable, cls).__new__(cls)
            else:
                logger.info("Key %s already exists", name)

    # function __init__ 
Example #4
Source File: ast_tools.py    From Computable with MIT License 6 votes vote down vote up
def build_atom(expr_string):
    """ Build an ast for an atom from the given expr string.

        If expr_string is not a string, it is converted to a string
        before parsing to an ast_tuple.
    """
    # the [1][1] indexing below starts atoms at the third level
    # deep in the resulting parse tree.  parser.expr will return
    # a tree rooted with eval_input -> test_list -> test ...
    # I'm considering test to be the root of atom symbols.
    # It might be a better idea to move down a little in the
    # parse tree. Any benefits? Right now, this works fine.
    if isinstance(expr_string, str):
        ast = parser.expr(expr_string).totuple()[1][1]
    else:
        ast = parser.expr(repr(expr_string)).totuple()[1][1]
    return ast 
Example #5
Source File: transformer.py    From oss-ftp with MIT License 6 votes vote down vote up
def decorator(self, nodelist):
        # '@' dotted_name [ '(' [arglist] ')' ]
        assert len(nodelist) in (3, 5, 6)
        assert nodelist[0][0] == token.AT
        assert nodelist[-1][0] == token.NEWLINE

        assert nodelist[1][0] == symbol.dotted_name
        funcname = self.decorator_name(nodelist[1][1:])

        if len(nodelist) > 3:
            assert nodelist[2][0] == token.LPAR
            expr = self.com_call_function(funcname, nodelist[3])
        else:
            expr = funcname

        return expr 
Example #6
Source File: test_parser.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_compile_expr(self):
        st = parser.expr('2 + 3')
        code = parser.compilest(st)
        self.assertEqual(eval(code), 5) 
Example #7
Source File: test_parser.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_expr(self, s):
        self.roundtrip(parser.expr, s) 
Example #8
Source File: __init__.py    From ImageFusion with MIT License 5 votes vote down vote up
def evaluate_marker(cls, text, extra=None):
        """
        Evaluate a PEP 426 environment marker on CPython 2.4+.
        Return a boolean indicating the marker result in this environment.
        Raise SyntaxError if marker is invalid.

        This implementation uses the 'parser' module, which is not implemented
        on
        Jython and has been superseded by the 'ast' module in Python 2.6 and
        later.
        """
        return cls.interpret(parser.expr(text).totuple(1)[1]) 
Example #9
Source File: __init__.py    From ImageFusion with MIT License 5 votes vote down vote up
def evaluate_marker(cls, text, extra=None):
        """
        Evaluate a PEP 426 environment marker on CPython 2.4+.
        Return a boolean indicating the marker result in this environment.
        Raise SyntaxError if marker is invalid.

        This implementation uses the 'parser' module, which is not implemented
        on
        Jython and has been superseded by the 'ast' module in Python 2.6 and
        later.
        """
        return cls.interpret(parser.expr(text).totuple(1)[1]) 
Example #10
Source File: transformer.py    From oss-ftp with MIT License 5 votes vote down vote up
def com_list_comprehension(self, expr, node):
        return self.com_comprehension(expr, None, node, 'list') 
Example #11
Source File: variables.py    From AlphaPy with Apache License 2.0 5 votes vote down vote up
def allvars(expr):
    r"""Get the list of valid names in the expression.

    Parameters
    ----------
    expr : str
        A valid expression conforming to the Variable Definition Language.

    Returns
    -------
    vlist : list
        List of valid variable names.

    """
    regex = re.compile('\w+')
    items = regex.findall(expr)
    vlist = []
    for item in items:
        if valid_name(item):
            vlist.append(item)
    return vlist


#
# Function vtree
# 
Example #12
Source File: __init__.py    From Flask-P2P with MIT License 5 votes vote down vote up
def evaluate_marker(cls, text, extra=None):
        """
        Evaluate a PEP 426 environment marker on CPython 2.4+.
        Return a boolean indicating the marker result in this environment.
        Raise SyntaxError if marker is invalid.

        This implementation uses the 'parser' module, which is not implemented
        on
        Jython and has been superseded by the 'ast' module in Python 2.6 and
        later.
        """
        return cls.interpret(parser.expr(text).totuple(1)[1]) 
Example #13
Source File: variables.py    From AlphaPy with Apache License 2.0 5 votes vote down vote up
def __str__(self):
        return self.expr


#
# Function vparse
# 
Example #14
Source File: variables.py    From AlphaPy with Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 name,
                 expr,
                 replace = False):
        # code
        self.name = name;
        self.expr = expr;
        # add key with expression
        Variable.variables[name] = self
            
    # function __str__ 
Example #15
Source File: __init__.py    From ImageFusion with MIT License 5 votes vote down vote up
def evaluate_marker(cls, text, extra=None):
        """
        Evaluate a PEP 426 environment marker on CPython 2.4+.
        Return a boolean indicating the marker result in this environment.
        Raise SyntaxError if marker is invalid.

        This implementation uses the 'parser' module, which is not implemented
        on
        Jython and has been superseded by the 'ast' module in Python 2.6 and
        later.
        """
        return cls.interpret(parser.expr(text).totuple(1)[1]) 
Example #16
Source File: test_parser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_issue_9011(self):
        # Issue 9011: compilation of an unary minus expression changed
        # the meaning of the ST, so that a second compilation produced
        # incorrect results.
        st = parser.expr('-3')
        code1 = parser.compilest(st)
        self.assertEqual(eval(code1), -3)
        code2 = parser.compilest(st)
        self.assertEqual(eval(code2), -3) 
Example #17
Source File: test_parser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_compile_expr(self):
        st = parser.expr('2 + 3')
        code = parser.compilest(st)
        self.assertEqual(eval(code), 5) 
Example #18
Source File: __init__.py    From ImageFusion with MIT License 5 votes vote down vote up
def evaluate_marker(cls, text, extra=None):
        """
        Evaluate a PEP 426 environment marker on CPython 2.4+.
        Return a boolean indicating the marker result in this environment.
        Raise SyntaxError if marker is invalid.

        This implementation uses the 'parser' module, which is not implemented
        on
        Jython and has been superseded by the 'ast' module in Python 2.6 and
        later.
        """
        return cls.interpret(parser.expr(text).totuple(1)[1]) 
Example #19
Source File: test_parser.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def check_expr(self, s):
        self.roundtrip(parser.expr, s) 
Example #20
Source File: transformer.py    From oss-ftp with MIT License 5 votes vote down vote up
def com_dictorsetmaker(self, nodelist):
        # dictorsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* [','])) |
        #                   (test (comp_for | (',' test)* [','])) )
        assert nodelist[0] == symbol.dictorsetmaker
        nodelist = nodelist[1:]
        if len(nodelist) == 1 or nodelist[1][0] == token.COMMA:
            # set literal
            items = []
            for i in range(0, len(nodelist), 2):
                items.append(self.com_node(nodelist[i]))
            return Set(items, lineno=items[0].lineno)
        elif nodelist[1][0] == symbol.comp_for:
            # set comprehension
            expr = self.com_node(nodelist[0])
            return self.com_comprehension(expr, None, nodelist[1], 'set')
        elif len(nodelist) > 3 and nodelist[3][0] == symbol.comp_for:
            # dict comprehension
            assert nodelist[1][0] == token.COLON
            key = self.com_node(nodelist[0])
            value = self.com_node(nodelist[2])
            return self.com_comprehension(key, value, nodelist[3], 'dict')
        else:
            # dict literal
            items = []
            for i in range(0, len(nodelist), 4):
                items.append((self.com_node(nodelist[i]),
                              self.com_node(nodelist[i+2])))
            return Dict(items, lineno=items[0][0].lineno) 
Example #21
Source File: test_parser.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def check_expr(self, s):
        self.roundtrip(parser.expr, s) 
Example #22
Source File: transformer.py    From oss-ftp with MIT License 5 votes vote down vote up
def com_with_item(self, nodelist, body, lineno):
        # with_item: test ['as' expr]
        if len(nodelist) == 4:
            var = self.com_assign(nodelist[3], OP_ASSIGN)
        else:
            var = None
        expr = self.com_node(nodelist[1])
        return With(expr, var, body, lineno=lineno) 
Example #23
Source File: transformer.py    From oss-ftp with MIT License 5 votes vote down vote up
def com_try_except_finally(self, nodelist):
        # ('try' ':' suite
        #  ((except_clause ':' suite)+ ['else' ':' suite] ['finally' ':' suite]
        #   | 'finally' ':' suite))

        if nodelist[3][0] == token.NAME:
            # first clause is a finally clause: only try-finally
            return TryFinally(self.com_node(nodelist[2]),
                              self.com_node(nodelist[5]),
                              lineno=nodelist[0][2])

        #tryexcept:  [TryNode, [except_clauses], elseNode)]
        clauses = []
        elseNode = None
        finallyNode = None
        for i in range(3, len(nodelist), 3):
            node = nodelist[i]
            if node[0] == symbol.except_clause:
                # except_clause: 'except' [expr [(',' | 'as') expr]] */
                if len(node) > 2:
                    expr1 = self.com_node(node[2])
                    if len(node) > 4:
                        expr2 = self.com_assign(node[4], OP_ASSIGN)
                    else:
                        expr2 = None
                else:
                    expr1 = expr2 = None
                clauses.append((expr1, expr2, self.com_node(nodelist[i+2])))

            if node[0] == token.NAME:
                if node[1] == 'else':
                    elseNode = self.com_node(nodelist[i+2])
                elif node[1] == 'finally':
                    finallyNode = self.com_node(nodelist[i+2])
        try_except = TryExcept(self.com_node(nodelist[2]), clauses, elseNode,
                               lineno=nodelist[0][2])
        if finallyNode:
            return TryFinally(try_except, finallyNode, lineno=nodelist[0][2])
        else:
            return try_except 
Example #24
Source File: transformer.py    From oss-ftp with MIT License 5 votes vote down vote up
def expr(self, nodelist):
        # xor_expr ('|' xor_expr)*
        return self.com_binary(Bitor, nodelist) 
Example #25
Source File: transformer.py    From oss-ftp with MIT License 5 votes vote down vote up
def comparison(self, nodelist):
        # comparison: expr (comp_op expr)*
        node = self.com_node(nodelist[0])
        if len(nodelist) == 1:
            return node

        results = []
        for i in range(2, len(nodelist), 2):
            nl = nodelist[i-1]

            # comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
            #          | 'in' | 'not' 'in' | 'is' | 'is' 'not'
            n = nl[1]
            if n[0] == token.NAME:
                type = n[1]
                if len(nl) == 3:
                    if type == 'not':
                        type = 'not in'
                    else:
                        type = 'is not'
            else:
                type = _cmp_types[n[0]]

            lineno = nl[1][2]
            results.append((type, self.com_node(nodelist[i])))

        # we need a special "compare" node so that we can distinguish
        #   3 < x < 5   from    (3 < x) < 5
        # the two have very different semantics and results (note that the
        # latter form is always true)

        return Compare(node, results, lineno=lineno) 
Example #26
Source File: transformer.py    From oss-ftp with MIT License 5 votes vote down vote up
def exec_stmt(self, nodelist):
        # exec_stmt: 'exec' expr ['in' expr [',' expr]]
        expr1 = self.com_node(nodelist[1])
        if len(nodelist) >= 4:
            expr2 = self.com_node(nodelist[3])
            if len(nodelist) >= 6:
                expr3 = self.com_node(nodelist[5])
            else:
                expr3 = None
        else:
            expr2 = expr3 = None

        return Exec(expr1, expr2, expr3, lineno=nodelist[0][2]) 
Example #27
Source File: transformer.py    From oss-ftp with MIT License 5 votes vote down vote up
def yield_stmt(self, nodelist):
        expr = self.com_node(nodelist[0])
        return Discard(expr, lineno=expr.lineno) 
Example #28
Source File: transformer.py    From oss-ftp with MIT License 5 votes vote down vote up
def parseexpr(self, text):
        """Return a modified parse tree for the given expression text."""
        return self.transform(parser.expr(text)) 
Example #29
Source File: parse.py    From LPHK with GNU General Public License v3.0 5 votes vote down vote up
def eval_string_and_vars(eq_string, vars_in):
    for var in vars_in:
        eq_string = eq_string.replace(var, str(vars_in[var]))
    eq = parser.expr(eq_string).compile()
    return eval(eq) 
Example #30
Source File: test_parser.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_issue_9011(self):
        # Issue 9011: compilation of an unary minus expression changed
        # the meaning of the ST, so that a second compilation produced
        # incorrect results.
        st = parser.expr('-3')
        code1 = parser.compilest(st)
        self.assertEqual(eval(code1), -3)
        code2 = parser.compilest(st)
        self.assertEqual(eval(code2), -3)